Evaluate attribute values

This guide is for a script that needs the value an attribute’s expression gives it, such as a mass defined as the sum of two other masses. The model assigns the expression; evaluating it is what turns wheel_rim.mass + tire.mass into a number. You need Syside Automator installed and licensed, and Models as Python objects explains the objects involved.

The recipe below runs against one small model. Create a file named wheel.sysml and paste it in, or adapt the names to a model of your own:

part wheel{
   part wheel_rim{
       part metal;
       attribute diameter;
       attribute mass = 5;
   }
   part tire{
       part rubber;
       attribute diameter;
       attribute mass = 10;
   }
   attribute mass = wheel_rim.mass + tire.mass;
}

Load the model first:

import syside
from syside import query

model, diagnostics = syside.load_model(["wheel.sysml"])

Evaluate an attribute’s expression

The recipe below collects every attribute with query.find_elements_of_type and keeps the ones named mass; Find and navigate elements covers the other ways to reach an element.

An attribute’s assigned expression is its feature_value_expression, and the Compiler evaluates it. Compiler.evaluate returns a tuple: the evaluation result first, the evaluation report second. Check that the evaluation succeeded before using the result:

for attr_element in query.find_elements_of_type(model, syside.AttributeUsage):
    if attr_element.name == "mass":
        expression = attr_element.feature_value_expression
        assert expression is not None
        value, report = syside.Compiler().evaluate(expression)
        if report.fatal:
            print(f"Error evaluating {attr_element.name}")
        else:
            assert attr_element.owner is not None
            print(f"Mass of {attr_element.owner.name} = {value}")
Mass of wheel = 15
Mass of wheel_rim = 5
Mass of tire = 10

The two literal masses evaluate to themselves; wheel’s mass comes out of the expression that sums them.

Note

The Compiler is the most general way of dealing with expression evaluation, since the output is dependent on the expression – in the above example it returned a number, but in the case of item driver = John it would return the ReferenceUsage instance of John. The Compiler supports evaluation of model level evaluable expressions, as defined in the specification; Expression evaluation carries the version-accurate list of what evaluates.

Evaluation works on the values the model fixes. When the model leaves values open and the question is what they could be, that is the Solver instead.