GRAIN_TYPE_CEREAL = u"cereal" GRAIN_TYPE_DME = u"dme" GRAIN_TYPE_LME = u"lme" IMPERIAL_TYPES = {
    u"volume": u"gallon",
    u"weight_large": u"lbs",
    u"weight_small": u"oz",
    u"temperature": u"degF",
} IMPERIAL_UNITS = u"imperial" KG_PER_POUND = 0.453592 POUND_PER_KG = 1.0 / KG_PER_POUND PPG_CEREAL = 30.0 PPG_DME = 44.0 PPG_LME = 36.0 SI_TYPES = {
    u"volume": u"liter",
    u"weight_large": u"kg",
    u"weight_small": u"mg",
    u"temperature": u"degC",
} SI_UNITS = u"metric" WEIGHT_TOLERANCE = 0.005 class GrainException(BrewdayException):
    pass def hwe_to_basis(hwe):
    """
    Hot Water Extract to Basis Percentage

    :param float hwe: Hot Water Extract as Ldeg/kg, dry basis
    :return: Basis as percentage
    :rtype: float
    """
    return hwe / LITERS_OF_WORT_AT_SG def hwe_to_ppg(hwe):
    """
    Hot Water Extract to Points Per Gallon

    :param float hwe: Hot Water Extract
    :return: Points Per Gallon
    :rtype: float
    """
    return hwe / PPG_TO_HWE_CONVERSION def ppg_to_hwe(ppg):
    """
    Points Per Gallon to Hot Water Extract

    :param float ppg: Points Per Gallon
    :return: Hot Water Extract
    :rtype: float
    """
    return ppg * PPG_TO_HWE_CONVERSION def validate_optional_fields(data, optional_fields, data_field=u"data"):
    """
    Validate fields which are optional as part of the data.

    :param dict data: A python dictionary to check for required fields
    :param list(tuple) optional_fields: Values and types to check for in data
    :param str data_field: The key in the data dictionary containing the optional fields
    :raises ValidatorException: Optional field is of the wrong type

    The format is a list of tuples where the first element is a string with
    a value that should be a key found in the data dict and
    where the second element is a python type or list/tuple of
    python types to check the field against.
    """  # noqa
    # If no optional data field present then return
    if data_field not in data:
        return
    for field, field_type in optional_fields:
        if field in data[data_field]:
            if field_type == str:
                try:
                    field_type = unicode
                except NameError:
                    field_type = str
            # With optional fields only check the type as they are overrides
            # and not all overrides need to be present
            if not isinstance(data[data_field][field], field_type):
                raise ValidatorException(
                    u"Optional field '{}' in '{}' is not of type '{}'".format(  # noqa
                        field, data_field, field_type
                    )
                ) def validate_percentage(percent):
    """
    Validate decimal percentage

    :param float percent: Percentage between 0.0 and 1.0
    :return: percentage
    :rtype: float
    :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
    """
    if 0.0 <= percent <= 1.0:
        return percent
    raise ValidatorException(u"Percentage values should be in decimal format") def validate_required_fields(data, required_fields):
    """
    Validate fields which are required as part of the data.

    :param dict data: A python dictionary to check for required fields
    :param list(tuple) required_fields: Values and types to check for in data
    :raises ValidatorException: Required field is missing from data
    :raises ValidatorException: Required field is of the wrong type

    The format is a list of tuples where the first element is a string with
    a value that should be a key found in the data dict and
    where the second element is a python type or list/tuple of
    python types to check the field against.
    """
    for field, field_type in required_fields:
        if field not in data:
            raise ValidatorException(
                u"Required field '{}' missing from data".format(field)  # noqa
            )
        if field_type == str:
            try:
                field_type = unicode
            except NameError:
                field_type = str
        if not isinstance(data[field], field_type):
            raise ValidatorException(
                u"Required field '{}' is not of type '{}'".format(  # noqa
                    field, field_type
                )
            ) def validate_units(units):
    """
    Validate units

    :param str units: Unit type
    :return: units
    :rtype: str
    :raises ValidatorException: If units is unknown
    """
    if units in [IMPERIAL_UNITS, SI_UNITS]:
        return units
    raise ValidatorException(
        u"Unkown units '{}', must use {} or {}".format(units, IMPERIAL_UNITS, SI_UNITS)
    )
import json
import sys
import textwrap
from .constants import GRAIN_TYPE_CEREAL
from .constants import GRAIN_TYPE_DME
from .constants import GRAIN_TYPE_LME
from .constants import IMPERIAL_TYPES
from .constants import IMPERIAL_UNITS
from .constants import KG_PER_POUND
from .constants import POUND_PER_KG
from .constants import PPG_CEREAL
from .constants import PPG_DME
from .constants import PPG_LME
from .constants import SI_TYPES
from .constants import SI_UNITS
from .constants import WEIGHT_TOLERANCE
from .exceptions import GrainException
from .utilities.malt import hwe_to_basis
from .utilities.malt import hwe_to_ppg
from .utilities.malt import ppg_to_hwe
from .validators import validate_optional_fields
from .validators import validate_percentage
from .validators import validate_required_fields
from .validators import validate_units
            return self.__unicode__().encode(u"utf8")

    def __unicode__(self):
        return self.name

    def __repr__(self):
        out = u"{0}('{1}'".format(type(self).__name__, self.name)
        if self.color:
            out = u"{0}, color={1}".format(out, self.color)
        if self.hwe:
            out = u"{0}, hwe={1}".format(out, round(self.hwe, 2))
        out = u"{0})".format(out)
        return out

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return False
        # Short name does not need to match
        if (
            (self.name == other.name)
            and (self.ppg == other.ppg)
            and (self.color == other.color)
        ):
            return True
        return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def to_dict(self):
        return {
            u"name": self.name,
            u"color": round(self.color, 1),
            u"ppg": round(self.ppg, 2),
            u"hwe": round(self.hwe, 2),
        }

    def to_json(self):
        return json.dumps(self.to_dict(), sort_keys=True)

    def format(self):
        msg = textwrap.dedent(
            u"""\
                {name} Grain
                -----------------------------------
                Color:             {color} degL
                PPG:               {ppg:0.2f}
                Hot Water Extract: {hwe:0.2f}""".format(
                **self.to_dict()
            )
        )
        return msg

    def get_working_yield(self, brew_house_yield):
        """
        Get Working Yield

        :param float brew_house_yield: The Percent Brew House Yield
        :return: The working yield
        :rtype: float
        """
        validate_percentage(brew_house_yield)
        return hwe_to_basis(self.hwe) * brew_house_yield

    def convert_to_cereal(self, ppg=None):
        if not ppg:
            raise GrainException(u"Must provide PPG to convert to cereal")
        return Grain(self.name, color=self.color, ppg=ppg)

    def convert_to_lme(self, ppg=PPG_LME):
        return Grain(self.name, color=self.color, ppg=ppg)

    def convert_to_dme(self, ppg=PPG_DME):
        return Grain(self.name, color=self.color, ppg=ppg)


class GrainAddition(object):
    """
    A representation of the grain as added to a Recipe.
    """

    def __init__(
        self, grain, weight=None, grain_type=GRAIN_TYPE_CEREAL, units=IMPERIAL_UNITS
    ):
        """
        :param Grain grain: The Grain object
        :param float weight: The weight of the grain addition
        :param str grain_type: The type of the grain being used
        :param str units: The units
        """
        self.grain = grain
        self.weight = weight
        self.grain_type = grain_type

        # Manage units
        self.set_units(units)

    def set_units(self, units):
        """
        Set the units and unit types

        :param str units: The units
        """
        self.units = validate_units(units)
        if self.units == IMPERIAL_UNITS:
            self.types = IMPERIAL_TYPES
        elif self.units == SI_UNITS:
            self.types = SI_TYPES

    def change_units(self):
        """
        Change units of the class from one type to the other

        :return: Grain Addition in new unit type
        :rtype: GrainAddition
        """
        if self.units == IMPERIAL_UNITS:
            weight = self.weight * KG_PER_POUND
            units = SI_UNITS
        elif self.units == SI_UNITS:

            weight = self.weight * POUND_PER_KG