Context

The context module provides support for calculations with quantities, in combination with the modules signature and kind_of_quantity. Kinds of quantity are associated with unique signatures in a context.

A Context is initialised by a set of quantities, which become a basis for that context. Other kinds of quantity can be declared by providing an expression that describes quantity in terms of the base quantities and possibly other quantities already declared.

For instance, in the following code block, resistance is declared in terms of voltage and current and power is declared in terms of voltage and resistance. The signature of power is \(\mathrm{I}^1\mathrm{V}^1\mathrm{T}^0\), which is displayed by the print statement as (1,1,0).

from QV import *

context = Context(
    ("Current","I"),("Voltage","V"),("Time","T")
)

context.declare('Resistance','R','Voltage/Current')
context.declare('Power','P','V*V/R')
print( context.signature('P') )

KindOfQuantity objects can be retrieved from a context and used in expressions:

Voltage = context['Voltage']
Resistance = context['Resistance']

tmp = Voltage/Resistance

print( tmp )
print( context.evaluate( tmp ) )

which displays

Div(V,R)
I

Here tmp is an intermediate result obtained by dividing objects representing voltage and current. QV does not automatically try to resolve intermediate results. The method Context.evaluate() must be used explicitly to resolve the kind of quantity of a temporary object.

class Context(*argv)

A Context keeps a register of KindOfQuantity instances, and associates each with a unique signature.

A Context is initialised by a set of quantities. Other quantities can then be declared as products and quotients of these ‘base’ quantities, or of other derived quantities already declared.

The signature of declared quantities must be unique.

Example:

>>> context = Context( ("Length","L"),("Time","T") )
>>> context.declare('Speed','V','Length/Time')
KindOfQuantity('Speed','V')
property base_quantities

Return the base quantities in this context

declare(koq_name, koq_symbol, expression)

Declare a KindOfQuantity defined by expression

The expression may be products and quotients of KindOfQuantity objects, or a string representing these operations.

A RuntimeError is raised if the signature resulting from expression is already associated with a kind of quantity.

evaluate(expression)

Return the quantity represented by expression

The argument expression may be products and quotients of KindOfQuantity objects, or a string representing these operations.

A RuntimeError is raised if the signature of the result is not associated with a kind of quantity in the context.

signature(koq)

Return the signature associated with koq