Tutorial 1.3: Using Tensor-Typed Value Objects and States in a DSL#

[1]:
import torch

from concepts.dsl.dsl_types import BOOL, INT64, FLOAT32, ObjectType, VectorValueType, Variable
from concepts.dsl.dsl_functions import Function, FunctionType
from concepts.dsl.function_domain import FunctionDomain
from concepts.dsl.expression import VariableExpression, FunctionApplicationExpression
from concepts.dsl.tensor_value import TensorValue, from_tensor
from concepts.dsl.tensor_state import NamedObjectTensorState
from concepts.dsl.executors.tensor_value_executor import FunctionDomainTensorValueExecutor

# See the documentation for TensorState for more details.
domain = FunctionDomain()
# Define an object type `person`.
domain.define_type(ObjectType('person'))
# Define a state variable `is_friend` with type `person x person -> bool`.
domain.define_function(Function('is_friend', FunctionType([ObjectType('person'), ObjectType('person')], BOOL)))

state = NamedObjectTensorState({
    'is_friend': TensorValue(BOOL, ['x', 'y'], torch.tensor([[1, 1, 1], [1, 1, 0], [1, 0, 1]], dtype=torch.bool))
}, object_names={
    'Alice': ObjectType('person'),
    'Bob': ObjectType('person'),
    'Charlie': ObjectType('person'),
})
executor = FunctionDomainTensorValueExecutor(domain)
[2]:
from concepts.dsl.executors.tensor_value_executor import compose_bvdict
compose_bvdict({'x': 'Alice'}, state)
[2]:
{'person': {'x': StateObjectReference(name='Alice', index=0)}}
[3]:
x = VariableExpression(Variable('x', ObjectType('person')))
y = VariableExpression(Variable('y', ObjectType('person')))
relation = FunctionApplicationExpression(domain.functions['is_friend'], [x, y])
relation
[3]:
FunctionApplicationExpression<is_friend(V::x, V::y)>
[4]:
executor.execute(relation, state, {'x': 'Alice', 'y': 'Bob'})
[4]:
Value[bool, axes=[], tdtype=torch.bool, tdshape=(), quantized]{tensor(True)}
[5]:
executor.execute('is_friend(x, y)', state, {'x': 'Alice', 'y': 'Bob'})
[5]:
Value[bool, axes=[], tdtype=torch.bool, tdshape=(), quantized]{tensor(True)}
[6]:
executor.execute('is_friend(x, "Charlie")', state, {'x': 'Alice', 'y': 'Bob'})
[6]:
Value[bool, axes=[], tdtype=torch.bool, tdshape=(), quantized]{tensor(True)}