Esempio n. 1
0
def testFormatFloat():
    """
    Convert unit of scalar where value is "0.0".
    """
    assert FormatFloat("%g", 0.0) == "0"
    assert FormatFloat("%g", -0.0) == "0"

    scalar = Scalar("length", 0.0, "m")
    assert FormatFloat("%g", scalar.GetValue()) == "0"

    assert locale.format_string("%g", scalar.GetValue("ft")) == "-0"
    assert FormatFloat("%g", scalar.GetValue("ft")) == "0"

    # Large float numbers on integer format.
    large_float_number = 1e010 * 1.0
    assert FormatFloat("%d", large_float_number) == "10000000000"

    # Infinity
    assert FormatFloat("%.3g", PLUS_INFINITY) == "+INF"
    assert FormatFloat("%.3g", MINUS_INFINITY) == "-INF"
    assert FormatFloat("%.3g", NAN) == "-1.#IND"

    # Digit grouping
    assert FormatFloat("%.2f", 1234567, False) == "1234567.00"
    assert FormatFloat("%.2f", 1234567, True) == "1234567.00"
Esempio n. 2
0
def testCubicFeetPerDayLegacyUnits() -> None:
    # test creating scalar using legacy representation and default category
    q = Scalar(1.0, "1000ft3/d")
    assert q.GetUnit() == "Mcf/d"

    # test creating scalar using legacy representation
    q = Scalar(category="volume flow rate", value=1.0, unit="1000ft3/d")
    assert q.GetUnit() == "Mcf/d"

    # test getting value using legacy representation
    assert approx(q.GetValue("M(ft3)/d")) == q.GetValue("MMcf/d")

    q = Scalar(category="volume flow rate", value=1.0, unit="M(ft3)/d")
    assert q.GetUnit() == "MMcf/d"
    assert approx(q.GetValue("M(ft3)/d")) == q.GetValue("MMcf/d")
    assert q.GetUnitName() == "million cubic feet per day"
Esempio n. 3
0
def testConversionToFullScalar() -> None:
    y = _LightweightScalar(value=1.0, unit="kg/m3", category="density")
    x = Scalar(value=y.GetValue(), unit=y.GetUnit(), category=y.GetCategory())

    assert x.GetValue() == 1.0

    assert x.GetUnit() == "kg/m3"
    assert x.GetCategory() == "density"
    assert x.GetQuantityType() == "density"

    assert x.GetQuantity().GetUnit() == "kg/m3"
    assert x.GetQuantity().GetCategory() == "density"
    assert x.GetQuantity().GetQuantityType() == "density"

    # Full Scalar supports conversion
    assert x.GetValue(unit="g/cm3") == 0.001
Esempio n. 4
0
def testScalarInvalidValue(unit_database_len_time):
    db = unit_database_len_time

    db.AddCategory("another-length", "length", min_value=0, max_value=15)

    scalar = Scalar("another-length", value=15, unit="m")
    assert scalar.IsValid()

    scalar = Scalar("another-length", value=-5, unit="m")
    assert not scalar.IsValid()

    # By default the validation will be performed. 15 is a valid value.
    scalar = Scalar("another-length", value=15, unit="m")
    assert scalar.IsValid()

    # Even invalid ,the scalar returns the value, unit and a formatted text.
    another = Scalar("another-length", value=3000, unit="m")
    assert not another.IsValid()
    assert another.GetValue("m") == 3000
    assert another.GetUnit() == "m"
    assert another.GetFormatted() == "3000 [m]"

    # By default the validation will be performed, and in this cases will raise ValueError.
    another_2 = Scalar("another-length", unit="m", value=5000)
    assert not another_2.IsValid()

    # Performing copy between invalid scalars. The validation is not performed on copy.
    copied = another.CreateCopy(unit="cm")
    assert not copied.IsValid()
    assert copied.GetValue("m") == 3000
    assert copied.GetUnit() == "cm"
    assert copied.GetFormatted() == "300000 [cm]"
Esempio n. 5
0
def testGetValueInvalidUnitError() -> None:
    from barril.units.unit_database import InvalidUnitError

    with raises(
            InvalidUnitError,
            match="Invalid unit for quantity_type volume flow rate: 1000ft3/foo"
    ):
        q = Scalar(1.0, "1000ft3/d")
        q.GetValue("1000ft3/foo")
Esempio n. 6
0
def testScalarHashEq():
    scalar1 = Scalar("length", 10, "m")
    scalar2 = Scalar("length", 10, "m")
    scalar3 = Scalar("length", 10, "cm")
    scalar4 = Scalar("length", scalar2.GetValue("cm"), "cm")

    assert scalar1 == scalar2
    assert hash(scalar1) == hash(scalar2)
    assert hash(scalar1) == hash(scalar1)
    assert scalar2 != scalar3
    assert hash(scalar2) != hash(scalar3)
    assert scalar3 != scalar4
    assert hash(scalar4) != hash(scalar3)
Esempio n. 7
0
def testConvertLegacyUnit():
    from barril.units.unit_database import _LEGACY_TO_CURRENT

    # test creating scalar using legacy representation and default category
    q = Scalar(1.0, "1000ft3/d")
    assert q.GetUnit() == "Mcf/d"

    # test creating scalar using legacy representation
    q = Scalar(category="volume flow rate", value=1.0, unit="1000ft3/d")
    assert q.GetUnit() == "Mcf/d"

    # test getting value using legacy representation
    assert approx(q.GetValue("M(ft3)/d")) == q.GetValue("MMcf/d")

    q = Scalar(category="volume flow rate", value=1.0, unit="M(ft3)/d")
    assert q.GetUnit() == "MMcf/d"
    assert approx(q.GetValue("M(ft3)/d")) == q.GetValue("MMcf/d")
    assert q.GetUnitName() == "million cubic feet per day"

    # Test all possible legacy formats
    for legacy, current in _LEGACY_TO_CURRENT:
        assert Scalar(1.0, legacy).GetUnit() == current
Esempio n. 8
0
    def _ScalarCheckMsgPredicate(cls, scalar: Scalar) -> Optional[str]:
        """
        :param Scalar scalar:
            The scalar to be checked against its limits

        :returns str:
            The built message saying if the scalar is less or greater than its limits
        """
        try:
            quantity = ObtainQuantity(scalar.GetUnit(), scalar.GetCategory())
            quantity.CheckValue(scalar.GetValue(), use_literals=True)

        except ValueError as error:
            return str(error)

        return None
Esempio n. 9
0
    def ChangingIndex(self,
                      index: int,
                      value: Union[float, "Scalar", Tuple],
                      use_value_unit: bool = True) -> "FixedArray":
        """
        Creates a FixedArray from based on this FixedArray changing a single value based on the
        passed index.

        i.e.: array.ChangingIndex(0, Scalar(1.0, 'm'))
              will create a new FixedArray where the index == 0 is changed to the passed value.

        :param value:
            The value to be used to set at the given index.

        :param index:
            The index which should be changed.

        :param use_value_unit:
            If True and a Scalar is passed, the newly created array will have the unit of the
            scalar, not of the original array, otherwise (if False) the FixedArray unit will be
            kept.

        :return:
            The created FixedArray.
        """
        from barril.units import Scalar

        if isinstance(value, tuple):
            scalar = Scalar(self.GetValues()[index],
                            self.GetUnit()).CreateCopy(*value)

        elif not isinstance(value, Scalar):
            scalar = Scalar(value, self.GetUnit())

        else:
            scalar = value

        if use_value_unit:
            quantity = scalar.GetQuantity()
        else:
            quantity = self.GetQuantity()

        values = list(self.GetValues(quantity.GetUnit()))
        values[index] = scalar.GetValue(quantity.GetUnit())
        return FixedArray(self.dimension, quantity, tuple(values))
Esempio n. 10
0
def testAllLegacyUnits(legacy: str, current: str, value: float) -> None:
    test_scalar = Scalar(value, legacy)
    assert test_scalar.GetUnit() == current
    assert approx(test_scalar.GetValue(legacy)) == value
    assert approx(test_scalar.GetValue(current)) == value
Esempio n. 11
0
def testDefaultValue(unit_database_len_pressure):
    """
        Scalar constructor considers the minimum and maximum values
        when default_value is not defined
    """
    db = unit_database_len_pressure

    db.AddCategory(
        category="my length", quantity_type="length", min_value=100.0, max_value=200.0
    )

    # if the default value is not defined, the scalar should not try to set the initial/first
    # value of the new instance to 0.0, but it should assume the minimum allowed value.
    # should not raise ValueError
    length = Scalar("my length")
    assert length.GetValue() == 100.0

    length = Scalar(ObtainQuantity("m", "my length"))
    assert length.GetValue() == 100.0

    length = Scalar(ObtainQuantity("m"))
    assert length.GetValue() == 0.0

    # invalid default value (< min)
    with pytest.raises(AssertionError):
        db.AddCategory(
            category="my pressure",
            quantity_type="pressure",
            default_value=50.0,
            min_value=100.0,
            max_value=200.0,
        )

    # invalid default value (> max)
    with pytest.raises(AssertionError):
        db.AddCategory(
            category="my pressure",
            quantity_type="pressure",
            default_value=300.0,
            min_value=100.0,
            max_value=200.0,
        )

    # invalid default value (<= min)
    with pytest.raises(AssertionError):
        db.AddCategory(
            category="my pressure",
            quantity_type="pressure",
            default_value=100.0,
            min_value=100.0,
            max_value=200.0,
            is_min_exclusive=True,
        )

    # invalid default value (>= min)
    with pytest.raises(AssertionError):
        db.AddCategory(
            category="my pressure",
            quantity_type="pressure",
            default_value=200.0,
            min_value=100.0,
            max_value=200.0,
            is_max_exclusive=True,
        )

    db.AddCategory(
        category="my pressure",
        quantity_type="pressure",
        min_value=100.0,
        max_value=200.0,
        default_value=150.0,
        is_min_exclusive=True,
        is_max_exclusive=False,
    )

    pressure = Scalar("my pressure")
    assert pressure.GetValue() == 150.0

    # default_value not informed. checking if the interval limits are respected
    # when is_min_exclusive or is_max_exclusive have been informed, so the default_value
    # must be
    with pytest.raises(RuntimeError):
        db.AddCategory(
            category="my pressure 2",
            quantity_type="pressure",
            min_value=100.0,
            max_value=200.0,
            is_max_exclusive=True,
        )