Build a model from a bill of materials
New in v1.1.0 Labs
In this guide, you build a SysML v2 model from a bill of materials (BOM) in a
CSV file. The model has one part definition for each item, one part for each row
of the file, and a mass on each assembly that is the sum of its parts’ masses.
The BOM can have any depth. The same script works for a BOM with ten rows or with
ten thousand. You need the Syside Python Library & CLI installed and licensed. For an introduction to the functions used here, see
Builder API.
In each row of the CSV, parent contains quantity of item. The item
with no parent is the product. Only purchased items have a mass. Bolt is in two
assemblies. Save the file as bom.csv:
item,parent,quantity,mass_kg
Rover,,1,
Chassis,Rover,1,
Body,Chassis,1,12.5
WheelAssembly,Chassis,4,
Wheel,WheelAssembly,1,1.8
HubMotor,WheelAssembly,1,2.4
Bolt,WheelAssembly,6,0.02
PowerSystem,Rover,1,
Battery,PowerSystem,2,3.1
Bolt,PowerSystem,8,0.02
Controller,Rover,1,0.6
Build the model:
Save the script below as
build_bom.py, next tobom.csv:import csv import functools import pathlib from collections import defaultdict import syside from syside import query from syside.experimental import builder BOM_FILE_PATH = pathlib.Path(__file__).parent / "bom.csv" STANDARD_LIBRARY = frozenset({syside.DocumentTier.StandardLibrary}) # The model is built in this package. With the import, the printed model # shows Real, not ScalarValues::Real. SEED = "package Bom { private import ScalarValues::Real; }" type Built = tuple[syside.PartDefinition, syside.AttributeUsage] def read_bom( path: pathlib.Path, ) -> tuple[dict[str, list[dict[str, str]]], dict[str, float]]: """Return the rows grouped by parent, and the mass of each purchased item.""" rows_under: defaultdict[str, list[dict[str, str]]] = defaultdict(list) mass_of: dict[str, float] = {} with path.open(newline="", encoding="utf-8") as file: for row in csv.DictReader(file): rows_under[row["parent"]].append(row) if row["mass_kg"]: mass_of[row["item"]] = float(row["mass_kg"]) return rows_under, mass_of def build_bom(model: syside.Model, path: pathlib.Path) -> Built: """Build one part definition per item of the BOM; return the product's.""" package = query.find_by_qualified_name(model, "Bom") real = query.find_by_qualified_name( model, "ScalarValues::Real", tiers=STANDARD_LIBRARY ) assert isinstance(package, syside.Package) assert isinstance(real, syside.DataType) rows_under, mass_of = read_bom(path) # Cached: an item in several assemblies is built only once @functools.cache def build(item: str) -> Built: """Build `item`, after everything inside it.""" definition = builder.new_part_def(package, item) terms: list[builder.ExpressionTemplate] = [] for row in rows_under.get(item, []): child, child_mass = build(row["item"]) quantity = int(row["quantity"]) part = builder.new_part( definition, row["item"][0].lower() + row["item"][1:], defined_by=[child], multiplicity=builder.bounds(quantity), ) part_mass = builder.dot(part, child_mass) terms.append( part_mass if quantity == 1 else builder.literal(quantity) * part_mass ) # Mass of a purchased item: from the file. Mass of an assembly: the sum # of its parts' masses. mass = builder.new_attribute( definition, "mass", defined_by=[real], equals=sum(terms[1:], terms[0]) if terms else mass_of[item], ) return definition, mass (product_row,) = rows_under[""] return build(product_row["item"]) def main() -> None: model = syside.load_model([("memory://bom.sysml", SEED)]) product, mass = build_bom(model, BOM_FILE_PATH) diagnostics = builder.resolve(model) if diagnostics.contains_errors(): raise syside.ModelError(model.unlock(), diagnostics) assert product.owner is not None print(syside.pprint(product.owner)) assert mass.feature_value_expression is not None value, report = syside.Compiler().evaluate( syside.vm.Context(model.lib), mass.feature_value_expression ) assert not report.fatal print(f"Total mass of {product.name}: {value:.2f} kg") if __name__ == "__main__": main()
No item names from the file are written in the script. The product is the row with an empty
parent.buildstarts at the product and goes down the tree, depth first:One definition per item.
buildis cached withfunctools.cache. Thepart deffor an item is created the first timebuildis called for it. Later calls return the same definition. An item that is in several assemblies, such asBolt, is defined once.One part per row. For each row, a part is created inside the parent’s definition. The part is typed by the item’s definition, and its multiplicity is the quantity.
One mass per item. The mass of a purchased item is the number in the file. The mass of an assembly is an expression: the sum of
quantity * part.massfor each of its parts. The expression is made withliteral(),dot()and Python’s*and+.
If you write these sums by hand, you must update them each time the BOM changes. With the script, they are made again from the BOM each time it runs.
Run
python build_bom.py. The output is the model, then the product’s mass, evaluated from the mass expressions:package Bom { private import ScalarValues::Real; part def Rover { part chassis : Chassis [1]; part powerSystem : PowerSystem [1]; part controller : Controller [1]; attribute mass : Real = chassis.mass + powerSystem.mass + controller.mass; } part def Chassis { part body : Body [1]; part wheelAssembly : WheelAssembly [4]; attribute mass : Real = body.mass + 4 * wheelAssembly.mass; } part def Body { attribute mass : Real = 12.5; } part def WheelAssembly { part wheel : Wheel [1]; part hubMotor : HubMotor [1]; part bolt : Bolt [6]; attribute mass : Real = wheel.mass + hubMotor.mass + 6 * bolt.mass; } part def Wheel { attribute mass : Real = 1.8; } part def HubMotor { attribute mass : Real = 2.4; } part def Bolt { attribute mass : Real = 0.02; } part def PowerSystem { part battery : Battery [2]; part bolt : Bolt [8]; attribute mass : Real = 2 * battery.mass + 8 * bolt.mass; } part def Battery { attribute mass : Real = 3.1; } part def Controller { attribute mass : Real = 0.6; } } // package Bom Total mass of Rover: 36.74 kgThe total, 36.74 kg, is the sum of each purchased item’s mass multiplied by the number of that item in the product. For more about evaluating expressions, see Evaluate attribute values.
To keep the model, write the printed text to a .sysml file. To use a BOM
exported from your PLM or ERP system, change the column names in read_bom. You
do not need to change build.