Skip to content

This feature is currently in Preview.

relationalai.experimental.solvers.abs()

Signature
abs(arg: dsl.Instance|SolverExpression) -> SolverExpression

Returns a solver expression that represents the absolute value of the input arg. Must be called in a Model.rule() or solvers.operators() context.

NameTypeDescription
argdsl.Instance, SolverExpressionA numeric solver variable or expression to take the absolute value of.

A SolverExpression object representing the absolute value of the input expression.

Use abs() with the SolverModel.constraint() method to express constraints like absolute deviation from a target value:

import relationalai as rai
from relationalai.experimental import solvers
# Create a model.
model = rai.Model("DietaryConstraints")
# Declare entity types.
Food = model.Type("Food")
Day = model.Type("Day")
Portion = model.Type("Portion")
23 collapsed lines
# Declare properties.
Food.calories.declare()
Food.fat.declare()
Food.salt.declare()
Food.carbs.declare()
Portion.food.declare()
Portion.day.declare()
# Define foods.
with model.rule():
Food.add(name="Oatmeal").set(calories=150, fat=3, salt=0.1, carbs=27)
Food.add(name="Egg").set(calories=70, fat=5, salt=0.2, carbs=1)
Food.add(name="Banana").set(calories=100, fat=0.5, salt=0.0, carbs=26)
Food.add(name="Toast").set(calories=80, fat=1, salt=0.3, carbs=15)
# Define days.
with model.rule():
for name in ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]:
Day.add(name=name)
# Define all possible food portions for each day.
with model.rule():
Portion.add(food=Food(), day=Day())
# Create a solver model.
solver_model = solvers.SolverModel(model)
# Define solver variables for portions.
with model.rule():
portion = Portion()
solver_model.variable(
portion,
name_args=["portion", portion.food.name, portion.day.name],
lower=0,
upper=5,
)
# Constrain total carbs to stay within 10g of a 50g target.
with solvers.operators():
portion = Portion()
total_carbs = solvers.sum(portion.food.carbs * portion, per=[portion.day])
solver_model.constraint(solvers.abs(total_carbs - 50) <= 10)