Units and quantities#
Units catch mistakes at build time and keep amounts consistent. A number times a unit is a quantity (3 * kW), and
quantities of different dimensions do not add, subtract, or compare. Values are stored in base units: each currency
in itself, power in W, energy in W×h, and time in months, so 0.05 / b.year is a rate per month that the ledger
integrates by the length of each period. Days and hours are separate dimensions, because their length in months
depends on the calendar: month and day never convert silently, and the days in a period come from
m.period_end - m.date.
Inside a render the same expressions give plain floats in base units, so @m.series functions work on ordinary
numbers.
Making units#
- boki.unit(name, definition=None)#
Return a new unit: a countable unit of its own, or one defined from other units.
Use it for quantities that are not money, power, or time, such as customers, GPUs, or cubic feet. A unit made from a name alone is a dimension of its own, and a unit made with a definition is a multiple of the definition.
- Parameters:
- namestr
Name of the unit, shown in messages and labels. Without
definitionthe name is also the name of the new dimension, so two calls with the same name give units of the same dimension, and a name such as"USD"or"month"gives the built-in dimension of that name.- definitionQuantity or Unit, optional
What one new unit equals, such as
8 * GPUfor a node of eight GPUs. The new unit has the dimensions ofdefinitionand its size. If it is None, the new unit is a dimension of its own. The default is None.
- Returns:
- Unit
The new unit. A number times it is a Quantity of that unit.
See also
boki.units.UnitThe class of units.
boki.units.QuantityA number with a unit.
Notes
Currencies are distinct dimensions:
USDandJPYdo not convert. Convert with an exchange-rate series (Model.fx). Money and counts take no SI prefix in tables (there is nokGPU).Examples
Define a countable unit and a unit built from it:
>>> from boki.units import unit >>> gpu = unit("GPU") >>> node = unit("node", 8 * gpu) >>> (2 * node + 4 * gpu).value 20.0
Two units with the same name are the same dimension:
>>> (unit("GPU") * 1 + 2 * gpu).value 3.0
- class boki.units.Unit(name, dims, scale=1.0)#
A unit of measure: a scale times a product of base dimensions.
kWis the dimension power (W) with the scale 1000,yearis the dimensionmonthwith the scale 12, andUSDis a dimension of its own with the scale 1. A number times a unit is a Quantity, checked when it is combined with others:3 * kWis 3000 W. Units multiply and divide into new units (kW * h,USD / year) and raise to integer powers. Make a new countable unit with unit; the built-in constants are listed on the units reference page.- Parameters:
- namestr
Name shown in messages and labels, such as
"kW".- dimsfrozenset
The dimension: a frozenset of
(dimension name, exponent)pairs such asfrozenset({("W", 1)}). The empty set is dimensionless.- scalefloat
Size of one unit in the base unit of its dimension, so
1000.0forkW(base unit W). The default is1.0.
- Attributes:
- namestr
The unit’s name.
- dimsfrozenset
The dimension, as
(dimension name, exponent)pairs.- scalefloat
Size of one unit in base units.
See also
boki.unitDefine a new unit.
boki.units.QuantityA number with a unit.
Notes
Base units are the dimension names themselves: a currency in itself, power in W, energy in W×h, and time in months. Days (
day) and hours (h) are dimensions of their own, because their length in months depends on the calendar. Only unit, the constants, and arithmetic on them create units, so the constructor is listed for completeness.Examples
Read a built-in unit:
>>> from boki.units import kW, year >>> (kW.name, kW.scale) ('kW', 1000.0) >>> (year.name, year.scale) ('year', 12.0)
Divide units to make a rate unit:
>>> from boki.units import USD >>> rate = USD / year >>> (rate.name, round(rate.scale, 4)) ('USD/year', 0.0833)
- __mul__(other)#
Return this unit times
other: a unit whenotheris a unit, else a quantity or series.- Parameters:
- otherUnit, Quantity, number, or Series
The factor. A unit gives the product unit, with the dimensions added and the scales multiplied. A number or Quantity gives that amount in this unit. A Series gives the series in this unit.
- Returns:
- Unit, Quantity, or Series
A unit named
"<this>*<other>"whenotheris a unit. Otherwise a Quantity, or a Series whenotheris a series. Inside a render the quantity is a plain float in base units.
- Raises:
- UnitError
At construction, if the product combines months and days.
See also
boki.units.Unit.__rmul__The number-first form,
3 * kW.
Examples
Multiply two units, or a unit by a number:
>>> from boki.units import kW, h >>> energy = kW * h >>> (energy.name, energy.scale) ('kW*h', 1000.0) >>> (kW * 3).value 3000.0
- __pow__(k)#
Return this unit raised to the power
k.- Parameters:
- kint
The exponent. It multiplies the exponent of every dimension, and the scale is raised to it.
- Returns:
- Unit
A unit named
"<this>^<k>".
Examples
Square a unit, or invert it with a negative exponent:
>>> from boki.units import kW, year >>> squared = kW ** 2 >>> (squared.name, squared.scale) ('kW^2', 1000000.0) >>> (year ** -1).name 'year^-1'
- __rmul__(other)#
Return
othertimes this unit: a quantity, or a series whenotheris a series.This is the usual way to write a quantity:
3 * kW,100 * USD,12 * month.- Parameters:
- othernumber, Quantity, or Series
The amount in this unit. A Quantity is multiplied by the unit, which combines their dimensions.
- Returns:
- Quantity, Series, or float
A Quantity holding the amount in base units. It is a Series when
otheris a series, and a plain float in base units inside a render (in an@m.seriesfunction).
- Raises:
- UnitError
At construction, if the product combines months and days.
See also
boki.units.Unit.__mul__The unit-first form,
kW * 3.
Examples
A quantity stores its value in base units:
>>> from boki.units import kW, year >>> q = 3 * kW >>> q.value 3000.0 >>> (2 * year).value 24.0
- __rtruediv__(other)#
Return
otherdivided by this unit: a quantity in the inverse unit.1 / b.yearand0.05 / b.yearare how a rate per time is written. Time is measured in months, so the quantity is stored per month and the ledger integrates it by each period’s length.- Parameters:
- othernumber
The numerator, such as
0.05for 5% per year.
- Returns:
- Quantity
The amount in the inverse unit, in base units:
0.05 / yearis0.05 / 12per month.
See also
boki.units.Unit.__truediv__Divide a unit by something.
Examples
A 6% annual rate is stored as 0.5% per month:
>>> from boki.units import year >>> rate = 0.06 / year >>> round(rate.value, 6) 0.005 >>> sorted(rate.dims) [('month', -1)]
- __truediv__(other)#
Return this unit divided by
other: a unit whenotheris a unit, else a quantity.- Parameters:
- otherUnit, Quantity, or number
The divisor. A unit gives a rate unit, with the dimensions subtracted and the scales divided. A Quantity such as
1000 * cfgives the price of one unit, in this unit per the quantity’s unit. A number divides this unit’s scale.
- Returns:
- Unit or Quantity
A unit named
"<this>/<other>"whenotheris a unit. Otherwise a Quantity equal to this unit’s scale divided byother.
- Raises:
- UnitError
At construction, if the quotient combines months and days.
See also
boki.units.Unit.__rtruediv__The number-first form,
1 / year.
Examples
Divide money by time to get a rate unit, or by a quantity to get a price:
>>> from boki.units import USD, kW, month, unit >>> (USD / month).name 'USD/month' >>> cf = unit("cf") >>> price = USD / (1000 * cf) >>> (price.value, sorted(price.dims)) (0.001, [('USD', 1), ('cf', -1)])
- class boki.units.Quantity(base_value, dims)#
A number with a unit, built at model-construction time.
A quantity is what
3 * kW,100 * USD,12 * monthand0.05 / yearproduce. It stores its value in the base units of its dimensions (3 * kWholds 3000 W) together with those dimensions, and every operation checks the dimensions: only quantities of the same dimensions are added, subtracted, or compared. A quantity is accepted wherever a model takes an amount, a rate, a life, or a period length. Inside a render, the same expressions give plain floats in base units, so@m.seriesfunctions work on ordinary numbers.- Parameters:
- base_valuefloat
The value in the base units of
dims.- dimsfrozenset
The dimension, as for Unit.dims.
- Attributes:
- valuefloat
The value in base units: currency units, W, W×h, and months.
- dimsfrozenset
The dimension, as
(dimension name, exponent)pairs.
See also
boki.units.UnitA unit of measure.
boki.UnitErrorThe error for units that do not fit.
Notes
Write quantities by multiplying a number by a unit; the constructor is listed for completeness. A plain number and a quantity with dimensions do not mix, except
0, which fits any unit. Quantities do not define==, which compares identity: comparea.value == b.valueafter checking the dimensions. A quantity of months added to or subtracted from a date shifts the date, asdate + 3 * monthdoes. When one operand is a Series, the operation gives a series.Examples
Add quantities, and convert a rate per year to a rate per month:
>>> from boki.units import USD, kW, year >>> power = 3 * kW + 2 * kW >>> power.value 5000.0 >>> sorted(power.dims) [('W', 1)] >>> fee = 120 * USD / year >>> fee.value 10.0 >>> sorted(fee.dims) [('USD', 1), ('month', -1)]
- __abs__()#
Return the absolute value of this quantity.
- Returns:
- Quantity
The same dimensions, with the value made nonnegative.
Examples
>>> from boki.units import USD >>> abs(-5 * USD).value 5.0
- __add__(o)#
Return the sum of this quantity and
o, or a date shifted by this many months.- Parameters:
- oQuantity, number, date, or Series
The value to add. A Quantity must have the same dimensions as this one. A plain number is accepted only if it is
0or this quantity is dimensionless. A date is shifted forward when this quantity is a number of months (date + 3 * month), rounded to a whole number of months, with the day of the month clamped to the length of the resulting month. A Series defers to the series.
- Returns:
- Quantity, date, or Series
A Quantity in base units when
ois a quantity or number, the shifted date whenois a date, and a Series whenois a series.
- Raises:
- UnitError
At construction, if the dimensions differ, if
ois a plain nonzero number and this quantity has dimensions, or ifois a date and this quantity is not a number of months.
See also
boki.units.Quantity.__sub__Subtract a quantity.
Examples
Add quantities of the same dimension, or shift a date by months:
>>> import datetime >>> from boki.units import kW, month >>> (2 * kW + 3 * kW).value 5000.0 >>> datetime.date(2027, 1, 31) + 3 * month datetime.date(2027, 4, 30)
- __ge__(o)#
Return whether this quantity is greater than or equal to
o.- Parameters:
- oQuantity or number
The value to compare with, with the rules of Quantity.__lt__.
- Returns:
- bool
Whether the value in base units is at least
o’s.
- Raises:
- UnitError
At construction, as for Quantity.__lt__.
See also
boki.units.Quantity.__gt__Greater than.
boki.units.Quantity.__le__Less than or equal.
Examples
>>> from boki.units import kW >>> 3 * kW >= 3 * kW True
- __gt__(o)#
Return whether this quantity is greater than
o.- Parameters:
- oQuantity or number
The value to compare with, with the rules of Quantity.__lt__.
- Returns:
- bool
Whether the value in base units is greater than
o’s.
- Raises:
- UnitError
At construction, as for Quantity.__lt__.
See also
boki.units.Quantity.__ge__Greater than or equal.
boki.units.Quantity.__lt__Less than.
Examples
>>> from boki.units import kW >>> 3 * kW > 2 * kW True
- __le__(o)#
Return whether this quantity is less than or equal to
o.- Parameters:
- oQuantity or number
The value to compare with, with the rules of Quantity.__lt__.
- Returns:
- bool
Whether the value in base units is at most
o’s.
- Raises:
- UnitError
At construction, as for Quantity.__lt__.
See also
boki.units.Quantity.__lt__Less than.
boki.units.Quantity.__ge__Greater than or equal.
Examples
>>> from boki.units import kW >>> 3 * kW <= 3 * kW True
- __lt__(o)#
Return whether this quantity is less than
o.- Parameters:
- oQuantity or number
The value to compare with. A Quantity must have the same dimensions as this one. A plain number is accepted only if it is
0or this quantity is dimensionless.
- Returns:
- bool
Whether the value in base units is less than
o’s.
- Raises:
- UnitError
At construction, if the dimensions differ, or if
ois a plain nonzero number and this quantity has dimensions.
See also
boki.units.Quantity.__le__Less than or equal.
boki.units.Quantity.__gt__Greater than.
Notes
To compare a quantity with a Series, write the series on the left (
series > quantity): a quantity on the left raises a TypeError for a series, because the comparison does not defer to the series.Examples
>>> from boki.units import kW >>> 2 * kW < 3 * kW True >>> 2 * kW < 0 False
- __mul__(o)#
Return this quantity times
o.- Parameters:
- onumber, Quantity, Unit, or Series
The factor. A number scales the quantity. A Quantity multiplies the values and adds the dimensions. A Unit multiplies by the unit’s scale and adds its dimensions. A Series defers to the series.
- Returns:
- Quantity or Series
The product in base units, with the combined dimensions, or a Series when
ois a series.
- Raises:
- UnitError
At construction, if the product combines months and days.
See also
boki.units.Quantity.__truediv__Divide a quantity.
Examples
Multiply a power by a time to get an energy:
>>> from boki.units import h, kW >>> energy = (3 * kW) * (2 * h) >>> energy.value 6000.0 >>> sorted(energy.dims) [('W', 1), ('h', 1)]
- __neg__()#
Return this quantity with its sign changed.
- Returns:
- Quantity
The same dimensions, with the value negated.
Examples
>>> from boki.units import USD >>> (-(5 * USD)).value -5.0
- __pow__(k)#
Return this quantity raised to the power
k.- Parameters:
- kint or float
The exponent. It multiplies the exponent of every dimension. A quantity with dimensions needs an int exponent; a dimensionless quantity accepts any number.
- Returns:
- Quantity
The value raised to
k, with the dimensions scaled byk.
- Raises:
- UnitError
At construction, if this quantity has dimensions and
kis not an int.
Examples
Square a power, or take the root of a dimensionless ratio:
>>> from boki.units import kW >>> square = (3 * kW) ** 2 >>> (square.value, sorted(square.dims)) (9000000.0, [('W', 2)]) >>> (((4 * kW) / (1 * kW)) ** 0.5).value 2.0
- __radd__(o)#
Return
oplus this quantity, so that a date or0can be on the left.Python calls this for
o + quantitywhenocannot add a quantity itself. It is__add__with the operands swapped, so the rules of Quantity.__add__ apply:date + 3 * monthshifts the date, and0 + quantityis the quantity.- Parameters:
- onumber, date, or Quantity
The left operand, with the forms of Quantity.__add__.
- Returns:
- Quantity, date, or Series
The result of
o + quantity, as for Quantity.__add__.
- Raises:
- UnitError
At construction, as for Quantity.__add__: a nonzero plain number does not add to a quantity with dimensions.
See also
boki.units.Quantity.__add__The quantity-first form.
Examples
A date on the left shifts by a quantity of months, and
0is accepted:>>> import datetime >>> from boki.units import kW, quarter >>> datetime.date(2027, 1, 15) + 1 * quarter datetime.date(2027, 4, 15) >>> (0 + 2 * kW).value 2000.0
- __rmul__(o)#
Return
otimes this quantity, so that a number can be on the left.Python calls this for
number * quantity. It is__mul__with the operands swapped, so2 * (3 * kW)is6 * kW.- Parameters:
- onumber, Quantity, or Unit
The left operand, with the forms of Quantity.__mul__.
- Returns:
- Quantity or Series
The product in base units, as for Quantity.__mul__.
- Raises:
- UnitError
At construction, if the product combines months and days.
See also
boki.units.Quantity.__mul__The quantity-first form.
Examples
>>> from boki.units import kW >>> (2 * (3 * kW)).value 6000.0
- __rsub__(o)#
Return
ominus this quantity, or a date shifted back by this many months.Python calls this for
o - quantitywhenocannot subtract a quantity itself.- Parameters:
- onumber or date
The left operand. A date is shifted back when this quantity is a number of months (
date - 3 * month), rounded to a whole number of months, with the day of the month clamped to the length of the resulting month. A plain number is accepted only if it is0or this quantity is dimensionless.
- Returns:
- Quantity or date
ominus this quantity as a Quantity, or the shifted date.
- Raises:
- UnitError
At construction, if
ois a plain nonzero number and this quantity has dimensions, or ifois a date and this quantity is not a number of months.
See also
boki.units.Quantity.__sub__The quantity-first form.
Examples
Shift a date back by a quantity of months, or negate a quantity with
0:>>> import datetime >>> from boki.units import USD, month >>> datetime.date(2027, 5, 31) - 3 * month datetime.date(2027, 2, 28) >>> (0 - 2 * USD).value -2.0
- __rtruediv__(o)#
Return
odivided by this quantity.Python calls this for
number / quantity. The result has the inverse dimensions.- Parameters:
- onumber
The numerator.
- Returns:
- Quantity
odivided by the value, in the inverse dimensions of this quantity.
See also
boki.units.Quantity.__truediv__The quantity-first form.
Examples
Invert a price per unit:
>>> from boki.units import kW >>> inverse = 1 / (4 * kW) >>> (inverse.value, sorted(inverse.dims)) (0.00025, [('W', -1)])
- __sub__(o)#
Return this quantity minus
o.- Parameters:
- oQuantity, number, or Series
The value to subtract. A Quantity must have the same dimensions as this one. A plain number is accepted only if it is
0or this quantity is dimensionless. A Series defers to the series. A date is not accepted here; subtract months from a date withdate - 3 * month.
- Returns:
- Quantity or Series
The difference in base units, or a Series when
ois a series.
- Raises:
- UnitError
At construction, if the dimensions differ, or if
ois a plain nonzero number and this quantity has dimensions.
See also
boki.units.Quantity.__add__Add a quantity.
boki.units.Quantity.__rsub__Subtract from a number or a date.
Examples
>>> from boki.units import USD >>> (500 * USD - 120 * USD).value 380.0
- __truediv__(o)#
Return this quantity divided by
o.- Parameters:
- onumber, Quantity, Unit, or Series
The divisor. A number scales the quantity. A Quantity divides the values and subtracts the dimensions. A Unit divides by the unit’s scale and subtracts its dimensions, so
120 * USD / yearis a rate per month. A Series defers to the series.
- Returns:
- Quantity or Series
The quotient in base units, with the dimensions subtracted, or a Series when
ois a series. It is dimensionless when both operands have the same dimensions.
- Raises:
- UnitError
At construction, if the quotient combines months and days.
See also
boki.units.Quantity.__mul__Multiply a quantity.
boki.units.Quantity.__rtruediv__Divide a number by a quantity.
Notes
Time is measured in months, so dividing an amount by
yeargives the amount per month: the ledger integrates a rate per time by the length of each period.Examples
Convert a yearly amount to a monthly rate, and divide two quantities of the same dimension:
>>> from boki.units import USD, kW, year >>> rate = 120 * USD / year >>> rate.value 10.0 >>> sorted(rate.dims) [('USD', 1), ('month', -1)] >>> ratio = (6 * kW) / (2 * kW) >>> (ratio.value, sorted(ratio.dims)) (3.0, [])
- exception boki.UnitError#
Error raised when units do not fit together.
UnitErroris a TypeError. boki raises it when an expression, a series, or a line is declared, and during a render when a series function returns a value in a different unit from the one declared. Typical causes:adding, subtracting, comparing, or choosing between values of different dimensions, such as
USDandkW, or a nonzero plain number and a quantity with a unit (0fits any unit);combining months and days, which have no fixed ratio; use
m.period_end - m.datefor the days in a period;passing a rate per time such as
0.05 / b.yearwhere a dimensionless per-period rate is required (for example boki.lib.compound, boki.lib.discount, boki.lib.npv);raising a quantity with a unit to a non-integer power, or converting it to a plain float;
an amount in a unit other than the entity’s currency.
See also
boki.units.QuantityA number with a unit.
boki.units.UnitA unit of measure.
Notes
A message names the dimensions involved in base units:
Wfor power,monthfor time, and the name of each currency. Time is measured in months, so1 / b.yearis a quantity in1/month.Examples
Adding power to money fails when the sum is written:
>>> import boki as b >>> from boki.units import USD, kW >>> try: ... 2 * kW + 3 * USD ... except b.UnitError as error: ... print(error) cannot add W and USD
Unit constants#
boki.units defines these units. day, h, month, quarter, and year are also available as b.day, b.h,
b.month, b.quarter, and b.year. The scale is the size of one unit in the base unit of its dimension. Each
currency is a dimension of its own: USD and JPY do not convert, so use an exchange-rate series
(Model.fx) to move between them. Define other units with boki.unit.
Name |
Dimension |
Scale |
Meaning |
|---|---|---|---|
|
USD |
1 |
US dollar |
|
JPY |
1 |
Japanese yen |
|
EUR |
1 |
euro |
|
GBP |
1 |
pound sterling |
|
CNY |
1 |
Chinese yuan |
|
W |
1 |
watt, the base unit of power |
|
W |
1,000 |
kilowatt |
|
W |
1,000,000 |
megawatt |
|
W×h |
1 |
watt-hour, the base unit of energy |
|
W×h |
1,000 |
kilowatt-hour |
|
W×h |
1,000,000 |
megawatt-hour |
|
day |
1 |
a day, a dimension of its own |
|
h |
1 |
an hour, a dimension of its own |
|
month |
1 |
a month, the base unit of time |
|
month |
3 |
three months |
|
month |
12 |
twelve months |