API Reference

Scalar

class barril.units.Scalar(category: Quantity, value: float | None = None)[source]
class barril.units.Scalar(category: str, value: float | None = None, unit: str | None = None)
class barril.units.Scalar(value: float, unit: str, category: str | None = None)
class barril.units.Scalar(value_and_unit: Tuple[float, str])

This object represents a scalar (a value that has an associated quantity).

Scalar Creation

Scalars can be created by giving a value, unit or category, in some combinations.

Assuming the default value for category “length” is 10[m], all the example below create equal scalars:

Scalar("length")
Scalar(10.0, "m", "length")
Scalar(10.0, "m")
Scalar((10.0, "m"))  # tuple of (value, unit)

The last form is useful if you want to make a convenient interface for users of a class or method, accepting either a tuple or Scalar:

def Compute(x, y):
    x, y = Scalar(x), Scalar(y)

Which allows the user of the method to just pass a tuple, without having to create a Scalar explicitly:

Compute(
    x=(10, "m"), y=(15, "m")
)  # is equivalent to Compute(x=Scalar(10, 'm'), y=Scalar(15, 'm'))

Note that the following form is invalid, because if category and value is given, unit is mandatory.

Scalar("length", 1.0)
Variables:

_internal_unit – unit which is visible to the outside world)

Note

In case you’re wondering, we cannot make a Scalar with __slots__ because our callback system (i.e.: callback.After) won’t work with it.

CheckValidity() None[source]
Raises:

ValueError – when current value is wrong somehow (out of limits, for example).

classmethod CreateEmptyScalar(value: float = 0.0) Scalar[source]

Allows the creation of a scalar that does not have any associated category nor unit.

Return type:

Scalar

Returns:

Returns an empty scalar (i.e.: without any unit) with the passed value and returns it.

GetAbstractValue(unit: str | None = None) float[source]
Parameters:

unit

GetFormatted(unit: str | None = None, value_format: str | None = None) str[source]

Returns this scalar in a formatted format (i.e.: formatted value + unit).

Parameters:
  • unit – The unit in which the value should be gotten.

  • value_format – See Scalar.GetFormattedValue

GetFormattedValue(unit: str | None = None, value_format: str | None = None) str[source]

Returns the scalar value formated using the given format or the default format.

The default format can be modified globally (for all Scalars) using the class method SetFormattedFormat.

Note

The unit is NOT returned in this method.

Parameters:
  • unit – The unit in which the value should be gotten.

  • value_format – If not None (default), replaces the default value_format defined in Scalar.FORMATTED_VALUE_FORMAT

Returns:

A string with the value of this scalar formatted.

GetValue(unit: str | None = None) float
Parameters:

unit

classmethod SetFormattedValueFormat(value_format: str) None[source]

Sets the format for the numeric part of the scalar.

property value: float
Parameters:

unit

Array

class barril.units.Array(category: str | Quantity)[source]
class barril.units.Array(values: ValuesType, unit: str, category: str | None = None)
class barril.units.Array(category: str, values: ValuesType, unit: str)
class barril.units.Array(category: Quantity, values: ValuesType)

Array represents a sequence of values that also have an unit associated.

Some ways to construct it (note that usually numpy arrays should be used).

Array(numpy.array([0, 1, 2, 3, 4], numpy.float64), "m")

Array([0, 1, 2, 3, 4], "m")

Array("length", [0, 1, 2, 3, 4], "m")

Array(ObtainQuantity("m", "length"), [0, 1, 2, 3, 4])

Arrays are a Generic subclass, parametrized by their container type:

a = Array([1, 2, 3], "m")
reveal_type(a)
note: Revealed type is "barril.units._array.Array[builtins.list*[builtins.int*]]"

Functions/methods which receive arrays can be declared with more specific types:

def compute(inputs: Array[np.ndarray]) -> Array[np.ndarray]:
    ...


def compute(inputs: Array[np.ndarray[np.float64]]) -> Array[np.ndarray[np.float64]]:
    ...
CheckValidity() None[source]
Raises:

ValueError – when current value is wrong somehow (out of limits, for example).

classmethod CreateEmptyArray(values: Sequence[float] | None = None) Array[source]

Allows the creation of a array that does not have any associated category nor unit.

Return type:

Array

classmethod FromScalars(scalars: Iterable[Scalar], *, unit: str | None = None, category: str | None = None) Array[source]

Create an Array from a sequence of Scalars.

When not defined, the unit and category assumed will be from the first Scalar on the sequence.

Parameters:
  • values – A sequence of Scalars. When the values parameter is an empty sequence and the unit is not provided an Array with an empty quantity will be returned.

  • unit – A string representing the unit, if not defined the unit from the first Scalar on the sequence will be used.

  • category – A string representing the category, if not defined the category from the first Scalar on the sequence will be used.

GetAbstractValue(unit: str | None = None) ValuesType[source]
Parameters:

unit – this is the unit in which we want the values

Returns:

the values stored. May be an a list of int, float, etc.

GetValues(unit: str | None = None) ValuesType
Parameters:

unit – this is the unit in which we want the values

Returns:

the values stored. May be an a list of int, float, etc.

ValidateValues(values: ValuesType, quantity: Quantity) None[source]

Set the value to store in this values_quantity. May be an int, float, numarray, list of floats, etc.

Parameters:
  • values – The values to be set.

  • quantity – The quantity of the values being passed (note that GetUnit will still return the previous unit set – this unit is only to indicate the internal value).

property values: ValuesType
Parameters:

unit – this is the unit in which we want the values

Returns:

the values stored. May be an a list of int, float, etc.

FixedArray

class barril.units.FixedArray(dimension: int, category: str | 'Quantity')[source]
class barril.units.FixedArray(dimension: int, values: ValuesType, unit: str)
class barril.units.FixedArray(dimension: int, category: str, values: ValuesType, unit: str)
class barril.units.FixedArray(dimension: int, category: str, unit: str)
class barril.units.FixedArray(dimension: int, category: Quantity, values: ValuesType)

Represents an Array with fixed number of elements.

Like Array, FixedArray is a Generic subclass, parametrized by their container type:

a = FixedArray(3, [1, 2, 3], "m")
reveal_type(a)
note: Revealed type is "barril.units._fixedarray.FixedArray[builtins.list*[builtins.int*]]"
ChangingIndex(index: int, value: float | Scalar | Tuple, use_value_unit: bool = True) FixedArray[source]

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.

Parameters:
  • value – The value to be used to set at the given index.

  • index – The index which should be changed.

  • 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.

Returns:

The created FixedArray.

CheckValues(values: ValuesType, dimension: int | None = None) None[source]

Checks whether the dimensions consistent with the dimensions in this unit point

classmethod CreateEmptyArray(dimension: int, values: ValuesType | None = None) FixedArray[source]

Allows the creation of a array that does not have any associated category nor unit.

Returns:

Returns an empty array.

IndexAsScalar(index: int, quantity: Quantity | None = None) Scalar[source]
Parameters:
  • index – The index which should be gotten as a Scalar.

  • quantity – The quantity in which we want the Scalar (uses the FixedArray quantity if not passed).

Return Scalar:

A Scalar representation of the given index.

FractionScalar

class barril.units.FractionScalar(quantity: str)[source]
class barril.units.FractionScalar(quantity: str, value: FractionValue | float, unit: str)
class barril.units.FractionScalar(quantity: IQuantity, value: FractionValue | float)
class barril.units.FractionScalar(quantity: str, unit: str)
class barril.units.FractionScalar(value: FractionValue | float, unit: str, category: str | None = None)

Base class for objects similar to scalars, but that represent its value as L{FractionValue} instance instead of a float. Useful to describe diameters for pipes and wells in a more natural way to the user (for instance, “5 3/4 inches”).

CheckValidity() None[source]
Raises:

ValueError – when current value is wrong somehow (out of limits, for example).

classmethod ConvertFractionValue(fraction_value: FractionValue, quantity: str | Quantity, from_unit: str, to_unit: str) FractionValue[source]

Converts the given fraction value to the given unit.

Parameters:
  • fraction_value – the fraction value to convert

  • quantity – the IQuantity object to use in the conversion, or the quantity type itself

  • from_unit – current unit of the given fraction value

  • to_unit – the unit to convert the fraction value to

Returns:

the converted fraction value

GetAbstractValue(unit: str | None = None) FractionValue[source]
Parameters:

unit

GetFormatted(unit: str | None = None) str[source]

Returns the string representation for this FractionScalar.

Parameters:

unit – If None, returns the current unit, otherwise, returns the string representation of the value converted to the given unit.

Returns:

The string representation

GetFormattedValue(unit: str | None = None, value_format: str | None = None) str[source]

Returns the value part, that is, the number and fraction.

Returns:

the formatted string

classmethod RegisterFractionScalarConversion() None[source]

Register a special unit conversion for FractionScalar.

Parameters:

db_unit (UnitDatabase) – The unit-database instance to register the conversion into.

property value: FractionValue
Parameters:

unit

UnitDatabase

class barril.units.UnitDatabase(default_singleton: bool = False)[source]

Registry with all the available quantity types and units that represent the physical units.

Quantity Types represent the type of the unit, for instance length or temperature, as strings. Every quantity type has one or more units associated with it.

Units represent one specific unit inside a quantity_type, for instance meters and centimeters for length.

AddCategory(category: str, quantity_type: str | None = None, valid_units: List[str] | None = None, override: bool = False, default_unit: str | None = None, default_value: float | None = None, min_value: float | None = None, max_value: float | None = None, is_min_exclusive: bool = False, is_max_exclusive: bool = False, caption: str = '', from_category: str | None = None) CategoryInfo[source]

Adds a category to the unit-management. If it already exists, throws an error if override is not set to True

Parameters:
  • category – The category to be added to the unit-management.

  • quantity_type – The quantity type that this category maps to.

  • valid_units – A set of the valid units for the given category.

  • override – Whether to replace the quantity type for the category.

  • default_unit – The default unit for the category

  • default_value – The default value for the category

  • min_value – Minimum value acceptable. If None, any value can be set.

  • max_value – Maximum value acceptable. If None, any value can be set.

  • is_min_exclusive – If the min_value given is exclusive.

  • is_max_exclusive – If the max_value given is exclusive.

  • caption – User friendly caption for this category.

  • from_category – Category to copy other parameters from.

Raises:

UnitsError – If the category was already added and override is not set to True

AddUnit(quantity_type: str, name: str, unit: str, frombase: str | Callable[[float], float], tobase: str | Callable[[float], float], default_category: str | None = None) None[source]

Registers a new unit type.

Parameters:
  • quantity_type – The quantity type for the added unit.

  • name – A user-friendly name for this unit.

  • unit – The unit to be added.

  • frombase – If string, an expression to convert from the base unit of this quantity_type to this unit. If callable, must accept a float value that applies the conversion.

  • tobase – If a string, an expression to convert from this unit to the base unit. If callable, must accept a float value that applies the conversion.

Note

Each expression must refer to %f or x as the current value of the unit.

Parameters:

default_category – The default category for the added unit (if any).

AddUnitBase(quantity_type: str, name: str, unit: str) None[source]

Add a base unit type. Inside each quantity_type, there must be at least one Base unit.

Parameters have the same meaning as in AddUnit().

CheckCategoryUnit(category: str, unit: str) None[source]

Check if the given category accepts the passed unit.

Raises:

InvalidUnitError – if the unit provided is not accepted for this category

CheckDefaultUnitDatabase() None[source]

Checks if this is the default unit-database. If it’s not a ‘default’ unit-database, an error is raised together with the stack trace from where it was originally created.

Raises:

AssertionError – raises error if this was not created as the default unit database.

CheckQuantityType(quantity_type: str) None[source]

Checks if the quantity type is valid. If it is not, raise an InvalidQuantityTypeError.

@raise InvalidQuantityTypeError @raise InvalidUnitError

CheckQuantityTypeUnit(quantity_type: str, unit: str) None[source]

Check if the given quantity type has the given unit.

@raise InvalidUnitError

CheckValueForCategory(category: str, value: float, unit: str | None = None) None[source]
Parameters:
  • category – The category to be checked.

  • value – The value to be checked for the given category.

  • unit – The unit of the value passed (if not available, the default value is considered).

Clear() None[source]

Removes all the quantity types registered.

Convert(category_or_quantity_type: str, from_unit: str | Sequence[Tuple[str, int]], to_unit: str | Sequence[Tuple[str, int]], value: Any) Any[source]

Converts a value from one unit to another unit (given the quantity type that contains both units), so, note that the quantity type at this point is always the same (can’t convert units with quantity types that don’t match).

Parameters:
  • category_or_quantity_type – The category or quantity type for doing the conversion (if it’s a category it’s converted into the quantity type inside this method).

  • from_unit – A string determining the unit from the value we want to convert or a list of exponents.

  • to_unit – A string determining to convert the value to or a list of exponents.

  • value – The value that should be converted.

Note

that from_unit and to_unit must only have 1 item at this point.

Returns:

The converted value

classmethod CreateDefaultSingleton() UnitDatabase[source]

Creates the default singleton instance, that will be used when no singleton has been installed. By default, tries to create the class without constructor.

Return type:

Singleton

Returns:

an instance of the singleton subclass

classmethod FillUnitDatabaseWithPosc(unit_database: UnitDatabase, fill_categories: bool = True) UnitDatabase[source]

Fills a unit database with the posc values.

Parameters:
  • unit_database (UnitDatabase) – The unit database to be filled.

  • fill_categories (bool) – Indicates whether for each quantity type a category with the same name should be created.

Return type:

UnitDatabase

Returns:

The unit database passed as a parameter.

FindSimilarUnitMatches(unit: str) List[str][source]

This function will use heuristics to find similar units in the unit database to the passed unit.

Parameters:

unit – The unit which doesn’t have a direct match in the unit dabatase.

Returns:

Returns a list with possible matches for the passed unit, sorted.

FindUnitCase(category: str, unit: str) str[source]

Given a unit in any case, returns a unit that is a match with the correct case within the unit-database.

Parameters:
  • category – The category for the given unit

  • unit – The unit that should be used to match the case.

Returns:

the unit considering the actual case used within the unit database.

Raises:

AssertionError – if no unit could be found or more than one was found (there should be only 1 match considering it in a case-insensitive way).

GetBaseUnit(quantity_type: str) str | None[source]
Parameters:

quantity_type – The quantity type for which we want a base unit.

Returns:

The base unit of the given quantity_type.

Raises:

InvalidQuantityTypeError – if the quantity type is not valid

GetCategoryInfo(category: str) CategoryInfo[source]
Parameters:

category – The category we’re interested in.

Returns:

The category info for the category passed.

GetCategoryQuantityType(category: str) str[source]
Returns:

The quantity type of some category.

GetDefaultCategory(unit: str) str | None[source]
Parameters:

unit – The unit for which we want the category.

Return type:

str or None

Returns:

The default category for the passed unit.

GetDefaultUnit(category: str) str[source]
Returns:

The default unit for the given category.

Note

This method shouldn’t return None, when the default_unit isn’t defined for the category the quantity type base unit is used.

GetDefaultValue(category: str) float[source]
Returns:

The default value for the given category.

GetInfo(quantity_type: str, unit: str, fix_unknown: bool = False, fix_legacy: bool = True) UnitInfo[source]
Parameters:
  • fix_unknown (bool) – If True won’t raise error if quantity_type is unkwnown (and unit may be anything). Returns the unknown unit info in this situation.

  • fix_legacy (bool) – If True and unit is in _LEGACY_TO_CURRENT, then it will return the current equivalent unit info.

Return type:

UnitInfo

Returns:

The unit object registered with the given unit

@raise InvalidQuantityTypeError @raise InvalidUnitError

GetInfos(quantity_type: str | None = None) List[UnitInfo][source]
Returns:

All UnitInfos from that quantity_type (if quantity_type is given), otherwise return all UnitInfos.

@raise InvalidQuantityTypeError

GetQuantityType(unit: str) str | None[source]
Returns:

A quantity_type that contains the respective unit.

GetQuantityTypes() List[str][source]
Returns:

A list of the available categories, sorted.

GetUnitName(quantity_type: str, unit: str) str[source]
Returns:

The user-friendly name for the given unit.

GetUnitNames(quantity_type: str) List[str][source]
Returns:

The user-friendly names for all the units in the given quantity_type.

Raises:

InvalidQuantityTypeError

GetUnits(quantity_type: str | None = None) List[str][source]
Returns:

The units of that quantity_type (if quantity_type is given) otherwise, returns all available units.

GetValidUnits(category: str) List[str][source]
Return type:

list(str)

Returns:

The valid units for a given category. If the valid categories weren’t given uses the valid units from quantity type.

IsValidCategory(category: str) bool[source]

Check if the given category is valid into the unit database.

Parameters:

category – The category to check the validity.

Returns:

True is it is a valid category; otherwise False.

IterCategories() Iterator[str][source]

Iterator for all the categories.

Returns:

An iterator that’ll provide all the categories.

Multiply(quantity1: Quantity, quantity2: Quantity, value1: T, value2: T) Tuple[Quantity, T][source]

Multiplication with different quantities.

Rationale:

  • the multiplication of different quantities can result in a derived quantity type.

  • the quantities / values should be transformed if there are quantity types that are equal in bot quantities (e.g.: if there’s cm in the quantity1 and m in the quantity2, the value1 and the quantity1 must be converted to m before proceeding with the actual multiplication)

  • note that if a given quantity type has different units in the quantity1 or in the quantity2, they must 1st be converted to have the same unit in a given quantity type.

  • after the quantities are compatible, it’s just a matter of creating a join of the available units and summing the expoents to create the resulting quantity (and multiplying the actual values).

Parameters:
  • quantity1 (IQuantity (related to value1)) –

  • quantity2 (IQuantity (related to value2)) –

  • value1 (iterable or number) –

  • value2 (iterable or number) –

Return type:

tuple(IQuantity, value)

classmethod RegisterAdditionalConversionType(class_: Type, func: Callable[[UnitDatabase, str, str, str, T], T]) None[source]

This function may be used to register conversions for additional classes, not originally treated (e.g.: IGridFunction)

Parameters:
  • class (type) – This is the class that should be treated. So, when a conversion is requested, if a class is an instance of the class passed, it’ll be used to do the conversions.

  • func (callable) – The function that should do the conversion. It’ll be called as func(unit_database, quantity_type, from_unit_info, to_unit_info, value)