The SysML v2 Book — OpenSysML Edition
Start with an empty file and build a smart coffee machine. You will describe its grinder, brewer and water tank; trace water and coffee through their ports; specify the brew sequence; and connect requirements to design decisions and verification cases. The point of writing the model is to answer engineering questions, not just to get through a parser.
How to use the book
Chapter 2 walks through a first model. Chapters 3–10 introduce the constructs as the design needs them; Chapter 11 puts them together. Chapters 12–14 refine the model and select views; Chapter 15 loads related files together and Chapter 16 runs calculations and behaviors. Appendices A–J cover notation, migration, interchange, tooling, dynamics, diagnostics, relationships, lexical conventions, review and time.
For the exercises use OpenSysML MDK 0.12.1 (installation). You can read the entire book offline, including its diagrams. Worked listings are accompanied by their model context; snippets in a progressively developed example are alternatives, not declarations to concatenate indiscriminately.
This is an independent adaptation of the original book. See credits, licenses and changes.
Why Textual SysML v2
SysML v2 is a language for describing systems – what they are made of, how they behave, and what they must do. You write it as plain text, the same way you write code.
Here is a complete SysML v2 model:
package CoffeeMachine {
part def Grinder;
part def Brewer;
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
}
}
Read it as: a CoffeeMachine contains a Grinder and a Brewer. It is not a
diagram, and it is not a database. It is text in a file, and that file is the
model.
Definition and usage: the idea everything else rests on
Look again at those seven lines. Grinder appears twice, and the two
appearances mean different things.
part def Grinder introduces a definition – the kind of thing a grinder
is. There is one of these no matter how many grinders exist.
part grinder : Grinder introduces a usage: the grinder role on each coffee machine. It does not create a particular grinder on your workbench.
If you have written code, the instinct is to read this as class and instance. It
is close enough to get started, and Chapter 3
will sharpen it. What matters now is that the split is not a convention someone
adopted – it is built into the language. The specification gives definitions and
usages their own clause of the textual notation (SysML §8.2.2.6), and nearly
every construct you will meet comes in both forms: action def and action,
state def and state, requirement def and requirement.
Learn to ask “is this a kind, or a particular one?” and a large part of SysML v2 stops being a vocabulary problem.
Why text
When your model is a text file, you inherit the tooling you already have:
- Diff and review. A change shows up as a line-by-line diff. A reviewer can comment on the exact line where a requirement changed or a port was renamed.
- Version control. Branch, merge, and tag model versions the way you tag releases. The model’s history is the repository’s history.
- Automation. A pipeline can parse the model, check its constraints, and fail the build before anyone sits down to a review meeting.
None of that is available when the model lives in a proprietary binary, and none of it needs a special tool beyond the ones you already run.
What the specification actually says about notation
It would be convenient to claim text is the one true form of a SysML v2 model. That is not what the standard says, and the real answer is more useful.
SysML v2 defines two concrete notations: a textual notation (§8.2.2) and a graphical one (§8.2.3). Both are normative. A tool can demonstrate Textual Notation Conformance, Graphical Notation Conformance, or both – and a tool claiming the graphical variant must support the textual notation at least far enough to render text inside diagrams correctly (SysML §2).
Underneath both sits the abstract syntax: the metamodel of elements and relationships that a model really consists of. Notation is how you write it down. This is why diagrams and text are not rivals. They are two projections of one model, which is also why a diagram can be generated from text but a well-formed model cannot be recovered from a picture alone.
Two conformance levels are mandatory for every conformant tool: Abstract Syntax Conformance and Model Interchange Conformance. Notation support is optional (SysML §2). So a tool is allowed to read and write SysML v2 models without offering either notation – which tells you where the standard thinks the model lives.
Interchange is specified too: projects travel as a .kpar archive, and textual
files inside it use the .sysml extension. Those extensions are normative, not
conventions.
Where SysML v2 came from
SysML v1 was a profile of UML – a set of stereotypes layered onto a general-purpose software modeling language. SysML v2 is not. It is a metamodel that extends the Kernel Modeling Language (KerML), a domain-independent language for building semantically rich modeling languages (SysML §1).
Two consequences you will feel while reading this book:
- Names from KerML surface constantly.
Occurrence,Feature,Classifier,Specializationare KerML’s, not SysML’s. When a chapter cites a KerML clause, that is why. - The standard library is part of the language. Types like
Real,Stringand the ISQ units are defined in model libraries that ship with the specification (Clause 9), not baked into the grammar.
The standard also specifies a formal transformation from SysML v1.7 to v2, so migration is a defined activity rather than a rewrite from scratch. That is Appendix B.
What this book builds
Sixteen chapters that grow one model – a smart coffee machine – from an empty file into a complete specification:
- Chapters 2–5 build the structure: definitions and usages, packages, parts, ports, attributes.
- Chapters 6–8 add behaviour: connections and interfaces, actions with control flow, states with guarded transitions.
- Chapters 9–10 make it checkable: expressions, constraints, requirements and verification cases.
- Chapter 11 assembles the whole thing into one coherent model.
- Chapters 12–14 go deeper: specialization and redefinition, metadata and views, libraries.
- Chapters 15–16 are about working with a model: projects and workspaces, and what it means to run one.
Then ten appendices of reference material – syntax, migration, the API, tooling notes, physics-aware simulation, diagnostic codes, relationship kinds, lexical rules, review checklists, and occurrences, time slices, and snapshots.
How to read it
Start at Chapter 2 and work forward; each chapter builds on the one before, and the model assumes you have the earlier chapters. If you already model in SysML v2, jump to what you need and follow the back-references.
Where a claim about the language is load-bearing, the text cites the clause so you can check it. Where something is a particular tool’s behaviour rather than the language’s, it says so – usually in a note like the ones you will meet in Chapter 8 – so you can skip those and still learn SysML v2.
A SysML listing may show just the members that change at a step. Use the accompanying model context to check it without guessing which definitions to import. Syntax templates use a text fence; their angle-bracket fields are not literal SysML.
You do not need the tool to follow along, but if you want it, Appendix D explains how to get it.
Here is that same coffee machine as a diagram – the same model, the other notation:
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch01.sysml.
Build Your First Model
In this chapter, you will build a coffee machine model from an empty file. By the end, you will have a typed, multi-definition model with attributes and imports – and you will understand the core concepts of SysML v2 through building, not through reading definitions.
Create coffee_machine.sysml and replace its contents at each step. To check the current step without opening a REPL, run sysml -strict -validate coffee_machine.sysml. Appendix D explains how to install the OpenSysML binary.
The complete worked project is in src/examples/coffee-machine/. Chapter 11 maps its files to the book.
Step 1: An Empty Package
Every SysML v2 model lives inside a package. A package is a namespace – it groups related model elements and gives them a home.
Type this into your file:
package CoffeeMachineDomain {
}
That is a valid model. It does not describe anything yet, but it parses and checks cleanly. A package with nothing inside it is like an empty directory: a place waiting for content.
Run sysml -strict -validate coffee_machine.sysml and confirm there are no errors.
Step 2: Your First Definition
Now add something inside the package. In SysML v2, a definition declares a reusable type – a blueprint for something that can exist in your system.
package CoffeeMachineDomain {
part def Grinder;
}
part def Grinder says: there is a kind of thing called a Grinder. It is a part definition – a structural component type. You have not placed a grinder anywhere yet. You have only said that grinders exist as a concept in your domain.
The keyword part def is how SysML v2 spells “define a component type.” You will see this pattern everywhere: <keyword> def <Name>.
Step 3: A Usage Inside a Definition
A definition by itself is just a type. To say that a coffee machine contains a grinder, you create a usage of that type inside another definition:
package CoffeeMachineDomain {
part def Grinder;
part def CoffeeMachine {
part grinder : Grinder;
}
}
part grinder : Grinder says: inside a CoffeeMachine, there is a part called grinder, and it is of type Grinder. This is a typed usage – the most fundamental pattern in SysML v2.
Notice the difference:
part def Grinder– defines a type (uppercase, no colon)part grinder : Grinder– uses that type in context (lowercase name, colon, type name)
This definition/usage split is how SysML v2 keeps models reusable. You define a type once, then use it wherever you need it.
Step 4: Adding More Definitions
A coffee machine has more than a grinder. Add a brewer and a water tank:
package CoffeeMachineDomain {
part def Grinder;
part def Brewer;
part def WaterTank;
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
}
}
Run sysml -strict -validate coffee_machine.sysml. No errors. The model now says: a CoffeeMachine is composed of three subsystems, each with a named role.
Compare this first sketch with the overview of the finished machine below.
Notice that each definition is independent. Grinder does not know about Brewer. They only meet inside CoffeeMachine, where they each have a named usage. This separation is intentional – it keeps definitions reusable across different contexts.
Step 5: Attributes and Imports
Definitions without properties are just names. To make the model useful, add attributes – measurable or configurable properties of each component.
Attributes need types. SysML v2 provides built-in scalar types like Real, Integer, Boolean, and String in the ScalarValues library. To use them, you need an import:
package CoffeeMachineDomain {
private import ScalarValues::*;
part def Grinder {
attribute grindSize : Real;
}
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
}
part def WaterTank {
attribute currentLevel : Real;
attribute maxCapacity : Real;
}
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
}
}
Several things happened:
private import ScalarValues::*brings all scalar types into scope. The::*means “import everything from this package.” Without this line,RealandStringwould be unresolved names.- Each definition now has
attributemembers. An attribute is a property with a type:attribute grindSize : Realsays the grinder has a numeric grind size setting. CoffeeMachineitself has aserialNumberattribute. Definitions can have both part usages (components) and attribute usages (properties).
Run sysml -strict -validate coffee_machine.sysml again. If you forget the import line, you will see errors like “unresolved name: Real.” That error tells you exactly what is missing – add the import and the errors disappear.
Step 6: Items – Things That Flow
Not everything in a system is a structural component. Some things are consumed, produced, or transferred. In SysML v2, these are items.
A coffee machine deals with water, coffee beans, and brewed coffee. These are not parts of the machine – they flow through it.
package CoffeeMachineDomain {
private import ScalarValues::*;
// Items: things that flow through the system
item def Water;
item def CoffeeBeans;
item def BrewedCoffee;
// Parts: structural components
part def Grinder {
attribute grindSize : Real;
}
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
}
part def WaterTank {
attribute currentLevel : Real;
attribute maxCapacity : Real;
}
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
}
}
item def Water is like part def Grinder, but it signals a different intent. Parts are components you assemble into a structure. Items are things that move, get consumed, or get produced. The distinction matters when you model behavior and flows in later chapters.
The // lines are comments. They are ignored by the checker but help readers navigate the model.
Step 7: An Enumeration
Some properties have a fixed set of valid values. The grind size might be Fine, Medium, or Coarse. SysML v2 models this with an enumeration:
package CoffeeMachineDomain {
private import ScalarValues::*;
// Items
item def Water;
item def CoffeeBeans;
item def BrewedCoffee;
// Enumerations
enum def GrindSetting {
fine;
medium;
coarse;
}
// Parts
part def Grinder {
attribute grindSize : GrindSetting;
}
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
}
part def WaterTank {
attribute currentLevel : Real;
attribute maxCapacity : Real;
}
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
}
}
enum def GrindSetting defines a type with exactly three values. The Grinder attribute now uses GrindSetting instead of Real, which is more precise – a reviewer can see exactly what values are valid.
What You Have Built
With the definitions expanded, you can see every attribute inside each part definition. Notice how CoffeeMachine contains typed usages of the other parts, and each part definition lists its own attributes:
Step back and look at what you have. In about 40 lines, you have:
- A package that organizes the model
- Part definitions for three subsystems (Grinder, Brewer, WaterTank) and the top-level CoffeeMachine
- Item definitions for things that flow (Water, CoffeeBeans, BrewedCoffee)
- An enumeration for a constrained value set (GrindSetting)
- Attributes on each definition, typed with scalar values or enumerations
- Typed usages that compose the subsystems into the machine
- An import that brings scalar types into scope
This is already a useful structural model. A reviewer can see what the system is made of, what properties each component has, and how the components relate.
What Comes Next
This model is the foundation for the rest of the book. Every chapter will extend it:
- Chapter 3 formalizes the definition/usage pattern you used here.
- Chapter 4 shows how to split this model across multiple files.
- Chapter 5 adds ports – interaction points where components connect.
- Chapter 6 wires the components together.
- Chapter 7 adds behavior: what the machine does when you press brew.
- Chapter 8 adds operating modes: idle, brewing, cleaning, error.
- Chapter 9 adds checkable logic: temperature ranges, safety interlocks.
- Chapter 10 adds requirements and traces them to the design.
- Chapter 11 assembles everything into one coherent model.
Keep your coffee_machine.sysml file. You will keep building on it.
Common Mistakes
Forgetting the import. If you use Real or String without private import ScalarValues::*, the checker will report unresolved names. The fix is always the same: add the import at the top of your package.
Leaving usages untyped. This is valid syntax:
part def CoffeeMachine {
part grinder;
}
But it tells a reviewer nothing about what kind of grinder this is. Always type your usages: part grinder : Grinder. Typed usages make the model checkable and reusable.
Defining everything at the top level. If you write definitions outside a package, they have no namespace boundary. As your model grows, name collisions become likely. Always wrap definitions in a package.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch02.sysml.
Definitions and Usages
In Chapter 2, you built a coffee machine model. Along the way, you wrote things like part def Grinder and part grinder : Grinder without much ceremony. This chapter explains why SysML v2 makes that split, what the different definition keywords mean, and how ownership works when you nest elements inside each other.
If you internalize one design rule from this book, make it this: definitions and usages are different jobs. A definition declares a reusable type. A usage places that type in a specific context. Every modeling decision you make in SysML v2 flows from that split.
Why the Split Exists
Consider the Grinder from Chapter 2:
part def Grinder {
attribute grindSize : GrindSetting;
}
part def CoffeeMachine {
part grinder : Grinder;
}
Grinder is a definition. It says: grinders exist, and they have a grind size. It does not say where a grinder lives, how many there are, or who owns one.
grinder is a usage. It says: inside a CoffeeMachine, there is one grinder, and it plays the role called grinder.
This separation is what makes the model reusable. Suppose you are modeling a coffee roastery that has a separate grinding station:
part def GrindingStation {
part grinder : Grinder;
part spareGrinder : Grinder;
}
The same Grinder definition appears in two completely different contexts – once inside CoffeeMachine, twice inside GrindingStation. The definition did not change. Only the usages differ.
Without this split, you would have to copy the grinder’s properties into every place it appears. Change the grind size attribute, and you would have to find and update every copy. The definition/usage pattern gives you a single source of truth.
The Definition Keywords
SysML v2 has several definition keywords, each signaling a different kind of thing. You have already seen three of them in Chapter 2. Here they are together:
part def – Structural Components
A part definition describes something you can assemble into a structure. Parts have spatial or compositional relationships with their containers. The grinder is inside the machine. The brewer is inside the machine. These are parts.
part def Grinder { ... }
part def Brewer { ... }
part def WaterTank { ... }
part def CoffeeMachine { ... }
Use part def when the thing you are describing is a component that belongs to an assembly. If you can point at it in a bill of materials or a physical breakdown, it is probably a part.
item def — What the system handles
An item definition describes an identifiable thing the system acts on over time, without requiring that the thing perform actions of its own (SysML §7.10). Items flow through the system, get consumed, get produced, or get exchanged.
item def Water;
item def CoffeeBeans;
item def BrewedCoffee;
The water in the tank is an identifiable amount of material the brewer processes; the tank is a structural unit of the machine. An item can be stored as well as transferred. A part specializes item: even a tank can itself be the item delivered to an assembly line.
Parts and items are not rival categories. A part definition is a kind of item definition (SysML §7.11), so every part can be treated as an item when that is the useful view – an engine flows down an assembly line as an item, then goes into a vehicle as a part. Choosing part def picks the primary framing; it does not forbid the other one.
The distinction becomes important when you add behavior in Chapter 7. Actions consume and produce items. Connections in Chapter 6 can carry items between ports. The item keyword sets up these downstream patterns.
attribute def – Properties and Value Types
An attribute definition describes a measurable or configurable property. You used attribute usages throughout Chapter 2 (grindSize, waterTemp, brewPressure), and you also defined one attribute type with enum def GrindSetting.
You can also define custom attribute types explicitly:
attribute def Temperature {
attribute value : Real;
attribute unit : String;
}
This defines Temperature as a structured value with a numeric part and a unit. You could then use it:
part def Brewer {
attribute waterTemp : Temperature;
attribute brewPressure : Real;
}
Use attribute def when you need a value type that has internal structure. For simple scalar properties, you can type attributes directly with Real, String, Integer, or Boolean from the ScalarValues library.
When to Use Which
| Keyword | What it models | Chapter 2 examples |
|---|---|---|
part def | Structural component | Grinder, Brewer, WaterTank, CoffeeMachine |
item def | Object that may be handled, stored or transferred | Water, CoffeeBeans, BrewedCoffee |
attribute def | Structured value type | (GrindSetting used enum def) |
enum def | Fixed set of values | GrindSetting |
If you are unsure, ask: “Is this thing a component of the assembly?” If yes, part def. “Does it flow through or get consumed?” If yes, item def. “Is it a measurable property?” If yes, attribute def or a scalar type.
You will meet more definition keywords in later chapters – action def for behavior in Chapter 7, state def for operating modes in Chapter 8, requirement def in Chapter 10. They all follow the same <keyword> def <Name> pattern.
How tools render this distinction
Definition and usage are distinct in the model even when a tool displays only their names. The SysML graphical notation uses different outlines; in OpenSysML output also read the keyword and the typing label.
Usages: Placing Types in Context
Every definition keyword has a corresponding usage keyword. You drop the def:
part def Grinder { ... } // definition
part grinder : Grinder; // usage
item def Water; // definition
item water : Water; // usage
attribute def Temperature; // definition
attribute temp : Temperature; // usage
A usage always answers three questions:
- What kind? The keyword (
part,item,attribute). - What name? The usage name (
grinder,water,temp). - What type? The definition after the colon (
Grinder,Water,Temperature).
The name identifies a role in this context, not a particular physical instance. The type links back to the definition. A reviewer looking at part grinder : Grinder knows immediately what kind of thing it is and where to find its properties.
Untyped Usages
You can write a usage without a type:
part def CoffeeMachine {
part grinder;
}
This is syntactically valid. But it tells a reviewer nothing about what kind of grinder this is. There is no link to a definition, no properties to check, no way for a tool to validate that the usage makes sense. Treat untyped usages as temporary scaffolding. Always add a type before the model goes into review.
Reuse: One Definition, Many Usages
The real power of the definition/usage split shows up when you reuse definitions across contexts. Consider a company that makes two coffee machine models:
package CoffeeMachineLineup {
private import CoffeeMachineDomain::*;
part def HomeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
}
part def OfficeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
part secondBrewGroup : Brewer;
attribute serialNumber : String;
}
}
Both machines use the same Grinder, Brewer, and WaterTank definitions from the CoffeeMachineDomain package you built in Chapter 2. The OfficeMachine happens to have a second brew group, but it reuses the same Brewer definition for both.
If you later add a descaleCount attribute to Brewer, both machines get it automatically. You do not touch HomeMachine or OfficeMachine at all. The definitions are the single source of truth; the usages just point at them.
This pattern also makes the model reviewable. When someone new reads part secondBrewGroup : Brewer, they can look up Brewer once and understand every place it appears. No hunting through duplicated property lists to check if they are all consistent.
Ownership and Membership
When you write an element inside another element’s braces, you are doing more than indenting text. You are declaring an ownership relationship.
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
}
The grinder usage is owned by the CoffeeMachine definition. This is called membership – grinder is a member of CoffeeMachine. Ownership has consequences:
- Scope. The name
grinderis visible insideCoffeeMachine. Code outsideCoffeeMachinemust use a qualified name likeCoffeeMachine::grinderto refer to it. - Lifecycle. A
partoritemusage declared like this is composite, and the values of a composite usage cannot exist after the instance that features them ceases to exist (SysML §7.6.3). Destroy aCoffeeMachine, and itsgrindergoes with it. - Containment. Composite parts are inside their owner, structurally. This is what makes
CoffeeMachinea composite: it contains its parts rather than merely knowing about them.
Ownership forms a tree. The package owns the definitions. Each definition owns its members. Each member might own further nested elements. This tree gives the model its structure and determines how names resolve.
Nesting Deeper
Ownership can go several levels deep. Suppose the grinder has an internal motor:
part def Motor {
attribute powerRating : Real;
}
part def Grinder {
attribute grindSize : GrindSetting;
part motor : Motor;
}
Now the ownership tree looks like this:
CoffeeMachineDomain (package)
Grinder (part def)
grindSize (attribute)
motor (part)
powerRating (attribute)
CoffeeMachine (part def)
grinder (part) : Grinder
brewer (part) : Brewer
...
Each element has exactly one owner. The motor usage is owned by Grinder. The grinder usage is owned by CoffeeMachine. The Grinder definition is owned by the CoffeeMachineDomain package. There is no ambiguity about where anything lives.
Composite vs. Reference Usages
Every part and item usage you have seen so far is composite – its values belong to the instance that features them and cannot outlive it. But sometimes you need to refer to something without containing it.
Consider a maintenance log that records which grinder was serviced:
part def MaintenanceRecord {
attribute date : String;
ref part servicedGrinder : Grinder;
}
The ref keyword says: this usage refers to a Grinder that exists somewhere else. The MaintenanceRecord does not contain a grinder. It just points at one.
Without ref, writing part servicedGrinder : Grinder makes the usage composite – the maintenance record would contain a grinder. That is clearly wrong. A maintenance record is a data entry, not a physical container for machine parts.
The distinction has teeth in the specification, not just in style. Values of a composite usage cannot also be values of another composite usage unless both sit on the same featuring instance (SysML §7.6.3) – a physical grinder is inside exactly one machine. Reference usages carry no such restriction, which is exactly why a record can point at a grinder some machine already contains. It is also why a bill-of-materials rollup counts composite usages and skips references.
Two kinds of usage are referential whether or not you write ref:
- Attribute usages. A value has no independent existence to contain, so
attribute grindSize : GrindSettingis always referential. - Directed usages. Anything declared
in,out, orinout– including the items inside the port definitions of Chapter 5 – is always referential.
Use ref when the relationship is “knows about” rather than “contains.” We will revisit reference usages when we cover connections in Chapter 6, where they play a larger role.
The Pattern Behind the Pattern
At this point, you have seen the definition/usage split applied to parts, items, and attributes. The pattern is always the same:
<keyword> def <Name> { <members> } // definition
<keyword> <name> : <Name>; // composite usage
ref <keyword> <name> : <Name>; // reference usage
This regularity is intentional. Every new SysML v2 concept you encounter – actions, states, requirements, constraints – follows this same structure. Once you can read part def and part, you can read action def and action, state def and state, requirement def and requirement. The keywords change; the pattern does not.
What Comes Next
Summary
You now understand the core modeling pattern of SysML v2: define a type, use it in context. You know the difference between parts (structural), items (flow), and attributes (values). You know that nesting creates ownership, and that ref makes a usage referential so it can point at something without containing it.
In Chapter 4, you will split the coffee machine model across multiple files, using packages and imports to organize definitions so that teams can work on different parts of the model independently.
Diagram
Common Mistakes
Using part def for everything. Not every concept is a structural component. Water flowing through a brewer is an item, not a part. A temperature reading is an attribute, not a part. Using the right keyword communicates intent and enables correct downstream analysis.
Duplicating definitions instead of reusing them. If HomeMachine and OfficeMachine both need a brewer, define Brewer once and use it twice. Do not create HomeBrewer and OfficeBrewer with identical properties. Specialize only when behavior or structure genuinely differs – Chapter 12 covers how.
Forgetting ref on non-containing usages. If a MaintenanceRecord has part servicedGrinder : Grinder without ref, the model says the record physically contains a grinder. This is a modeling error that tools may not catch as a syntax problem – it is a semantic mistake. When the relationship is “refers to” rather than “contains,” always use ref.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch03.sysml.
Packages and Imports
The coffee machine model from Chapter 2 fits in a single file. That will not last. As soon as a second engineer needs to work on the model, or a second subsystem needs its own definitions, you need a way to split things up without breaking name resolution.
SysML v2 gives you two tools for this: packages for grouping and imports for connecting.
When One File Is Not Enough
Here is the model from Chapter 2, all in one file:
package CoffeeMachineDomain {
private import ScalarValues::*;
item def Water;
item def CoffeeBeans;
item def BrewedCoffee;
enum def GrindSetting {
fine;
medium;
coarse;
}
part def Grinder {
attribute grindSize : GrindSetting;
}
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
}
part def WaterTank {
attribute currentLevel : Real;
attribute maxCapacity : Real;
}
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
}
}
This is 30 lines. But over the next several chapters, this model will grow to include ports, connections, actions, states, constraints, and requirements. One file will become hard to navigate and harder to review.
The fix is not to scatter definitions randomly across files. It is to decide what belongs together and draw clear boundaries.
Packages Are Namespace Boundaries
A package is a container for related model elements. Every name inside a package is scoped to that package. Two different packages can each define a Status enumeration without collision, because the full name includes the package: Brewing::Status versus Maintenance::Status.
You already used a package in Chapter 2. The new idea is using multiple packages to separate concerns.
Here is the coffee machine model split into two packages:
package CoffeeTypes {
private import ScalarValues::*;
item def Water;
item def CoffeeBeans;
item def BrewedCoffee;
enum def GrindSetting {
fine;
medium;
coarse;
}
}
package CoffeeParts {
private import ScalarValues::*;
private import CoffeeTypes::*;
part def Grinder {
attribute grindSize : GrindSetting;
}
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
}
part def WaterTank {
attribute currentLevel : Real;
attribute maxCapacity : Real;
}
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
}
}
CoffeeTypes holds items and enumerations – domain vocabulary that does not depend on the machine structure. CoffeeParts holds the structural definitions and imports the types it needs.
The split follows a principle: separate what things are from how they are assembled.
Wildcard vs. Explicit Imports
The private import CoffeeTypes::* line is a wildcard import. It brings every public member of CoffeeTypes into scope: Water, CoffeeBeans, BrewedCoffee, and GrindSetting all become directly usable names.
Wildcard imports are convenient when you are building a model and the package boundaries are still shifting. But they hide which names actually get used. If someone adds a Pressure attribute definition to CoffeeTypes later, it silently enters scope in CoffeeParts – possibly colliding with a local name.
An explicit import names exactly what you need:
package CoffeeParts {
private import ScalarValues::Real;
private import ScalarValues::String;
private import CoffeeTypes::GrindSetting;
part def Grinder {
attribute grindSize : GrindSetting;
}
}
Now a reviewer can see at a glance: this package uses Real, String, and GrindSetting. Nothing else. If GrindSetting gets renamed or removed, this import line will fail and point you to the problem.
Use wildcard imports while exploring. Switch to explicit imports when the model stabilizes. Standard library packages like ScalarValues are a reasonable exception – wildcard-importing ScalarValues::* is common practice because those types rarely change and are used everywhere.
Qualified Names Without Importing
You do not always need an import. You can refer to any element by its fully qualified name:
package CoffeeParts {
part def Grinder {
attribute grindSize : CoffeeTypes::GrindSetting;
}
}
This is verbose but unambiguous. It works well for one-off references where adding an import would be noise. If you use the same qualified name three or more times, an import is cleaner.
Visibility: Public and Private Members
By default, every member of a package is public – visible to any package that imports it (KerML §7.2.5.2). You can make a member private so it is only visible inside its own package:
package CoffeeTypes {
private import ScalarValues::*;
// Public: other packages can use these
item def Water;
item def CoffeeBeans;
item def BrewedCoffee;
enum def GrindSetting {
fine;
medium;
coarse;
}
// Private: internal helper, not part of the public API
private item def UsedGrounds;
}
UsedGrounds exists inside CoffeeTypes but will not appear in CoffeeParts even with a wildcard import. This is useful when a package has internal helpers that other packages should not depend on.
Think of visibility the same way you think about public and private functions in code. Expose what other packages need. Keep implementation details hidden.
There is a third keyword, protected. Outside a type it behaves exactly like private; inside a type it matters for what specializations inherit. Reach for it in Chapter 12 territory, not here.
Imports Have Visibility Too
The visibility keywords do not only apply to members. They apply to imports, and this is the part that surprises people.
(public | protected | private) private import <Package>::<name-or-*>;
package Structure {
// Anyone importing Structure also gets these
public import Definitions::*;
// Structure can use these; importers of Structure cannot
private import Internal::*;
}
An import’s visibility decides whether the names it brings in are visible to your importers, or only to you. If the import is public, the imported memberships become public in the importing namespace – you have re-exported them. If it is private, they stay yours (SysML §7.5.3, KerML §7.2.5.4).
Read it as: public import forwards, private import consumes.
SysML textual notation requires a visibility prefix on an import. Choose private to consume names here without re-exporting them:
package Structure {
private import Definitions::*; // private -- NOT re-exported
}
A package that imports Structure gets nothing from Definitions. If you meant
to pass those names through, you have to say public import.
This is exactly why the coffee machine model’s package layout writes
public import in each of its concern packages: Structure, Behavior, and
QualityModel each re-export what they pull in, so a consumer imports one
package and gets a coherent set of names without knowing how the model is split
internally.
Importing a whole subtree
private import <Package>::**;
Suffixing an import with ::** makes it recursive: it takes the namespace’s
members and then keeps going into nested namespaces (KerML §7.2.5.4). One **
replaces a column of imports when you genuinely want everything under a root.
package CoffeeMachineAnalysis {
private import CoffeeMachineDomain::**;
}
Recursion stops at what was actually imported – it follows owned members of imported namespaces, and does not drag in memberships that arrived through implied specializations. Use it when you want a whole subtree and be aware that, like any wildcard, it makes the origin of a name harder to see at a glance.
An import may also carry documentation or a filter (SysML §7.5.3). Start with an explicit member import when the goal is simply to make one name visible.
Nested Packages
Packages can contain other packages. This creates a hierarchy:
package CoffeeMachineDomain {
package Types {
private import ScalarValues::*;
item def Water;
item def CoffeeBeans;
item def BrewedCoffee;
enum def GrindSetting {
fine;
medium;
coarse;
}
}
package Parts {
private import ScalarValues::*;
private import CoffeeMachineDomain::Types::*;
part def Grinder {
attribute grindSize : GrindSetting;
}
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
}
part def WaterTank {
attribute currentLevel : Real;
attribute maxCapacity : Real;
}
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
}
}
}
From outside the model, you would refer to CoffeeMachineDomain::Parts::CoffeeMachine. From inside Parts, you can refer to its own members directly.
To reach a sibling package, it helps to know how a name gets resolved. Resolution starts in the local namespace and then searches outwards through each containing namespace, up to the root and finally the global namespace (KerML §7.2.5.1). So from inside Parts, the name Types resolves – it is a member of the enclosing CoffeeMachineDomain – and Types::GrindSetting works with no import at all. What the import buys you is the unqualified name: without private import CoffeeMachineDomain::Types::*, the bare name GrindSetting does not resolve inside Parts, because it is a member of the sibling package, not of the parent.
Nesting is useful for large models with several subsystem domains. For most models, one level of packages is enough. Do not nest deeper than two levels unless the model genuinely has that much structure.
When you want to see the nesting at a glance rather than read it from source, build a view def :> BrowserView over the package — BrowserView is one of the eight standard view definitions (SysML §9.2.20) covered in Chapter 13, and it presents the containment hierarchy as a tree.
Splitting Across Files
In SysML v2, a file is just a container for text. The language does not mandate a relationship between file names and package names. But a predictable convention saves time.
Here is a practical layout for the coffee machine model, with one package per file:
coffee-machine/
types.sysml -- CoffeeTypes package
parts.sysml -- CoffeeParts package
architecture.sysml -- top-level assembly (later chapters)
types.sysml:
package CoffeeTypes {
private import ScalarValues::*;
item def Water;
item def CoffeeBeans;
item def BrewedCoffee;
enum def GrindSetting {
fine;
medium;
coarse;
}
}
parts.sysml:
package CoffeeParts {
private import ScalarValues::*;
private import CoffeeTypes::GrindSetting;
part def Grinder {
attribute grindSize : GrindSetting;
}
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
}
part def WaterTank {
attribute currentLevel : Real;
attribute maxCapacity : Real;
}
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
}
}
Nothing in the language ties an element to the file it was declared in. Names resolve by namespace, not by file position, so the order the files are loaded in does not matter.
OpenSysML. Pass both files to
sysml -strict -validate types.sysml parts.sysml, or pass their containing directory. Names resolve across the files loaded together; one text file does not automatically load a sibling merely because it imports its package.
The convention is simple: one package per file, file name matches the package purpose. This makes it easy to find where a definition lives without searching. When you are ready to give your directory a formal identity with versioned dependencies, see Chapter 15.
What Changes, What Stays the Same
The model content has not changed. CoffeeMachine still contains a Grinder, a Brewer, and a WaterTank. The grinder still has a GrindSetting attribute. What changed is the organization: types in one package, parts in another, each in its own file.
This reorganization pays off starting in Chapter 5, when you add ports to the part definitions. You will import from CoffeeParts and CoffeeTypes rather than working inside one large package where everything is tangled together.
The browser view shows how the model’s packages and their contents form a tree:
Common Mistakes
Circular imports. If package A imports from B and B imports from A, you have a circular dependency. The specification explicitly permits circularity in imports (KerML §8.2.3.5.1), so this is legal and a conformant tool must cope with it – but it makes your model hard to understand and refactor. If two packages need each other, they probably belong in the same package, or you need to extract the shared elements into a third package.
Over-splitting. Creating a separate package for every single definition adds import noise without improving clarity. Group things that change together. If Grinder, Brewer, and WaterTank are always used as a set, keeping them in one package is better than scattering them across three.
Expecting a sibling package’s members to be in scope. A nested package does see the names its parent holds – resolution searches outwards – so Types, and anything else declared directly in CoffeeMachineDomain, resolves from inside Parts with no import. What you do not get is the sibling’s members: GrindSetting needs either the qualifier Types::GrindSetting or an import. Nesting gives you a naming hierarchy; it does not flatten one package’s members into another.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch04.sysml.
Structure
Your coffee machine model has definitions, usages, attributes, and an enumeration. It describes what things are and what properties they carry. But it says nothing about how those parts interact with the outside world – where water enters the brewer, where ground beans come out of the grinder, or how many heating elements exist. This chapter fills those gaps.
You will add ports to define interaction boundaries, multiplicity to say how many of something exist, and port definitions to type exactly what flows through each boundary. By the end, your coffee machine will have a fully specified structural interface.
Composite Structure Revisited
Before adding new concepts, look at what composite structure already gives you. In Chapter 2, you built this:
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
}
This says a CoffeeMachine is composed of three parts. The keyword part inside a definition creates an ownership relationship: the grinder, brewer, and water tank exist because the coffee machine exists. If you destroy the machine, the parts go with it. This is composite structure – the whole owns the parts.
Each part usage is typed. part grinder : Grinder does not just say “there is something called grinder.” It says the grinder conforms to the Grinder definition, which means it carries every attribute and port that Grinder declares. Type a usage, and all the definition’s features come along for free.
But right now, these three parts sit side by side inside CoffeeMachine with no way to interact. The grinder has no output chute. The brewer has no water inlet. To model interaction, you need ports.
Ports: Where Things Cross a Boundary
A port is a point on a part where interaction happens. Think of a physical connector, a pipe fitting, or an electrical terminal. In SysML v2, a port declares that something can flow into or out of a component at a specific point.
Here is the simplest possible port:
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
port waterInlet;
}
This adds an untyped port called waterInlet to the Brewer. It compiles, but it does not say anything useful. What flows through it? In what direction? To make ports meaningful, you need two things: a port definition that types the port, and a direction that says which way things flow.
Port Definitions
A port definition describes the kind of interaction point. It declares what items flow through it and in which direction.
port def WaterPort {
in item water : Water;
}
This says: a WaterPort is an interaction point where Water flows in. The direction keyword in is part of the item usage inside the port definition. Now apply it:
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
port waterInlet : WaterPort;
}
port waterInlet : WaterPort says: the brewer has an interaction point called waterInlet, and it conforms to the WaterPort definition. Because WaterPort declares in item water : Water, a reviewer (or a tool) can verify that anything connected to waterInlet must supply Water, flowing inward.
The pattern mirrors what you already know: port def defines a reusable type, port creates a usage of that type. Same definition/usage split as part def and part.
Direction: in, out, inout
Port definitions use direction keywords to declare which way items flow through a port. There are three:
in– the item flows into the owning partout– the item flows out of the owning partinout– the item flows in both directions
Direction is relative to the part that owns the port. When you write in item water : Water inside a port on the Brewer, you are saying water flows into the brewer through this port. From the perspective of whatever is connected on the other side, that same water is flowing out.
Here is what all three look like in port definitions:
port def WaterPort {
in item water : Water;
}
port def GroundCoffeePort {
out item grounds : CoffeeBeans;
}
port def StatusPort {
inout attribute level : Real;
}
WaterPort receives water. GroundCoffeePort emits ground coffee. StatusPort can both send and receive a level reading – useful for a sensor that reports values but can also be calibrated.
A single port definition can carry multiple items:
port def BrewInputPort {
in item water : Water;
in item grounds : CoffeeBeans;
}
This models a port where two distinct items enter. That is less common for physical ports (you would typically use separate connectors), but useful for logical interfaces where a single interaction point carries multiple signals.
Why Direction Matters
Direction is not decoration. It enables three things:
-
Connection validation. When you wire two ports together in Chapter 6, tools can check that an
outport connects to aninport of a compatible type. Connecting twoinports is a modeling error. -
Flow analysis. Direction tells you which way items move through the system. In Chapter 7, action flows will use port directions to determine data dependencies.
-
Interface contracts. A port definition is a contract: “this component expects to receive Water here.” Any component with a matching port can plug in. Direction is part of that contract.
If you omit direction, the item has no declared flow direction. That weakens every check that depends on knowing which way things move. Always declare direction on items inside port definitions.
Building Port Definitions for the Coffee Machine
Now apply ports to your existing model. Think about each component and ask: what crosses its boundary?
Grinder: Coffee beans go in; ground coffee comes out.
port def BeanInputPort {
in item beans : CoffeeBeans;
}
port def GroundCoffeePort {
out item grounds : CoffeeBeans;
}
Both ports carry CoffeeBeans, but at different stages. The beans that enter are whole; the grounds that exit have been processed. For now, both are typed as CoffeeBeans. In a more detailed model, you might define separate item types for whole beans and ground beans. Keep it simple until the model demands more precision.
Brewer: Water and ground coffee go in; brewed coffee comes out.
port def WaterPort {
in item water : Water;
}
port def BrewOutputPort {
out item coffee : BrewedCoffee;
}
WaterTank: Water goes out (to the brewer).
port def WaterSupplyPort {
out item water : Water;
}
Notice that WaterPort and WaterSupplyPort both involve Water, but in opposite directions. WaterPort receives water (in); WaterSupplyPort provides water (out). When you connect them in Chapter 6, the directions will match: one outputs what the other inputs.
Adding Ports to Existing Parts
With port definitions in hand, update the part definitions from Chapter 2. You are not redefining these parts – you are extending them with ports:
package CoffeeMachineDomain {
private import ScalarValues::*;
// Items
item def Water;
item def CoffeeBeans;
item def BrewedCoffee;
// Enumerations
enum def GrindSetting {
fine;
medium;
coarse;
}
// Port definitions
port def BeanInputPort {
in item beans : CoffeeBeans;
}
port def GroundCoffeePort {
out item grounds : CoffeeBeans;
}
port def WaterPort {
in item water : Water;
}
port def WaterSupplyPort {
out item water : Water;
}
port def BrewOutputPort {
out item coffee : BrewedCoffee;
}
// Parts with ports
part def Grinder {
attribute grindSize : GrindSetting;
port beanInput : BeanInputPort;
port groundOutput : GroundCoffeePort;
}
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
port waterInlet : WaterPort;
port groundInput : BeanInputPort;
port brewOutput : BrewOutputPort;
}
part def WaterTank {
attribute currentLevel : Real;
attribute maxCapacity : Real;
port waterOut : WaterSupplyPort;
}
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
}
}
Look at what the model says now. The Grinder accepts beans through beanInput and emits grounds through groundOutput. The Brewer receives water and grounds, then outputs brewed coffee. The WaterTank supplies water. Every boundary is named, typed, and directional.
Notice that Brewer.groundInput reuses BeanInputPort. That is the same port definition used by Grinder.beanInput. Reuse is the point of port definitions: define the interface once, use it on any part that needs it. The Brewer accepts beans (ground) through the same type of input port as the Grinder, because structurally the interface is the same – coffee material flowing inward.
This general view shows the structural definitions with their ports and typing relationships:
The figure is a static view of the project. The port definitions specify the contract; their placement on this page is a rendering choice.
Enumerations: A Brief Recap
Chapter 2 introduced enum def GrindSetting with three values. Enumerations are attribute definitions with a fixed set of members. A few additional patterns are worth knowing.
Enumeration values can carry data. The data is declared once, on an attribute definition, and each value fills it in:
attribute def BrewRatio {
attribute ratio : Real;
}
enum def BrewStrength :> BrewRatio {
enum light { :>> ratio = 15.0; }
enum medium { :>> ratio = 12.0; }
enum strong { :>> ratio = 10.0; }
}
BrewStrength specializes BrewRatio, so it inherits ratio; each value then redefines ratio with its own number. Any attribute typed by BrewStrength can be asked for its ratio, because there is one ratio feature rather than three.
Resist the temptation to declare attribute ratio : Real inside the enumeration definition itself. Setting aside annotations – a doc or a comment is always welcome – an enumeration definition’s body holds only its enumeration values (SysML §7.8.2). The definition is a set of alternatives, not a place to hang features. Declaring a fresh ratio inside each value instead would parse, but it would give you three unrelated attributes and nothing common to query.
You can reference enum members using qualified names:
BrewStrength::strong
GrindSetting::fine
This is the same :: scoping syntax you use with packages and imports. An enum definition is a namespace; its members are named elements inside that namespace.
For most modeling work, simple enumerations like GrindSetting are sufficient. Use attributed enumerations when the domain genuinely needs data attached to each variant.
Multiplicity
So far, every usage in the model means “exactly one.” The coffee machine has one grinder, one brewer, one water tank. But real systems are not always that simple. A machine might have multiple heating elements, zero or more optional accessories, or a sensor array with a specific count.
Multiplicity declares how many instances of a usage can exist. You write it in square brackets, most commonly right after the type – though the specification also allows it directly after the name, or after a :> or :>> clause, and only one multiplicity per usage (SysML §7.6.3):
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
part heatingElement : HeatingElement [2];
port waterInlet : WaterPort;
port groundInput : BeanInputPort;
port brewOutput : BrewOutputPort;
}
part heatingElement : HeatingElement [2] says: every Brewer contains exactly two heating elements. Not one, not three – two.
Multiplicity Notation
The general form is [lower..upper]. Common patterns:
| Notation | Meaning |
|---|---|
[1] | Exactly one (common explicit singleton intent) |
[2] | Exactly two |
[0..1] | Optional – zero or one |
[1..*] | One or more |
[0..*] | Any number, including zero |
[2..4] | Between two and four |
The * means “unbounded.” [0..*] is the most permissive multiplicity: any number of instances.
When You Omit Multiplicity
If you write part grinder : Grinder with no brackets, you almost always get [1..1] anyway. The specification declares an implicit [1..1] when all three of these hold (SysML §7.6.3):
- the usage is an attribute usage, an item usage (including a part usage, but not a connection usage), or a port usage;
- it is owned by a definition or another usage – not directly by a package;
- and it declares no subsetting or redefinition of its own.
Every usage in the coffee machine model meets all three, so the model already means “exactly one” everywhere. When those conditions do not hold – a usage sitting directly in a package, or one that subsets an inherited collection – the usage takes the bounds of whatever it subsets or redefines, falling back to the most general [0..*] if nothing tighter is inherited.
Writing [1] therefore changes nothing about the meaning. It makes the intent visible:
part def CoffeeMachine {
part grinder : Grinder [1];
part brewer : Brewer [1];
part waterTank : WaterTank [1];
}
This is more verbose but leaves nothing to a reader’s memory of the default rule. Use explicit multiplicity when the count matters for analysis, and leave it off when “one” is obvious from context.
Multiplicity on Attributes and Ports
Multiplicity is not limited to parts. Attributes and ports support it too:
part def SensorArray {
attribute readings : Real [0..*];
port outlets : PowerOutlet [6];
}
readings carries zero or more values. outlets provides exactly six connection points. You will not need multi-valued attributes or ports for the coffee machine, but the syntax is the same wherever multiplicity appears.
Attribute Definitions and Default Values
Chapter 2 used Real, String, and GrindSetting as attribute types. Two additional patterns are worth knowing before you see the full model.
Attribute definitions create reusable value types, the same way part def creates reusable component types:
attribute def TemperatureRange {
attribute min : Real;
attribute max : Real;
}
Then use it on a part: attribute operatingTemp : TemperatureRange. This bundles related properties into a single named attribute instead of scattering loose fields.
Values attach a number to an attribute, and there are three ways to do it that mean three different things:
part def WaterTank {
attribute currentLevel : Real := 0.0;
attribute maxCapacity : Real default = 1500.0;
attribute nominalPressure : Real = 1.0;
port waterOut : WaterSupplyPort;
}
:=is an initial value.currentLevelstarts at zero and changes as the tank fills.default =is an overridable default.maxCapacityis 1500.0 unless a particular usage says otherwise. Writingdefault 1500.0, with the=elided, means the same thing.- A bare
=is a binding. It asserts that the attribute is that value, for every instance, at all times.
The bare = is the one that catches people out. attribute currentLevel : Real = 0.0 does not say “starts empty” – it asserts the level is always zero (SysML §7.6.3). Reach for = when the value is a genuine constant of the type, := when it is a starting point, and default = when a usage should be free to override it. For computed values derived from other properties, see Chapter 9.
The Complete Model So Far
Here is the full coffee machine model after this chapter. Everything from Chapter 2 is preserved; ports, port definitions, and explicit multiplicity are the additions:
package CoffeeMachineDomain {
private import ScalarValues::*;
// Items: things that flow through the system
item def Water;
item def CoffeeBeans;
item def BrewedCoffee;
// Enumerations
enum def GrindSetting {
fine;
medium;
coarse;
}
// Port definitions: typed interaction boundaries
port def BeanInputPort {
in item beans : CoffeeBeans;
}
port def GroundCoffeePort {
out item grounds : CoffeeBeans;
}
port def WaterPort {
in item water : Water;
}
port def WaterSupplyPort {
out item water : Water;
}
port def BrewOutputPort {
out item coffee : BrewedCoffee;
}
// Structural definitions with ports
part def Grinder {
attribute grindSize : GrindSetting;
port beanInput : BeanInputPort;
port groundOutput : GroundCoffeePort;
}
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
port waterInlet : WaterPort;
port groundInput : BeanInputPort;
port brewOutput : BrewOutputPort;
}
part def WaterTank {
attribute currentLevel : Real := 0.0;
attribute maxCapacity : Real default = 1500.0;
port waterOut : WaterSupplyPort;
}
part def CoffeeMachine {
part grinder : Grinder [1];
part brewer : Brewer [1];
part waterTank : WaterTank [1];
attribute serialNumber : String;
}
}
Count the ports. The grinder has two (beans in, grounds out). The brewer has three (water in, grounds in, coffee out). The water tank has one (water out). Together, these ports define every boundary where material crosses from one subsystem to another.
The CoffeeMachine itself does not have ports yet. That is intentional – the machine’s external interface (where the user puts beans in, where the cup sits) is a design decision for later. Right now, the internal boundaries are what matter for wiring subsystems together.
What Comes Next
The parts have boundaries, but nothing connects them. The grinder’s groundOutput and the brewer’s groundInput are compatible – they both involve CoffeeBeans flowing in matching directions – but the model does not say they are wired together.
Chapter 6 adds connections and interfaces to wire these ports together, completing the structural picture. The ports you defined here are the endpoints; Chapter 6 provides the wires.
Common Mistakes
Forgetting direction on port items. This compiles:
port def WaterPort {
ref item water : Water;
}
But without in, out, or inout, tools cannot validate connections or analyze flow direction. Always specify direction.
Defining ports without port definitions. You can write port waterInlet; with no type, but that tells tools nothing about what flows through it. An untyped port is like an untyped attribute – technically valid, practically useless.
Mismatched directions at connection time. If you define WaterPort as in and WaterSupplyPort as in, you cannot connect them – both sides are trying to receive. One side must output what the other inputs. Think of directions as pipe fittings: a supply end connects to a receiving end.
Over-specifying multiplicity. Writing [1] on every single usage adds noise without information when the count is obvious. Use explicit multiplicity when it conveys design intent: [2] for dual heating elements, [0..1] for optional accessories, [1..*] for extensible arrays. Leave it off when “one” is self-evident.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch05.sysml.
Connections and Interfaces
Your coffee machine has parts and ports. The WaterTank has an outlet, the Brewer has inlets, the Grinder has an output. But right now, nothing is wired together. The ports exist in isolation – interaction points with nothing to interact with.
This chapter connects the machine. You will start with the simplest possible connection, add port-level wiring, define interface contracts, and finally model what actually flows through those wires. By the end, the coffee machine will be a connected system, not just a bag of parts.
The Simplest Connection
A connection in SysML v2 says: these two parts interact. The simplest form names the two ends directly:
part def CoffeeMachine {
part waterTank : WaterTank;
part brewer : Brewer;
connect waterTank to brewer;
}
connect waterTank to brewer creates a connector between the two part usages. It says the water tank and brewer are linked somehow, but it does not say how. No ports are involved. No item type is specified. It is a statement of topology: these two parts interact.
This is useful early in modeling when you want to capture the fact that two subsystems communicate before you have worked out the details. A reviewer can see the interaction structure without getting buried in port definitions.
But there is a problem. The connection says nothing about where on each part the interaction happens, or what moves between them. For a coffee machine, that matters. Water enters the brewer through a specific inlet, not through the grinder’s bean hopper. To express that, you need port-level connections.
Connecting Through Ports
In Chapter 5, you added ports to the coffee machine’s parts. The WaterTank has a waterOut port that sends Water. The Brewer has a waterInlet that receives Water and a groundInput port that receives ground CoffeeBeans. The Grinder has a groundOutput that sends ground CoffeeBeans.
Now connect them at the port level:
part def CoffeeMachine {
part waterTank : WaterTank;
part brewer : Brewer;
part grinder : Grinder;
connect waterTank.waterOut to brewer.waterInlet;
connect grinder.groundOutput to brewer.groundInput;
}
This is more precise. connect waterTank.waterOut to brewer.waterInlet says: the water tank’s waterOut port is connected to the brewer’s waterInlet port. The dot notation navigates from the part usage to its port.
Two things changed from the simple form:
- Each end is a port, not a part. The connection targets the specific interaction point on each component.
- Direction matters implicitly.
waterOutis typed byWaterSupplyPort, which declaresout item water;waterInletis typed byWaterPort, which declaresin item water. The connection goes from a source of Water to a sink of Water. SysML v2 does not force you to declare the direction on the connector itself – the port definitions already carry that information.
This is the form you will use most often. Port-level connections make the interaction topology explicit and checkable. A tool can verify that the types on each end are compatible: an outlet sending Water connects to an inlet receiving Water.
Naming Your Connections
Every connection so far has been anonymous. You can give a connector a name if you want to refer to it later – in constraints, requirements, or documentation:
part def CoffeeMachine {
part waterTank : WaterTank;
part brewer : Brewer;
part grinder : Grinder;
connection waterLine connect waterTank.waterOut to brewer.waterInlet;
connection beanFeed connect grinder.groundOutput to brewer.groundInput;
}
waterLine and beanFeed are now named connectors. The names do not change behavior, but they make the model more readable and give you handles to attach flows, constraints, or requirements to specific connections.
Interface Definitions
A connection says two ports are linked. An interface definition says what a valid connection between two kinds of ports looks like. It is a contract.
Suppose you want to formalize what it means to connect a water source to a water consumer. Define an interface:
interface def WaterSupply {
end supplierPort : WaterSupplyPort;
end consumerPort : WaterPort;
}
interface def WaterSupply declares a reusable connection contract with two ends. Each end is typed by a port definition. Any connection that matches this pattern – a WaterSupplyPort on one side, a WaterPort on the other – conforms to the WaterSupply interface.
You use the interface when creating the connection:
part def CoffeeMachine {
part waterTank : WaterTank;
part brewer : Brewer;
interface waterLine : WaterSupply {
end supplierPort ::> waterTank.waterOut;
end consumerPort ::> brewer.waterInlet;
}
}
This says: the connection between waterTank.waterOut and brewer.waterInlet is an instance of the WaterSupply interface. The ::> binds each interface end to a specific port usage.
When do you need interface definitions? Not always. For simple models, direct connect statements are fine. Interface definitions earn their keep when:
- Multiple connections follow the same pattern and you want to enforce consistency.
- You need to attach shared constraints or metadata to a class of connections.
- You are modeling a system where the interface contract matters independently of who implements it – like a standardized connector.
Item Flows
Connections and interfaces describe the topology: what is linked to what. Item flows describe the content: what actually moves through a connection.
You already defined item types in Chapter 2 – Water, CoffeeBeans, BrewedCoffee. An item flow says that a specific item type travels along a specific connection:
part def CoffeeMachine {
part waterTank : WaterTank;
part brewer : Brewer;
part grinder : Grinder;
connection waterLine connect waterTank.waterOut to brewer.waterInlet;
connection beanFeed connect grinder.groundOutput to brewer.groundInput;
flow of Water from waterTank.waterOut.water to brewer.waterInlet.water;
flow of CoffeeBeans from grinder.groundOutput.grounds to brewer.groundInput.beans;
}
flow of Water from waterTank.waterOut to brewer.waterInlet says: Water moves from the tank’s outlet to the brewer’s inlet. The of Water clause types the flow. The from ... to ... clause identifies the source and destination.
Item flows serve a different purpose than connections. A connection says two ports are linked. A flow says something specific travels through that link. You can have a connection without a flow (the link exists, but you have not specified what moves), and in principle you can have multiple flows on the same connection (water and dissolved minerals, say).
In practice, most connections carry one primary flow, and you will often write both the connection and the flow together. The flow is what makes reviewers confident the model is complete: not just “these parts are linked” but “Water moves from here to there.”
Named Flows
Like connections, flows can be named:
flow hotWater of Water from waterTank.waterOut.water to brewer.waterInlet.water;
flow groundBeans of CoffeeBeans from grinder.groundOutput.grounds to brewer.groundInput.beans;
Named flows are useful when you need to reference them in constraints or requirements. For example, a requirement might say “the hotWater flow shall not exceed 95 degrees Celsius.” Without a name, you have nothing to point at.
Flow Definitions
Every flow so far has been a usage written directly where it happens. Flows have
definitions too, the same way parts and actions do – and if you find yourself
writing the same of <Item> from <port> to <port> shape repeatedly, that is the
signal to define it once.
flow def <Name> {
end <name> : <SourcePortType>;
end <name> : <TargetPortType>;
}
flow def WaterFlow {
end supply : WaterSupplyPort;
end intake : WaterPort;
ref item :>> payload : Water;
}
part def CoffeeMachine {
part waterTank : WaterTank;
part brewer : Brewer;
flow supplyLine : WaterFlow from waterTank.waterOut.water to brewer.waterInlet.water;
}
A flow definition is a reusable kind of flow. Its end members say what the
two sides must be – here, that a WaterFlow always runs from something with a
WaterSupplyPort to something with a WaterPort. The usage then names the
particular flow and says which ports it connects.
Read it as: WaterFlow is the kind of movement; supplyLine is this
movement, in this machine.
This is the def/usage split from Chapter 3 applied to flows, and it buys the same things it always does. The definition is one place to document what the flow means, one place to attach a constraint on its rate or temperature, and one thing a requirement can point at for every machine rather than for one instance.
The coffee machine’s own model defines WaterFlow, CoffeeFlow and SteamFlow
this way, and then declares usages against them.
Flows that also order
action def SupplyWater {
action deliver { out item water : Water; }
action receiveWater { in item water : Water; }
succession flow waterThenCoffee of Water from deliver.water to receiveWater.water;
}
A succession flow does two jobs at once: it carries something, and it
constrains time. The plain flow says water moves from the tank to the brewer.
succession flow adds that the source end completes before the target end
begins – the ordering meaning you met as first ... then in
Chapter 7, attached to a flow rather than to two actions.
Reach for it when the sequence matters as much as the transfer: the receiving action must start after the delivering action finishes, rather than overlapping it.
Binding Connectors
There is one more kind of connector you should know about: the binding connector. A regular connection says two separate things interact. A binding says two things are the same thing, seen from different contexts.
Suppose you expose a port on the CoffeeMachine itself, and you want to bind it to an internal part’s port:
part def Brewer {
port waterInlet : WaterPort;
port groundInput : BeanInputPort;
port brewOutput : BrewOutputPort;
}
part def CoffeeMachine {
port dispenserOut : BrewOutputPort;
part brewer : Brewer;
bind dispenserOut = brewer.brewOutput;
}
bind dispenserOut = brewer.brewOutput says: the machine’s dispenserOut port is the brewer’s brewOutput port. They are not separate endpoints with something flowing between them. They are the same port, exposed at two levels of the hierarchy. What appears on brewer.brewOutput appears on dispenserOut, by identity.
Bindings are how you thread internal ports up to an external interface. If the CoffeeMachine is used inside a larger system – a cafe counter, say – that outer system connects to dispenserOut without knowing about the brewer inside.
Allocation
Every relationship so far has been structure-to-structure: this port talks to that port, this item moves along that link. Allocation is the one that crosses between models. It says a behavioral element is the responsibility of a structural one – this step of the brew cycle is the grinder’s job.
You need it because the two decompositions are deliberately independent (Chapter 7 makes that point about actions). BrewCycle breaks into grind, heat, and extract; CoffeeMachine breaks into grinder, waterTank, and brewer. Nothing in either decomposition says which part does which step. Allocation is where you write that down:
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
perform action brewCycle : BrewCycle;
// Commit each step of the cycle to the part responsible for it
allocate brewCycle.grind to grinder;
allocate brewCycle.heat to waterTank;
allocate brewCycle.extract to brewer;
}
allocate brewCycle.grind to grinder says: whatever the grind step requires, the grinder is what has to deliver it. That is a claim a reviewer can check. If grind needs 200 W and the grinder is specified at 150 W, the allocation is where the mismatch surfaces – not in a meeting six months later. Allocations are also queryable in both directions: “what does the brewer have to do?” and “who is responsible for heating?” both have answers in the model.
When you need to attach anything to the allocation itself – a rationale, a margin, a review status – name it and give it a definition, exactly as with connections:
allocation def FunctionToComponent;
part def CoffeeMachine {
part grinder : Grinder;
perform action brewCycle : BrewCycle;
allocation grindAlloc : FunctionToComponent allocate brewCycle.grind to grinder;
}
Reach for the bare allocate when the mapping is the whole story, and the named form when the mapping itself needs properties. Allocation is not limited to behavior-to-structure: the same construct maps requirements to components, logical designs to physical ones, or software functions to processors. The pattern is always “this element is realized by that one”.
The Connected Coffee Machine
Here is the coffee machine with all of its connections and flows in one place. This builds on the ports from Chapter 5 and the definitions from Chapter 2:
package CoffeeMachineConnections {
private import CoffeeMachineDomain::*;
part def CoffeeMachine {
// Internal parts
part waterTank : WaterTank;
part brewer : Brewer;
part grinder : Grinder;
// External port
port dispenserOut : BrewOutputPort;
// Port-level connections
connection waterLine connect waterTank.waterOut to brewer.waterInlet;
connection beanFeed connect grinder.groundOutput to brewer.groundInput;
// Typed flows -- what moves through each connection
flow hotWater of Water from waterTank.waterOut.water to brewer.waterInlet.water;
flow groundBeans of CoffeeBeans from grinder.groundOutput.grounds to brewer.groundInput.beans;
// Binding -- expose brewer output as machine output
bind dispenserOut = brewer.brewOutput;
}
}
Read this model from top to bottom. The parts tell you what the machine is made of. The connections tell you how the parts are wired. The flows tell you what moves through those wires. The binding tells you where the output appears to the outside world.
A reviewer looking at this model can answer: What are the subsystems? How do they connect? What flows between them? Where does the product come out? That is a complete structural interaction picture, and it took about 15 lines.
The Progression
This chapter followed a deliberate progression that mirrors how you should model connections in practice:
- Simple connect.
connect tank to brewer– capture the topology before the details. - Port-level connect.
connect waterTank.waterOut to brewer.waterInlet– specify exactly where interaction happens. - Named connection.
connection waterLine connect ...– give handles for later reference. - Interface definition.
interface def WaterSupply– formalize reusable connection contracts. - Item flow.
flow of Water from ... to ...– specify what moves. - Binding.
bind dispenserOut = brewer.brewOutput– expose internal ports to the outside. - Allocation.
allocate brewCycle.grind to grinder– commit behavior to the structure responsible for it.
You do not need all seven levels for every connection. Many models get by with port-level connections and typed flows. Interface definitions and bindings appear when the model needs to formalize contracts or manage hierarchy. Start simple and add precision where the design demands it.
Visualizing Connections
This interconnection view shows how the parts connect through their ports, with item flows indicating what travels through each connection:
This is the Interconnection view — one of the eight standard view definitions covered in Chapter 13. If you are coming from SysML v1, you will recognize the same content under the older labels: a part-level Interconnection is what v1 called an Internal Block Diagram (IBD), and a definition-level Interconnection is what v1 called a Block Definition Diagram (BDD).
Connecting two ports does not, by itself, solve a conservation equation. If a review needs a balance of mass or energy, write the balance and its assumptions explicitly; see Appendix E.
Common Mistakes
Connecting definitions instead of usages. This is wrong:
connect WaterTank to Brewer; // Intentional error: definitions, not the parts in this machine.
Connections link usages – the specific parts inside a context. You cannot connect WaterTank as a type; you connect waterTank, the specific instance inside CoffeeMachine.
Mismatched port types on a connection. If waterTank.waterOut sends Water but brewer.groundInput expects CoffeeBeans, connecting them is a type error. The port types on each end of a connection should be compatible. This is one of the main benefits of typed ports – the model catches wiring mistakes.
Omitting the topology when it matters. A flow specifies a transfer. If the review also needs to know which pipe or interface carries the transfer, model that connection explicitly.
Using bind when you mean connect. A binding says two things are identical. A connection says two separate things interact. If the water tank and brewer are separate parts with different ports, you want connect. If you are exposing an internal port at a higher level in the hierarchy, you want bind.
What Comes Next
The coffee machine now has structure, ports, connections, and flows. It is fully wired but entirely static. In Chapter 7, you will add behavior – the brew cycle that moves water through the tank, grinds beans, and produces coffee. The connections you built here become the pathways that behavior uses.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch06.sysml.
Actions
Up to this point, the coffee machine model describes what the system is – parts, attributes, ports, connections. But a machine that only has structure does nothing. This chapter adds behavior: what the system does when someone presses the brew button.
In SysML v2, behavior is modeled with actions. An action definition describes a reusable unit of behavior, the same way a part definition describes a reusable structural component. Actions compose into workflows through sequencing, parallelism, branching, and signaling.
Defining an Action
An action definition declares a kind of behavior. It follows the same def pattern you have seen with parts and items:
action def GrindBeans;
That says: there is a kind of behavior called GrindBeans. It does not say when or where it happens. It is a type, not an occurrence.
To say that something performs this behavior, you create an action usage inside another action:
action def GrindBeans;
action def HeatWater;
action def BrewCycle {
action grind : GrindBeans;
action heat : HeatWater;
}
action grind : GrindBeans says: inside a BrewCycle, there is a step called grind, and it is of type GrindBeans. This is the same definition/usage pattern from Chapter 2, applied to behavior instead of structure.
Without anything else, the two sub-actions have no defined order. SysML v2 does not assume sequential execution. You have to say it.
Sequential Composition
The first ... then statement declares that one action must complete before another begins:
action def BrewCycle {
action grind : GrindBeans;
action heat : HeatWater;
first grind then heat;
}
first grind then heat creates a succession – an ordering constraint that says grind finishes before heat starts. This is a directed relationship between two action usages, not a property of either action by itself.
You can chain successions to build longer sequences:
action def BrewCycle {
action grind : GrindBeans;
action heat : HeatWater;
action extract : ExtractCoffee;
action dispense : DispenseCoffee;
first grind then heat;
first heat then extract;
first extract then dispense;
}
That reads: grind, then heat, then extract, then dispense. Each first ... then is a separate succession statement. Together they form a chain.
Every action has two implicit endpoints: start and done. You can anchor your sequence to them:
action def BrewCycle {
action grind : GrindBeans;
action heat : HeatWater;
action extract : ExtractCoffee;
action dispense : DispenseCoffee;
first start then grind;
first grind then heat;
first heat then extract;
first extract then dispense;
first dispense then done;
}
first start then grind says that grind is the first thing that happens when a BrewCycle begins. first dispense then done says the cycle finishes after dispensing completes. These endpoints make the boundary of the action explicit – a reviewer can see exactly where behavior begins and ends.
You can also chain successions on a single line using the then keyword after an action usage:
action def BrewCycle {
action grind : GrindBeans;
then action heat : HeatWater;
then action extract : ExtractCoffee;
then action dispense : DispenseCoffee;
}
The then before an action usage is shorthand: it creates a succession from the previously declared action to the current one. This form is more compact but means the same thing as writing separate first ... then statements.
Naming a succession
Everything so far has written the ordering inline, inside the action body. There is a second form that names it:
succession [<name>] [first] <source> then <target>;
action def BrewCycle {
action grind : GrindBeans;
action heat : HeatWater;
action extract : Extract;
succession grindDone first grind then heat;
succession first heat then extract;
}
Read the first one as: this ordering constraint is called grindDone, and it
says grind comes before heat.
Both lines declare the same kind of relationship the bare first ... then does.
What the keyword buys you is a name, and a named succession is a model
element like any other – you can document it, refer to it from a requirement, or
allocate it. That is why larger models tend to use this form for the orderings
that matter and the bare form for the rest.
In the short unnamed related-features form, the specification makes first optional. succession heat then extract; and
succession first heat then extract; mean the same thing – the specification says
so directly: “If a succession declaration includes only the related features part,
then the keyword first can be omitted” (KerML §7.4.6.4). The coffee machine’s own
examples use explicit first where that makes the source easier to see.
One more thing that clause tells you, and it is worth knowing because it explains
what a succession actually is: if you give a succession no explicit type, it is
implicitly typed by the library association HappensBefore, which lives in the
standard library’s Occurrences package. An ordering constraint
is not a special syntactic device bolted onto actions – it is a connector, typed
from the standard library, whose two ends happen to be things ordered in time.
Action Parameters
Actions often need inputs and produce outputs. You declare these with in and out parameters:
action def GrindBeans {
in item beans : CoffeeBeans;
out item grounds : GroundCoffee;
}
in item beans : CoffeeBeans says that GrindBeans receives coffee beans as input. out item grounds : GroundCoffee says it produces ground coffee as output. The item keyword here means the parameter carries an item – something that flows through the system.
Parameters make the interface of an action explicit. When you compose actions, the outputs of one step can connect to the inputs of the next:
action def GrindBeans {
in item beans : CoffeeBeans;
out item grounds : GroundCoffee;
}
action def ExtractCoffee {
in item grounds : GroundCoffee;
in item water : HotWater;
out item coffee : BrewedCoffee;
}
A reviewer can see at a glance what each step needs and what it produces, without reading the internals.
Parallel Composition with Fork and Join
Not everything in a workflow happens one step at a time. In the coffee machine, heating water and grinding beans can happen simultaneously – the grinder and the heater are independent subsystems.
SysML v2 models parallelism with fork and join nodes. A fork splits one flow into multiple concurrent paths. A join waits for all concurrent paths to complete before continuing.
action def BrewCycle {
action grind : GrindBeans;
action heat : HeatWater;
action extract : ExtractCoffee;
action dispense : DispenseCoffee;
fork forkNode;
first start then forkNode;
first forkNode then grind;
first forkNode then heat;
join joinNode;
first grind then joinNode;
first heat then joinNode;
first joinNode then extract;
first extract then dispense;
first dispense then done;
}
Here is what happens at runtime:
- The cycle starts.
forkNodesplits execution into two concurrent paths.grindandheatrun in parallel.joinNodewaits until bothgrindandheatfinish.extractruns after the join.dispenseruns after extraction.- The cycle ends.
The fork keyword declares a fork node – a control node with no behavior of its own. Its job is to start multiple paths at the same time. The join keyword declares a join node that synchronizes those paths back together. Think of a fork as a split and a join as a rendezvous.
Fork and join nodes are not actions with duration. They are instantaneous control points. The real work happens in the action usages (grind, heat, extract, dispense). The control nodes just direct traffic.
Decisions and Merges
Sometimes a workflow needs to choose between paths based on a condition. SysML v2 models this with decide and merge nodes.
A decision node picks one outgoing path. A merge node brings multiple alternative paths back together. Where fork/join models “do all of these,” decide/merge models “do one of these.”
Suppose the coffee machine can make either espresso or drip coffee, depending on a setting:
action def BrewCycle {
in attribute espressoMode : Boolean;
action grind : GrindBeans;
action heat : HeatWater;
action espressoExtract : ExtractEspresso;
action dripExtract : ExtractDrip;
action dispense : DispenseCoffee;
first start then grind;
first grind then heat;
decide decideMethod;
first heat then decideMethod;
first decideMethod if espressoMode then espressoExtract;
first decideMethod if not espressoMode then dripExtract;
merge mergeMethod;
first espressoExtract then mergeMethod;
first dripExtract then mergeMethod;
first mergeMethod then dispense;
first dispense then done;
}
After heating, the decideMethod node evaluates the condition. If espressoMode is true, execution follows the path to espressoExtract. Otherwise, it follows the path to dripExtract. Only one path runs.
The mergeMethod node reunites the two alternatives. Whichever extraction method was chosen, execution continues to dispense after the merge. The merge does not wait for both paths – only one path is active, and the merge simply accepts whichever one arrives.
This is the key difference between fork/join and decide/merge:
- Fork/join: all paths execute concurrently, join waits for all.
- Decide/merge: one path executes based on a condition, merge accepts whichever arrives.
The guard condition (if espressoMode) is attached to the outgoing succession from the decision node. The else keyword marks the default path taken when no guard is satisfied.
Combining Control Flow
Real workflows combine sequencing, parallelism, and decisions. Here is a more complete brew cycle that uses all three:
package CoffeeMachineActions {
private import ScalarValues::*;
private import CoffeeMachineDomain::*;
action def GrindBeans {
in item beans : CoffeeBeans;
}
action def HeatWater {
in item water : Water;
}
action def ExtractEspresso;
action def ExtractDrip;
action def DispenseCoffee {
out item coffee : BrewedCoffee;
}
action def BrewCycle {
in attribute espressoMode : Boolean;
in item beans : CoffeeBeans;
in item water : Water;
out item coffee : BrewedCoffee;
action grind : GrindBeans {
in item :>> beans = BrewCycle::beans;
}
action heat : HeatWater {
in item :>> water = BrewCycle::water;
}
action espressoExtract : ExtractEspresso;
action dripExtract : ExtractDrip;
action dispense : DispenseCoffee {
out item :>> coffee = BrewCycle::coffee;
}
// Grind and heat in parallel
fork forkPrep;
first start then forkPrep;
first forkPrep then grind;
first forkPrep then heat;
join joinPrep;
first grind then joinPrep;
first heat then joinPrep;
// Choose extraction method
decide decideMethod;
first joinPrep then decideMethod;
first decideMethod if espressoMode then espressoExtract;
first decideMethod if not espressoMode then dripExtract;
merge mergeMethod;
first espressoExtract then mergeMethod;
first dripExtract then mergeMethod;
// Dispense and finish
first mergeMethod then dispense;
first dispense then done;
}
}
Read the control flow section from top to bottom and you get the full story: the cycle starts by forking into parallel preparation (grind and heat). After both finish, a decision selects the extraction method. After extraction, the results merge and the coffee is dispensed.
The action parameters (in item beans, out item coffee) make the data flow explicit alongside the control flow. The binding in item beans = BrewCycle::beans connects the sub-action’s input to the enclosing action’s parameter. This is how data threads through a composed workflow.
Send and Accept
Actions can communicate with each other through signals. The send action transmits a signal, and the accept action waits for one to arrive. This is how you model event-driven behavior – one part of the system notifying another that something happened.
action def NotifyReady {
part display : Panel;
send new BrewComplete() to display;
}
send BrewComplete() to display says: transmit a BrewComplete signal to the display part. The signal is an item that carries information about an event.
On the receiving side:
action def WaitForBrew {
accept brewDone : BrewComplete;
}
accept brewDone : BrewComplete says: pause and wait until a BrewComplete signal arrives. When it does, execution continues and the signal is available as brewDone.
You can use accept inside an action body to model a step that blocks until an event occurs:
action def ServeCustomer {
part customerDisplay : Panel;
accept orderReceived : BrewRequest;
then action brew : BrewCycle;
then action notify send new BrewComplete() to customerDisplay;
}
This reads: wait for a brew request, then perform the brew cycle, then notify the customer display. The accept at the beginning means the action does not start its real work until the triggering event arrives.
Routing a message through a specific port
When a part has more than one port, a plain send ... to <part> leaves the channel unspecified. The via keyword routes a signal along a particular port so the model says which connection carries it:
action def RouteSignalThroughPort {
port communicationPort : CommunicationPort;
send new LowWaterSignal() via communicationPort;
}
send LowWaterSignal() via communicationPort says: route the LowWaterSignal through the communicationPort, not whichever other port the part happens to have. This matters when a part exposes several ports and the routing decision is part of the model, not left to the runtime.
On the receiving side you can select an incoming channel with via as well:
action def RouteAcceptThroughPort {
port communicationPort : CommunicationPort;
accept alert : FaultSignal via communicationPort;
}
accept alert : FaultSignal via communicationPort says: wait for a FaultSignal arriving on the communicationPort. The via keyword selects which incoming channel the message comes from, so an accept with a port filter only fires for messages on that port.
Send and accept are the bridge between structure and behavior. The structural model defines ports and connections (Chapter 6). The behavioral model uses send and accept to say what signals travel through those connections and when.
Connecting Actions to Structure
An action definition describes behavior in the abstract. To say which part of the system performs it, you use perform inside a part definition:
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
perform action brewCycle : BrewCycle;
}
perform action brewCycle : BrewCycle says: a CoffeeMachine performs a BrewCycle. This connects the structural model (what the machine is made of) with the behavioral model (what the machine does). You can also allocate individual sub-actions to specific parts, saying that the grinder performs the grinding and the brewer performs the extraction – that is what allocate is for, covered in Chapter 6.
This separation is deliberate. The action decomposition (BrewCycle contains grind, heat, extract, dispense) is independent of the structural decomposition (CoffeeMachine contains grinder, brewer, waterTank). You can change the action decomposition without touching the structure, and vice versa. The perform relationship is the bridge between the two.
Actions That Modify State
So far every action the coffee machine has performed only reads its inputs and produces outputs – the model describes data flowing through the workflow, but nothing changes a value mid-flight. Real behavior is messier: an action increments a brew counter, flips a mode flag, or aborts a cycle when a sensor trips. SysML v2 has constructs for all three – assignments, bidirectional parameters, loops, and early termination – and they all live inside action bodies, the same bodies you have been writing.
Assignment
An assignment mutates a value as the workflow runs. It binds an expression to an attribute or a parameter reference with the := operator:
assign <target> := <expression>;
Here is a brew cycle that records how many brews it has run:
action def BrewCycle {
inout attribute brewCycles : Integer;
assign brewCycles := brewCycles + 1;
}
assign brewCycles := brewCycles + 1 says: take the current value of brewCycles, add one to it, and write the result back. This is an assignment – it runs when the action body executes, not when the model is parsed. It is different from declaring an attribute with an initial value (which is set once when the part is created), and different from a calc (which is a pure function of its inputs). An assignment is a side effect on a binding the caller owns.
That is why the target has to be something the action can reach back out to. Writing to a plain in parameter would be pointless – the caller would never see the change. The next section makes the mechanics explicit.
inout parameters
Parameters come in three directions. in carries a value into the action; out carries a value out of it. inout does both: the caller supplies an initial value, the action can read it and write it back:
action def ToggleMode {
inout attribute espressoMode : Boolean;
}
inout attribute espressoMode : Boolean says: the caller hands the action the current value of espressoMode, and any change the action makes is visible to the caller when the action completes. Inside the action body, espressoMode reads like an in and writes like an out.
Use inout whenever the natural model of the behavior is “update this thing in place” rather than “take an old value, return a new one”. A mode toggle, a running counter, a shared status flag – all of these want inout, because the same binding carries the value in and the updated value out.
While loops
Not every workflow is a fixed sequence of steps. Sometimes you need to keep doing something as long as a condition holds. A while loop runs its body repeatedly until a guard becomes false:
while <condition> { ... }
Stir the water until it reaches the target temperature:
action def HeatAndStir {
in attribute targetTemp : Real;
inout attribute currentTemp : Real;
while currentTemp < targetTemp {
action stir : Stir;
assign currentTemp := currentTemp + 1.0;
}
}
while currentTemp < targetTemp { ... } says: as long as currentTemp is below targetTemp, keep running the actions inside the braces. The condition is evaluated at the start of each iteration; when it becomes false, the loop exits and execution continues after the closing brace.
Reach for while when the number of iterations is not known up front – a polling loop, a feedback controller, a “keep trying until the sensor is happy” pattern. If you already know how many times to run, the next loop is clearer.
For loops
When you have a collection and want to do something once per element, a for loop iterates over it:
for <item> in <collection> { ... }
Process each brew request in a queue:
action def FulfillRequest { in item order : BrewRequest; }
action def ProcessBrewQueue {
in item brewRequests : BrewRequest[0..*];
out attribute successCount : Integer;
assign successCount := 0;
for request : BrewRequest in brewRequests {
action brew : FulfillRequest {
in item :>> order = request;
}
assign successCount := successCount + 1;
}
}
for request : BrewRequest in brewRequests { ... } says: bind request to each element of brewRequests in turn and run the body once per element. Inside the body, request refers to the current element. The loop runs over the whole sequence; when it is done, execution continues after the loop.
for is the loop to reach for when the iteration is driven by data – one pass per item in a collection – rather than by a runtime condition. It keeps the “does this run the right number of times?” question off the reviewer’s plate: the answer is “once per element”.
The loop variable is in scope inside the loop body. A declaration of the request type alone is not an iterable collection; supply an actual parameter or feature such as brewRequests.
Terminate
A workflow should be able to abort early when something goes wrong. The terminate action stops the enclosing action immediately and returns control to the caller:
terminate;
Abort a brew if the temperature is unsafe:
action def BrewCycle {
port panelPort : CommunicationPort;
in attribute temperature : Real;
if temperature > 105.0 {
send new FaultSignal() via panelPort;
terminate;
}
then action extract : ExtractCoffee;
}
terminate; says: stop this action right now. No further actions in the current scope run – the extract step below the guard never executes. The fault signal has already been sent; the caller is handed back control with the action in an aborted state.
Use terminate for hard cutoffs: a safety interlock that must not let the rest of the cycle proceed, a validation failure that makes the rest of the work meaningless. It is the action equivalent of an early return – reach for it when nothing later in the body should run.
The Story So Far
Summary
The coffee machine now has behavior. Here is what the model captures after this chapter:
- Action definitions for each step:
GrindBeans,HeatWater,ExtractEspresso,ExtractDrip,DispenseCoffee. - A composed workflow (
BrewCycle) that sequences, parallelizes, and branches those steps. - Parameters that thread data (beans, water, coffee) through the workflow.
- Control flow with fork/join for parallelism and decide/merge for branching.
- Send and accept for event-driven communication between parts.
- Message routing with
via <port>to direct signals through a specific channel. - Assignment (
:=) andinoutparameters for state a workflow mutates in place. - Loops –
whilefor condition-driven repetition,forfor collection iteration. - Terminate for an early, clean abort of an action body.
- Perform to connect actions to the parts that execute them.
Diagram
The next chapter, Chapter 8, builds on this foundation. Where actions describe what the machine does during a single brew, states describe which mode the machine is in over time: idle, brewing, cleaning, error. Actions will appear again as entry, do, and exit behaviors attached to states.
Common Mistakes
Forgetting to sequence sub-actions. If you write two action usages without any first ... then between them, SysML v2 does not assume they run in order. They have no defined ordering at all. Always add explicit successions.
Confusing fork/join with decide/merge. A fork starts all outgoing paths concurrently. A decision picks exactly one. If you use a fork where you meant a decision, your model says the system does both things at the same time – which may not be what you intended. Likewise, a join waits for all incoming paths. A merge just accepts whichever single path arrives. Mixing them up changes the semantics of your workflow.
Writing one massive action body. It is tempting to put all behavior into a single action definition with dozens of sub-actions and complex control flow. Break large actions into smaller named definitions. Each definition should represent a meaningful step that can be reviewed and discussed independently. Compose them in a top-level action the way you compose parts in a top-level structure.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch07.sysml.
States
Your coffee machine has structure – parts, ports, connections – and behavior – the BrewCycle action that grinds, heats, extracts, and dispenses. But an action describes what happens. It does not describe when the machine is allowed to do it.
A real coffee machine has operating modes. It sits idle until someone presses a button. It brews, then returns to idle. It enters a cleaning cycle periodically. It shuts down into an error mode when something goes wrong. These modes govern which actions are permitted and which transitions between modes are allowed.
SysML v2 models operating modes with states and transitions. This chapter adds a MachineStates state definition to the coffee machine, covering state definitions and usages, transitions with guards and triggers, entry and exit actions, and nested states.
Defining States
A state definition declares a reusable operating mode, the same way a part definition declares a reusable component type. The pattern should look familiar:
state def Idle;
state def Brewing;
These are definitions – blueprints for modes that can be used inside a larger state machine. By themselves, they do not say which system uses them or how they connect.
To build a state machine, you create a composite state definition that contains state usages and transitions between them:
state def MachineStates {
state idle : Idle;
state brewing : Brewing;
transition first idle then brewing;
}
The pattern mirrors what you saw with parts. state def Idle defines a type. state idle : Idle creates a usage of that type inside MachineStates. The transition says: from idle, proceed to brewing.
The keyword first in transition first idle then brewing identifies the source state. The keyword then identifies the target. Read it as: “transition, starting from idle, then go to brewing.”
Building the Coffee Machine States
The coffee machine needs four operating modes: idle (waiting for input), brewing (making coffee), cleaning (maintenance cycle), and error (fault detected). Start with the definitions and a containing state machine:
package CoffeeMachineStates {
state def Idle;
state def Brewing;
state def Cleaning;
state def Error;
state def MachineStates {
state idle : Idle;
state brewing : Brewing;
state cleaning : Cleaning;
state error : Error;
transition first idle then brewing;
transition first brewing then idle;
transition first idle then cleaning;
transition first cleaning then idle;
}
}
The project’s operating-mode view includes the brew and steam modes. Follow the arrows to distinguish the initial state from the states reachable later.
This is a valid state machine, but it is too permissive. Nothing prevents the machine from transitioning to brewing when there is no water, or from leaving error without intervention. Every transition fires unconditionally. You need guards.
Guards
A guard is a boolean condition on a transition. The transition only fires when the guard evaluates to true. In SysML v2, you write a guard with the if keyword after the source state:
transition first <source> if <condition> then <target>;
Add guards to the coffee machine transitions. Assume the machine has boolean attributes that represent sensor readings:
package CoffeeMachineStates {
private import ScalarValues::*;
attribute def StartBrewSignal;
attribute def StartCleanSignal;
state def Idle;
state def Brewing;
state def Cleaning;
state def Error;
state def MachineStates {
attribute waterAvailable : Boolean;
attribute cupDetected : Boolean;
attribute brewComplete : Boolean;
attribute cleanComplete : Boolean;
attribute faultDetected : Boolean;
state idle : Idle;
state brewing : Brewing;
state cleaning : Cleaning;
state error : Error;
transition first idle
if waterAvailable and cupDetected
then brewing;
transition first brewing
if brewComplete
then idle;
transition first idle
if cleanComplete == false
then cleaning;
transition first cleaning
if cleanComplete
then idle;
transition first idle
if faultDetected
then error;
transition first brewing
if faultDetected
then error;
}
}
Now the idle-to-brewing transition only fires when water is available and a cup is detected. The brewing-to-idle transition only fires when the brew cycle has completed. And any state can reach error when a fault is detected.
Guards make transition intent explicit. A reviewer reading this model can see exactly what conditions must hold for each mode change. This is especially valuable for safety-critical transitions – you do not want the machine to start brewing with no cup in place.
Triggers
Guards check conditions, but they do not say what event initiates the transition. A trigger specifies the event that causes a transition to fire. In SysML v2, triggers use the accept keyword:
transition first <source> accept <event> then <target>;
The event is typically an attribute definition that represents a signal. You define the signal type, then reference it in the transition:
attribute def StartBrewSignal;
state def MachineStates {
attribute waterAvailable : Boolean;
attribute cupDetected : Boolean;
state idle : Idle;
state brewing : Brewing;
transition first idle
accept StartBrewSignal
if waterAvailable and cupDetected
then brewing;
}
Read this as: “When the machine is in idle and receives a StartBrewSignal, if water is available and a cup is detected, transition to brewing.”
Triggers and guards work together. The trigger says what event to respond to. The guard says whether the response is allowed. You can have a trigger without a guard (always respond to the event), a completion transition qualified by a guard, or both.
Time-driven triggers: accept after
Some transitions fire on the passage of time rather than on an external signal. The spec gives you accept after(<duration>) for that case, with duration literals using SI time-units:
transition first heating accept after(30 [s]) then ready;
transition first cooling accept after(0.5 [s]) then off;
transition first warming accept after(t_dead) then idle; // a duration-valued attribute
Use a duration-valued quantity, such as 0.5 [SI::s]. Do not assume that every prefixed unit symbol is declared under that spelling in the installed library. The duration argument is a real expression: a literal like 30 [s], a model attribute like t_dead, or a calc result.
accept after is one member of a small family of trigger constructors from the spec stdlib (Triggers.kerml). The other two move the triggering event off the passage of time and onto a moment or a condition.
Condition triggers: when
A condition trigger fires when a Boolean condition becomes true, rather than when an external signal arrives. The spec constructor is TriggerWhen; in the textual form you write it on the transition as a when clause:
transition first <source> accept when <condition> then <target>;
Stand down the brewer once the water is hot enough:
transition first brewing accept when waterTemp >= 92.0 then ready;
accept when waterTemp >= 92.0 says: while the machine is in brewing, watch waterTemp; the instant the condition changes from false to true, the transition fires. Note the difference from a guard. A guard (if) is evaluated at the moment a trigger event occurs and decides whether the response is allowed. A when trigger is the event – it watches the condition continuously and fires the transition the moment it becomes true, with no external signal involved.
when describes a change in the truth of a condition. It does not specify an integration algorithm or the numerical accuracy of a threshold crossing.
Absolute-time triggers: at
after is relative – d time units elapse in the source state. at is absolute – the transition fires at a specific moment on the clock. The spec constructor is TriggerAt:
transition first <source> accept at <time-expression> then <target>;
Start the clean cycle on a schedule:
attribute cleanTime : Time::TimeInstantValue;
transition first idle accept at cleanTime then cleaning;
accept at cleanTime says: when the machine is in idle, fire the transition at the clock instant named by cleanTime. cleanTime is a point on the timeline, not a duration – so at is what you reach for when the trigger is a deadline or a schedule, where after is what you reach for when the trigger is “wait, then go”.
Transitions on port messages
Every trigger so far listens for a signal by name. But the signal can also be a message arriving on a specific port. The via keyword (the same one you saw on action send/accept in Chapter 7) routes the trigger to a particular channel:
transition first <source> accept <name> : <Signal> via <port> then <target>;
Suppose the brewer exposes a dispensePort and emits CupReady on it when a cup is in place. The machine dispenses only when that specific port reports readiness:
port def DispensePort {
out item ready : CupReady;
}
part def Brewer {
port dispensePort : DispensePort;
}
state def DispenseControl {
part brewer : Brewer;
state brewing; state dispensing;
transition first brewing
accept cup : CupReady via brewer.dispensePort
then dispensing;
}
accept cup : CupReady via brewer.dispensePort says: wait for a CupReady message arriving on brewer.dispensePort, and bind it to cup when it arrives. The via <port> clause makes the trigger precise about which connection carries the message, instead of listening for any CupReady in the machine’s namespace.
Port-message triggers pay off in component architectures where several parts emit the same signal type on different ports; via is how you say which one this transition is waiting on.
Entry actions as full expressions
The body of an entry or exit action does not have to be a plain reference to an action declared elsewhere. It can be an inline action with a body of its own – an assignment, a nested step, or a sequence of these – so you can drive state-local computation from the state itself rather than through a separate action def.
state Brewing {
entry action setPower { assign brewer.heaterPower := 1500.0; }
exit action clearPower { assign brewer.heaterPower := 0.0; }
}
When the entry/exit logic is reused across states, lift it into an action def. When it is a single in-place setting or a one-line calc, write it inline.
Entry and Exit Actions
When the machine enters a state, it often needs to do something – turn on a heater, start a timer, display a status message. When it leaves a state, it may need to clean up – turn off a pump, reset a counter. SysML v2 models these with entry and exit actions inside a state.
action def LogMessage;
action def StartHeating;
action def StopHeating;
state def Brewing {
entry action : StartHeating;
exit action : StopHeating;
}
The entry action runs every time the machine enters the Brewing state. The exit action runs every time it leaves. These are guarantees: no matter which transition enters Brewing, the heater starts. No matter which transition leaves, the heater stops.
There is also a do action, which runs continuously while the state is active:
action def MonitorTemperature;
state def Brewing {
entry action : StartHeating;
do action : MonitorTemperature;
exit action : StopHeating;
}
The do action is the ongoing behavior of the state. Think of entry as setup, do as the main work, and exit as teardown.
The Full Coffee Machine State Model
Putting it all together – states, transitions with guards and triggers, and entry/exit actions:
package CoffeeMachineStates {
private import ScalarValues::*;
// Signal definitions for triggers
attribute def StartBrewSignal;
attribute def StartCleanSignal;
attribute def FaultSignal;
attribute def ResetSignal;
// Action definitions for entry/exit
action def LogStatus;
action def StartHeating;
action def StopHeating;
action def RunCleanCycle;
action def StopCleanCycle;
action def DisableOutputs;
// State definitions with entry/exit behavior
state def Idle {
entry action : LogStatus;
}
state def Brewing {
entry action : StartHeating;
exit action : StopHeating;
}
state def Cleaning {
entry action : RunCleanCycle;
exit action : StopCleanCycle;
}
state def Error {
entry action : DisableOutputs;
}
// The composite state machine
state def MachineStates {
attribute waterAvailable : Boolean;
attribute cupDetected : Boolean;
attribute brewComplete : Boolean;
attribute cleanComplete : Boolean;
state idle : Idle;
state brewing : Brewing;
state cleaning : Cleaning;
state error : Error;
// Start in idle
entry; then idle;
// Idle -> Brewing: user requests brew, preconditions met
transition first idle
accept StartBrewSignal
if waterAvailable and cupDetected
then brewing;
// Brewing -> Idle: brew cycle finished
transition first brewing
if brewComplete
then idle;
// Idle -> Cleaning: user requests cleaning
transition first idle
accept StartCleanSignal
then cleaning;
// Cleaning -> Idle: clean cycle finished
transition first cleaning
if cleanComplete
then idle;
// Any operational state -> Error: fault detected
transition first idle
accept FaultSignal
then error;
transition first brewing
accept FaultSignal
then error;
transition first cleaning
accept FaultSignal
then error;
// Error -> Idle: operator resets
transition first error
accept ResetSignal
then idle;
}
}
Several things to notice:
entry; then idle;at the top ofMachineStatesdeclares the initial state. When the state machine starts, it entersidlefirst.- Each state definition carries its own entry/exit behavior.
Brewingalways starts the heater on entry and stops it on exit, regardless of which transition enters or leaves. - The
FaultSignaltransitions are repeated for each source state. In SysML v2, each transition has exactly one source and one target. If three states can reacherror, you write three transitions. - The
ResetSignaltransition fromerrorback toidleis the only way out of the error state. This is a deliberate design choice – the operator must explicitly acknowledge and reset the fault.
Nested States
States can contain substates. When the machine is brewing, it might go through sub-modes: heating, extracting, and dispensing. You model this by putting state usages inside a state definition:
state def Brewing {
entry action : StartHeating; then heating;
state heating;
state extracting;
state dispensing;
transition first heating
then extracting;
transition first extracting
then dispensing;
exit action : StopHeating;
}
From the outside, the machine is in Brewing. From the inside, it moves through heating, extracting, and dispensing as substates. When the final substate completes, the Brewing state itself completes, and the outer state machine transitions to whatever follows.
Nested states are useful when a single operating mode has internal phases, but the rest of the system only needs to know about the outer mode. Keep nesting shallow – one level of substates covers most real systems. Deep nesting makes models hard to review.
Parallel States
Recall the closing remark from the full model above: “The FaultSignal transitions are repeated for each source state. If three states can reach error, you write three transitions.” That repetition is not just tedious – it is fragile. Add a fourth operational state, and you have to remember to give it a FaultSignal transition too. Miss one, and your machine can sit in that state forever ignoring a fault.
The reason this hurts is that the model treats a fault as something each operational mode has to anticipate individually. But a fault is not a property of brewing or cleaning – it is a property of the machine as a whole, one that should be able to interrupt whichever mode is active. SysML v2 has a construct for exactly this: a state that contains parallel regions – independent sub-machines that run concurrently inside one parent state.
Defining orthogonal regions
A region is written as a state usage nested inside a composite state, just like the nested substates you have already seen. Two things are different: you include more than one, each with its own initial transition, and you mark the parent parallel. That keyword is not decoration, and the specification is explicit about what it switches: with isParallel true the owned states are all performed in parallel, and with it false only one owned state may be performed (SysML §8.3.18.5):
state def <Parent> parallel {
state <regionA> {
/* one sub-machine: states + transitions + its own entry; then ... */
}
state <regionB> {
/* a second sub-machine, running concurrently with regionA */
}
}
The parent state def contains two named sub-machines. Entering the parent enters both; neither waits on the other. Read it as: “while the machine is in <Parent>, region A and region B are each doing their own thing, in parallel.”
One constraint comes with parallel, and the specification names it. Under validateStateDefinitionParallelSubactions (SysML §8.3.18.5): if a state definition is parallel, its owned actions – which includes its owned states – must have no incoming and no outgoing transitions. Every transition a region declares stays inside that region. This is what makes the regions orthogonal – you cannot transition from a substate of one region to a substate of another, which is exactly the independence the next section relies on.
Splitting the fault out of the operational modes
Apply this to the coffee machine. Give MachineStates two regions: an operational region that runs idle, brewing, and cleaning, and a supervision region that just listens for a fault and can move the whole machine to error:
state def MachineStates parallel {
attribute brewComplete : Boolean;
attribute cleanComplete : Boolean;
attribute waterAvailable : Boolean;
attribute cupDetected : Boolean;
// Region 1: the operational lifecycle
state operational {
state idle : Idle;
state brewing : Brewing;
state cleaning : Cleaning;
entry; then idle;
transition first idle
accept StartBrewSignal
if waterAvailable and cupDetected
then brewing;
transition first brewing if brewComplete then idle;
transition first idle accept StartCleanSignal then cleaning;
transition first cleaning if cleanComplete then idle;
}
// Region 2: fault supervision, running concurrently
state supervision {
state armed;
state error : Error;
entry; then armed;
transition first armed accept FaultSignal then error;
transition first error accept ResetSignal then armed;
}
}
Now the fault lives in one place. The supervision region has a single FaultSignal transition, regardless of how many operational modes exist in the other region. Add a fifth or sixth operational state to the operational region and you do not touch the fault handling at all.
The trade-off is that the two regions are independent. A region does not know which substate of its sibling is active. If the fault recovery needed to behave differently depending on whether the machine was brewing or cleaning, a single supervision region would not be enough – you would be back to per-mode transitions (or you would model that knowledge a different way). Reach for parallel regions when a concern truly cuts across all the sibling substates, not when it branches on them.
Completion
SysML v2 has no final marker on a state. What it has instead is a pair of boundary states that every state inherits. States::StateAction, the standard library’s base type for every state definition, declares ref state start and ref state done – the starting and ending snapshots of the state’s performance. You mark completion by transitioning to done:
state def OneShot {
state warmup;
state ready;
entry; then warmup;
transition first warmup accept ReadySignal then ready;
transition first ready then done;
}
The last transition says: once ready has been reached, the enclosing OneShot state is finished. That is the same shape the standard library uses for its own state machines – Actions.sysml writes transition aTransition first start accept apayload: Anything via receiver then done;. start and done are ordinary inherited features, so you reference them by name like any other substate; there is no keyword to remember.
In the MachineStates model above, nothing transitions to done, so the machine never completes on its own – which is what you want for a machine that runs until it is switched off.
Resuming an interrupted region
When a region is interrupted – by a fault, by its parent being exited and re-entered, or by a transition that points at the composite from the outside – it restarts from its initial substate. Sometimes that is wrong. A brew interrupted by a clean cycle should, on returning to brewing, pick up where it left off, not restart grinding.
SysML v2 has no history pseudostate. If you are coming from SysML v1 or UML, this is one of the constructs that did not carry over: there is no shallow or deep history marker in the language, and no library element that stands in for one. Resuming is something you model explicitly.
The straightforward way is to keep the last active substate in an attribute and branch on it when the region is re-entered:
state def BrewPhases {
attribute resumeAt : String;
state dispatch;
state grinding { entry action markGrinding { assign resumeAt := "grinding"; } }
state extracting { entry action markExtracting { assign resumeAt := "extracting"; } }
entry; then dispatch;
// Re-entry branches on the recorded phase instead of always restarting
transition first dispatch if resumeAt == "extracting" then extracting;
transition first dispatch if resumeAt != "extracting" then grinding;
transition first grinding accept PhaseDone then extracting;
}
Each phase records that it was entered; a small dispatch state reads that record and routes to the right phase using ordinary guarded transitions. It is more verbose than a history marker, but the state being remembered is now a visible part of the model – which is what a reviewer needs anyway. Deep history has no shorthand either: nest the same pattern, one attribute per level.
Parallel regions and their local transitions are model constructs. A run chooses an order when concurrent steps are enabled: one trace is not proof that all permitted schedules have the same outcome.
Completion Transitions
Every transition so far has an explicit trigger – a signal, a duration, a condition, a port message. But a state that runs a do behavior has one more way to leave: it can finish. A completion transition fires when the source state’s do behavior completes, with no trigger written at all:
transition first <source> then <target>;
The absence of a trigger is the trigger. The Brewing state from the nested-states section runs MonitorTemperature as its do action; when that action ends, the state is done, and a completion transition can carry the machine onward. Like every transition, it connects state usages, so it lives in the containing state machine:
state def Brewing {
entry action : StartHeating;
do action : MonitorTemperature;
exit action : StopHeating;
}
state def Dispensing;
state def BrewSequence {
state brewing : Brewing;
state dispensing : Dispensing;
transition first brewing then dispensing; // fires when brewing's `do` completes
}
Read it as: “when the brewing state is done, go to dispensing.” No accept, no when, no after – the completion of the do behavior is the implicit event.
Completion is stricter in a parallel composite: the parent is not finished while any region is still running. Since there is no final marker in the language, a region signals that it is finished the way any state does – by transitioning to its inherited done state, as in the OneShot example above.
Exhibiting State Machines on Parts
So far the state machine has lived in its own state def MachineStates, separate from the parts it governs. SysML v2 also lets a part carry its own state machine inline, with the exhibit keyword.
part def <Part> {
exhibit state <name> { <states and transitions> };
}
Give the brewer its own small lifecycle, owned by the part rather than declared outside it:
part def Brewer {
attribute waterTemp : Real;
exhibit state brewingMode {
state heating;
state ready;
entry; then heating;
transition first heating accept when waterTemp >= 92.0 then ready;
}
}
exhibit state brewingMode { ... } says: every Brewer instance runs its own brewingMode state machine. The states and transitions live inside the part definition, so a reviewer reading Brewer sees the part’s structure and its lifecycle in one place.
Exhibiting is the structural counterpart to the parallel regions from earlier. Parallel regions live inside a composite state and share one machine. An exhibit lives on a part and is owned by that part – the part’s internal modes are its own API, and other parts reach them by sending signals to that part. Reach for exhibit when a component’s modes are nobody else’s business; reach for a shared state def when the modes are a property of the system the parts belong to.
States and Actions Together
States and actions serve different roles. Actions describe what happens – the sequence of steps in a brew cycle. States describe when things are allowed – the machine must be in Idle before it can start brewing.
In a complete model, you connect them. The do action inside a state can reference an action definition:
action def BrewCycle {
action grind : GrindBeans;
action heat : HeatWater;
action extract : ExtractCoffee;
action dispense : DispenseCoffee;
first grind then heat;
first heat then extract;
first extract then dispense;
}
state def Brewing {
entry action : StartHeating;
do action : BrewCycle;
exit action : StopHeating;
}
When the machine enters Brewing, it runs StartHeating, then executes BrewCycle as its ongoing behavior, and runs StopHeating when it leaves. The state governs the lifecycle; the action governs the procedure.
A discrete state can select which physical equation applies, for example heat input while the heater is on. This is the difference between a controller mode and a continuous state variable such as temperature (Appendix E).
Common Mistakes
Forgetting the initial state. A composite state definition without entry; then <state>; has no defined starting point. Reviewers and tools will not know which substate activates first. Always declare the initial transition.
Omitting guards on safety-critical transitions. An unguarded transition from idle to brewing means the machine can start brewing at any time – no water check, no cup check. If a transition has safety implications, give it a guard. The guard makes the precondition visible in the model, not hidden in implementation code.
Using states where actions belong. If a “state” has no transitions into or out of it and just runs a fixed sequence of steps, it is probably an action, not a state. States model modes that the system can be in. Actions model procedures that the system performs. The test is: can the system stay in this mode indefinitely, waiting for an event? If yes, it is a state. If it always runs to completion, it is an action.
What You Have Built
The detailed lifecycle view includes the nested machines. To read a transition, locate its source and target before examining its trigger.
The coffee machine now has a complete lifecycle model. MachineStates defines four operating modes with guarded, triggered transitions between them. Entry and exit actions ensure consistent setup and teardown. The initial state is explicit, the error state requires a deliberate reset, and the guard on idle to brewing enforces preconditions that a reviewer can inspect.
In Chapter 9, you will add constraints – checkable logic that makes properties like temperature ranges and safety interlocks part of the model itself.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch08.sysml.
Expressions and Constraints
So far, the coffee machine model describes what the system is and what it does. It has structure (parts, ports, connections), behavior (actions with control flow), and modes (states with guarded transitions). What it cannot do yet is answer a quantitative question: Is the brew temperature correct? Is it safe to dispense?
This chapter adds checkable logic. You will write expressions that compute values, define calculations that can be reused, and create constraints that the model must satisfy. By the end, the coffee machine will have a temperature target calculation, a safety interlock constraint, and the language vocabulary you need to read every expression in the book.
Expression Basics
An expression in SysML v2 is any combination of values and operators that produces a result. You have already seen simple expressions in attribute defaults and transition guards. Now we look at the full operator set.
The everyday operators come in four families:
Arithmetic: +, -, *, /
Relational: <, >, <=, >=
Equality: ==, !=
Logical: and, or, not, xor, implies, and the eager pair & and |
These work the way you expect from engineering math. Arithmetic operators produce numeric results. Relational and equality operators produce Boolean results. Logical operators combine booleans.
Here is an expression that checks whether a temperature is within brewing range:
waterTemp >= 90.0 and waterTemp <= 96.0
And one that computes a total cycle time:
grindSeconds + heatSeconds + extractSeconds
Both are just expressions – sequences of values and operators. They become useful when you put them inside calculations and constraints.
and or &? They are not the same
There are two spellings of logical conjunction, and the difference is the one you know from programming languages even though it is spelled differently here.
and is conditional. In the grammar its right-hand side is a reference to
an expression rather than the expression itself, which is what lets it be left
unevaluated when the left side already decides the answer. & is eager: both
sides are plain operands and both are evaluated. or and | divide the same way.
That matters when the right-hand side is expensive or unsafe:
constraint def SafeToBrew {
in waterTank : WaterTank[0..1];
in minimumLevel : Real;
doc /* The second test is only reached when a tank is present. */
waterTank != null and waterTank.level > minimumLevel
}
With and, the level is never read when there is no tank. With & it would be.
Prefer and and or – they are the safer default and what the rest of this
book uses. Reach for & or | only when you actually want both sides evaluated
regardless.
Try
sysml -e "true and false"to evaluate a closed Boolean expression. An expression involvingwaterTankalso needs a model and a value for that feature.
xor is exclusive or, and implies is logical implication – a implies b is
false only when a is true and b is false. Both are ordinary infix operators,
and both evaluate: sysml -e 'true xor false' gives true, and
sysml -e 'true implies false' gives false.
Operator Precedence and Parentheses
SysML v2 follows standard mathematical precedence: multiplication and division bind tighter than addition and subtraction, relational operators bind tighter than logical ones. But relying on precedence in complex expressions is a recipe for review comments.
Compare these two:
not brewCommand or cupDetected and lidClosed
(not brewCommand) or (cupDetected and lidClosed)
They mean the same thing, but only the second one is obvious at a glance. Parentheses cost nothing to write and save time in every review. Use them whenever an expression has more than one logical operator.
Operators Beyond the Basics
The four families above cover most everyday model logic. The language has more, and you need them once your model gets serious.
Power and modulo. ** (or ^) raises to a power, % is integer remainder.
attribute squaredTemperatureError = tempDelta ** 2;
attribute selfTestSlot = cycleNumber % 10; // every tenth cycle is a self-test
More logical operators. Beyond and, or, not, the spec gives you xor (exclusive or) and implies (logical implication). They are useful when a boolean condition reads more naturally as one of these forms:
attribute brewOk = brewRequested implies cupPresent; // identical to: not brewRequested or cupPresent
attribute exactlyOne = manualOverride xor scheduledRun; // exactly one is active at a time
Null coalescing. ?? returns its left operand if that operand has a value, otherwise its right operand. Use it for defaulting:
configuredTargetTemp ?? 93.0
If configuredTargetTemp is set, you get that value; otherwise you get 93.0. This is far cleaner than if configuredTargetTemp != null ? configuredTargetTemp else 93.0.
Type tests and coercion. istype, hastype, and as ask and answer questions about an element’s classification:
attribute isExactly = sensor istype Thermistor; // is `sensor` exactly Thermistor?
attribute isAKind = sensor hastype Sensor; // is `sensor` Sensor or any subtype?
ref part coerced = sensor as Thermistor; // treat sensor as a Thermistor
istype is exact; hastype includes subtypes; as is a coercion that gives you access to the more specific feature set.
Sequence operators. When an attribute has multiplicity greater than one, you have a sequence, and you operate on it with -> operators. The per-element rule goes in a body expression – braces holding an in parameter, a ;, and the expression over that parameter:
ref part highPower = brewers->select {in b : Brewer; b.power > 1000.0}; // filter
attribute allTargets = brewers->collect {in b : Brewer; b.targetTemp}; // map
ref part healthy = brewers->reject {in b : Brewer; b.fault}; // filter (negated)
attribute allBelow = brewers->forAll {in b : Brewer; b.targetTemp <= 100.0}; // every element satisfies
attribute anyFault = brewers->exists {in b : Brewer; b.fault}; // some element satisfies
These compose. A common pattern is “is every brewer’s temperature in the safe range?”:
brewers->forAll {in b : Brewer; b.waterTemp >= 90.0 and b.waterTemp <= 96.0}
You will reach for ->forAll and ->select constantly once a model has any non-trivial structure. They turn what would be a repeated constraint into one rule that scales with the part count.
Indexing and ranges. #(n) selects the n’th element of a sequence; .. builds a range:
ref part firstBrewer = brewers#(1); // first brewer
attribute cycleNumbers = 1..5; // sequence 1, 2, 3, 4, 5
Metadata access. @ reads a metadata annotation; @@ reads all annotations of a kind. You will see these in Chapter 13, where metadata drives view rendering.
Qualified enumeration references. When two enumerations share a literal name, qualify the reference with :::
mode == BrewMode::Espresso // not just `Espresso`
Most of these operators show up rarely, but when you need ?? or ->forAll, no other operator does the job. Reach for them by name; do not work around them.
String Literals and Structured Values
So far every value in this chapter has been a number or a Boolean. SysML v2 treats strings as ordinary value types too, and it lets you build your own structured value types out of them.
String literals are written with double quotes:
attribute label : String := "Brewing";
attribute statusText : String := if waterLow ? "Low Water" else "System OK";
The quotes are not part of the value. You can include escaped characters like \" (an embedded quote) or \n (a newline) inside the literal. Strings are useful for human-readable labels and diagnostics; the next chapter uses them inside doc comments on requirements.
The second example uses the conditional expression from the next section – if <cond> ? <then> else <else> – with two string results.
Structured attribute definitions group a small, fixed set of named, typed fields into one value. There is no anonymous tuple type in the language – you name the record with an attribute def and then use it like any other type:
attribute def SensorReading {
attribute name : String;
attribute value : Real;
attribute unit : String;
}
attribute reading : SensorReading;
SensorReading is the type of a three-field record – a label, a measurement, and a unit. An attribute def is the right shape when a few values belong together (a sensor reading with its units, a coordinate’s x/y/z) but you do not need a full part def to give them an identity: an attribute value has no occurrence, no ports, and no lifecycle. Compare it to a sequence, which holds many values of one type: a structured attribute holds few values of different types, named.
The Conditional Expression
SysML v2 has a conditional expression with the syntax if <condition> ? <then-value> else <else-value>. This is not an if-statement – it is an expression that evaluates to one of two values.
if ambient < 18.0 ? 94.0 else 93.0
This reads: if the ambient temperature is below 18 degrees, the result is 94.0; otherwise 93.0. You will use this pattern in calculations where the output depends on a condition.
The ? separating the condition from the then-value is required. It prevents ambiguity in cases where the condition itself contains operators.
Calculations: Reusable Computations
A calc def defines a reusable computation. It takes typed inputs, declares a return, and contains an expression that computes the result.
calc def TargetBrewTemp {
in ambient : Real;
return result : Real = if ambient < 18.0 ? 94.0 else 93.0;
}
This says: given an ambient temperature, compute a target brew temperature. If the environment is cold (below 18 degrees), aim higher to compensate for heat loss.
A calc def is like a function in a programming language, but it lives inside your model. It has a name, typed parameters, and a body that computes a return value. The in keyword marks input parameters. The return keyword marks the output.
You can use a calculation anywhere you need its result. Inside a part, you create a usage of the calculation:
part def Brewer {
attribute waterTemp : Real;
attribute ambientTemp : Real;
calc targetTemp : TargetBrewTemp {
in :>> ambient = ambientTemp;
return :>> result;
}
}
The usage targetTemp binds the calculation’s input to a concrete attribute. Whenever ambientTemp has a value, targetTemp can be evaluated. This is how calculations connect abstract formulas to specific parts of the model.
A reference in a calculation definition must resolve where that definition is written. Pass a value through an in parameter when different callers supply it. The call can refer to an attribute in the surrounding part without putting the part name inside the reusable formula.
Computed Attributes
For one-shot values that do not need a name or reuse, SysML v2 lets you put the expression directly on an attribute:
part def Brewer {
attribute ambientTemp : Real;
attribute targetTemp : Real = if ambientTemp < 18.0 ? 94.0 else 93.0;
}
targetTemp is now an attribute whose value is computed from ambientTemp. There is no separate calc def and no usage to bind. Reading targetTemp evaluates the right-hand side; if ambientTemp is set, you get a number.
Use a computed attribute when:
- the formula appears in exactly one place,
- it has no parameters (it reads other attributes by name),
- you do not need to reuse it,
- you do not need a named contract to refer to.
Use a calc def instead when any of those things are false. A calc def is a named, parametric, reusable equation. A computed attribute is a one-shot derived value.
Computed attributes evaluate lazily on read, and they compose. You can write:
part def Brewer {
attribute ambientTemp : Real;
attribute targetTemp : Real = if ambientTemp < 18.0 ? 94.0 else 93.0;
attribute boilerLimit : Real = 100.0;
attribute headroom : Real = boilerLimit - targetTemp;
attribute safe : Boolean = headroom > 0.0;
}
Reading safe evaluates headroom, which in turn reads targetTemp, which reads ambientTemp. The evaluation order is dictated by what the reader needs; you do not write it explicitly.
Why this matters. The chapter used to suggest you wrap every conditional default in a
calc def. That is overkill for one-shot fields. Computed attributes give you a small DAG of derived values withoutin/returnceremony, and the lazy-on-read evaluation means you do not pay for them until something asks.
Equations and Overrides
Once you start treating calc defs as named equations, two things follow.
First, the body of a calc def is the equation. Every usage of that calc def is an instance of the same equation, evaluated against whatever scope the usage is in. Two parts that use TargetBrewTemp are not running two different formulas – they are running the same formula with different bindings.
Second, you can replace the bindings without touching the equation. The simplest case is at the usage site:
part highAltitudeBrewer : Brewer {
calc temperatureAtAltitude : TargetBrewTemp {
in :>> ambient = highAltitudeBrewer.ambientTemp - 5.0; // override: simulate cooler effective ambient
return :>> result;
}
}
The equation is unchanged; only the input binding moved. The same idea extends to overriding attribute values along a feature chain (boiler.power = 1500.0) or substituting a whole calc def via subclassing and :>>-redefinition. Trade studies, sensitivity sweeps, and “what if the heater were 1.5 kW” exploration all work this way.
Why this matters. Most useful analyses in a system model are not “evaluate the model once”. They are “evaluate it many times with different parameters and compare”. Once you separate equations (the calc bodies) from bindings (the values flowing in), you can vary the bindings without forking the model. Authors who do not see this distinction tend to copy entire packages just to change one number.
Calculations Over Sequences
Once a part has multiplicity, calcs over sequences become the natural way to ask system-level questions. The sequence operators from earlier (->select, ->collect, ->forAll) are first-class inside calc bodies:
calc def WorstHeadroom {
in stations : Brewer[*];
return : Real = stations->collect {in s : Brewer; s.boilerLimit - s.targetTemp}->reduce NumericalFunctions::min;
}
This calc takes a sequence of brewers and returns the smallest headroom across them all. The ->collect builds a sequence of headroom values; ->reduce NumericalFunctions::min folds that sequence to a single number by applying min pairwise. (min and max in the standard library are two-argument functions, so a sequence is reduced with them rather than aggregated by them.) The whole thing is one expression.
->forAll and ->exists are useful in constraint bodies, not just calcs:
constraint def AllStationsSafe {
in stations : Brewer[*];
stations->forAll {in s : Brewer; s.waterTemp >= 90.0 and s.waterTemp <= 96.0}
}
This says “every brewer is in the safe range”. One named constraint scales with however many brewers exist.
Why this matters. Without sequence operators in calc and constraint bodies, an author writes parallel attribute trees (“worstHeadroom1, worstHeadroom2, …”) or tries to extract aggregations into the structural model. The collection operators put the aggregation where it belongs – in the equation – and let the system grow without rewriting the calc.
Calculations as ODE Right-Hand Sides
When a calc def captures the time-derivative of a state variable, you can flag that intent by subtyping GetDerivative from the standard library’s StateSpaceRepresentation package:
private import StateSpaceRepresentation::*;
calc def HeaterRhs :> GetDerivative {
in t : Real;
in temp : Real;
in heaterPower : Real;
in lossCoeff : Real;
in thermalMass : Real;
return dT_dt : Real = (heaterPower - lossCoeff * temp) / thermalMass;
}
HeaterRhs is still an ordinary calc def. The supertype :> GetDerivative carries the contract: this calc returns the time-derivative of one named state variable. There is no special metadata, no magic string, no tool-specific annotation – just a stdlib supertype.
A second pattern, GetOutput, captures algebraic outputs as a function of state and inputs (for example, “the sensor reading is the boiler’s temp plus a fixed offset”). Together, GetDerivative and GetOutput describe a state-space block in the spec’s standard way; they are usually grouped under an action def :> ContinuousStateSpaceDynamics. All three come from StateSpaceRepresentation.
We cover ODE authoring properly in Chapter 16, which shows the coffee machine evolving over time with a heater turning on and off. For now, the only thing to take away is that the spec gives you a language shape for derivatives and algebraic outputs – you do not need to leave SysML to describe them.
A derivative is a rate. Evaluating it at one temperature gives a slope, not the next temperature; computing a trajectory also needs an initial value, a time interval and an integration method.
Constraints: Reusable Rules
A constraint def defines a reusable boolean rule. Its body is an expression that must evaluate to true for the model to be considered valid.
constraint def BrewTempInRange {
in temp : Real;
temp >= 90.0 and temp <= 96.0
}
This constraint takes a temperature and checks that it falls within the safe brewing range. It does not enforce anything on its own – it just defines the rule. Think of it as a named predicate: a question that can be answered true or false.
Constraints and calculations look similar. The difference is intent:
- A
calc defcomputes a value. Its body is an assignment:result = <expression>. - A
constraint defchecks a condition. Its body is a boolean expression with no assignment.
Both are reusable. Both take typed parameters. But a calculation answers “what is the value?” while a constraint answers “is this acceptable?”
How Constraints Find Their Values
Constraint bodies often reference attributes by short name – waterTemp, cupPresent – and you might wonder how the language decides which waterTemp. Two scoping rules cover the cases you will hit:
-
In a part context. A constraint asserted inside a part resolves names by walking the owner chain outward.
waterTempfirst looks for an attribute namedwaterTempon the part the assertion lives in, then on its owner, and so on. The first match wins. -
In a requirement context. A constraint inside a
requirement defresolves names against the requirement’s declaredsubject,actor, and parameter list. The satisfy site (covered in Chapter 10) supplies the concrete bindings.
Mixing the two scoping models is the single biggest source of “constraint always passes” or “constraint cannot find variable” failures in real models. If you assert a constraint in a part and the body references specification.inputSupply.voltage, every name on that path must resolve through the owner chain – there is no implicit “specification” sitting at the top level of the package. If the model intended specification to be a parameter, it belongs as an in parameter on the constraint or as a parameter on the surrounding requirement.
A short rule of thumb: constraints inside parts read attributes by name from the enclosing part. Constraints inside requirements read attributes by name from the requirement’s parameters and subject. If you find yourself reaching across packages to name a value, you probably want a parameter.
Asserting Constraints
A constraint definition by itself is just a template. To apply it, you use assert constraint inside a part or other context:
part def Brewer {
attribute waterTemp : Real;
attribute ambientTemp : Real;
calc targetTemp : TargetBrewTemp {
in :>> ambient = ambientTemp;
return :>> result;
}
assert constraint tempCheck : BrewTempInRange {
in :>> temp = waterTemp;
}
}
The assert constraint line does two things. First, it creates a usage of BrewTempInRange inside Brewer, binding the constraint’s temp parameter to the brewer’s waterTemp attribute. Second, the assert keyword declares that this constraint must hold – it is not just a check you could run, it is a stated requirement on this part.
An asserted constraint is a commitment. It says: in any valid instance of Brewer, waterTemp must be between 90.0 and 96.0. When the constraint is evaluated – either by a static check or as the model runs – it produces a verdict that is either true (the assertion holds) or false (it does not), with the operand values that contributed. The same machinery powers require constraint inside a requirement; we pick that up in Chapter 10.
You can also assert a constraint inline, without referencing a named definition:
assert constraint {
waterTemp >= 90.0 and waterTemp <= 96.0
}
This works for one-off checks, but named constraints are better for anything you might reuse or need to trace to a requirement.
Asserting That Something Must Not Hold
The opposite of assert constraint is assert not constraint. It says: this combination must never hold.
part def Brewer {
attribute dispenseRequested : Boolean;
attribute cupPresent : Boolean;
assert not constraint {
dispenseRequested and not cupPresent
}
}
This reads cleanly as “it must never be the case that a dispense was requested with no cup present”. You could write the same rule as a positive assertion – assert constraint { not dispenseRequested or cupPresent } – but the negated form usually reads better when the unsafe combination is what you care about.
assert not is a separate language form, not just a textual transformation. Use it whenever the rule you want to express is “this must never be true.”
Building the Coffee Machine’s Logic
The coffee machine from previous chapters has structure, connections, actions, and states. Now add the quantitative logic that makes it checkable.
The Temperature Calculation
The brewer needs to know what temperature to target. That depends on ambient conditions – a cold room means more heat loss, so the target should be higher. This is exactly what calc def is for:
package CoffeeMachineAnalysis {
private import ScalarValues::*;
private import CoffeeMachineDomain::*;
calc def TargetBrewTemp {
in ambient : Real;
return target : Real = if ambient < 18.0 ? 94.0 else 93.0;
}
}
This is a simple two-branch formula. In a real system, it might be a polynomial curve fit or a lookup table. The point is that it lives in one place with a clear name, typed inputs, and a typed output.
The Safety Interlock
A coffee machine should not dispense hot water unless a cup is present. This is a safety interlock – a boolean rule that must be satisfied before the brew action proceeds:
package CoffeeMachineAnalysis {
private import ScalarValues::*;
private import CoffeeMachineDomain::*;
calc def TargetBrewTemp {
in ambient : Real;
return target : Real = if ambient < 18.0 ? 94.0 else 93.0;
}
constraint def SafetyInterlock {
in cupDetected : Boolean;
in brewCommand : Boolean;
not brewCommand or cupDetected
}
}
Read the constraint body carefully: not brewCommand or cupDetected. This is the logical implication “if brewCommand, then cupDetected.” It evaluates to true in three cases: no brew command was given, a cup is detected, or both. It is false only when a brew is commanded with no cup present – exactly the unsafe condition.
You could write the same rule using implies:
constraint def SafetyInterlock {
in cupDetected : Boolean;
in brewCommand : Boolean;
brewCommand implies cupDetected
}
Both forms mean the same thing. implies reads more naturally when the rule is “A requires B”; not A or B reads more naturally when you want the user to see both branches.
Applying Both to the Machine
Now bring the calculation and constraint into the coffee machine structure:
package CoffeeMachineSystem {
private import ScalarValues::*;
private import CoffeeMachineDomain::*;
private import CoffeeMachineAnalysis::*;
part coffeeMachine : CoffeeMachine {
attribute ambientTemp : Real;
attribute cupPresent : Boolean;
attribute brewRequested : Boolean;
part :>> brewer : Brewer {
calc targetTemp : TargetBrewTemp {
in :>> ambient = coffeeMachine.ambientTemp;
return :>> result;
}
assert constraint tempSafe : BrewTempInRange {
in :>> temp = waterTemp;
}
}
assert constraint interlock : SafetyInterlock {
in :>> cupDetected = cupPresent;
in :>> brewCommand = brewRequested;
}
}
}
Two things are asserted here. Inside brewer, the tempSafe constraint checks that the actual water temperature stays within range. At the machine level, the interlock constraint checks that no brew can happen without a cup. Both are named, both are traceable, and both can be verified independently.
The targetTemp calculation inside brewer binds to the machine’s ambient temperature. It does not enforce anything – it computes the target. The tempSafe constraint checks that the actual temperature (measured by a sensor, represented by waterTemp) stays in range. These are complementary: the calculation says what the temperature should be, and the constraint says what range is acceptable.
Calculations with Multiple Inputs
A calculation can take as many inputs as needed. Here is one that estimates the total brew cycle time:
calc def BrewCycleTime {
in grindSeconds : Real;
in heatSeconds : Real;
in extractSeconds : Real;
return total : Real = grindSeconds + heatSeconds + extractSeconds;
}
And a more interesting one that adjusts extraction time based on grind size:
calc def AdjustedExtractTime {
in baseSeconds : Real;
in grindFactor : Real;
return adjusted : Real = baseSeconds * grindFactor;
}
You can compose calculations by using one calculation’s output as another’s input. This lets you build up complex formulas from simple, testable pieces.
Constraints with Multiple Conditions
A single constraint can check several conditions at once using logical operators:
constraint def ReadyToBrew {
in waterLevel : Real;
in minWaterLevel : Real;
in temp : Real;
in cupPresent : Boolean;
cupPresent and waterLevel >= minWaterLevel
and temp >= 90.0 and temp <= 96.0
}
This combines three checks: cup is present, water level is sufficient, and temperature is in range. It is a single named rule that answers a clear engineering question: is the machine ready to brew?
When a compound constraint like this gets long, consider splitting it. You already have BrewTempInRange and SafetyInterlock as separate constraints. A composite constraint can reference them conceptually while keeping the logic explicit.
When to Use What
Expressions, calculations, and constraints serve different purposes. Here is when to reach for each:
Use a bare expression when you need a one-time value – an attribute default, a transition guard, or a simple formula that appears in exactly one place.
Use a computed attribute when the value is derived from other attributes in the same part, and you do not need parameters or a name to refer to it elsewhere.
Use calc def when a computation is reusable, has clear inputs and outputs, or is complex enough to deserve a name. If you find yourself writing the same arithmetic in two places, extract it into a calculation.
Use constraint def when a boolean rule represents an engineering requirement – a range check, a safety condition, or an interlock. If someone might ask “where is that rule defined?” it should be a named constraint.
Use assert constraint to commit to a rule in a specific context. An unasserted constraint is just a definition sitting on a shelf. Assertion is what makes it binding.
Use assert not constraint when the rule you want is “this combination must never happen.” The negated form often reads better than its positive equivalent.
Reading Constraints as Math
Every expression you write in SysML v2 has a clean mathematical reading. Reviewers and stakeholders often see the math form before they see the source. Knowing the operator-to-notation correspondence makes constraints easier to read in both directions:
| Source | Math notation |
|---|---|
>=, <=, != | ≥, ≤, ≠ |
and, or, not | ∧, ∨, ¬ |
implies | ⇒ |
^ or ** | superscript: xⁿ |
/ | fraction: a / b |
abs(x) | ` |
sqrt(x) | √x |
brewer.boiler.power | subscripted identifier |
So temp >= 90.0 and temp <= 96.0 reads as 90.0 ≤ temp ≤ 96.0, and not brewCommand or cupDetected reads as ¬brewCommand ∨ cupDetected. When a constraint is hard to read in source form, try writing it the way it would render mathematically – often the cleaner phrasing is the one that translates directly. Prefer abs(x) over an ad-hoc conditional, prefer implies over not A or B when the rule is “A requires B”, and prefer pow(x, 2) over x ** 2 when the constraint is going to be reviewed verbally.
Common Mistakes
Writing constraints that do not evaluate to boolean. A constraint body must be an expression that produces true or false. If you accidentally write an arithmetic expression (like a + b) instead of a comparison (like a + b <= limit), the model will not check.
Forgetting to assert. Defining a constraint def does nothing until you assert it somewhere. If you define SafetyInterlock but never write assert constraint ... : SafetyInterlock, the rule exists in the model but is never checked. This is the most common oversight when adding constraints.
Duplicating logic instead of naming it. If the expression waterTemp >= 90.0 and waterTemp <= 96.0 appears in three places, a change to the range requires three edits. Define it once as a constraint def and reference it wherever needed.
Using calculations where constraints belong. If you write a calc def that returns a boolean, ask yourself whether it should be a constraint def instead. Calculations compute values; constraints check conditions. Using the right one makes the model’s intent clearer to reviewers.
Referencing an attribute that has no assigned value. When a constraint walks a chain like specification.inputSupply.busbarCurrentRating, every step must resolve to a bound value. If specification is declared but never given a binding (no part instance, no :>> redefinition, no satisfy site supplying it), the chain cannot evaluate. The fix is almost always to make the missing binding explicit – either declare the constraint inside a part that owns those features, or add the missing values as in parameters and let the satisfy site supply them. The error you see at evaluation time will name the unbound variable; treat it as a model-completeness signal, not a bug in the constraint.
What Comes Next
The coffee machine now has checkable logic: a temperature calculation that adapts to ambient conditions, a safety interlock that prevents dispensing without a cup, and the language vocabulary – expanded operators, equations, sequence calculations, computed attributes, and asserted constraints both positive and negated – to write the rest of the system.
In Chapter 10, you will turn these engineering rules into formal requirements and trace them from stakeholder intent through design to verification evidence. The constraints you defined here will become the “satisfy” targets that link requirements to the model.
In Chapter 16, you will let the same model run – ODE state variables advancing in time, calc defs serving as right-hand sides, asserted constraints firing per-tick as live monitors. The :> GetDerivative pattern from earlier in this chapter is the doorway into that.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch09.sysml.
Requirements and Verification
Your coffee machine has structure, connections, behavior, states, and constraints. You can describe what the system is made of, how it behaves, and what rules it must obey. But none of that answers a fundamental engineering question: does the design actually meet what was asked for?
That is what requirements and verification are for. A requirement captures something the system must do or be. A satisfaction link says which part of the design addresses it. A verification case says how you plan to prove it. Together, these three elements form a traceability loop – the mechanism that connects stakeholder intent to design decisions to objective evidence.
SysML v2 models requirements as first-class elements, not as external documents referenced by ID. They live in the same model as the parts, actions, and constraints they trace to. This means tools can check whether every requirement has a design link and a verification plan, rather than relying on spreadsheets and manual audits.
Defining a Requirement
A requirement starts with requirement def. Like part definitions and action definitions, a requirement definition is a reusable type. You can give it a short identifier (useful for document references) and a doc comment that carries the requirement text.
The short identifier goes in angle brackets and single quotes – <'REQ-TEMP-001'>. The quotes are what let it contain hyphens, which a plain identifier cannot; Appendix H covers that form and the rest of the naming rules.
package CoffeeMachineRequirements {
requirement def <'REQ-TEMP-001'> BrewTempReq {
doc /* The brewer extraction temperature shall remain
between 90 and 96 degrees Celsius during brewing. */
}
}
BrewTempReq is the model name you use in SysML code. REQ-TEMP-001 is the short ID – a human-readable tag that maps to whatever requirement numbering scheme your project uses. The doc comment holds the requirement text itself. This text is not checked by the model, but it is visible to reviewers and tools.
You can define as many requirements as your project needs. Here is a second one for the safety interlock from Chapter 9:
package CoffeeMachineRequirements {
requirement def <'REQ-TEMP-001'> BrewTempReq {
doc /* The brewer extraction temperature shall remain
between 90 and 96 degrees Celsius during brewing. */
}
requirement def <'REQ-SAFE-001'> SafetyInterlockReq {
doc /* The system shall not initiate a brew cycle
unless a cup is detected on the drip tray. */
}
}
Each requirement stands alone as a definition. It does not yet say anything about which part of the design addresses it or how you would test it. Those connections come next.
Requirement Text vs. Formal Constraints
The doc comment on a requirement is prose. It communicates intent to human readers, but the model checker cannot evaluate it. For requirements where precision matters, you can add a formal constraint inside the requirement body.
requirement def <'REQ-TEMP-001'> BrewTempReq {
doc /* The brewer extraction temperature shall remain
between 90 and 96 degrees Celsius during brewing. */
attribute temp : Real;
require constraint { temp >= 90.0 and temp <= 96.0 }
}
The require constraint block adds a machine-checkable condition alongside the prose. The temp attribute is a parameter of the requirement – it represents whatever value needs to satisfy the condition. When this requirement is linked to a design element, the attribute can be bound to an actual property.
A formal condition lets an evaluator compare a bound temperature with the limits. A satisfy relationship records a claim; it is not evidence that a physical machine passed a test.
Not every requirement needs a formal constraint. Some requirements are inherently qualitative (“the user manual shall be written in English”) and do not benefit from formalization. The general rule: if the requirement text contains a number, a range, or a logical condition, consider adding a require constraint to make it checkable.
Subjects, Actors, and the Binding Surface
A requirement can declare a subject – the element it constrains. The subject says “this requirement is about that thing.”
requirement def <'REQ-TEMP-001'> BrewTempReq {
doc /* The brewer extraction temperature shall remain
between 90 and 96 degrees Celsius during brewing. */
subject brewer : Brewer;
}
The subject keyword declares that BrewTempReq applies to a Brewer. This is a typed parameter: any element that satisfies this requirement must be (or contain) a Brewer. Subjects make requirements more precise. Without a subject, a requirement floats – you know it exists, but not what it applies to. With a subject, the requirement is anchored to a specific kind of element.
A requirement can also declare one or more actors – the elements that interact with the subject. Actors are typed in the same way as subjects:
requirement def <'REQ-SAFE-001'> SafetyInterlockReq {
doc /* The system shall not initiate a brew cycle
unless a cup is detected on the drip tray. */
subject machine : CoffeeMachine;
actor user : Operator;
}
The actor declaration says “this requirement is about how the Operator interacts with the CoffeeMachine.” Actors are useful when a requirement is fundamentally about an interaction, not just a property of a single part.
Together, the subject, the actors, and any attribute parameters form the requirement’s binding surface – the set of names that a satisfy site must supply. The binding surface is also the scope inside which a require constraint resolves names (recall Chapter 9, “How Constraints Find Their Values”). When the runtime evaluates the constraint, it walks this surface, not the surrounding package, to find values.
Why this matters. Authors often write
require constraintbodies that reference attributes the requirement does not declare. The constraint then either picks up the wrong attribute by accident or fails to evaluate because no value is bound. The fix is to declare every name the constraint uses as part of the binding surface – subject, actor, orattribute– so the satisfy site has a clean place to supply them.
Satisfying a Requirement
A requirement on its own is just an assertion about what should be true. To close the loop, you need to say which part of the design addresses it. That is what satisfy does.
part def CoffeeMachine {
part brewer : Brewer;
satisfy requirement : BrewTempReq;
}
The satisfy statement inside CoffeeMachine says: this design element claims to address BrewTempReq. The exact strength of that claim depends on the requirement.
Requirements with no formal constraint are pure traceability links. The model does not check whether CoffeeMachine actually meets the qualitative goal – the link just makes the relationship explicit and queryable. A tool or a reviewer can ask “which requirements does CoffeeMachine satisfy?” and get a definitive answer.
Requirements that carry a require constraint are stronger. The satisfy site supplies the bindings for the requirement’s parameters (subject, actors, attributes), and at evaluation time – whether driven by a static check, a verification case, or a simulation – the constraint is evaluated against those bindings and produces a verdict. This is not a manual claim; the model knows whether the constraint holds for the values the satisfy site supplied. We unpack the verdict shape in How Verification Verdicts Work, below.
You can satisfy multiple requirements from the same design element:
part def CoffeeMachine {
part brewer : Brewer;
part grinder : Grinder;
part waterTank : WaterTank;
satisfy requirement : BrewTempReq;
satisfy requirement : SafetyInterlockReq;
}
You can also place satisfaction links at a more specific level. If the temperature requirement is really about the brewer, not the whole machine, put the satisfaction there:
part def Brewer {
attribute waterTemp : Real;
attribute brewPressure : Real;
satisfy requirement : BrewTempReq;
}
Where you place the satisfy link is a modeling decision. Put it at the level of the design element that is actually responsible for meeting the requirement. If the brewer controls the temperature, the brewer should carry the satisfaction link.
Verification Cases
Satisfaction says “this design addresses this requirement.” But that is a claim, not evidence. Verification cases capture how you plan to produce evidence.
A verification case is defined with verification def. Inside it, an objective block declares which requirement it verifies:
verification def BrewTempTest {
doc /* Measure extraction temperature across 10 consecutive
brew cycles and confirm all readings fall within range. */
objective {
verify requirement : BrewTempReq;
}
}
BrewTempTest is a verification case that targets BrewTempReq. The doc comment describes the test procedure in prose. The verify statement inside the objective block creates the formal link.
A verification case can verify more than one requirement:
verification def SafetyInterlockTest {
doc /* Attempt to start a brew cycle with no cup present.
Confirm the system rejects the command. Then place a cup,
retry, and confirm the cycle starts. */
objective {
verify requirement : SafetyInterlockReq;
}
}
You can also define actions inside a verification case to describe the test procedure as modeled steps:
verification def SafetyInterlockTest {
doc /* Verify that the brew interlock prevents operation
without a cup. */
action removeCup { doc /* Remove any cup from the tray. */ }
action attemptBrew { doc /* Press the brew button. */ }
action confirmRejection { doc /* Verify the machine refuses to brew. */ }
action placeCup { doc /* Place a cup on the tray. */ }
action retryBrew { doc /* Press the brew button again. */ }
action confirmSuccess { doc /* Verify the brew cycle starts. */ }
first removeCup then attemptBrew;
first attemptBrew then confirmRejection;
first confirmRejection then placeCup;
first placeCup then retryBrew;
first retryBrew then confirmSuccess;
objective {
verify requirement : SafetyInterlockReq;
}
}
This level of detail is optional. For many projects the prose description in doc is sufficient. But when your verification plan will eventually drive automated test execution or when reviewers need to see the exact sequence, modeling the steps as actions makes the procedure unambiguous. The essential thing is the verify link – it connects the requirement to a planned piece of evidence.
How Verification Verdicts Work
Keep three things separate: the text of the requirement, the claim that a design satisfies it, and the evidence obtained by a particular verification case. SysML’s VerificationCases::VerdictKind includes pass, fail, inconclusive and error. For example, a calibrated sensor reading of 97 °C contradicts a 90–96 °C requirement; a missing reading is not evidence of compliance or of an out-of-range temperature. A broken test instrument is a different failure again.
In the project, brewTemperature is a requirement usage. benchMachine supplies the observed values. The BrewTempTest objective identifies the same requirement, and its return expression compares the subject’s measured temperature with the acceptance band. A doc describing a test procedure would not perform these comparisons.
sysml -instantiate CoffeeRequirements::benchMachine -requirement 'CoffeeRequirements::brewTemperature CoffeeRequirements::benchMachine' src/examples/coffee-machine
sysml -instantiate CoffeeRequirements::benchMachine -analysis 'Verification::BrewTempTest CoffeeRequirements::benchMachine' src/examples/coffee-machine
The first command asks about a requirement. The second runs one named verification case. Inspect the verdict and its evidence: a single value of 93 °C says nothing about the temperature on the other nine shots in a ten-shot test.
Verifying a time-dependent requirement
A final sample cannot establish that a boiler stayed within limits for a whole cycle. Define the interval (for example, extraction rather than warm-up), what is measured, and what to do with missing samples. A simulation supplies observations from a model, a bench test from hardware. Record which one you used. Chapter 16 shows how to trace a state machine and vary a thermal input without modifying the design.
The Full Traceability Loop
With requirements, satisfaction, and verification in place, you have a complete traceability loop. Here it is for the coffee machine, all in one package:
package CoffeeMachineRequirements {
private import ScalarValues::*;
private import CoffeeMachineDomain::*;
// --- Requirements ---
requirement def <'REQ-TEMP-001'> BrewTempReq {
doc /* The brewer extraction temperature shall remain
between 90 and 96 degrees Celsius during brewing. */
subject brewer : Brewer;
attribute temp : Real;
require constraint { temp >= 90.0 and temp <= 96.0 }
}
requirement def <'REQ-SAFE-001'> SafetyInterlockReq {
doc /* The system shall not initiate a brew cycle
unless a cup is detected on the drip tray. */
subject machine : CoffeeMachine;
}
requirement def <'REQ-BREW-001'> BrewTimeReq {
doc /* A brew cycle shall complete within 60 seconds
from initiation to coffee dispensed. */
subject machine : CoffeeMachine;
attribute duration : Real;
require constraint { duration <= 60.0 }
}
// --- Satisfaction (in a usage context) ---
part coffeeMachine : CoffeeMachine {
satisfy requirement : BrewTempReq;
satisfy requirement : SafetyInterlockReq;
satisfy requirement : BrewTimeReq;
}
// The form above is the most common, but the spec also accepts:
//
// satisfy requirement brewTempReq : BrewTempReq by brewer;
//
// which gives the satisfaction usage its own name (`brewTempReq`)
// and lets you spell out which design element does the satisfying
// (`by brewer`) when it is not the enclosing element.
// --- Verification ---
verification def BrewTempTest {
doc /* Measure extraction temperature across 10 consecutive
brew cycles. All readings must fall between 90 and
96 degrees Celsius. */
objective {
verify requirement : BrewTempReq;
}
}
verification def SafetyInterlockTest {
doc /* Attempt brew with no cup: confirm rejection.
Place cup, retry: confirm cycle starts. */
objective {
verify requirement : SafetyInterlockReq;
}
}
verification def BrewTimeTest {
doc /* Time 5 consecutive brew cycles from button press
to coffee dispensed. All must complete within
60 seconds. */
objective {
verify requirement : BrewTimeReq;
}
}
}
Read this from the bottom up: BrewTempTest verifies BrewTempReq, which is satisfied by coffeeMachine. That is one complete loop. Every requirement has a design link (who addresses it) and an evidence link (how you check it). A reviewer can trace from any requirement to both its design rationale and its verification plan.
This is where SysML v2 earns its keep as an engineering tool. The model is not just a picture of the system – it is a queryable database of commitments. You can ask:
- Which requirements have no satisfaction link? (Unaddressed requirements.)
- Which requirements have no verification case? (Unverified claims.)
- Which verification cases are not linked to any requirement? (Orphan tests.)
These are the questions that project reviews are built around. With model-based requirements, the answers come from the model itself rather than from manually maintained traceability matrices.
Requirement Decomposition
Large requirements are hard to verify directly. A common pattern is to decompose a top-level requirement into smaller, testable pieces. You can express this using nested requirements or by specializing a parent requirement.
requirement def <'REQ-PERF-001'> PerformanceReq {
doc /* The coffee machine shall deliver acceptable
performance across all operating conditions. */
requirement <'REQ-PERF-001a'> startupTimeReq {
doc /* The machine shall reach operating temperature
within 90 seconds of power-on. */
}
requirement <'REQ-PERF-001b'> brewTimeReq {
doc /* Each brew cycle shall complete within
60 seconds of initiation. */
}
}
The nested requirements startupTimeReq and brewTimeReq are children of PerformanceReq. Each child can have its own satisfaction and verification links. The parent captures the high-level intent; the children are the testable leaves.
Keep decomposition shallow. One or two levels is usually enough. Deep requirement hierarchies create more traceability overhead than they solve.
Use Cases and Concerns
SysML v2 includes two related concepts that provide context for requirements.
A use case describes a goal-oriented interaction with the system. It is defined with use case def:
use case def BrewEspresso {
doc /* The user selects espresso, the machine grinds beans,
heats water, extracts coffee, and dispenses into cup. */
subject machine : CoffeeMachine;
objective {
doc /* Deliver a single espresso shot to the user. */
}
}
Use cases sit at a higher level than actions. Where an action definition describes a sequence of steps, a use case describes a stakeholder goal. Use cases are useful for capturing “why does this behavior exist?” and for organizing requirements around user-facing scenarios.
A concern captures a stakeholder interest or worry:
concern def SafetyConcern {
doc /* The machine must not create burn hazards or
dispense onto the counter without a cup. */
}
Concerns are lightweight. They give requirements a “why” – a named reason for their existence. You do not need concerns for every requirement, but they help when a reviewer asks “why does this requirement exist?” and the answer involves stakeholder context that is not obvious from the requirement text alone.
Both use cases and concerns are optional. Many projects work fine with just requirements, satisfaction, and verification. Add use cases when you need to organize requirements around user goals. Add concerns when stakeholder rationale needs to be explicit.
Analysis Cases
A verification case asks a yes/no question – does the design meet the requirement? An analysis case asks a different question – what is the answer? – and returns a typed result. Use analysis def:
analysis def ThermalLossAnalysis {
doc /* Estimate the heat lost from the brewer during a 30-second
idle period at an ambient temperature of 20 degrees C. */
subject brewer : Brewer;
return lossRate : Real;
}
analysis def defines a case whose purpose is to compute something, not to check something. The body is shaped like the calc def from Chapter 9: it declares inputs (here, via the subject), does work, and returns typed outputs. The difference from a bare calc is that an analysis case carries the same envelope as a verification case – a subject, a doc-driven purpose, optional actor – so it sits inside the same traceability structure as the rest of the model.
Reach for analysis def when the engineering question is estimation (worst-case heat loss, peak load, mean time to brew) rather than compliance. The analysis case can even feed a verification case: it produces the number the verification case then checks against a requirement.
The General case Envelope
Verification, analysis, and use cases are siblings. All three are specializations of a single case def:
case def ThermalLoadProfile {
subject brewer : Brewer;
out idleLoad : Real;
out heatingLoad : Real;
}
case def is the common envelope. Every case definition can carry a subject, an optional actor, an objective, and a body. verification def adds a verify requirement linkage; analysis def adds return values; use case def adds stakeholder actions. The grammar equips them with the same structure; the intent is what you choose when you pick the keyword.
For most modeling, you spell out the specific kind (verification def, analysis def, use case def) and never write the bare case def. But knowing they share an envelope pays off when you build tooling that treats all three uniformly, or when you specialize a case family of your own.
Combining evidence across cases
Specify the acceptance rule before combining results. If all ten shots must be in range, one out-of-range sample disproves that run’s claim. Nine in-range shots with the tenth unmeasured do not establish a pass. Keep the case, test conditions, sample count and failures alongside any summary. A project dashboard’s rollup policy is not a four-valued law of the language.
Putting It Together: The Coffee Machine Grows
The coffee machine now has three layers of traceability. Here is how the pieces connect:
Structure (from Chapter 2 through Chapter 6): CoffeeMachine contains Grinder, Brewer, and WaterTank, connected through ports and interfaces.
Behavior (from Chapter 7 and Chapter 8): BrewCycle defines the action sequence. MachineStates defines the operating modes with guarded transitions.
Constraints (from Chapter 9): BrewTempSafe checks the temperature range. SafetyInterlock prevents brewing without a cup.
Requirements and verification (this chapter): BrewTempReq, SafetyInterlockReq, and BrewTimeReq capture the engineering intent. Satisfaction links connect them to the design. Verification cases connect them to evidence.
The constraints from Chapter 9 and the requirements from this chapter serve different purposes. A constraint is a rule the model enforces – it evaluates to true or false against actual values. A requirement is a commitment the project tracks – it may reference a constraint, but its primary purpose is traceability.
Consider the temperature range. In Chapter 9, you defined:
constraint def BrewTempSafe {
in temp : Real;
temp >= 90.0 and temp <= 96.0
}
In this chapter, you defined:
requirement def <'REQ-TEMP-001'> BrewTempReq {
doc /* The brewer extraction temperature shall remain
between 90 and 96 degrees Celsius during brewing. */
attribute temp : Real;
require constraint { temp >= 90.0 and temp <= 96.0 }
}
These are not redundant. The constraint lives in the design and can be asserted against actual values during analysis or simulation. The requirement lives in the traceability structure and connects to satisfaction links, verification cases, and project reviews. You can have a constraint without a requirement (an internal design rule that nobody asked for) and a requirement without a constraint (a qualitative goal that cannot be formalized). When both exist for the same concern, the constraint makes the requirement checkable and the requirement makes the constraint traceable.
Visualizing Requirements and Traceability
Requirements
Requirements grid
Common Mistakes
Satisfaction without verification. A satisfy link is a claim, not evidence. If you satisfy a requirement but never define a verification case for it, you have an unverified claim. Some tools will flag this, but even without tooling, make it a habit: every satisfy should have a corresponding verify somewhere.
Requirements with no subject. A requirement without a subject can still be satisfied, but it is harder for reviewers to understand what it applies to. When you know which element a requirement targets, say so with subject.
Overly deep decomposition. Splitting one requirement into ten sub-requirements creates a maintenance burden. Each sub-requirement needs its own satisfaction and verification links. Prefer fewer, testable leaf requirements over deep hierarchies.
Duplicating constraint logic in requirements. If you already have a constraint def BrewTempSafe from Chapter 9, you do not need to rewrite that logic inside the requirement. You can reference the constraint or simply note in the requirement text that the constraint captures the formal condition. Do not maintain the same expression in two places.
What You Have Built
Your coffee machine model now includes:
- Three requirements with short IDs, prose text, subjects, and formal constraints
- Satisfaction links from the design to each requirement
- Verification cases with objectives that trace back to each requirement
- A complete traceability loop: requirement to design to evidence
This is the layer that makes the model auditable. In Chapter 11, you will assemble all of these pieces – structure, behavior, constraints, requirements, and verification – into one coherent system model.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch10.sysml.
Your Complete System Model
What evidence would show that an espresso machine meets its extraction-temperature requirement? This chapter follows one measurement from the brewer, through a design claim, to a verification verdict. It uses the structure and behavior from earlier lessons, but does not require their files.
The Model So Far
Here is what each chapter contributed:
- Chapter 2 defined the core types:
Grinder,Brewer,WaterTank,CoffeeMachine, plus item definitions forWater,CoffeeBeans, andBrewedCoffee. - Chapter 5 added typed ports to each component:
beanInputandgroundOutputon the grinder;waterInlet,groundInput, andbrewOutputon the brewer;waterOuton the water tank. - Chapter 6 wired the components together with connections and typed item flows.
- Chapter 7 defined
BrewCycleas a sequence of actions with parallel branches. - Chapter 8 defined
MachineStateswith guarded transitions between operating modes. - Chapter 9 added
BrewTempTarget(calculation) andSafetyInterlock(constraint). - Chapter 10 added requirements with
satisfyandverifylinks.
Package Organization
The next six listings form one self-contained model. Paste them, in order, into an empty .sysml file or download the combined file. It uses only the standard library. Do not load vocabulary.sysml or the larger coffee-machine project alongside it: those are separate teaching models.
Start with the materials and grind settings. No part owns them yet.
package CoffeeMachineDomain {
// Domain vocabulary
item def Water;
item def CoffeeBeans;
item def GroundCoffee;
item def BrewedCoffee;
enum def GrindSetting {
fine;
medium;
coarse;
}
}
The assembly supplies the context: brewer.waterTemp is a measurement on this machine’s brewer. Ground coffee and water each have a directed pair of ports: the receiving or supplying side uses the conjugate type.
package CoffeeMachineStructure {
private import ScalarValues::*;
private import CoffeeMachineDomain::*;
port def BeanInputPort {
in item beans : CoffeeBeans;
}
port def GroundCoffeePort {
out item grounds : GroundCoffee;
}
port def WaterPort {
in item water : Water;
}
port def BrewOutputPort {
out item coffee : BrewedCoffee;
}
part def Grinder {
attribute grindSize : GrindSetting;
port beanInput : BeanInputPort;
port groundOutput : GroundCoffeePort;
}
part def Brewer {
attribute waterTemp : Real; // measured extraction temperature in degrees Celsius
attribute brewPressure : Real;
port waterInlet : WaterPort;
port groundInput : ~GroundCoffeePort;
port brewOutput : BrewOutputPort;
}
part def WaterTank {
attribute currentLevel : Real;
attribute maxCapacity : Real;
port waterOut : ~WaterPort;
}
part def CoffeeMachine {
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
connect waterTank.waterOut to brewer.waterInlet;
connect grinder.groundOutput to brewer.groundInput;
flow of Water from waterTank.waterOut.water to brewer.waterInlet.water;
flow of GroundCoffee from grinder.groundOutput.grounds to brewer.groundInput.grounds;
}
}
Grinding and heating can proceed in parallel. Extraction waits for both. The controlled machine exhibits a state machine: a brew command can leave idle only if a cup is present.
package CoffeeMachineBehavior {
private import CoffeeMachineDomain::*;
private import CoffeeMachineStructure::CoffeeMachine;
private import ScalarValues::Boolean;
action def GrindBeans { in item beans : CoffeeBeans; out item grounds : GroundCoffee; }
action def HeatWater { in item water : Water; out item hotWater : Water; }
action def ExtractCoffee {
in item water : Water; in item grounds : GroundCoffee; out item coffee : BrewedCoffee;
}
action def DispenseCoffee { in item coffee : BrewedCoffee; }
action def BrewCycle {
action grind : GrindBeans; action heat : HeatWater;
action extract : ExtractCoffee; action dispense : DispenseCoffee;
fork prepare; join prepared;
first start then prepare;
first prepare then grind; first prepare then heat;
first grind then prepared; first heat then prepared;
first prepared then extract; first extract then dispense; first dispense then done;
flow from grind.grounds to extract.grounds;
flow from heat.hotWater to extract.water;
flow from extract.coffee to dispense.coffee;
}
attribute def BrewCommand; attribute def ShotPoured;
attribute def CleanCommand; attribute def Cleaned;
attribute def Fault; attribute def Reset;
part def ControlledMachine :> CoffeeMachine {
attribute cupPresent : Boolean;
exhibit state machineStates {
entry; then idle;
state idle;
state brewing { do action cycle : BrewCycle; }
state cleaning; state error;
transition first idle accept BrewCommand if cupPresent then brewing;
transition first brewing accept ShotPoured then idle;
transition first idle accept CleanCommand then cleaning;
transition first cleaning accept Cleaned then idle;
transition first brewing accept Fault then error;
transition first error accept Reset then idle;
}
}
}
Write the acceptance rules once. The target temperature is a setpoint; the temperature-band constraint evaluates a measurement. Both the requirement and its test reuse the latter rule.
package CoffeeMachineAnalysis {
private import ScalarValues::*;
calc def BrewTempTarget {
in ambient : Real;
return target : Real = if ambient < 18.0 ? 94.0 else 93.0;
}
constraint def BrewTempSafe {
in celsius : Real;
celsius >= 90.0 and celsius <= 96.0
}
constraint def SafetyInterlock {
in started : Boolean; in cupPresent : Boolean;
started implies cupPresent
}
constraint def WithinBrewTime {
in seconds : Real;
seconds < 60.0
}
}
Declare the requirement usages and identify the design that claims to satisfy them. benchMachine and hotShot differ only in measured temperature. Only benchMachine makes satisfaction claims.
package CoffeeMachineRequirements {
private import CoffeeMachineBehavior::ControlledMachine;
private import CoffeeMachineAnalysis::*;
private import ScalarValues::*;
part def TestMachine :> ControlledMachine {
attribute brewStarted : Boolean;
attribute elapsedSeconds : Real;
}
requirement def <'REQ-TEMP-001'> BrewTempReq {
doc /* The measured extraction temperature shall be in the range 90–96 °C inclusive. */
subject machine : TestMachine;
require constraint { BrewTempSafe(machine.brewer.waterTemp) }
}
requirement def <'REQ-SAFE-001'> SafetyInterlockReq {
doc /* Brewing shall not start without a cup. */
subject machine : TestMachine;
require constraint { SafetyInterlock(machine.brewStarted, machine.cupPresent) }
}
requirement def <'REQ-TIME-001'> BrewTimeReq {
doc /* A brew cycle shall take less than 60 seconds. */
subject machine : TestMachine;
require constraint { WithinBrewTime(machine.elapsedSeconds) }
}
requirement brewTemperature : BrewTempReq;
requirement interlock : SafetyInterlockReq;
requirement brewTime : BrewTimeReq;
part benchMachine : TestMachine {
part :>> brewer { :>> waterTemp = 96.0; }
:>> cupPresent = true; :>> brewStarted = true; :>> elapsedSeconds = 45.0;
}
satisfy brewTemperature by benchMachine;
satisfy interlock by benchMachine;
satisfy brewTime by benchMachine;
// A second observation for testing the temperature limit, not a design claim.
part hotShot : TestMachine {
part :>> brewer { :>> waterTemp = 97.0; }
:>> cupPresent = true; :>> brewStarted = true; :>> elapsedSeconds = 45.0;
}
}
Each verification objective names the same requirement usage as the design claim. Run a case on a particular subject to obtain a verdict.
package CoffeeMachineVerification {
private import CoffeeMachineRequirements::*;
private import CoffeeMachineAnalysis::*;
private import VerificationCases::VerdictKind;
verification def BrewTempTest {
subject machine : TestMachine;
objective { verify brewTemperature; }
return verdict : VerdictKind = if BrewTempSafe(machine.brewer.waterTemp)
? VerdictKind::pass else VerdictKind::fail;
}
verification def SafetyInterlockTest {
subject machine : TestMachine;
objective { verify interlock; }
return verdict : VerdictKind = if SafetyInterlock(machine.brewStarted, machine.cupPresent)
? VerdictKind::pass else VerdictKind::fail;
}
verification def BrewTimeTest {
subject machine : TestMachine;
objective { verify brewTime; }
return verdict : VerdictKind = if WithinBrewTime(machine.elapsedSeconds)
? VerdictKind::pass else VerdictKind::fail;
}
}
How the Packages Connect
CoffeeMachineDomain supplies the material types used by structure and behavior. ControlledMachine specializes the structural CoffeeMachine, so the subject of a test can have both a brewer and operating modes. CoffeeMachineAnalysis depends only on the standard library. Requirements bring the machine and the rules together; verification imports the named requirements and the same rules.
Cross-Concern Traceability
Follow the temperature measurement in either direction:
benchMachine.brewer.waterTempsupplies 96 °C. This is a recorded observation, not the calculated temperature target.brewTemperatureis aBrewTempRequsage. Its required constraint evaluatesBrewTempSafeon the subject’s brewer.satisfy brewTemperature by benchMachine;identifies the design making the claim.BrewTempTesthasobjective { verify brewTemperature; }. Its return expression applies the same inclusive band to the specified test subject. The objective records which requirement the test verifies; it does not compute the verdict for us.
Run the chapter from the edition root. The checks below need only the six packages shown above:
model=src/examples/lessons/ch11.sysml
req=CoffeeMachineRequirements
ver=CoffeeMachineVerification
sysml -strict -validate "$model"
sysml -satisfy "$model"
sysml -instantiate "$req::benchMachine" -analysis "$ver::BrewTempTest $req::benchMachine" "$model"
sysml -instantiate "$req::hotShot" -analysis "$ver::BrewTempTest $req::hotShot" "$model"
What Makes This Model Review-Ready
The three satisfaction assertions are about benchMachine: temperature at the included upper boundary, a cup present when brewing started, and 45 seconds elapsed. The temperature case passes for that machine. It fails for hotShot at 97 °C; the last command is an intentional negative test. A structural check succeeds in both cases. Finding an unacceptable observation is the test doing its job, not a syntax error.
These checks do not establish how an actual machine acquired the readings, or that all future shots stay in range. For that conclusion a reviewer would need a sampling plan and test results from the hardware.
The model on disk
For the chapter exercise, use the single six-package model. The larger companion project below is independent: it develops the same system in more detail, with different package names and its own measured inputs. From the edition root, load the directory as one model:
sysml -strict -validate src/examples/coffee-machine
sysml -list views src/examples/coffee-machine
File in src/examples/coffee-machine/ | Question it answers |
|---|---|
definitions.sysml, typing-and-specialization.sysml | What is a brewer, and what is different about an espresso brewer? |
ports-and-interfaces.sysml, connections.sysml, flows.sysml | Where can water pass between the tank and the brewer? |
actions.sysml, brew-cycle-flow.sysml | Which steps must wait for grinding and heating? |
states.sysml, orchestration.sysml | Which modes exist? Which timed transitions does the example run exercise? |
calculations.sysml, demo-analysis.sysml | How do time and power depend on operating conditions? |
requirements.sysml | What is required, which machine claims compliance, and what does the verification case measure? |
metadata.sysml, views.sysml, book-views.sysml, package-structure.sysml | How can each reviewer find the relevant elements without copying the model? |
Exploring the Model
These four figures were rendered from the larger companion project, not from the six-package exercise. Each selects a different aspect of that project:
Structure
Actions
States
Requirements
Extending the Model
This model is a foundation, not a finished product. Real projects extend it in several directions:
- More requirements. Add power consumption, noise level, maintenance interval requirements.
- More states. Add
Steaming,Descaling,Standbymodes with guarded transitions. - More actions. Add
SteamMilk,RunDescaleactions with their own control flow. - Variants. Use specialization (Chapter 12) to create
EspressoMachineandDripMachinevariants. - Governance. Use metadata and views (Chapter 13) to add review status and stakeholder-specific model slices.
- Physical units. Use library quantities (Chapter 14) to replace
RealwithTemperatureValueandPressureValue.
The structure is ready for all of these. Each extension adds to the model without rewriting what exists.
Specialization and Redefinition
By now you have a complete coffee machine model: definitions, usages, ports, connections, actions, states, constraints, and requirements. Everything so far has been about building one machine. But what happens when you need a second kind of machine – one that shares most of the original design but changes a few things?
You could copy CoffeeMachine, rename it, and edit the copy. That works once. It becomes a maintenance problem the moment you fix a bug in the original and forget to propagate it to the copy. SysML v2 gives you better tools: specialization and redefinition. This chapter covers four related mechanisms for refining types without duplicating them.
Specialization
Specialization says: this new type is a kind of an existing type. It inherits everything from the general type and can add more.
The operator is :>.
package CoffeeMachineVariants {
private import CoffeeMachineDomain::*;
part def EspressoMachine :> CoffeeMachine {
attribute pumpPressure : Real;
}
}
EspressoMachine :> CoffeeMachine means every EspressoMachine is a CoffeeMachine. It inherits all of CoffeeMachine’s features – the grinder, the brewer, the waterTank, the serialNumber. Then it adds pumpPressure, which only espresso machines have.
You have actually been using specialization implicitly since Chapter 2. When you write part def Grinder, it implicitly subclassifies the base library definition Parts::Part. When you write attribute waterTemp : Real, the attribute usage implicitly subsets the base library usage Attributes::attributeValues. Definitions get an implicit subclassification, usages an implicit subsetting, and writing your own explicit specialization suppresses the implicit one (SysML §7.6.8). The :> operator just makes the relationship explicit between your own types.
When to specialize
Specialize when the new type genuinely is a kind of the base type. Every instance of the specialized type should be substitutable wherever the general type is expected.
Good uses:
EspressoMachine :> CoffeeMachine– an espresso machine is a coffee machine.PressurizedBrewer :> Brewer– a pressurized brewer is a brewer.LargeWaterTank :> WaterTank– it is still a water tank, just bigger.
Bad uses:
Grinder :> CoffeeMachine– a grinder is not a coffee machine.BrewCycle :> CoffeeMachine– an action is not a structural type.
If the “is a kind of” sentence does not sound right in plain English, specialization is probably the wrong tool.
Multiple specialization
A definition can specialize more than one general type:
part def HeatedGrinder :> Grinder, HeatedComponent {
attribute grindTemp : Real;
}
HeatedGrinder inherits from both Grinder and HeatedComponent. This is useful when a concept belongs to two categories simultaneously. Use it sparingly – deep multiple-inheritance hierarchies become difficult to reason about.
Redefinition
Specialization adds new features. Redefinition replaces an inherited feature with a more specific version. The operator is :>>.
Suppose CoffeeMachine has a general target temperature attribute:
part def CoffeeMachine {
attribute targetTemp : Real;
}
An espresso machine needs that temperature locked to a specific value:
part def EspressoMachine :> CoffeeMachine {
attribute brewTemp :>> targetTemp = 94.0;
}
The line attribute brewTemp :>> targetTemp = 94.0 does three things at once:
- It says
brewTempredefines the inheritedtargetTemp. - It gives the feature a new name in this context:
brewTempinstead oftargetTemp. - It binds the value
94.0.
That third one is a binding, not a suggestion: a bare = asserts the value for every instance of the type. If you want a value a particular usage can still override, write default = 94.0 instead (SysML §7.6.3, and Chapter 5).
Inside an EspressoMachine, there is no separate targetTemp alongside brewTemp. The inherited feature is brewTemp. If you access targetTemp on an EspressoMachine instance, you get the same feature that brewTemp names.
Redefinition with tighter typing
You can also redefine a feature to narrow its type:
part def CoffeeMachine {
part brewer : Brewer;
}
part def EspressoMachine :> CoffeeMachine {
part espressoBrewer :>> brewer : PressurizedBrewer;
}
The inherited brewer is redefined to be typed by PressurizedBrewer (which itself specializes Brewer). The redefined type must be compatible with the original – you cannot redefine a Brewer as a WaterTank. Redefinition is a kind of subsetting, and a subsetting feature’s type has to specialize the type of what it subsets (KerML §8.3.3.3.10).
When to redefine
Redefine when an inherited feature needs to be more specific in the specialized context. Common cases:
- Binding a value:
:>> targetTemp = 94.0 - Narrowing a type:
:>> brewer : PressurizedBrewer - Tightening multiplicity:
:>> sensors [2]on a base that allows[1..*]
Do not redefine for cosmetic renaming alone. If the inherited name is fine and the type does not change, there is nothing to redefine.
Subsetting
Subsetting narrows a collection. Where redefinition replaces a feature, subsetting says: this feature is a subset of that inherited collection.
The operator is :> applied to a usage (not a definition). Context determines which relationship you get: on a definition, :> is subclassification; on a usage, it is subsetting (SysML §7.6.2, §7.6.3). The long spellings make it explicit – specializes on definitions, subsets on usages.
part def CoffeeMachine {
part sensors : Sensor[1..*];
}
part def EspressoMachine :> CoffeeMachine {
part tempSensors :> sensors : TemperatureSensor[1..2];
part pressureSensors :> sensors : PressureSensor[1];
}
tempSensors :> sensors says the temperature sensors are a subset of the total sensors collection. pressureSensors :> sensors is another subset. Both are parts of the same inherited sensors group, but they carve it into named subsets with more specific types.
The key difference from redefinition: subsetting does not replace the inherited feature. The sensors collection still exists. tempSensors and pressureSensors are portions of it.
When to subset vs. redefine
- Redefine when the specialized type has exactly one version of the inherited feature, and you want to replace it entirely.
- Subset when the inherited feature is a collection and you want to name specific portions of it without replacing the whole.
If the base type has part brewer : Brewer (a single part), redefine it. If the base type has part sensors : Sensor[1..*] (a collection), subset it.
Conjugation
Conjugation makes a type inherit another type’s features with their input and output directions reversed (SysML §7.12.3). The operator is ~ (tilde) placed before a type name.
You saw ports in Chapter 5. A port definition declares features with directions:
port def WaterSupplyPort {
out item water : Water;
}
When a water tank sends water out, it uses WaterSupplyPort directly. But the brewer that receives that water needs the same port shape with the direction flipped – out becomes in. Chapter 5 handled that by defining a second port type by hand: WaterPort, with in item water. Conjugation gets you the receiving side for free instead:
part def WaterTank {
port waterOut : WaterSupplyPort;
}
part def Brewer {
port waterInlet : ~WaterSupplyPort;
}
~WaterSupplyPort is WaterSupplyPort with all directions reversed. The out item water becomes in item water. The port shapes are structurally compatible – they carry the same items in opposite directions – which is exactly what you need for a connection.
When to conjugate
Conjugate when two components interact through complementary ports and the only difference is direction. This is the standard pattern for producer/consumer, sender/receiver, and request/response pairs.
Do not conjugate when the two sides of an interaction carry different items or have different structure. In that case, define two separate port types.
Putting It Together: The EspressoMachine
Here is a fuller example that uses specialization, redefinition, and conjugation together:
package CoffeeMachineVariants {
private import ScalarValues::*;
private import CoffeeMachineDomain::*;
part def PressurizedBrewer :> Brewer {
attribute boilerPressure : Real;
}
part def EspressoMachine :> CoffeeMachine {
// Redefine the brewer to a pressurized variant, and pin the
// water temperature it inherits from Brewer
part espressoBrewer :>> brewer : PressurizedBrewer {
attribute :>> waterTemp = 94.0;
}
// Add espresso-specific features
attribute shotVolume : Real;
}
}
Read this from top to bottom:
PressurizedBrewer :> Brewer– a new brewer type that addsboilerPressure.EspressoMachine :> CoffeeMachine– inherits grinder, brewer, water tank, serial number.espressoBrewer :>> brewer– the inheritedbrewerpart is redefined to usePressurizedBrewer.:>> waterTemp = 94.0– the brewer’s water temperature is bound to 94.0. Note where this line sits: insideespressoBrewer, becausewaterTempis a feature ofBrewer, not ofCoffeeMachine. A redefinition can only target a feature the enclosing type actually inherits, soattribute brewTemp :>> waterTempwritten directly inEspressoMachinewould fail to resolve.shotVolume– a new attribute that only espresso machines have.
That fourth line also shows a shortcut worth knowing: a redefining usage with no declared name takes the name of the feature it redefines (SysML §7.6.5), so this one is still called waterTemp.
An EspressoMachine instance has everything a CoffeeMachine has, plus the refinements. Any constraint, requirement, or verification case that references CoffeeMachine applies to EspressoMachine too, because specialization preserves that relationship.
Decision Guide
When you need to refine a type, choose the simplest mechanism that fits:
| Situation | Mechanism | Operator | Example |
|---|---|---|---|
| New type is a kind of existing type | Specialization | :> | EspressoMachine :> CoffeeMachine |
| Inherited feature needs a new default or narrower type | Redefinition | :>> | brewTemp :>> targetTemp = 94.0 |
| Inherited collection needs named subgroups | Subsetting | :> on usage | tempSensors :> sensors |
| Port directions need to be flipped | Conjugation | ~ | port waterInlet : ~WaterSupplyPort |
| Just adding new features to a type | Specialization alone | :> | Add pumpPressure in subtype |
| Replacing a part with a more specific variant | Redefinition | :>> | espressoBrewer :>> brewer |
| Documenting a family of named alternatives | Variation | variation / variant | see below |
Start at the top of this table. If specialization alone solves your problem, stop there. Reach for redefinition only when you need to change something inherited, not just add to it. Use subsetting only for genuine collections. Use conjugation only for direction inversion.
Variation
Sometimes a design has several named alternatives that share a common base by deliberate choice, rather than one refining the next. A coffee machine might offer two brew profiles – standard and intense – where neither is a refinement of the other; both are options the customer picks between.
variation <keyword> def <ChoiceName> :> <BaseName> {
variant <keyword> <name> : <AlternativeName>;
variant <keyword> <name> : <AlternativeName>;
}
part def BrewProfile {
attribute targetTemp : Real;
}
part def StandardBrew :> BrewProfile;
part def IntenseBrew :> BrewProfile;
variation part def BrewProfileChoice :> BrewProfile {
variant part standardProfile : StandardBrew;
variant part intense : IntenseBrew;
}
part def CoffeeMachine {
part brewProfile : BrewProfileChoice;
}
BrewProfileChoice is a variation – a variation point, marked by the variation keyword before the kind keyword. Its members are its variants, each marked variant. A brewProfile typed by BrewProfileChoice resolves to exactly one of them per configuration.
The direction of those two keywords is what people get backwards. variation goes on the choice, not on the alternatives, and variant goes on the members inside it. Five rules follow, and the specification states all of them (SysML §7.6.7, with the formal constraints at §8.3.6.2):
- Variant usages may only be declared inside a variation.
- Every usage in a variation’s body is a variant, so a variation cannot carry ordinary features of its own. That is why
targetTemplives onBrewProfileand reachesBrewProfileChoiceby inheritance. - A variation is always abstract. You never write
abstracton it, and you never instantiate the choice – only a variant. - The kind of a variant must match the kind of its variation:
variant partinside avariation part def. - A variation may not specialize another variation. You can build a variation on an ordinary definition, as
BrewProfileChoicebuilds onBrewProfile, but you cannot chain choices together – a choice of choices is not a thing (validateDefinitionVariationSpecialization).
Usages can be variation points too, with the same shape – variation part transmission : Transmission { variant ...; } turns a single usage into a choice rather than a whole definition.
The point of variation is not refinement – it is alternation. Where EspressoMachine :> CoffeeMachine says every EspressoMachine is a CoffeeMachine, a variation says a given configuration picks one of several peers.
Use variation when the model genuinely enumerates alternatives the system can be configured into. When the relationship is “this is a more specific kind of that,” plain specialization is clearer; variation is the right tool only for the “choose one of these” pattern.
Elaboration: The Implicit Pass
Everything in this chapter – specialization, redefinition, subsetting, conjugation, variation – is something you write. But the model is also understood to gain relationships you did not write down. Weaving those in is called elaboration: the model is read as if a small set of implicit relationships were filled in for you.
Suppose a library declares:
part def Grinder {
attribute rpm : Real;
}
and your model specializes it:
part def HeatedGrinder :> Grinder {
attribute heatLevel : Real;
}
You wrote one :>, but HeatedGrinder is now understood to have both rpm (inherited from Grinder) and heatLevel. You did not redeclare rpm; elaboration supplies it. The same is true when specialization chains: declare BurrGrinder :> HeatedGrinder on top of HeatedGrinder :> Grinder, and the generalization from BurrGrinder all the way up to Grinder is implicit, so a constraint that references Grinder also sees every specialization of it as a valid operand.
The same idea fills in two more structures:
- Library-defined features. Standard-library supertypes (such as
Part) carry features the spec says every specialization gains; you don’t write them, but elaboration treats them as present. - Subsetting portions. When
tempSensors :> sensorsandpressureSensors :> sensorsboth subset the same collection, elaboration recognizes them as portions of the one inheritedsensorscollection, so they participate together in any query oversensors.
The point of elaboration is that you model in the direct relationships and the spec supplies the transitive ones. You don’t have to flatten the chain, redeclare inherited features, or enumerate library extensions – they are understood to exist because the spec says they do.
Do not infer a storage strategy from this rule. A tool can compute an inherited feature when asked; its absence as a second authored declaration is not a missing part of the model.
Common Mistakes
Specializing when composition is enough. If you just need a coffee machine with different parts inside, you do not need a new definition. Create a usage and configure it:
// Unnecessary specialization:
part def LargeCoffeeMachine :> CoffeeMachine {
part bigTank :>> waterTank : LargeWaterTank;
}
// Often sufficient: just a configured usage
part largeMachine : CoffeeMachine {
part bigTank :>> waterTank : LargeWaterTank;
}
The second form creates a specific usage of CoffeeMachine with a redefined water tank. No new definition needed. Specialize only when other parts of your model need to reference the new type by name – in constraints, requirements, or further specializations.
Redefining without a semantic reason. Renaming an inherited feature just because you prefer a different name adds noise to the model. Redefinition is a semantic statement: “this feature means something more specific here.” If the inherited name and type are fine, leave them alone.
Defining mirrored port types by hand. If you see two port definitions that are identical except that in and out are swapped, replace one with a conjugation. Two definitions means two places to update when the port structure changes. Conjugation keeps them automatically synchronized.
What You Have Built
The coffee machine now has a family, not just a shape. EspressoMachine
specializes CoffeeMachine, redefines the brewer to a pressurized one and pins
the temperature it inherits, and adds what only espresso machines have.
Four relationships did that work, and they are worth keeping straight:
- Specialization (
:>on a definition) – a more specific kind. - Redefinition (
:>>) – an inherited feature, made more specific here. - Subsetting (
:>on a usage) – this feature’s values are among those. - Conjugation (
~) – the same interface with its directions reversed.
Variation is the odd one out, and deliberately so: it is alternation rather
than refinement. EspressoMachine :> CoffeeMachine says every espresso machine
is a coffee machine. A variation says a configuration picks one of several peers.
In Chapter 13 the model starts carrying information about itself – maturity, ownership, safety classification – and you will use that to generate views for particular readers.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch12.sysml.
Metadata and Views
Your coffee machine model is built. It has structure, behavior, states, constraints, requirements, and verification cases. But models do not exist in isolation. People need to review them, approve them, and understand them – and different people care about different things.
This chapter covers two features that serve that human side of modeling: metadata for attaching governance information to model elements, and views for presenting the right slice of the model to the right stakeholder.
Comments vs. doc vs. Metadata
You have already used // comments throughout the model. Comments are notes in the source text. A tool ignores them during analysis. They are for the person reading the .sysml file, not for the model itself.
SysML v2 provides two more layers for human-oriented information, and the distinction matters.
doc is a model-level documentation string. Unlike a comment, doc is part of the model. A tool can extract it, display it in a hover tooltip, or include it in a generated report. You place it inside the element it describes:
part def Brewer {
doc /* Heats water and forces it through ground coffee
under controlled pressure and temperature. */
attribute waterTemp : Real;
attribute brewPressure : Real;
}
Metadata is structured, queryable data attached to model elements. Review status, maturity level, safety classification, responsible team – these are not free text. They have known fields and known values, and you need to filter or report on them. Metadata is the right tool for that job.
The rule of thumb: if it must be queried, filtered, or enforced by tooling, make it metadata. If it explains intent to a human reader, use doc. If it is a local note to yourself, use a comment.
Defining Metadata
A metadata definition looks like any other definition in SysML v2. You declare it with metadata def, and it can have attributes:
package CoffeeMachineGovernance {
private import ScalarValues::*;
metadata def ReviewStatus {
attribute status : String;
attribute reviewer : String;
}
metadata def SafetyClass {
attribute level : String;
}
}
ReviewStatus is now a reusable type. It says: anything that carries a review status has a status string and a reviewer string. You define it once, in one package, and every team uses the same structure.
This is important. If one team invents ReviewInfo with a state field and another invents ApprovalStatus with a currentStatus field, you end up with incompatible schemas that no tool can query uniformly. Centralize your metadata definitions early.
Annotating Elements with Metadata
To attach metadata to a model element, you use the @ annotation syntax. Use about when the annotation is declared alongside its target:
package CoffeeMachineStructure {
private import ScalarValues::*;
private import CoffeeMachineGovernance::*;
@ReviewStatus about CoffeeMachine {
:>> status = "approved";
:>> reviewer = "Systems Team";
}
part def CoffeeMachine {
doc /* Top-level system definition for the Smart Coffee Machine. */
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
attribute serialNumber : String;
}
}
The @ReviewStatus about CoffeeMachine { ... } block annotates the CoffeeMachine definition. The :>> syntax redefines the metadata attributes with specific values. After this annotation, any tool that queries the model can determine that CoffeeMachine has been approved by the Systems Team.
You can annotate any element – definitions, usages, requirements, actions, states. The about clause explicitly identifies the target; inside the element you can instead omit it:
@SafetyClass about SafetyInterlockReq { :>> level = "SIL-2"; }
requirement def SafetyInterlockReq {
doc /* The machine shall disable the heater if water
temperature exceeds 100 degrees Celsius. */
}
Now the safety interlock requirement carries its safety integrity level as structured data, not as a note buried in a comment.
Multiple Annotations
An element can carry more than one annotation. Stack them:
@ReviewStatus about Brewer {
:>> status = "in-review";
:>> reviewer = "Safety Board";
}
@SafetyClass about Brewer { :>> level = "SIL-2"; }
part def Brewer {
doc /* Heating subsystem. Under safety review. */
attribute waterTemp : Real;
attribute brewPressure : Real;
}
The Brewer now carries both governance metadata and safety classification. A review dashboard could show all elements where status is "in-review", or all elements classified as SIL-2.
A Maturity Tracking Example
Metadata is especially useful for tracking model maturity across a project lifecycle. Here is a pattern that covers the typical progression:
package CoffeeMachineGovernance {
private import ScalarValues::*;
metadata def ReviewStatus {
attribute status : String;
attribute reviewer : String;
}
metadata def SafetyClass {
attribute level : String;
}
metadata def MaturityLevel {
attribute level : String;
}
}
Then, as the model evolves, annotations track where each element stands:
@MaturityLevel about BrewCycle { :>> level = "preliminary"; }
action def BrewCycle;
@MaturityLevel about WaterTank { :>> level = "baselined"; }
part def WaterTank;
@MaturityLevel about BrewTempReq { :>> level = "verified"; }
requirement def BrewTempReq;
A project manager does not need to understand the brew cycle control flow to know that the action definition is still preliminary. The metadata tells them directly.
From Metadata to Views
Metadata tells tools about the status of individual elements. But stakeholders do not review individual elements. They review slices of the model that are relevant to their concerns. A safety engineer cares about hazards, interlocks, and safety-classified requirements. An architect cares about structural decomposition and interfaces. Showing either of them the entire model is counterproductive.
SysML v2 formalizes this with two concepts: viewpoints and views.
Viewpoints: Defining Stakeholder Concerns
A viewpoint declares what a particular stakeholder cares about. It does not select specific model elements – it describes the kind of information that matters for a particular review purpose.
package CoffeeMachineViews {
viewpoint def SafetyViewpoint {
doc /* Concerns: hazard mitigations, safety interlocks,
and safety-classified requirements. */
}
viewpoint def ArchitectureViewpoint {
doc /* Concerns: structural decomposition, subsystem
interfaces, and key part definitions. */
}
}
Think of a viewpoint as a lens. SafetyViewpoint says: when you look through this lens, you want to see safety-related elements. ArchitectureViewpoint says: through this lens, you want to see structure.
A viewpoint can also specify stakeholder to name who uses it, and purpose to explain why:
viewpoint def VerificationViewpoint {
doc /* Requirement-to-test traceability for verification closure. */
}
Views: Selecting Model Content
A view usage is the concrete selection. It is typed by a view def, can satisfy one or more viewpoints, and uses expose to pull specific elements into the view.
Before getting into stakeholder-specific views, it helps to see the simplest possible case: one view definition, one usage, one expose. This is the running anchor we will refine through the rest of the chapter.
package CoffeeMachineViews {
private import CoffeeMachineStructure::*;
view def CoffeeOverview;
view overview : CoffeeOverview {
expose CoffeeMachine;
}
}
That’s a complete, valid view: a definition that names the kind of view, and a usage that picks up the definition and exposes the top-level part. Anything that walks the model can ask “what does the overview view contain?” and get back the CoffeeMachine element and – by transitive containment – everything inside it.
The definition supplies a reusable recipe (filter, render); the usage selects concrete content with expose. An exposed element remains owned by its original namespace.
Now, the more interesting case. A view usage can satisfy one or more viewpoints, and can expose more than one element. satisfy reaches a viewpoint because a ViewpointDefinition is a RequirementDefinition in the abstract syntax – satisfying a viewpoint and satisfying a requirement are the same relationship:
package CoffeeMachineViews {
private import CoffeeMachineStructure::*;
private import CoffeeMachineRequirements::*;
viewpoint def SafetyViewpoint {
doc /* Concerns: hazard mitigations and safety interlocks. */
}
viewpoint def ArchitectureViewpoint {
doc /* Concerns: structural decomposition and interfaces. */
}
view def SafetyReviewView;
view def ArchitectureReviewView;
view safetyReview : SafetyReviewView {
viewpoint perspective : SafetyViewpoint;
expose CoffeeMachineRequirements::SafetyInterlockReq;
expose CoffeeMachineRequirements::BrewTempReq;
}
view architectureReview : ArchitectureReviewView {
viewpoint perspective : ArchitectureViewpoint;
expose CoffeeMachineStructure::CoffeeMachine;
expose CoffeeMachineStructure::Brewer;
expose CoffeeMachineStructure::Grinder;
expose CoffeeMachineStructure::WaterTank;
}
}
expose is the key operation. It does not copy the element into the view. It references it. The safetyReview view usage satisfies SafetyViewpoint and exposes two requirements. The architectureReview view usage satisfies ArchitectureViewpoint and exposes four structural definitions. A tool rendering the safety review shows only the safety requirements – the grinder and its grind settings are nowhere in sight.
This is the critical difference between a view and a package. A package owns its members. A view exposes references to members that live elsewhere. The underlying model is unchanged. Views are projections, not copies.
Two flavours of expose: member and namespace
expose comes in two forms, and the choice is more than syntactic sugar.
view interfaceReview : ArchitectureReviewView {
expose CoffeeMachineStructure::Brewer; // member expose
expose CoffeeMachineStructure::*; // namespace expose
}
The first form is a member expose: it pulls one named element into the view. The second is a namespace expose: it pulls every member of the named namespace into the view. The trailing ::* is the cue.
Member expose is precise; namespace expose is sweeping. You reach for namespace expose when the natural unit of review is a whole package – the safety package, the requirements package, the API surface – and you do not want the view to drift behind the package as new elements are added. Once CoffeeMachineStructure::* is exposed, anything new you drop into that package is automatically visible in the view.
Both forms are subject to the same qualified-name resolution. If you misspell the qname, the view exposes nothing for that line. There is no error – the line is parsed, the qname does not resolve, and tools simply have nothing to show. That silent failure mode is one of the more common authoring mistakes; we return to it in Common Mistakes below.
Anonymous view usages
A view usage does not have to be named. When you want a one-off slice of the model – to share a screenshot in a review, to drop a quick visualization into a diagram, to test what a particular expose would surface – you can write the usage inline without giving it a name:
view scratch { expose CoffeeMachine; }
That is a complete view usage. There is no view def, no satisfaction, no rendering – just a name and a body. Tools treat it like any other view usage: they resolve the expose, project the element, and render the result. Anonymous views are the modeling equivalent of a scratch buffer. Reach for them when you want a slice now and have not yet decided whether the slice deserves a definition.
Combining Metadata and Views
Metadata and views work well together. You can use metadata annotations to mark which elements belong in which review, and then build views that surface exactly those elements:
package CoffeeMachineReview {
private import ScalarValues::*;
private import CoffeeMachineGovernance::*;
private import CoffeeMachineStructure::*;
private import CoffeeMachineRequirements::*;
viewpoint def SafetyViewpoint {
doc /* All elements classified SIL-2 or above,
plus their associated requirements. */
}
view def SafetyReviewView;
// The safety review exposes only safety-relevant elements
view safetyReview : SafetyReviewView {
viewpoint perspective : SafetyViewpoint;
expose CoffeeMachineRequirements::SafetyInterlockReq;
expose CoffeeMachineRequirements::BrewTempReq;
expose CoffeeMachineStructure::Brewer;
}
viewpoint def ArchitectureViewpoint {
doc /* System decomposition for architecture board review. */
}
view def ArchitectureReviewView;
// The architecture review exposes structural elements
view architectureReview : ArchitectureReviewView {
viewpoint perspective : ArchitectureViewpoint;
expose CoffeeMachineStructure::CoffeeMachine;
expose CoffeeMachineStructure::Grinder;
expose CoffeeMachineStructure::Brewer;
expose CoffeeMachineStructure::WaterTank;
}
}
Notice that Brewer appears in both views. The safety engineer sees it because it contains the heater that is safety-classified. The architect sees it because it is a major subsystem. Same element, different reasons, different context. The model does not duplicate anything.
Filtering a View with filter
expose says “pull this element (or namespace) in”. Sometimes you want the opposite shape: pull a whole namespace in, then filter out the parts that do not belong in this particular view. That is what filter is for.
Note where each half lives: expose sits in the view usage, while filter typically sits in the view definition, where it becomes part of the reusable recipe and screens whatever any usage of that definition exposes. (A usage body may carry its own filter too, for one-off narrowing.)
A filter clause is a Boolean expression evaluated once per element that the view exposes. If the expression is true, the element stays in the view; if it is false, the element is dropped.
The spec’s own filter idiom is a classification test: the @ operator asks whether the current element is classified by a metaclass or a metadata definition. That is the portable form, and it is what the standard library’s own filtered packages use:
view def PartsOnlyPortable {
filter @SysML::PartUsage; // metaclass test
}
view partsOnly : PartsOnlyPortable {
expose CoffeeMachineStructure::*;
}
view def MandatorySafety {
filter @SIL2;
}
view mandatorySafety : MandatorySafety {
expose CoffeeMachineStructure::*;
}
The second view tests for a more specific annotation. In the shared vocabulary, metadata def SIL2 :> SafetyClassification { :>> level = "SIL-2"; } captures the value that the review is interested in. Apply @SIL2 to the relevant elements, then select them with filter @SIL2;. This avoids a qualified reference to a feature of the metadata type outside its featuring context.
The simplest filters are literal:
view def AllOfIt { filter true; } // accept everything
view def NoneOfIt { filter false; } // accept nothing
filter true and filter false are useful as scaffolding – a starting point you can sharpen.
Use metaclasses rather than comparing a private renderer’s strings. The filter below recognizes a part usage even if the user renames it. For a review of one specific definition it is simpler to expose that definition directly:
view def PartsOnly { filter @SysML::PartUsage; }
view structureParts : PartsOnly { expose CoffeeMachineStructure::**; }
view brewerOnly { expose CoffeeMachineStructure::Brewer; }
You can stack filters. Multiple filter clauses on the same view compose as logical AND: an element passes only if every filter accepts it.
view def SafetyParts {
filter @SysML::PartUsage;
filter @SafetyClassification;
}
view safetyParts : SafetyParts { expose CoffeeMachineStructure::**; }
Only a part usage carrying the specified metadata meets both filters. If an expected member is missing, check the exposed scope first, then test each predicate. sysml -explain filter-not-evaluated explains the difference between a valid filter the tool does not evaluate and a misspelled reference, which is a diagnostic. Do not rely on either as a selection rule.
Renderings
A view says what to show. A rendering says how to show it. They are separate concepts because the same slice of the model can sensibly appear as a table, a tree, a diagram, or a matrix depending on who is reading it.
The spec gives you a small kit:
rendering def Foo;declares a rendering by name.- A
renderclause can reference a rendering usage (render Views::asTreeDiagram;) or declare a typed rendering inline (render rendering presentation : StandardRendering;). - A view usage can override its definition’s rendering by writing its own
renderclause in the usage body.
Here is the running coffee-machine example with a rendering attached:
package CoffeeMachineViews {
private import CoffeeMachineStructure::*;
private import CoffeeMachineRequirements::*;
rendering def StandardRendering;
view def SafetyReviewView {
render rendering presentation : StandardRendering;
}
view safetyReview : SafetyReviewView {
viewpoint perspective : SafetyViewpoint;
expose CoffeeMachineRequirements::SafetyInterlockReq;
expose CoffeeMachineRequirements::BrewTempReq;
}
}
The render rendering presentation : StandardRendering; line is a ViewRenderingMembership: it declares a rendering usage inside the view and types it by the rendering definition. The view uses the rendering by owning a usage of it.
A rendering definition can carry attributes – things like layout direction, paper size, page break preferences – but most authors start with an empty rendering def and let the tool’s defaults take over. The point of the rendering is the binding: the view declares its intent, and the tool that consumes the view picks up the matching rendering and presents the slice accordingly.
What Kind of Diagram Does a View Become?
You have written view def SafetyReviewView and view def CoffeeOverview. When a tool renders one of these, what shape does it choose? A flat list? A tree? A diagram with boxes and lines? The standard view definition describes the intended content. The producing tool interprets the rendering member, including an inherited rendering.
The standard library package StandardViewDefinitions defines exactly eight standard view definitions, each corresponding to a recognizable diagram shape. When you write view def Foo :> InterconnectionView, you are saying “this view should be presented as an interconnection diagram”. When you write view def Foo :> ActionFlowView, you are saying “this view should be presented as an action-flow diagram”. The supertype is the contract.
The eight standard view definitions are:
| Supertype | What it shows |
|---|---|
GeneralView | Any exposed elements, as a general graph of nodes and edges |
InterconnectionView | Features as (nested) nodes and the connections between them as edges |
ActionFlowView | Actions, their parameters, and the flows between them |
StateTransitionView | States and the transitions between them |
SequenceView | Time-ordered event occurrences and messages on lifelines |
GeometryView | Spatial items visualized in two or three dimensions |
GridView | Elements and relationships in a rectangular grid (tables, matrices) |
BrowserView | The hierarchical membership structure (containment tree) |
Pick the supertype that matches the question the view is answering. “Show me how the parts connect” → InterconnectionView. “Show me the order of actions in the brew cycle” → ActionFlowView. “Show me the state machine” → StateTransitionView. The supertype is the difference between a view that lands as a useful diagram and one that lands as a generic table.
Two diagram kinds you might expect are deliberately not on the list. There is no UseCaseView and no RequirementView in the standard library. For those, the library’s own documentation on GeneralView gives the recipe: specialize GeneralView and narrow it with a filter. A requirement view, for example, is a GeneralView filtered to requirement elements:
view def RequirementOverview :> GeneralView {
filter @SysML::RequirementDefinition or @SysML::RequirementUsage
or @SysML::SatisfyRequirementUsage;
}
The same pattern gives you a package view, a definition-and-usage view, or any other slice-by-kind: GeneralView plus the metaclass filter naming the kinds you want.
view def CoffeeStructure :> InterconnectionView;
view def BrewSequence :> ActionFlowView;
view def HeaterStateMachine :> StateTransitionView {
filter @SysML::StateUsage or @SysML::TransitionUsage;
}
view structure : CoffeeStructure { expose CoffeeMachine; }
view brewOrder : BrewSequence { expose BrewCycle; }
view heaterStates : HeaterStateMachine { expose Brewer; }
Each of those views asks for model elements wrapped in a different presentation contract. The tool consuming them picks the appropriate diagram engine based on the supertype. Choose the intended view kind explicitly. A view def Foo with no supertype is treated as the most general kind of view – GeneralView is the root of the family – and renders as a generic projection; the renderer does not infer a kind from the view’s name.
The Stakeholder → Viewpoint → View → Rendering Chain
Everything in this chapter so far has been one element at a time. Pulling them together: SysML v2’s view model is a single chain that runs from a person’s concern at one end to a rendered artifact at the other.
Stakeholder a person or role with a question
│
│ has
▼
Viewpoint the question, captured as a requirement
│ (`viewpoint def` is a kind of `requirement def`)
│ satisfied by
▼
View Usage the concrete view — exposes the content and declares
│ which viewpoints it satisfies
│ (typed by a View Definition: the reusable recipe —
│ supertype + filters + rendering;
│ `view def` is a kind of `part def`)
│ rendered through
▼
Rendering Usage the visual style applied
│
│ produces
▼
View artifact what a human sees
Here is the full chain in 25 lines:
package SafetyReview {
private import CoffeeMachineStructure::*;
// Stakeholder — a role
part def SafetyEngineer;
// Viewpoint — the concern, expressed as a requirement
viewpoint def SafetyConcernViewpoint {
subject selectedView : Views::View;
stakeholder reviewer : SafetyEngineer;
doc /* Reviewers must see all SIL-2-classified parts. */
}
// Rendering — the style
rendering def DarkInterconnection;
// View Definition — the recipe
view def SafetySIL2View :> InterconnectionView {
render rendering dark : DarkInterconnection;
filter @SIL2;
}
// View Usage — the concrete instance
view sil2Diagram : SafetySIL2View {
viewpoint perspective : SafetyConcernViewpoint;
expose CoffeeMachine;
}
}
Reading top to bottom: a SafetyEngineer is the stakeholder; the SafetyConcernViewpoint captures their concern; the DarkInterconnection is a reusable rendering style; the SafetySIL2View is the recipe that filters to SIL-2 parts only and applies the dark rendering; the sil2Diagram is the concrete view a tool actually renders – it exposes the content and declares that it satisfies the viewpoint.
(Strictly, a satisfy declaration may target a named viewpoint usage; a nested composite viewpoint usage is itself asserted satisfied. A satisfy declaration is an ordinary usage member, so the grammar admits it inside a view def body as well – the standard library’s own abstract View definition carries one. But the satisfaction claim reads most naturally on the concrete view, and that is where this book puts it.)
You do not have to use every link in the chain. Most authors start at the View end (view def + view usage) and add viewpoints + stakeholders only when traceability becomes a requirement. But when you do need traceability, every link is queryable: “which views satisfy this viewpoint”, “which viewpoints concern this stakeholder”, “what is the rendering for this view”. The chain is the trace.
Finding and rendering a view
An editor outline shows what a file declares. A view selects elements for a stakeholder; it may expose elements from several files. To discover the published selections and render one, load the project rather than just the file declaring the view:
sysml -list views src/examples/coffee-machine
sysml -render BookViews::connectionOverview -render-form dot -o connections.dot src/examples/coffee-machine
dot -Tsvg connections.dot -o connections.svg
DOT is the rendering description; Graphviz lays it out as a static SVG. For a one-off exploration OpenSysML also has pseudo-views. A named view usage, unlike a shell command, travels with the model and can be reviewed along with it.
When to Add Metadata and Views
You do not need metadata or views from day one. They become valuable when the model is shared beyond the original author:
- Add
docearly. As soon as someone else will read your definitions, document intent. It costs almost nothing and saves review time. - Add metadata when governance starts. When the project has formal reviews, maturity gates, or safety classifications, metadata ensures that status is tracked in the model, not in a spreadsheet that drifts out of sync.
- Add views when stakeholders diverge. When different reviewers need different slices, views prevent the “here is the entire model, find what you need” problem.
If you are working alone on a small model, comments and doc may be all you need. If you are on a team with safety reviews, architecture boards, and verification milestones, metadata and views are essential governance infrastructure.
Visualizing Views and Metadata
Views
Metadata
Common Mistakes
Storing review status only in comments. A comment like // approved by safety board 2024-03-15 is invisible to tooling. If you need to query which elements are approved, that information must be metadata. Use @ReviewStatus { :>> status = "approved"; } instead.
Creating one giant view for all stakeholders. A view that exposes everything is just the model again. The value of a view is in what it leaves out. Keep views small and purpose-driven. If a stakeholder does not need to see the grinder to make their decision, do not expose it.
Duplicating model content in views. Views reference elements with expose. They do not redefine them. If you find yourself copying attribute lists or requirement text into a view, you are doing it wrong. Expose the original element and let the tool present it.
Proliferating metadata definitions. If the safety team defines SafetyLevel and the quality team defines SafetyRating with the same fields, you have a schema drift problem. Agree on shared metadata definitions early and put them in a governance package that everyone imports.
Treating an unevaluated filter as evidence. A syntax error, an unresolved name and a valid predicate the renderer cannot evaluate are different diagnoses. Check -strict -validate and the actual output before accepting a filtered view.
Treating render as a styling hook. render rendering presentation : StandardRendering; selects a RenderingDefinition. It does not set fonts, colours, or themes. If you want a view to look a particular way, the visual style is a property of the tool that consumes the view, not of the view itself. Use render to declare presentation intent (“table”, “diagram”, “matrix”) and let the tool’s visual style apply.
Confusing a file outline with a view. A file outline follows the source tree. A view selects content with expose and can draw from more than one namespace.
Forgetting the supertype on view def. A bare view def Foo; is legal but renders as a generic projection – the most general view, GeneralView. For an interconnection, action-flow, or state-transition diagram, you must specialize from the matching standard definition: view def Foo :> InterconnectionView { ... }. There is no name-based fallback — a view called FooInterconnection without an explicit :> InterconnectionView still renders as a general view.
Putting expose in a view definition. Define the reusable selection criteria there, but put expose in the view usage (SysML §7.26).
What You Have Built
The model can now describe itself and present itself.
Metadata attaches structured facts about elements – maturity, owner, safety
classification – distinct from doc, which carries prose for a human, and from
comments, which are not in the model at all.
Views turn that into something a reader can use. The chain runs
stakeholder → viewpoint → view → rendering: someone has a concern, a viewpoint
states it, a view selects the elements that answer it, and a rendering says what
form the answer takes. expose (in the usage) chooses content, filter (in the
definition) narrows it, and the definition’s supertype decides what kind of
diagram you get.
The thing most worth remembering is that a view is part of the model. It is not a diagram someone drew and saved – it is a declaration of what a particular reader needs, which is why it can be reviewed, versioned, and regenerated when the model changes.
Chapter 14 turns outward to what you did not write: the standard library, and how much of the language is defined in it.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch13.sysml.
Libraries
You have been using libraries since Chapter 2. Every time you wrote private import ScalarValues::*, you reached into a model library that ships with the specification. This chapter makes that implicit knowledge explicit: what those libraries are, how they are layered, how to find things in them, and how to write one of your own.
The single most useful idea in this chapter is that the library is not a convenience bundle shipped alongside the language. A large part of what the language means is defined by library models, written in the same language you write. That is a deliberate design decision, and it is the reason this chapter is worth your time.
Why the Library Is Part of the Language
KerML is built in three syntactic layers, each adding more specific constructs on the one below (KerML §6.1):
- The Root Layer holds the most general constructs for structuring models: elements, relationships, annotations, packaging.
- The Core Layer holds the most general constructs whose semantics are based on classification.
- The Kernel Layer provides commonly needed modeling capabilities, such as associations and behavior.
Only the Core Layer is grounded directly, by interpreting it in mathematical logic. The Kernel Layer is different: its meaning comes from relating its abstract syntax constructs to model elements in the Kernel Semantic Library, which is written in KerML itself (KerML §6.1). A model you write reuses elements of that library in order to have any semantics at all, and the library models are what state the conditions under which a real system conforms to your model.
The specification is explicit about the payoff, and it is aimed squarely at you: because the library models are expressed in the same language as user models, engineers and tool builders can inspect them to understand what a model actually specifies (KerML §6.1).
So when this chapter tells you to go and read a library file, that is not a debugging tip. It is the intended way to find out what your own model means.
The Library Is Written in the Language
Here is the actual declaration of Real, from ScalarValues.kerml in the shipped standard library (the doc comments are elided):
standard library package ScalarValues {
private import Base::DataValue;
abstract datatype ScalarValue specializes DataValue;
datatype Boolean specializes ScalarValue;
datatype String specializes ScalarValue;
abstract datatype NumericalValue specializes ScalarValue;
abstract datatype Number specializes NumericalValue;
datatype Complex specializes Number;
datatype Real specializes Complex;
datatype Rational specializes Real;
datatype Integer specializes Rational;
datatype Natural specializes Integer;
datatype Positive specializes Natural;
}
These are KerML declarations from the library, not declarations to load again in a SysML project.
A model library is a collection of models meant to be reused across many user models, marked with the library keyword so tooling can recognize its contents as library elements (KerML §7.4.14). The libraries that ship with the specification go one step further and add standard, a marker reserved for the kernel and systems libraries and other recognized standard libraries (KerML §7.4.14).
This explains something you may have wondered about. Real is not a reserved word. It is not in the grammar. It is an ordinary datatype declared in an ordinary package, and you import it for exactly the same reason you import CoffeeBeans from your own package – because it lives somewhere else. Misspell it and you get an unresolved name, not a syntax error. Shadow it with a local declaration and the local one wins.
The same is true all the way down. part def Grinder works because Parts.sysml in the Systems Model Library declares abstract part def Part :> Item;, and your definition picks that up implicitly (SysML §9.1; see Chapter 12). Arithmetic works because RealFunctions.kerml declares functions named '+' and '*'.
The clearest case is ordering. When you write a succession in an action body – grind, then brew – and give it no explicit type, what you have created is a connector typed by a library association. Occurrences.kerml declares it:
assoc all HappensBefore specializes HappensLink, Without { <doc and end features> }
An ordering constraint, which certainly feels like it ought to be a grammar rule, turns out to be an association in a library file you can open and read. Nothing here is built in that could have been written down instead.
The Three Layers
The libraries are stacked in three layers, from general to specific.
| Layer | Where it is specified | What lives there |
|---|---|---|
| Kernel Model Library | KerML Clause 9 | The Semantic Library (§9.2), the Data Type Library (§9.3), the Function Library (§9.4) |
| Systems Model Library | SysML §9.2 | Parts, Items, Ports, Attributes, Actions, States, Requirements, Views, and 13 more |
| Domain Libraries | SysML §9.3 – §9.8 | Metadata, Analysis, Cause and Effect, Requirement Derivation, Geometry, Quantities and Units |
The Kernel Model Library is the foundation. The Semantic Library gives every element its meaning – Base, Occurrences, Performances, Transfers, Links, Objects and the rest (KerML §9.2). The Data Type Library holds the values: ScalarValues, Collections, VectorValues (KerML §9.3). The Function Library holds everything an expression can call (KerML §9.4). You name the Data Type Library constantly and the other two almost never.
The Systems Model Library is SysML’s own layer, and it is what turns a KerML classifier into a part, an action, or a requirement. You rarely import from it by hand, because every definition and usage you write already specializes something in it implicitly. part def Grinder picks up Parts::Part whether you ask for it or not.
Domain Libraries are the ones you import deliberately. They model concepts from domains of particular importance in systems engineering, and they are normative – available in every conformant model, not an optional add-on (SysML §9.1). Six of them ship: the Metadata Domain Library (§9.3), Analysis (§9.4), Cause and Effect (§9.5), Requirement Derivation (§9.6), Geometry (§9.7), and Quantities and Units (§9.8).
OpenSysML resolves shipped standard-library names without a project-specific library switch. An import still controls how those names can be written locally.
What a Wildcard Import Actually Brings In
You have written private import ScalarValues::* in every chapter. Now you can say precisely what it does, because you have seen the file. It brings in eleven names:
ScalarValue, Boolean, String, NumericalValue, Number, Complex, Real, Rational, Integer, Natural, Positive.
It does not bring in DataValue, even though ScalarValues imports it, because that import is written private import Base::DataValue. Which brings us to the rule that matters most when you start writing libraries of your own.
<visibility> import <QualifiedName>::*;
library package CoffeeIndustryTypes {
private import ScalarValues::*;
public import ISQ::CelsiusTemperatureValue;
enum def RoastLevel {
light;
medium;
dark;
}
item def CoffeeBeans {
attribute roast : RoastLevel;
attribute origin : String;
attribute recommendedBrewTemp : CelsiusTemperatureValue;
}
}
An import has its own visibility, independent of the visibility of the things it imports. A public import re-exports: anyone who imports CoffeeIndustryTypes also gets CelsiusTemperatureValue. A private import does not: String is usable inside CoffeeIndustryTypes but does not leak out of it.
A private import is not forwarded. Here the consumer can name a bean and a Celsius temperature because the library owns one and explicitly re-exports the other:
package CoffeeMachineModel {
private import CoffeeIndustryTypes::*;
private import ScalarValues::*;
part def Grinder {
item currentBeans : CoffeeBeans;
attribute targetTemp : CelsiusTemperatureValue;
}
}
CoffeeBeans and RoastLevel arrive because they are owned public members. CelsiusTemperatureValue arrives only because the library re-exported it with public import. Real and String do not arrive through CoffeeIndustryTypes at all – hence the second import line. If you are writing a library and you want consumers to get a type you depend on, you must say public import. The standard library is meticulous about this: ISQ.sysml writes private import ScalarValues::Real; for its internal need and public import ISQBase::*; for the twelve ISO 80000 parts it exists to aggregate.
The other thing to know about wildcards is what happens on a collision. If an imported name clashes with an owned member, or with a visible name from another imported namespace, the conflicting membership is hidden – it is simply excluded from the importing namespace (KerML §7.2.5.4). There is no error. Two wildcard imports that both export Temperature will quietly cancel each other out, and the failure surfaces later as an unresolved name at the point of use. This is the concrete cost of a wildcard import, and it is why the advice from Chapter 4 hardens as a model grows: wildcard while exploring, explicit once it matters.
Explicit single-member imports keep the dependency visible at the point of use; a wildcard is often more convenient while exploring.
There is a third form worth knowing, because the library documentation uses it:
private import <QualifiedName>::**;
The ::** suffix makes the import recursive – it imports the namespace, its visible members, and then recurses into each imported member that is itself a namespace (KerML §7.2.5.4). Reach for it rarely. private import ISQ::** is a very large hammer, as the next section makes clear.
Quantities and Units
attribute waterTemp : Real says almost nothing. Celsius, Fahrenheit, kelvin? The Quantities and Units Domain Library (SysML §9.8) exists to close that gap, and it is the most practical thing in this chapter.
Two packages do the work. ISQ gives you the quantity types – the International System of Quantities from ISO/IEC 80000. SI gives you the units. A dimensioned literal pairs a number with a unit:
<number> [ <unit> ]
package CoffeeMachineWithUnits {
private import ISQ::CelsiusTemperatureValue;
private import ISQ::PressureValue;
private import ISQ::VolumeValue;
private import ISQ::DurationValue;
private import SI::*;
part def Brewer {
attribute waterTemp : CelsiusTemperatureValue;
attribute brewPressure : PressureValue = 900000.0 [SI::Pa];
attribute brewTime : DurationValue = 25.0 [SI::s];
}
part def WaterTank {
attribute currentLevel : VolumeValue;
attribute maxCapacity : VolumeValue = 1.5 [SI::L];
}
}
The square brackets are not array syntax. [ is a genuine operator, declared in the library as calc def '[' { in num: Number[1]; in mRef: ScalarMeasurementReference[1]; return quantity : ScalarQuantityValue[1]; } in QuantityCalculations. It takes a number and a measurement reference and constructs a quantity value. The specification uses the same form in an accept action: accept after 30 [SI::s] (SysML §8.4.13.6).
SI::Pa, SI::s, SI::L are the unit short names. SI.sysml declares each unit with both, as in attribute <Pa> pascal : PressureUnit = N/m^2; – so SI::Pa and SI::pascal name the same thing, and the unit’s definition in terms of the base units is right there in the model.
Watch the temperature names
This is worth a paragraph because it will bite you. There is no ISQ::TemperatureValue declared anywhere. The name resolves, but only as an alias: ISQThermodynamics.sysml contains alias TemperatureValue for ThermodynamicTemperatureValue;. Thermodynamic temperature is measured in kelvin. So attribute waterTemp : ISQ::TemperatureValue = 93.0 [SI::K] describes water 180 degrees below freezing.
There are three temperature quantities, and the distinction between them is real physics rather than library clutter:
package TempOptions {
private import ISQ::ThermodynamicTemperatureValue;
private import ISQ::CelsiusTemperatureValue;
private import ISQ::TemperatureDifferenceValue;
private import SI::*;
part def Brewer {
attribute targetTemp : ThermodynamicTemperatureValue = 366.15 [SI::K];
attribute elementRise : TemperatureDifferenceValue = 6.0 [SI::'°C'];
attribute brewTemp : CelsiusTemperatureValue = 93.0 [SI::'°C_abs'];
}
}
ThermodynamicTemperatureValue (ISQBase.sysml) is absolute temperature in kelvin. CelsiusTemperatureValue (ISQThermodynamics.sysml) is the Celsius reading. TemperatureDifferenceValue is declared in ISQ.sysml itself, and its doc comment explains why it has to exist separately: a difference of 6 °C is not the same kind of quantity as a temperature of 6 °C.
The unit names repay a close look, because they are how the library encodes that difference. SI::'°C' is typed TemperatureDifferenceUnit, and it converts to kelvin with a factor of 1. SI::'°C_abs' is not a unit at all: it is typed IntervalScale, which sits under MeasurementScale rather than MeasurementUnit, and it carries an explicit zero shift against the kelvin scale.
The reason for that split is visible in the library. UnitConversion declares exactly three features – referenceUnit, conversionFactor, isExact. There is no offset anywhere in it, so unit conversion is purely multiplicative. An absolute Celsius reading needs a zero shift, so it cannot be expressed as a MeasurementUnit, and the library models it as a scale instead. Celsius is an interval scale, not a ratio scale, and the type hierarchy says so.
The 273.15 is not missing, either – it is inside the '°C_abs' declaration, as a placement of one coordinate frame relative to another:
The following is an excerpt of the SI library, not a second definition to add to a model:
private attribute zeroDegreeCelsiusInKelvin: ThermodynamicTemperatureValue = 273.15 [K];
attribute zeroDegreeCelsiusToKelvinShift : CoordinateFramePlacement :>> transformation {
:>> source = K; :>> origin = zeroDegreeCelsiusInKelvin;
}
That is worth noticing, because it reframes what looks like a gap. The library has not forgotten about Celsius. It has decided that a scale with a shifted origin is a coordinate frame placement, not a unit conversion – which is precisely why Celsius cannot be another derived unit in the manner of km or kPa.
Quote both names – ° is not an identifier character, so SI::'°C' needs the single quotes.
An interval scale has a shifted origin; a temperature difference does not. Leave the scale explicit when recording Celsius readings.
The scale of it
Some sense of proportion, since it bears on how you import. ISQ is almost entirely an aggregator: twelve public imports, one for base quantities and eleven for the numbered ISO/IEC 80000 parts, plus the three temperature-difference declarations it owns. Those twelve packages declare 945 attribute defs between them, of which 524 are distinct *Value quantity types, plus 250 aliases. SI adds 255 units. SI also does public import ISQ::*, so private import SI::* pulls every quantity type in behind the units.
That is fine – name resolution does not care about volume – but it is a lot of surface for a collision to hide in. If your model needs four quantity types, import four quantity types.
Use sysml -explain incommensurable-binding for the diagnostic on a value bound to a feature of an incompatible dimension. A reading in watts is not a stored energy in watt-hours.
Finding Things in the Library
Consult the published model libraries. A definition in the library determines what a name means. Whether a particular evaluator computes its body is a different question. For instance RealFunctions declares operations on real numbers; QuantityCalculations covers quantities with units. Check the qualified name and parameter types rather than choosing solely by the spelling sqrt.
For a local expression, use OpenSysML’s -e option. To test a function you have written, pass the model and call it with -calc:
sysml -e 'true implies false'
sysml -calc 'CoffeeCalculations::ExtractionTime(92.0, 9.0)' src/examples/coffee-machine
A successful static check is about the loaded model. An evaluator returning an undetermined result is not the same as a syntax error or an unresolved name.
Reading a kernel library file
Open a file under library.systems/ and it looks like the SysML you have been writing all book. Open one under library.kernel/ and the first line may not. The kernel libraries are written in KerML, one layer below SysML, and they use declaration keywords SysML models never need. Here is enough to stop being surprised by them.
| KerML | What it declares | Real use |
|---|---|---|
struct | A structure. SysML’s part def and item def sit on this. | abstract struct Object specializes Occurrence |
assoc | An association – a relationship as a classifier. | assoc all HappensBefore specializes HappensLink, Without |
assoc struct | An association that is also a structure, so the link itself has features. | abstract assoc struct LinkObject specializes Link, Object |
function | A function. This is the KerML spelling; SysML writes calc def. | function sqrt{ in x: Real[1]; return : Real[1]; } |
behavior | A behavior. SysML’s action def sits on this. | abstract behavior Performance specializes Occurrence |
inv | An invariant – a constraint that must hold. | inv { flattenedSize == size(elements) } |
bool | A boolean expression, not a boolean type. | bool guard[*] subsets enclosedPerformances; |
bool is the one most likely to mislead, so it is worth being explicit: the grammar production is BooleanExpression, and bool introduces an expression that yields a boolean. It is not a shorthand for the Boolean datatype.
You will also meet disjoint, which asserts that two types can have no common instances:
abstract behavior Performance specializes Occurrence disjoint from Object { <body> }
That says a performance is never an object – something happening is not something existing. It reads oddly the first time and then becomes one of the more useful things in the semantic library.
Three further keywords exist for writing a relationship as a standalone, separately named declaration rather than inline:
subclassifier X specializes Y,disjoining <name> disjoint X from Y, andinverting <name> inverse X of Y. They are rare – across all 36 kernel library files,subclassifieris used once and the other two never. If you meet them, they are the same relationships in a different shape.
That is the whole surprise. The kernel libraries are not a different language; they are the layer SysML’s own keywords are defined on top of, which is exactly what KerML §6.1 says they are.
The Function Library
The libraries are not only a type vocabulary. They also declare every function an expression can call:
package TankMath {
private import ScalarValues::*;
part def WaterTank {
attribute maxCapacity : Real default = 1500.0;
attribute currentLevel : Real := 0.0;
attribute headroom : Real = max(0.0, maxCapacity - currentLevel);
attribute fillFraction : Real = currentLevel / maxCapacity;
}
}
max is not built into the language. It is declared in RealFunctions, and it is in scope because the Function Library loads with every project. Here is the useful subset, with the package each name actually comes from:
| Group | Package | Names |
|---|---|---|
| Real arithmetic | RealFunctions | abs, min, max, sqrt, floor, round, sum, product, re, im, arg |
| Cross-numeric | NumericalFunctions | isZero, isUnit, abs, min, max, sum, product, sum0, product1 |
| Conversions | RealFunctions, IntegerFunctions, RationalFunctions | ToInteger, ToRational, ToReal, ToNatural, ToString |
| Trigonometric | TrigFunctions | sin, cos, tan, cot, arcsin, arccos, arctan, deg, rad |
| Strings | StringFunctions | Length, Substring, ToString |
| Sequences | SequenceFunctions | size, isEmpty, notEmpty, includes, excludes, union, intersection, including, excluding, subsequence, head, tail, last |
| Collections | CollectionFunctions | size, isEmpty, notEmpty, contains, containsAll, head, tail, last |
| Iteration and filtering | ControlFunctions | select, selectOne, collect, reject, reduce, forAll, exists, allTrue, anyTrue, minimize, maximize |
| Occurrences | OccurrenceFunctions | isDuring, create, destroy, addNew, addNewAt |
| Quantities | QuantityCalculations | ConvertQuantity, ToDimensionOneValue, plus dimension-aware abs, min, max, sqrt, sum, product |
Two things to keep straight.
First, arithmetic, ordering and equality are written as operators, not as function calls. Exponentiation is ** or ^; ordering is < > <= >=; inequality is !=. There is no pow, no lessThan, no notEquals – reach for the operator. Appendix A has the full operator table.
But – and this is the interesting part – those operators are library functions. RealFunctions declares function '**' and function '<'. BaseFunctions declares function '==', function 'istype', function 'as' and function 'meta'. ControlFunctions declares function 'if', function 'and', function 'or', function 'implies'. The names are quoted because they are not identifiers, and that is the only reason a grep for function istype comes back empty while function 'istype' finds it. So the operators are not a separate mechanism bolted onto the grammar; they are library functions with special syntax, which is why QuantityCalculations can declare its own '+' and give addition a dimension-aware meaning for quantity values.
Second, that table is a subset, not an inventory. Each number type has its own package (IntegerFunctions, NaturalFunctions, RationalFunctions, ComplexFunctions, VectorFunctions), and there are more for booleans, data values and scalars. Look for a library name before writing your own calc def.
Writing Your Own Library Package
Everything above applies to libraries you write. The declaration takes one extra keyword:
library package <Name> { ... }
library package CoffeeIndustryTypes {
private import ScalarValues::*;
public import ISQ::CelsiusTemperatureValue;
enum def RoastLevel {
light;
medium;
dark;
}
item def CoffeeBeans {
attribute roast : RoastLevel;
attribute origin : String;
attribute recommendedBrewTemp : CelsiusTemperatureValue;
}
}
library marks the package as reusable vocabulary rather than part of one particular design, which lets tooling treat everything inside it as a library element (KerML §7.4.14). Define domain vocabulary once here, import it everywhere else, and the definitions cannot drift apart.
Three things to get right when you write one:
- Re-export what your consumers need.
public importfor anything that appears in a signature they will use;private importfor your internal dependencies. Getting this backwards produces a library whose types nobody can name. - Keep the export surface small. Your consumers will wildcard-import you. Every public name is a potential silent collision.
- Do not write
standard.standard library packageis reserved for the kernel and systems libraries and other recognized standard libraries (KerML §7.4.14). It is not a quality marker for your own work.
Libraries the Runtime Recognizes
Several library packages define patterns that an implementation can interpret. A declaration of a pattern is not a promise of a numerical solver.
From the Analysis Domain Library (SysML §9.4):
| Package | What it provides |
|---|---|
StateSpaceRepresentation | The ODE pattern: calc def GetDerivative and calc def GetOutput to subtype, action def ContinuousStateSpaceDynamics to specialize (see Chapter 16) |
TradeStudies | TradeStudy, EvaluationFunction, MinimizeObjective, MaximizeObjective |
SampledFunctions | SampledFunction, SamplePair, and the Domain / Range / Sample / Interpolate calculations |
AnalysisTooling | Exactly two declarations, both metadata: metadata def ToolExecution and metadata def ToolVariable, for tying a model to an external analysis tool |
From the Kernel Model Library (KerML §9.2):
| Package | What it provides |
|---|---|
Occurrences | Occurrence, Life, and the snapshots / startShot / endShot structure – anything with temporal extent |
Clocks | Clock, BasicClock, and the universalClock feature |
SpatialFrames | SpatialFrame, CartesianSpatialFrame, and the defaultFrame feature |
Performances | The Performance and Evaluation hierarchy behind actions and expressions |
Choose dimensioned types when the equation depends on units. Write conservation equations where needed; do not assume a connector synthesizes them. See Appendix E.
What You Have Built
You can look up a quantity type and its unit separately, use explicit visibility to control which names travel through a library, and test the numerical meaning with a concrete calculation.
The remaining question is where the library comes from – which libraries a project loads, how versions get pinned, and how you ship your own library package so somebody else can depend on it. That is Chapter 15.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch14.sysml.
Projects and Workspaces
Two Questions That Sound Alike
In Chapter 4, you organized model elements into packages and made names visible across package boundaries with import. In Chapter 14, you saw that a large share of the language’s meaning lives in standard libraries your model draws on. Both chapters kept quiet about a practical question: when you write private import BeverageTypes::*, how does a tool know where BeverageTypes lives – which file, which directory, which version?
The honest answer is that these are two different questions, and only one of them belongs to SysML v2.
- “What does this name mean here?” is a language question. KerML defines name resolution precisely: resolution starts in the local namespace and searches outward through containing namespaces (KerML §7.2.5.1), and
importmakes another namespace’s visible members available under shorter names (KerML §7.2.5.4). Every conformant tool must answer this question the same way. - “Which files and projects should be loaded so those names exist at all?” is a tooling question. The specification defines resolution over the elements a tool has loaded; it does not say how the tool decides what to load. Manifests, dependency declarations, version pins, lock files, and workspace layouts are each tool’s own answer, and they differ between tools.
Keep the two apart and this chapter is short. An import is part of your model and travels with it. A dependency declaration is part of your project setup and does not.
import Is Language; a Dependency Is Not
Here is the boundary in one example. The model side is SysML v2 and means the same thing in every conformant tool:
package BeverageTypes {
item def Water;
item def CoffeeBeans;
}
package CoffeeParts {
private import BeverageTypes::*;
part def WaterTank {
item water : Water;
}
}
The import says: inside CoffeeParts, the visible members of BeverageTypes may be used by their unqualified names. It says nothing about disk layout. BeverageTypes could be in the same file, another file, another project, or an archive fetched from a server – the import is equally correct in all four cases, and equally meaningless if no loaded element provides the name.
The project side is about which inputs OpenSysML loads. In the beverage workspace the library and its consumer are separate files. From the edition root:
sysml -strict -validate src/examples/beverage-workspace/beverage-types/src/types.sysml src/examples/beverage-workspace/coffee-machine/src/parts.sysml
Loading the consumer alone does not make the other project’s declarations available. Loading the two directories instead of the two files is another way to supply the same model elements. The text in the import stays the same.
The practical rule: if removing a line changes what your model means, it is language. If removing it changes what your tool can find, it is tooling.
Projects, Commits, and Interchange
The language stops at name resolution, but OMG does standardize two things above the level of a single file, and both are worth knowing at concept level.
Projects and commits. The SysML v2 specification suite includes a standard API for model repositories, organized around a small set of concepts: a project is a top-level container for a model, a branch is a named line of development within it, and a commit is an immutable snapshot of the model at a point in time. These are interchange notions – they let two tools talk about “the same model at the same version” without sharing an implementation. Appendix C covers the API surface itself.
Interchange artifacts. As Chapter 1 noted, model interchange is normative: a project travels as a .kpar archive, and the textual files inside it use the .sysml extension. A .kpar bundles model files with .project.json (project identity and dependencies) and .meta.json (archive metadata, including the model index). These are artifacts tools produce and consume so that models can cross tool boundaries; in day-to-day modelling you author .sysml files and let your toolchain generate the interchange form when you publish.
That is the whole standardized story: names resolve by KerML’s rules, projects and commits identify model versions, and .kpar carries a project between tools. Everything else – how dependencies are declared, how versions are pinned and cached, how several projects are grouped into a workspace – is toolchain territory.
Working with projects in OpenSysML
For this book the workspace is simply the set of input files. OpenSysML accepts a directory and walks it; it loads the named sources together before resolving names. Do not pass the whole book: independent exercises deliberately reuse package names. To share the coffee machine, share src/examples/coffee-machine/; -library-root is for locating installed dependency projects, not importing an arbitrary sibling package into scope.
For project interchange, use KerML project metadata and .kpar, not a tool-specific workspace manifest. OpenSysML’s -bundle takes a project directory, -o selects the archive and -unbundle restores a project to a new or empty directory. Try the beverage project in a new scratch directory:
out=$(mktemp -d)
sysml -bundle src/examples/beverage-workspace -o "$out/beverage.kpar"
sysml -unbundle "$out/beverage.kpar" -o "$out/restored"
sysml -strict -validate "$out/restored"
OpenSysML generates archive metadata when the source directory does not supply it. A repository commit, a package namespace and a directory are distinct: changing the way you load the files need not change a single model name.
What travels and what does not
A public import still re-exports the same members in a receiving tool. A local dependency search path does not travel inside that declaration. Pin the exact model and library releases along with the command used to check them. Chapter 16 uses the same project for several different runs.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/ch15.sysml.
Running Your Model
A structure, a state machine and a requirement can all be valid declarations before anyone runs them. Checking answers “is this model well formed?” Running asks a different question: “given these inputs and this schedule, what happens?” This chapter uses one calculation, one timed controller and the instrumented machine from Chapter 10. Run the commands from the root of this edition.
16.A What It Means for a SysML v2 Model to Run
Start with the distinction that everything else depends on:
the model a file (or workspace) of declarations. Has a tree shape,
cross-references, types. Has no time and no current value.
a run of it one trajectory through that model. Has a clock, a current
value for every observable, a history, and a current state
for every state machine.
The model is not the run. The model is what you wrote. A run is one execution of it. One model has many possible runs.
The language already has vocabulary for this, in KerML rather than SysML. A definition classifies; the thing classified is an occurrence, and clause 9.2.4.2.13 of the KerML specification puts it plainly: “An Occurrence is Anything that happens over time and space (the four physical dimensions). Occurrences can be portions of another Occurrence within time and space, including slices in time, leading to snapshots that take zero time.”
That sentence is the whole abstraction. A run is an occurrence. A tick is a snapshot of it. Asking “what is waterTemp?” of the model is a category error; you ask it of a snapshot.
Authors coming from static tools blur the two. They edit the model when they want to change one run; they talk about the answer when there are many. Hold the distinction and three later patterns become obvious: overriding a binding (§16.C) changes the run, not the model; verification (§16.D) checks a run; a Monte Carlo sweep is N runs over one model.
A run you can read
The controller model distinguishes cold, heating and ready. It starts in cold, waits one simulated second, enters heating, then waits five more seconds. Advancing six seconds lets both timers become due. Here is the timed model used by both commands:
state def BoilerController {
entry; then cold;
state cold; state heating; state ready;
transition switchOn first cold accept after 1 [s] then heating;
transition reachTarget first heating accept after 5 [s] then ready;
}
Instantiate the part that exhibits the state machine before starting the clock. The first command gives you an initial observation, the second the trace through the two deadlines:
sysml -instantiate Orchestration::EspressoMachine -state 'Orchestration::BoilerController Orchestration::EspressoMachine' src/examples/coffee-machine
sysml -instantiate Orchestration::EspressoMachine -trace -state 'Orchestration::BoilerController Orchestration::EspressoMachine' -advance 6 src/examples/coffee-machine
Without -advance the state command takes the initial transition. Follow the second run’s trace to see what changed. These are delays in the controller example: they do not establish that a physical heater warms water in six seconds. An action is a different kind of behavior. The -action option runs a named action. The successions in BrewController put preparation before extraction and extraction before dispensing:
sysml -action Orchestration::BrewController src/examples/coffee-machine
The example passes the modeled inlet temperature of 93 °C from prepare to extract, and the resulting 36 g dose from extract to pour. A completed action with a 36 g result is different evidence from an assertion that the boiler started in its cold state.
16.B Continuous and discrete models
A controller state such as heating selects a mode. Water temperature is a continuous state variable. In a simple lumped boiler model with constant heat capacity C, the rate is dT/dt = (heaterPower − heatLoss) / C. Multiplying a rate by a duration is valid if the rate stays constant over that interval. If heat loss depends on temperature, the right-hand side must be evaluated along the trajectory. A threshold transition may occur between two samples.
SysML’s StateSpaceRepresentation library names the state equation (GetDerivative), output equation (GetOutput), and dynamics (ContinuousStateSpaceDynamics). Declaring these constructs is not an instruction to use a specific integrator. See Appendix E for hybrid models and the distinction between a computed value and a trajectory.
The thermal example solves the constant-net-power case algebraically. Heating from 20 °C to 93 °C at 1,350 W net with a heat capacity of 1,045 J/K takes about 56.5 s. Watts are joules per second; the kelvin temperature difference cancels the per-kelvin in heat capacity. The calculation in the project is:
calc def HeatTime {
in thermalMass : Real;
in target : Real;
in ambient : Real;
in heaterPower : Real;
in heatLoss : Real;
return seconds : Real = thermalMass * (target - ambient) / (heaterPower - heatLoss);
}
This simple estimate omits pump and control transients. It is undefined at zero net power and does not describe heating if net power is negative.
sysml -calc 'CoffeeMachineAnalysis::HeatTime(1045.0, 93.0, 20.0, 1400.0, 50.0)' src/examples/coffee-machine
16.C One model, many runs
The analysis asks whether heating can finish in 60 seconds. The thermalCheck usage supplies a nominal input; the definition also accepts other heater powers. Vary the input to the definition rather than redefining an already bound value on the nominal usage:
sysml -analysis CoffeeMachineAnalysis::thermalCheck src/examples/coffee-machine
sysml -instantiate CoffeeRequirements::benchMachine -analysis 'CoffeeMachineAnalysis::ThermalAnalysis CoffeeRequirements::benchMachine.brewer' -sweep 'heaterPower=1200..1600:200' src/examples/coffee-machine
At 1,200 W the estimated time is about 66.3 s: this scenario misses the target. At 1,600 W the same formula gives about 49.2 s. All three rows use the same model. OpenSysML returns exit status 1 for this sweep because the first row misses its objective; the other two satisfy it. Inspect the rows rather than discarding the unsuccessful design. None of the estimates is a bench measurement.
16.D Verdicts and traces
A satisfaction claim, a result returned by a verification case and the trace that explains an execution answer different questions. The requirement model gives an instrumented machine a measured extraction temperature. Evaluate the claim against that subject, then run the case which names it:
sysml -satisfy src/examples/coffee-machine
sysml -instantiate CoffeeRequirements::benchMachine -analysis 'Verification::BrewTempTest CoffeeRequirements::benchMachine' src/examples/coffee-machine
A case giving pass for a sample does not prove the temperature never left the band. For a timing problem, inspect the state trace instead. For example, stop the boiler run at time 3 and at time 6; only the latter interval includes the deadline for entering ready. If two steps may run in either order, record the scheduling policy with the evidence; a single trace witnesses one execution. The -schedule, -trace and -render-run options are OpenSysML facilities, not new SysML keywords.
For repeatable evidence, retain the model revision, inputs, tool version, simulated duration, command and result together. That lets a reviewer distinguish a changed design from changed test conditions. Appendix D gives the tool entry points; Appendix F explains when an error prevented a check from running at all.
Appendix A: Syntax Quick Reference
This appendix is a compact index of SysML v2 syntax forms. For each construct family you will find the canonical declaration pattern, a one-line description of purpose, and a pointer to the chapter that explains the semantics in full. Use it as a quick lookup when you know what you want to write but cannot remember the exact keyword order.
Each code block is a minimal but valid syntax template. Angle-bracket placeholders like <Name> are things you supply. Items in [...] are optional. Items separated by | are alternatives.
Operators and Relationship Punctuation
Every relationship in SysML v2 is written as a punctuation token after a name. This table covers all the tokens you will encounter in declarations.
| Token | Long form | Meaning |
|---|---|---|
: | defined by | Type a feature: names the classifier the feature conforms to |
:> | specializes / subsets | Specialize a type or subset a feature |
:>> | redefines | Redefine (override) an inherited feature |
::> | references | Reference-subsetting: a non-owning reference to another feature |
=> | crosses | Cross-subsetting: coordinates the two ends of a binary connection definition |
~ | (none) | Conjugated port typing: port p : ~P types a port by the conjugate of P (flips in/out) |
= | (feature value) | Bind a feature value (default or fixed) |
:= | (initial value) | Set an initial value that may change at runtime |
default = | (default value) | Set a default value that specializations may override |
default := | (default initial) | Set a default initial value |
The long forms are the SysML spellings. KerML spells : as typed by and has a general conjugates keyword on type declarations; neither is a SysML keyword. Appendix G lists the full symbol/keyword pairs with the metamodel class each one creates.
Examples
part def MachineBase {
attribute waterTemp : Real;
part components : Grinder[*];
part sensors : CupSensor[1..*];
}
part def EspressoUnit :> MachineBase {
part grinder : Grinder :> components;
attribute espressoBrewTemp :>> waterTemp;
ref primarySensor ::> sensors;
port waterReturn : ~WaterPort;
attribute maxTemp : Real = 96.0;
attribute currentTemp : Real := 20.0;
attribute targetTemp : Real default = 93.0;
}
Multiplicity
Multiplicity constrains how many instances of a feature may exist. Write it in brackets after the feature name (or after its type).
| Syntax | Meaning |
|---|---|
[1] | Exactly one (default for most features) |
[0..1] | Zero or one (optional) |
[1..*] | One or more |
[*] | Zero or more (unbounded) |
[2] | Exactly two |
[1..4] | Between one and four |
// Two sensors, exactly
part sensors : CupSensor [2];
// Optional steam wand
part steamWand : SteamWand [0..1];
// Any number of logged events
item events : LogEvent [*];
Feature Modifiers
These keywords add properties to a feature declaration. Most are prefixes that appear before the feature keyword; ordered and nonunique are the exception – they follow the multiplicity.
| Modifier | Meaning |
|---|---|
abstract | Feature or definition has no direct instances; must be specialized |
in | Input direction (for action parameters) |
out | Output direction (for action parameters) |
inout | Bidirectional (for action parameters) |
ref | Non-owning reference usage (does not own the referenced element) |
derived | Value computed from other features; not directly settable |
constant | Value stays the same for the entire existence of the featuring instance (KerML files spell it const) |
variation | Marks a definition or usage as a variation point whose variant members are the allowed choices |
ordered | Sequence order of feature values is significant (written after the multiplicity) |
nonunique | Duplicate values are permitted (written after the multiplicity) |
var | Value may vary over time (KerML files only) |
end | Marks a connector end feature |
// Abstract part: every concrete machine must specialize this
abstract part def Machine;
// Input parameter
action def SetPressure { in attribute targetPressure : Real; }
// Derived attribute computed from sub-parts
derived attribute totalMass : Real;
// Ordered list of brew steps (`ordered` follows the multiplicity)
ref action brewSteps : BrewStep [*] ordered;
Visibility
Visibility controls whether a member is accessible outside its owning namespace.
| Keyword | Meaning |
|---|---|
public | Accessible everywhere (default for package members) |
private | Accessible only within the owning namespace |
protected | Inherited by specializations of the owning definition or usage, but not visible outside; on other namespaces (e.g. package members) it is equivalent to private |
package CoffeeMachineDomain {
public part def CoffeeMachine; // visible outside
private part def InternalBoard; // hidden from importers
}
Documentation and Comments
// Line note -- discarded by the parser
//* Block note, also discarded.
It runs to the closing marker, so always close it. */
/* A bare block comment IS model data: it becomes a Comment element
whose body is this text */
doc /* Documentation attached to the owning element as model data */
comment about CoffeeMachine
/* Standalone annotating comment -- can target any element */
// and //* are hidden terminals (hidden(WS, ML_NOTE, SL_NOTE)) – the parser throws them away, so nothing downstream can see them. /* ... */ is not hidden: alone it becomes a Comment element, and after doc it becomes documentation on the owning element.
Mind the closing marker: ML_NOTE is defined as '//*' -> '*/', so a //* note runs until the next */ anywhere later in the file. Leave one unclosed and it silently swallows everything up to the next block comment. Appendix H covers doc versus //* and when to reach for each.
Group 1: Packages and Namespaces
Packages organize model elements into named scopes.
// Plain package
package <Name> {
<members>
}
// Library package (marks reusable standard content)
library package <Name> {
<members>
}
// Standard library package (normative standard libraries only)
standard library package <Name> {
<members>
}
Grammar: SysML.xtext lines 183-208
See: Chapter 4: Packages and Imports
Group 2: Imports and Aliases
Imports bring names from other namespaces into scope.
// Import a single named member
private import <Package>::<Name>;
// Import all public members of a package
private import <Package>::*;
// Import all members recursively (including nested packages)
private import <Package>::*::**;
// Private import (imported names stay private to this namespace)
private import <Package>::*;
// Alias: give a new local name to an existing element
alias <LocalName> for <Package>::<OriginalName>;
Grammar: SysML.xtext lines 234-298
See: Chapter 4: Packages and Imports
Group 3: Definitions and Usages
Every major element kind has a paired definition (reusable type) and usage (instance within a context). The pattern is uniform across all element families.
// General pattern
<keyword> def <Name> [specialization] {
<members>
}
<keyword> <name> [: <Type>] [specialization] [= <value>];
<keyword> <name> [: <Type>] [specialization] {
<members>
}
The definition declares a reusable classifier. The usage declares an occurrence of that classifier within an owning definition.
Grammar: SysML.xtext lines 303-330; KerML.xtext lines 460-558
See: Chapter 3: Definitions and Usages
Group 4: Typing and Specialization
These four relationships control how types relate to each other.
part def Assembly {
part components : Grinder[*];
part grinder : Grinder :> components;
}
part def EspressoAssembly :> Assembly {
part espressoGrinder :>> grinder;
port waterReturn : ~WaterPort;
}
Grammar: KerML.xtext lines 332-626
See: Chapter 12: Specialization and Redefinition
Group 5: Structural Constructs
Attribute
Holds a data value (scalar, string, quantity, etc.).
// Definition
attribute def <Name> [: <SuperType>] { <members> }
// Usage
attribute <name> : <Type> [multiplicity] [= <value>];
attribute def Temperature :> Real;
attribute waterTemp : Temperature = 93.0;
Grammar: SysML.xtext lines 739-749
Enumeration
A type whose values are a fixed set of named literals.
enum def <Name> {
<literal>;
<literal>;
}
enum def DrinkSize {
small;
medium;
large;
}
Grammar: SysML.xtext lines 764-787
Item
A thing that can flow through the system (material, energy, signal, data).
// Definition
item def <Name> [: <SuperType>] { <members> }
// Usage
item <name> : <Type> [multiplicity];
item def Water;
item def BrewedCoffee;
item waterSupply : Water [1];
Grammar: SysML.xtext lines 910-916
See: Chapter 5: Structure
Part
A physical or logical component that composes a system.
// Definition
part def <Name> [:> <SuperType>] { <members> }
// Usage
part <name> : <Type> [multiplicity];
part def CoffeeMachine {
part grinder : Grinder [1];
part brewer : Brewer [1];
}
part myCoffeeMachine : CoffeeMachine;
Grammar: SysML.xtext lines 932-938
See: Chapter 5: Structure
Port
An interaction point through which a part communicates with its environment.
// Definition
port def <Name> { <port features> }
// Usage
port <name> : <PortType>;
port <name> : ~<PortType>; // conjugated: reverses in/out
port def WaterPort {
out item waterOut : Water;
}
part def WaterTank {
port waterOut : WaterPort;
}
part def Brewer {
port waterInlet : ~WaterPort; // conjugated: receives water
}
Grammar: SysML.xtext lines 952-985
See: Chapter 5: Structure
Connection
A link between two or more parts or port ends.
// Definition
connection def <Name> [:> <SuperType>] { <members> }
// Usage: named connection
connection <name> connect <source> to <target>;
// Usage: anonymous inline connection
connect <source> to <target>;
// Binding connector (equates two features)
bind <feature1> = <feature2>;
connection def WaterLine :> BinaryConnection;
connect waterTank.waterOut to brewer.waterInlet;
bind brewer.targetTemp = controlPanel.setTemp;
Grammar: SysML.xtext lines 1015-1080
See: Chapter 6: Connections and Interfaces
Interface
A typed connection between ports, specifying a protocol.
// Definition
interface def <Name> {
end <portName> : <PortType>;
end <portName> : <PortType>;
}
// Usage
interface <name> : <InterfaceType> connect <port1> to <port2>;
interface <name> connect <port1> to <port2>; // untyped
interface def WaterInterface {
end supply : WaterPort;
end demand : ~WaterPort;
}
interface waterLine : WaterInterface connect
waterTank.waterOut to brewer.waterInlet;
Grammar: SysML.xtext lines 1102-1181
See: Chapter 6: Connections and Interfaces
Allocation
A directed mapping from one element to another (logical-to-physical, function-to-component).
// Definition
allocation def <Name> [:> <SuperType>];
// Usage
allocate <source> to <target>;
allocation <name> allocate <source> to <target>;
allocate brewCycle to brewer;
allocation heatingAlloc allocate heatAction to brewer.heatingElement;
Grammar: SysML.xtext lines 1195-1216
See: Chapter 6: Connections and Interfaces
Group 6: Behavioral Constructs
Action
A unit of behavior with inputs, outputs, and internal control flow.
// Definition
action def <Name> {
in <param> : <Type>;
out <result> : <Type>;
<action body>
}
// Usage
action <name> : <ActionType>;
// Perform (reference an action that already exists elsewhere)
perform action <name> : <ActionType>;
// Succession (ordering between two steps)
first <actionName>
then <nextAction>;
action def BrewCycle {
in beanType : BeanType;
out coffee : BrewedCoffee;
action grind : GrindBeans;
action heat : HeatWater;
action extract : Extract;
first grind then heat;
first heat then extract;
}
action brewCycle : BrewCycle;
Grammar: SysML.xtext lines 1352-1518
See: Chapter 7: Actions
Action Nodes (Control Flow)
Built-in action node types for structured control flow inside an action body.
// Conditional
if <condition> {
<true branch>
} else {
<false branch>
}
// While loop
while <condition> {
<body>
}
// Loop-until variant (`loop` takes no condition of its own)
loop {
<body>
} until <condition>;
// For loop
for <var> : <Type> in <collection> {
<body>
}
// Send a message (`to` names the receiver, `via` the sending port; both optional)
send <payloadExpr> to <receiver>;
send <payloadExpr> via <senderPort>;
send <payloadExpr> via <senderPort> to <receiver>;
// Accept a message or trigger
accept <payload> : <Type>;
accept <payload> : <Type> via <port>;
accept at <time>;
accept after <duration>;
accept when <change-condition>;
// Assignment
assign <target> := <expr>;
// Control nodes (name optional)
fork <name>; // split into concurrent branches
join <name>; // wait for all branches
merge <name>; // accept whichever branch arrived
// A decision node is followed by its branches, one succession per line
decide <name>;
if <guardExpr> then <targetStep>;
else <targetStep>;
// Abort the enclosing action
terminate;
Grammar: SysML.xtext lines 1437-1734
See: Chapter 7: Actions
State
A named state in a state machine; may contain entry, do, and exit sub-actions.
// Definition
state def <Name> {
entry; // or: entry <action>;
do; // or: do <action>;
exit; // or: exit <action>;
transition <Name> first <state>
accept <trigger>
if <guard>
do <effect>
then <target>;
}
// Usage
state <name> : <StateType>;
// Exhibit (reference a state that exists elsewhere)
exhibit state <name> : <StateType>;
exhibit state <name> { <states and transitions> }
exhibit <stateUsageRef>;
// Parallel states
state <name> parallel {
<region1>;
<region2>;
}
state def MachineStates {
attribute cupDetected : Boolean;
state idle;
state brewing;
state cleaning;
transition T1 first idle
accept StartBrewEvent
if cupDetected
then brewing;
transition T2 first brewing
accept BrewCompleteEvent
then idle;
}
state machineStates : MachineStates;
Grammar: SysML.xtext lines 1735-1923
See: Chapter 8: States
Transition
A directed arc between two states, with optional trigger, guard, and effect.
transition [<Name>] first <source>
[accept <trigger> [via <port>]]
[if <guard-expression>]
[do <effect-action>]
then <target>;
transition T1 first idle
accept StartBrewEvent
if cupSensor.cupDetected
then brewing;
Grammar: SysML.xtext lines 1849-1877
See: Chapter 8: States
Succession
Ordering relationship between two occurrences (temporal “happens before”).
// Inline within an action or state body
first <occurrence1>
then <occurrence2>;
// Explicit succession
succession <name> first <occurrence1> then <occurrence2>;
// Guarded target -- follows a decision node, one line per branch
if <guardExpr> then <targetStep>;
// Default target -- taken when no guard matched (note: no `then`)
else <targetStep>;
Grammar: SysML.xtext lines 1028-1033
See: Chapter 7: Actions
Flow
A directed transfer of items between feature ends.
// Definition
flow def <Name> [:> <SuperType>];
// Usage: anonymous inline flow
flow of <ItemType> from <source> to <target>;
// Named flow usage
flow <name> of <ItemType> from <source> to <target>;
// Succession flow (ordered flow across a time boundary)
succession flow of <ItemType> from <source> to <target>;
flow def WaterFlow { end source : WaterSupplyPort; end sink : WaterPort; }
flow of Water from waterTank.waterOut.water to brewer.waterInlet.water;
Grammar: SysML.xtext lines 1230-1285
See: Chapter 6: Connections and Interfaces
Calculation
A function-like behavior that returns a value. Used for expressions and analyses.
// Definition
calc def <Name> {
in <param> : <Type>;
return <result> : <ReturnType>;
<result expression>
}
// Usage
calc <name> : <CalcType>;
calc def BrewTime {
in volume : Real;
in pressure : Real;
return t : Real = volume / pressure * 60.0;
}
Grammar: SysML.xtext lines 1937-1974
See: Chapter 9: Expressions and Constraints
Group 7: Analytical Constructs
Constraint
A Boolean predicate that must hold for the model to be valid.
// Definition
constraint def <Name> {
<boolean expression>
}
// Usage
constraint <name> : <ConstraintType>;
// Inline constraint
constraint { <boolean expression> }
// Assert a constraint holds
assert constraint <name>;
// Assert a constraint does not hold
assert not constraint <name>;
constraint def BrewTempInRange {
in brewer : Brewer;
brewer.waterTemp >= 90.0 and brewer.waterTemp <= 96.0
}
part def TestStation {
part sample : Brewer;
assert constraint inRange : BrewTempInRange { in :>> brewer = sample; }
}
Grammar: SysML.xtext lines 1988-2012
See: Chapter 9: Expressions and Constraints
Concern
A stakeholder interest modeled as a requirement-like predicate.
// Definition
concern def <Name> { <requirement body> }
// Usage
concern <name> : <ConcernType>;
Grammar: SysML.xtext lines 2150-2160
See: Chapter 10: Requirements and Verification
Group 8: Requirements
Requirements capture what a system must do or be.
Requirement
// Definition
requirement def <Name> {
subject <subjectName> : <SubjectType>;
assume constraint { <assumption expression> }
require constraint { <requirement expression> }
frame <concern>;
stakeholder <name>;
}
// Usage
requirement <name> : <RequirementType>;
requirement def BrewTimeRequirement {
subject machine : CoffeeMachine;
require constraint { machine.brewTime <= 60.0 }
}
requirement brewTime : BrewTimeRequirement;
Grammar: SysML.xtext lines 2026-2110
See: Chapter 10: Requirements and Verification
Satisfy
Declares that a subject satisfies a requirement.
// Reference an existing requirement usage
satisfy <requirementUsageRef> by <subject>;
// Declare the satisfied requirement here, typed by a requirement definition
satisfy requirement [<name>] : <RequirementDef> by <subject>;
assert satisfy <requirementUsageRef> by <subject>;
assert not satisfy <requirementUsageRef> by <subject>;
satisfy requirement : BrewTimeReq by myCoffeeMachine;
Grammar: SysML.xtext lines 2112-2120
See: Chapter 10: Requirements and Verification
Group 9: Cases
Cases are structured analyses with a subject, objective, and result.
Analysis Case
Captures a system analysis (e.g., performance, safety).
analysis def <Name> {
subject <name> : <SubjectType>;
objective { <requirement body> }
<action body items>
return <result> : <ResultType>;
}
analysis <name> : <AnalysisType>;
Grammar: SysML.xtext lines 2227-2233
See: Chapter 10: Requirements and Verification
Verification Case
Documents how a requirement is verified.
verification def <Name> {
subject <name> : <SubjectType>;
objective { verify requirement <ReqName>; }
}
verification <name> : <VerificationType>;
Grammar: SysML.xtext lines 2249-2255
See: Chapter 10: Requirements and Verification
Use Case
Documents system usage by actors.
use case def <Name> {
subject <name> : <SubjectType>;
actor <actorName> : <ActorType>;
objective { <requirement body> }
}
use case <name> : <UseCaseType>;
// Include another use case inline
include use case <name>;
Grammar: SysML.xtext lines 2287-2301
See: Chapter 10: Requirements and Verification
Group 10: Views and Viewpoints
Views select and frame content for a specific audience.
Viewpoint
Defines the concerns and stakeholders a view must address.
viewpoint def <Name> {
stakeholder <name> : <StakeholderType>;
frame <concern>;
require constraint { <criteria> }
}
viewpoint <name> : <ViewpointType>;
Grammar: SysML.xtext lines 2399-2405
See: Chapter 13: Metadata and Views
View
Projects selected model content through a rendering.
view def <Name> :> <SupertypeView> {
filter <BooleanExpression>;
render rendering <name> : <RenderingDef>;
}
view <name> : <ViewType> {
expose <element>; // member expose
expose <Namespace>::*; // namespace expose
filter <BooleanExpression>;
render <renderingUsageRef>;
}
// Anonymous view usage — no def required
view <name> { expose <element>; }
view def StructuralView :> InterconnectionView {
filter @SysML::PartUsage;
render rendering asTree : Views::GraphicalRendering;
}
view structuralView : StructuralView {
expose CoffeeMachineDomain::*;
}
view scratch { expose CoffeeMachine; } // anonymous
A view definition supplies a reusable recipe; expose selects model elements in a view usage.
The eight standard view definitions (package StandardViewDefinitions) are: GeneralView, InterconnectionView, ActionFlowView, StateTransitionView, SequenceView, GeometryView, GridView, BrowserView. There is no standard UseCaseView or RequirementView; a requirement view is written as a GeneralView specialization with a requirement-metaclass filter.
Use Boolean expressions such as filter @SysML::PartUsage; or filter @Safety and Safety::isMandatory;. Multiple filters constrain the same selection together.
Grammar: SysML.xtext lines 2315-2383
See: Chapter 13: Metadata and Views
Rendering
Defines how a view’s contents should be displayed.
rendering def <Name> { <rendering body> }
rendering <name> : <RenderingType>;
Grammar: SysML.xtext lines 2417-2427
Group 11: Metadata
Metadata annotates any model element with typed, queryable data.
// Definition (a metaclass)
metadata def <Name> {
attribute <field> : <Type>;
}
// Usage: attach metadata to an element
@<MetadataType> { <field> = <value>; }
// Using the metadata keyword explicitly
metadata <name> : <MetadataType> about <element>;
// Prefix form: a user-defined keyword before the declaration it annotates
#<MetadataType>
<annotated element>
metadata def ReviewStatus {
attribute reviewer : String;
attribute approved : Boolean;
}
part def CoffeeMachine {
// Without an `about` clause, a metadata usage annotates its
// containing element -- so this attaches to CoffeeMachine
@ReviewStatus { :>> reviewer = "Alice"; :>> approved = true; }
}
Grammar: SysML.xtext lines 115-177
See: Chapter 13: Metadata and Views
Group 12: Expressions
Expressions compute values. They appear in constraints, feature values, calculations, and guard conditions.
Arithmetic and Logic Operators
| Category | Operators |
|---|---|
| Arithmetic | + - * / % ** ^ |
| Comparison | < > <= >= |
| Equality | == != === !== |
| Logical (eager – both operands evaluated) | & | xor |
| Logical (short-circuit) | and or implies |
| Null coalescing | ?? |
| Unary | + - ~ not |
| Ternary conditional | if <cond> ? <then> else <else> |
| Range | <low>..<high> |
Type Testing and Casting
// Test whether a value is an instance of a type
<expr> hastype <Type>
<expr> istype <Type>
<expr> @ <Type>
// Cast to a type
<expr> as <Type>
// Metaclass test / cast
<expr> @@ <MetaType>
<expr> meta <MetaType>
// Extent: all instances of a type
all <Type>
Collection and Feature Navigation
// Dot notation: navigate to an owned feature
brewer.waterTemp
// Feature chaining: navigate through a chain
machine.brewer.waterTemp
// Sequence expression (parenthesized, comma-separated)
(a, b, c)
// Range (also usable in expressions)
1..10
// Indexing (1-based)
<sequence>#(n)
// Sequence operators (arrow form; the per-element rule is a body expression)
<sequence>->select {in <x>; <predicate over x>}
<sequence>->collect {in <x>; <expr over x>}
<sequence>->reject {in <x>; <predicate over x>}
<sequence>->forAll {in <x>; <predicate over x>}
<sequence>->exists {in <x>; <predicate over x>}
// Aggregators (argument-list form -- the sequence is the argument)
<sequence>->size()
<sequence>->isEmpty()
<sequence>->notEmpty()
<sequence>->sum()
<sequence>->product()
// min and max are two-argument functions, so a sequence is folded with ->reduce
<sequence>->reduce min
<sequence>->reduce max
Body Expression (Inline Function)
// Body expression -- the inline function passed to ->select, ->collect, ->forAll, ...
{in <param>; <expression>}
{in <param> : <Type>; <expression>}
Grammar: KerMLExpressions.xtext (full file, 579 lines)
See: Chapter 9: Expressions and Constraints
Occurrence Modifiers
Occurrences (parts, items, actions, states) can carry temporal modifiers.
| Keyword | Meaning |
|---|---|
individual | Represents exactly one real-world individual (not a reusable type) |
snapshot | A portion that captures the state at an instant in time |
timeslice | A portion that spans a time interval |
individual part myEspressoMachine : EspressoMachine {
snapshot part machineAtStartup;
timeslice part machineInOperation;
}
Grammar: SysML.xtext lines 801-860
The Definition/Usage Pattern (Summary)
Every major construct family in SysML v2 follows this paired pattern:
| Definition keyword | Usage keyword | What it models |
|---|---|---|
attribute def | attribute | Scalar data value |
enum def | enum | Enumerated type |
item def | item | Flowing thing |
part def | part | Physical/logical component |
port def | port | Interaction point |
connection def | connection | Link between ends |
interface def | interface | Typed port-to-port link |
allocation def | allocation | Logical-to-physical mapping |
flow def | flow | Item transfer |
action def | action | Unit of behavior |
state def | state | State machine state |
calc def | calc | Returning computation |
constraint def | constraint | Boolean predicate |
requirement def | requirement | System obligation |
concern def | concern | Stakeholder interest |
case def | case | Generic structured analysis |
analysis def | analysis | System analysis case |
verification def | verification | Verification case |
use case def | use case | Actor-system interaction |
viewpoint def | viewpoint | Stakeholder concern framing |
view def | view | Projected model content |
rendering def | rendering | Display format |
metadata def | metadata or @ | Model annotation |
connect <a> to <b> is not the connection usage keyword – it is the clause that introduces the ends, and stands alone only as the short form of an unnamed connection. The same pattern holds for allocate (usage keyword allocation) and bind (usage keyword binding). See Appendix G for the metamodel class behind each pair.
Cross-References
- Chapter 1: Why Textual SysML v2 introduces the definition/usage split and explains why the language is text-first.
- Chapter 3: Definitions and Usages explains ownership and membership semantics.
- Chapter 4: Packages and Imports explains packages and imports in depth.
- Chapter 5: Structure explains parts, items, attributes, and ports.
- Chapter 6: Connections and Interfaces explains connections, interfaces, allocations, and flows.
- Chapter 7: Actions explains actions, action nodes, and successions.
- Chapter 8: States explains state machines and transitions.
- Chapter 9: Expressions and Constraints explains calculations, constraints, and expressions.
- Chapter 10: Requirements and Verification explains requirements, concerns, cases, and satisfaction.
- Chapter 12: Specialization and Redefinition explains every relationship operator in the table above.
- Chapter 13: Metadata and Views explains the metadata system, views, and viewpoints.
Source Anchors
See the OMG SysML specification, KerML specification and pilot grammar sources. Chapter 11 indexes the accompanying coffee-machine files.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/appendix-a.sysml.
Appendix B: Migration from SysML v1
If you have existing SysML v1 models, this appendix maps the v1 concepts to their v2 equivalents and provides a practical migration approach.
Concept Mapping
SysML v2 replaces SysML v1’s diagram-centric approach with a textual, element-centric model. Many v1 concepts have direct v2 equivalents, but the framing is different.
Structural Concepts
| SysML v1 | SysML v2 | Notes |
|---|---|---|
| Block | part def | Blocks become part definitions. The keyword changed, but the intent is the same. |
| Block property | part usage | A property typed by a Block becomes a typed part usage. |
| Value Type | attribute def | Value types become attribute definitions. |
| Value Property | attribute usage | Properties typed by a value type become attribute usages. |
| Flow Port | port def / port | Flow ports become port definitions with directional items. |
| Full Port | port def / port | Full ports become port definitions. The in/out direction model is more explicit. |
| Item Flow | flow on connection | Item flows are now part of connection modeling. |
| Internal Block Diagram | Composite structure in part def | No separate diagram type – structure is expressed inline. |
| Block Definition Diagram | part def declarations | Definitions are written directly in text. |
Behavioral Concepts
| SysML v1 | SysML v2 | Notes |
|---|---|---|
| Activity | action def | Activities become action definitions. |
| Activity Partition | Ownership or allocation | Partitions become structural ownership or explicit allocations. |
| State Machine | state def with state usages | State machines are modeled as state definitions with transitions. |
| State | state def / state | States become state definitions (reusable) or state usages (in context). |
| Transition | transition ... from ... to ... | Transitions name source, target, guard, and trigger explicitly. |
| Signal | item def | Signals become item definitions that flow through ports. |
Requirements and Traceability
| SysML v1 | SysML v2 | Notes |
|---|---|---|
| Requirement | requirement def | Requirements become first-class model elements with doc text. |
| Satisfy relationship | satisfy | Direct equivalent. Applied inside the satisfying element. |
| Verify relationship | verify inside verification def | Verification cases explicitly link to requirements. |
| Derive relationship | Specialization (:>) | Derived requirements specialize their parent. |
| Copy relationship | No direct equivalent | Use specialization or imports instead. |
| Requirement Diagram | Package with requirements | No separate diagram – requirements live in packages. |
Organizational Concepts
| SysML v1 | SysML v2 | Notes |
|---|---|---|
| Package | package | Direct equivalent. |
| Model | Top-level package | No separate Model element. Packages serve the same role. |
| Profile | metadata def | Profiles become metadata definitions applied with @. |
| Stereotype | metadata def | Stereotypes become metadata definitions. |
| Tagged Value | attribute in metadata def | Tagged values become attributes on metadata definitions. |
| View | view / viewpoint def | Views and viewpoints are now explicit model elements. |
Semantic Caveats
The mapping tables above are one-to-one enough to be useful, but three of the mappings hide a change in meaning. These are the ones teams get wrong.
A v1 Block splits into two concepts
In v1 a Block played two roles with no syntactic distinction. On a BDD it stood for a classifier – a reusable type. On an IBD it appeared as a property – an occurrence of another Block owned by a parent. Tools inferred the role from context.
v2 makes the distinction mandatory and syntactic. Every v1 Block becomes one of:
part defif it was used as a type – something instantiated more than once, referenced from elsewhere, or specialized.- a
partusage (nodef) if it was used as a slot – one occurrence inside one owning definition.
So a v1 Block: CoffeeMachine with part properties brewer : Brewer and grinder : Grinder becomes two kinds of element:
part def Brewer { }
part def Grinder { }
part def CoffeeMachine {
part brewer : Brewer;
part grinder : Grinder;
}
Brewer and Grinder are definitions; brewer and grinder are usages of them. The test when you are unsure: can this element be typed by, specialized by, or referenced from somewhere else? If yes, it needs def.
FlowPort direction becomes conjugation
A v1 FlowPort carried direction as a flag – in, out, or inout – and you matched an out port to an in port when connecting.
v2 uses conjugation instead. You write one port def from one side’s perspective and take its conjugate with ~, which reverses every flow direction inside it. Two ports are connector-compatible when one is the conjugate of the other:
port def WaterOutlet {
out item water : Water;
}
part def WaterTank {
port supply : WaterOutlet; // supplies water
}
part def Brewer {
port inlet : ~WaterOutlet; // receives water (conjugate)
}
out item water becomes in item water in ~WaterOutlet. You did not write a second port def; the language derived it.
For migration: for every pair of v1 FlowPorts you used to connect, write one port def and apply ~ at the other end. Writing symmetric WaterInlet/WaterOutlet pairs is the v1 pattern translated literally, not the v2 idiom.
Stereotypes become first-class metadata
In v1, extending the language meant a UML Profile: a Profile package holding Stereotype elements that extended base metaclasses, applied through ProfileApplication, with tagged values as owned Property elements. It worked, but profiles coupled models together, tagged values were stringly-typed in practice, and cross-tool compatibility was uneven.
v2 replaces the whole mechanism with metadata def – an ordinary element declared in a package alongside part def, carrying typed attributes, applied with @. No profile file, no ProfileApplication, no metaclass extension:
metadata def Safety {
attribute level : String;
attribute 'standard' : String;
}
@Safety about Brewer { :>> level = "SIL-2"; :>> 'standard' = "IEC-61508"; }
part def Brewer {
attribute waterTemp : Real;
}
Three consequences. The annotations live in your package structure, so they import, specialize, and query like anything else. The attributes are strongly typed – including quantity types from ISQ – where v1 tagged values defaulted to String even when a number was meant. And :>> is just the redefinition syntax you already use everywhere else; there is no separate tagged-value syntax.
One thing metadata does not do, which profiles attempted: it does not extend the metamodel. Stacking @ annotations adds independent annotations to an element; it does not create new kinds of element or new structural relationships. If you wrote profiles to introduce constructs that behaved like SysML built-ins, those have to be re-expressed with standard v2 mechanisms.
Diagram Types to Constructs
v1 divided modeling across nine diagram types, each a separate artifact with its own notation. v2 derives graphical views from shared model elements; the concerns each diagram addressed still exist as language constructs. This table maps the concern; the view table further down maps how you would render it.
| v1 diagram type | Abbr. | v2 constructs covering the same concern |
|---|---|---|
| Block Definition Diagram | BDD | part def, attribute, port def, interface def, item def, connection def at package scope |
| Internal Block Diagram | IBD | part usages, connect, flow, port usages inside a part def body |
| Requirement Diagram | REQ | requirement def, requirement usages, satisfy, verify, nested decomposition; refinement is expressed by specialization (:>), not a refine keyword |
| Activity Diagram | ACT | action def, action usages, first/then successions, flow, fork, join, decide, merge, send, accept |
| State Machine Diagram | STM | state def, state usages, transition, accept, if guard, do effect, entry/do/exit sub-actions, exhibit state |
| Parametric Diagram | PAR | constraint def, constraint usages, assume constraint, require constraint |
| Sequence Diagram | SD | message usages plus successions between action performers. Partial: message is real surface syntax but produces a FlowUsage – there is no Message metaclass and no interaction def form (see Appendix G) |
| Use Case Diagram | UC | use case def, use case usages, actor, subject, include use case |
| Package Diagram | PKG | package, import, alias; public / private visibility |
What replaces the BDD/IBD boundary
The BDD/IBD split was the most operationally significant boundary in v1: the BDD defined types, the IBD defined the internal architecture of one Block. In v2 both live in one part def body:
part def CoffeeMachine {
// BDD-style: typed part usages naming sub-components
part grinder : Grinder;
part brewer : Brewer;
part waterTank : WaterTank;
// IBD-style: connectivity between those parts' ports
connect waterTank.waterOut to brewer.waterInlet;
flow of Water from waterTank.waterOut.water to brewer.waterInlet.water;
}
No file boundary, no diagram boundary, and no synchronization problem between the two.
What replaces the REQ diagram
A v1 Requirements Diagram showed Requirement-stereotyped Classes, containment decomposition, DeriveReqt arrows, and satisfy/verify dependencies. These become body members and relationships on requirement def:
requirement def BrewSafetyReqs {
doc /* The brewer shall not operate unsafely. */
subject machine : CoffeeMachine;
// nested decomposition (v1 containment)
requirement temperatureReq : WaterTemperatureReq;
requirement cupReq : CupPresenceReq;
}
// v1 satisfy dependency -> v2 satisfy
part myCoffeeMachine : CoffeeMachine {
satisfy requirement : BrewSafetyReqs;
}
Note the : in satisfy requirement : BrewSafetyReqs. The name slot after requirement declares a requirement usage; the type annotation is what binds it to BrewSafetyReqs. Writing satisfy requirement BrewSafetyReqs; parses, but it declares an untyped usage that happens to share the name and links to nothing.
What replaces the PAR diagram
A v1 Parametric Diagram showed ConstraintBlock instances with parameters wired together by binding connectors. In v2 the constraint usage and its bindings are written inline:
constraint def TemperatureInRange {
in attribute temp : Real;
in attribute minTemp : Real;
in attribute maxTemp : Real;
temp >= minTemp and temp <= maxTemp
}
part def Brewer {
attribute waterTemp : Real;
assert constraint brewTempOk : TemperatureInRange {
in :>> temp = waterTemp;
in :>> minTemp = 90.0;
in :>> maxTemp = 96.0;
}
}
The v1 binding connectors become :>> redefinitions on the constraint usage. Same structure, inline text.
Migration Strategy
Migration works best in phases. Do not try to convert everything at once.
Phase 1: Structure First
Start with your block definitions and their properties. Convert blocks to part def, value types to attribute def, and block properties to typed usages. This gives you a structural baseline in v2 that you can check immediately.
// v1: Block "Grinder" with value property "grindSize: Real"
// v2:
part def Grinder {
attribute grindSize : Real;
}
Phase 2: Requirements and Traceability
Migrate your requirements next. Convert each v1 requirement into a requirement def with a short ID and doc text. Add satisfy links to the structural elements from Phase 1.
requirement def <'REQ-001'> BrewTempReq {
doc /* Extraction temperature shall remain between 90 and 96 C. */
}
part def CoffeeMachine {
satisfy requirement : BrewTempReq;
}
This gives you traceable requirements early, before you tackle behavior.
Phase 3: Behavior
Convert activities to action def and state machines to state def. The biggest change is that v2 uses textual control flow (first...then, fork, join, decide, merge) instead of diagram-based arrows. Guards and triggers on transitions are now written inline.
Phase 4: Governance and Views
Add metadata definitions to replace profiles and stereotypes. Create viewpoints and views to replace v1’s diagram-based stakeholder communication.
Choose a standard view definition according to the question the v1 diagram answered:
| v1 Diagram | v2 View Definition |
|---|---|
| Block Definition Diagram | GeneralView with a definition/usage filter |
| Internal Block Diagram | InterconnectionView |
| Parametric Diagram | InterconnectionView with binding relationships |
| Activity Diagram | ActionFlowView |
| State Machine Diagram | StateTransitionView |
| Sequence Diagram | SequenceView |
| Use Case Diagram | GeneralView with a use-case filter (no standard UseCaseView exists) |
| Requirement Diagram | GeneralView with a requirement-metaclass filter |
| Package Diagram | BrowserView |
These are language concepts. A tool may offer a convenient rendering for a use case or requirement, but that does not introduce a standard UseCaseView or RequirementView. See Chapter 13.
Key Mindset Shifts
From diagrams to text. In v1, the diagram was the primary artifact. In v2, the text is the source of truth and diagrams are generated views. This changes your workflow: you edit text files, review diffs, and run checks – not drag boxes on a canvas.
From implicit to explicit. v1 often relied on diagram layout to convey meaning. v2 makes everything explicit in text: ownership, direction, typing, sequencing. This feels verbose at first but pays off in reviewability and automation.
From copy to reuse. v1 models often duplicated similar blocks across diagrams. v2’s definition/usage pattern makes reuse natural: define once, use everywhere. Resist the urge to copy-paste definitions.
From monolithic to modular. v1 models often lived in one large project file. v2 models naturally split across files and packages, with imports making dependencies visible. Plan your package structure early.
Common Migration Pitfalls
Direct syntax translation without cleanup. Migration is an opportunity to improve model quality. Do not just translate v1 ambiguity into v2 ambiguity – tighten definitions, add types, and make traceability explicit.
Postponing verification links. In v1, verification was often managed outside the model. In v2, verification cases are model elements. Add them during migration, not after.
Mixing conventions. If part of your team uses v1 habits (untyped usages, missing imports) while another part uses v2 patterns, the model becomes inconsistent. Set v2 conventions early and enforce them in review.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/appendix-b.sysml.
Appendix C. The Systems Modeling API
Alongside the textual notation this book teaches, the SysML v2 specification suite defines a second interchange surface: the Systems Modeling API and Services specification, a standard REST/HTTP API for programmatic access to model data. Where the textual notation is how people write and exchange models, the API is how tools do – a requirements-management system pulling coverage data, a CI job comparing two versions of a model, a dashboard tracking element counts across a programme, all without any of them parsing anyone’s source files.
This appendix explains the API as the OMG specification defines it: the concepts, why they are shaped the way they are, and what any conformant implementation gives you. It is a reference companion to the modelling chapters – you do not need any of it to write a SysML v2 model. Come here when you are ready to connect a model to your broader engineering toolchain.
Why a standard API exists
The textual notation answers “what does this model say?”; the API answers “how do tools agree on which model, at which version, says it?”. Interchange needs an identity story as much as it needs a syntax. The API specification supplies that story with four concepts:
| Concept | Description |
|---|---|
| Project | A top-level container. Every model lives inside a project. |
| Branch | A named line of development within a project (similar to git). |
| Commit | An immutable snapshot of the model at a point in time. |
| Element | Any SysML element: parts, requirements, actions, connections, … |
Two tools that share nothing but this vocabulary can still talk about “the same model at the same version”. A commit is immutable, so any query pinned to a project and a commit is reproducible: the same request returns the same answer next month, regardless of what the model has become since. That is the property every downstream artifact – a coverage report, an exported diagram, an audit trail – should be built on.
On top of these concepts the specification defines resource-oriented services: listing and creating projects, walking a project’s branches and commits, retrieving and storing elements at a commit, navigating ownership and relationships, and a query language (PrimitiveConstraint / CompoundConstraint objects) for filtering elements server-side. The element payloads are JSON, governed by a published JSON Schema, so the shape of a PartUsage on the wire is as standardised as its textual syntax.
Where the OMG definition lives
The OMG Systems Modeling API and Services specification publishes the standard services and their machine-readable artifacts. The API Cookbook shows requests against a model repository.
OpenSysML can write an experimental local JSON element representation with sysml -convert api-json -o beverage.json src/examples/beverage-workspace/beverage-types/src/types.sysml. Exporting these records does not create a project, commit or REST server. Use a repository service if you need branch identity or transactional writes. A language server (LSP), gRPC client and repository REST API are not interchangeable protocols.
Working with a model API
These practices are about the interchange concepts, not any particular implementation; they hold against any conformant store.
Always pin a commit. Reports and exports should record the commit ID that produced them, so results are reproducible and auditable. Without a pinned commit, the same query can return different answers across runs – and nobody can tell whether the model changed or the report did.
Read first, write later. Build trust in your automation by producing useful reports before attempting programmatic model modifications. Read-only automation cannot corrupt model data; teams that jump straight to programmatic writes often create elements that conflict with manual modelling.
Query server-side. Downloading every element and filtering locally works for small models but does not scale. The query surface exists so the store does the filtering.
Keep automation narrow. One well-maintained coverage report is worth more than ten fragile scripts.
A good first target is requirement coverage: query for requirements lacking a verification case, and pair it with a requirement-to-verification traceability matrix (Chapter 10). It is read-only, it produces immediate review value, and it exercises the identity story end to end.
Further reading
- Chapter 15 – how the project/commit interchange notions relate to workspaces and manifests when you are authoring.
- Chapter 10 – the verification semantics behind coverage queries.
- The OMG materials listed above are the normative reference for endpoints, payloads, and the query language.
Appendix D: Tooling Notes (OpenSysML)
This edition targets Open-MBEE OpenSysML MDK 0.12.1. Use sysml -version to identify the executable; other projects use the same command name. All paths below are relative to this edition, not the upstream tool’s checkout.
Install and check
On macOS the Homebrew formula is open-mbee/tap/opensysml. Other platforms and release archives are covered by the installation guide. After installing, run:
sysml -version
sysml -strict -validate src/examples/coffee-machine
An ordinary sysml file.sysml opens a REPL. Use -validate in a script so it exits, and -strict to diagnose accepted nonstandard notation as errors. Load the whole coffee-machine directory so imports and qualified names see their dependencies. Independent exercises, by contrast, should not all be loaded into one namespace.
From a question to a command
| Question | Command (from the edition root) |
|---|---|
| What is the result of a closed expression? | sysml -e 'true implies false' |
| How long at a given temperature and pressure? | sysml -calc 'CoffeeCalculations::ExtractionTime(92.0, 9.0)' src/examples/coffee-machine |
| What does the design claim to satisfy? | sysml -satisfy src/examples/coffee-machine |
| Does the temperature case pass for the bench machine? | sysml -instantiate CoffeeRequirements::benchMachine -analysis 'Verification::BrewTempTest CoffeeRequirements::benchMachine' src/examples/coffee-machine |
| Which transitions occur by simulated time 6? | sysml -instantiate Orchestration::EspressoMachine -trace -state 'Orchestration::BoilerController Orchestration::EspressoMachine' -advance 6 src/examples/coffee-machine |
| Which diagrams can I regenerate? | sysml -list views src/examples/coffee-machine |
Validation is not execution. -calc needs values for its inputs, and -state needs a simulated time interval for timers beyond the initial transition. Preserve the status, diagnostics and verdict; do not interpret successful parsing as a passing test.
Editing, rendering and scripting
sysml-lsp connects an editor to the language server. The editor guide covers setup. In a terminal sysml -explain unresolved provides help for the same diagnostic vocabulary (Appendix F). Use -json or -format sarif when another tool needs structured diagnostics.
The checked-in illustrations come from declared views. For graph-shaped views OpenSysML produces DOT and Graphviz lays it out; a grid can be exported as CSV. Regenerate with python3 tools/render-figures.py. The REPL, CLI reference and behavior guide describe the runtime in detail. A command on the current documentation site may belong to a later release: use sysml -help for the installed binary.
Appendix E. Physics-aware Simulation Reference
Continuous equations and discrete transitions describe different aspects of one system. This appendix separates what the SysML libraries express from the particular numerical experiment a tool performs.
E.1 The state-space representation pattern – [SPEC]
A state equation gives a derivative; an output equation gives the quantities to observe. GetDerivative, GetOutput and ContinuousStateSpaceDynamics in StateSpaceRepresentation supply the standard vocabulary (SysML §9.4.4). For a simple boiler, let T be water temperature, P input power, k the heat-loss coefficient, Ta ambient temperature, and C thermal capacity. The state equation is dT/dt = (P − k(T − Ta)) / C. A possible Boolean output is 90 <= T and T <= 96 when T is expressed in degrees Celsius.
Chapter 9 models a derivative for a simple linear loss term. Here temp in the loss term is the temperature relative to ambient, so lossCoeff * temp represents power leaving the vessel. The result is a rate, not a temperature reading:
private import StateSpaceRepresentation::*;
calc def HeaterRhs :> GetDerivative {
in t : Real;
in temp : Real;
in heaterPower : Real;
in lossCoeff : Real;
in thermalMass : Real;
return dT_dt : Real = (heaterPower - lossCoeff * temp) / thermalMass;
}
State the initial temperature and units as well as the equation. At T = Ta the heat-loss term vanishes. At P = k(T − Ta) the derivative is zero. These checks expose sign and unit mistakes before anyone chooses an integration step. Validating a derivative declaration or computing one slope does not numerically integrate the model. Chapter 16 supplies an executable estimate with constant net power.
E.2 Hybrid behavior
A thermostat is hybrid: the continuous state T exists in both heater on and heater off modes, while the input power changes when the controller switches. The two modes can share an equation with different inputs. A bouncing ball, by contrast, needs a reset of velocity at impact; a change in the mode name alone does not reverse it.
E.3 Change triggers and threshold crossings
accept when temperature >= limit describes the transition condition. A solver taking large time steps may report the crossing later than one which locates the event inside the step. Record step size, tolerances and event policy when interpreting results. To prevent chatter, specify separate on/off thresholds (for example 90 °C and 96 °C) and identify which state each transition leaves. A scheduled after in OpenSysML is a timer, not a zero-crossing detector.
E.4 Occurrences and Life – [SPEC]
The spec’s Occurrence model (Occurrences.kerml in the Kernel Semantic Library) gives every happening a temporal identity. A Life is the complete temporal extent of an occurrence; an occurrence’s snapshots are its instantaneous time slices; and the library defines temporal relations between occurrences – HappensBefore (one occurrence completes before another begins) and HappensDuring (one occurrence’s extent lies within another’s).
This is the lifecycle layer everything dynamic hangs off. A simulation trajectory is an occurrence unfolding; a verdict stream is a time-indexed reading of snapshots; “did the pump start before the valve opened?” is a HappensBefore question. Chapter 16 §16.A develops the run-as-occurrence framing; Appendix J covers the occurrence vocabulary in depth.
E.5 Spatial frames – [SPEC]
SpatialFrames.kerml (Kernel Semantic Library) supplies the spec’s spatial surface. A SpatialFrame is a three-dimensional body that provides a spatial extent for positions to be measured against, and the library defines functions such as PositionOf (the position of a point relative to a frame at a given time) and CurrentPositionOf (the same, against a clock’s current time).
A model that imports SpatialFrames::* can declare frames, place occurrences within them, and ask “where is X, in frame F, at time t?” as a model-level query. Spatial frames matter most for multi-body mechanical systems and any model that must switch between body-fixed and inertial coordinates.
E.6 Performances and Evaluation – [SPEC]
Performances.kerml (Kernel Semantic Library) defines a Performance as an execution of a behaviour – itself a kind of occurrence, so everything in E.4 applies to it. An Evaluation is the performance of a function: the act of computing a result, as an occurrence with its own temporal extent, with BooleanEvaluation as the predicate case. StatePerformances.kerml adds StatePerformance and StateTransitionPerformance – a state being occupied, a transition being taken – plus helpers such as allSubstatePerformances for walking a nested state machine’s performance record.
This is the layer verification ultimately reads: when a verification case runs against a simulation (Chapter 10), the constraint checks it performs over the trajectory are, in the library’s terms, boolean evaluations over performances.
E.7 Checking the physical assumptions
Derive a balance from the topology; write it as a constraint instead of assuming that a connection enforces it. Distinguish power (W) from energy (J), an absolute temperature from a temperature rise, and a measured trajectory from an estimate. The coffee-machine thermal analysis shows its inputs and equation so that a reader can reproduce the estimate without an external solver. A validated declaration is not heater calibration data.
Appendix F: Reading OpenSysML Diagnostics
A diagnostic has a severity, a location, a message and an implementation-specific code. A language rule may have a different name in the OMG specification. Never change a valid model simply to match a code copied from another tool.
Start at the source location
Consider a deliberately faulty model:
package Broken {
private import ScalarValues::*;
part def Machine { part brewer : Brewwer; }
}
Save it as broken.sysml. sysml -strict -validate broken.sysml reports import-visibility on the import and unresolved on the type reference. First use private import ScalarValues::*; (or omit this unused import); then declare Brewer and correct the spelling. A visibility prefix does not make a nonexistent type exist. This is a negative example; it is not an exercise that should pass unmodified.
Look up the installed vocabulary
sysml -explain import-visibility
sysml -explain unresolved
sysml -explain incommensurable-binding
With no code, sysml -explain lists the catalog. nonstandard-notation identifies syntax the tool accepts beyond the specification in its normal mode; strict mode promotes this finding to an error. filter-not-evaluated signals a limitation of evaluation, not a successful decision that all members meet a predicate.
Use diagnostics in review
Use sysml -strict -validate -json src/examples/coffee-machine for machine-readable diagnostics. Inspect the exit status and severity; the absence of text on stdout is not proof of success. When a check did not run because the model failed to load, do not report a verification failure against the system itself. Reduce an unexpected result to a small model, retain the tool version and relevant clause, and distinguish a questionable implementation result from a modeling error.
Appendix G: Relationship & Element Kinds Reference
Appendix A answers “how do I write this?”. This appendix answers a different question: “what is this, and does it actually exist?”
Every construct you write in SysML v2 produces one or more elements in an underlying metamodel – a fixed set of classes with fixed names and fixed inheritance. When you write part engine : Engine; you create a PartUsage whose typing is a FeatureTyping; when you write :> you create a Subclassification or a Subsetting depending on context. Tool APIs, model interchange files, diagnostic messages, and the specification itself all speak in these class names, so sooner or later you will meet one and need to know what it is.
The tables below are that dictionary. Read them in this direction:
- Metamodel class is the authoritative name, as declared in the OMG vocabulary files. Where the class lives in KerML rather than SysML, that is noted – SysML inherits the whole KerML metamodel, so a great many “SysML” relationships are really KerML’s.
- Specializes is the direct parent from
rdfs:subClassOf. This is the fastest way to understand an unfamiliar kind:RedefinitionspecializesSubsettingspecializesSpecialization, which tells you almost everything about how redefinition behaves. - Textual form is what you type. Some kinds have a keyword, some have a punctuation token, some have both, and a few have no textual notation at all – they exist only as structure the parser creates for you. That last group is called out explicitly, because knowing you cannot write something directly saves you looking for a syntax that does not exist.
- Clause is where the specification defines the notation. Clause numbers prefixed
KerMLare from the KerML specification; the rest are SysML.
Nothing here is extrapolated. Every row was checked against the vocabulary files, the specification text, and the reference grammar, and the handful of names that turn out not to exist are listed in their own section rather than quietly dropped.
A keyword does not imply a metaclass
Before the tables, one principle, because it is the single most common way to get lost in a reference like this: the notation and the metamodel are two separate vocabularies, and they do not line up one-to-one. A keyword you can type is not a promise that a class of the same name exists, and a class that exists is not a promise that there is a keyword for it. All three combinations occur:
| Has a keyword | No keyword | |
|---|---|---|
| Has a metaclass | ReturnParameterMembership, written return | ResultExpressionMembership, written as a bare trailing expression |
| No metaclass | message, which produces a FlowUsage | nothing to name, so nothing to look up |
So when a search of the vocabulary for some name comes up empty, that is not yet an answer. It rules out one of two possibilities, and the keyword may still be perfectly normative notation for a class with a different name. Each of the three cells above is worked through below – message under Messages, the two memberships in the membership table – and the same reasoning is what separates the genuinely non-existent names in Names that do not exist from the merely differently-named ones.
The specialization family
These are the relationships you write as a token inside a declaration. They all descend from Specialization, and each has both a symbol and an equivalent keyword. The pairs are fixed by the specification’s lexical structure, not by convention.
| Metamodel class | Specializes | Textual form | Clause |
|---|---|---|---|
Specialization | Relationship | :> or specializes | KerML 7.3.2.3 |
Subclassification | Specialization | :> or specializes (on a definition) | KerML 7.3.3.3 |
FeatureTyping | Specialization | : or defined by | KerML 7.3.4.3 |
Subsetting | Specialization | :> or subsets | KerML 7.3.4.4 |
Redefinition | Subsetting | :>> or redefines | KerML 7.3.4.5 |
ReferenceSubsetting | Subsetting | ::> or references | 7.13.2 |
CrossSubsetting | Subsetting | => or crosses | 7.13.2, 8.4.9.1 |
The six symbol/keyword pairs are defined as lexical terminals in clause 8.2.2.1.2, which is worth reading once because it is the only place they are all listed together:
DEFINED_BY = ':' | 'defined' 'by'
SPECIALIZES = ':>' | 'specializes'
SUBSETS = ':>' | 'subsets'
REFERENCES = '::>' | 'references'
CROSSES = '=>' | 'crosses'
REDEFINES = ':>>' | 'redefines'
Two of these deserve a note. First, :> is genuinely ambiguous in the source – it creates a Subclassification on a definition and a Subsetting on a feature – so the metamodel class you get depends on what you attached it to, not on the token. Second, in SysML the long form of : is defined by, not typed by; typed by is the KerML spelling of the same terminal and typed is not a SysML keyword at all.
CrossSubsetting is the newest member of the family and is not covered elsewhere in this book. It lets a binary connection definition declare that each end must be one of the values of a feature reached through the other end, which keeps the two sides of the connection coordinated:
package CrossExample {
part def Device {
part connectingHub : Hub[1];
}
part def Hub {
part connectedDevice : Device[*];
}
connection def DeviceToHub {
end part device : Device crosses hub.connectedDevice;
end part hub : Hub crosses device.connectingHub;
}
}
Relationships with their own declaration syntax
These are written as standalone statements rather than as a token on some other declaration.
| Metamodel class | Specializes | Textual form | Clause |
|---|---|---|---|
Dependency | Relationship | dependency [<name> from] <clients> to <suppliers>; | 7.3.2 |
Annotation | Relationship | none directly; created by doc, comment, and bare /* */ (// and //* notes are discarded at parse time and create no element) | 7.4.1 |
Import | Relationship | import | 7.5.3 |
MembershipImport | Import | import <ns>::<member>; | 7.5.3 |
NamespaceImport | Import | import <ns>::*; | 7.5.3 |
Expose | Import | expose (inside a view) | 7.26.2 |
MembershipExpose | Expose, MembershipImport | expose <ns>::<member>; | 7.26.2 |
NamespaceExpose | Expose, NamespaceImport | expose <ns>::*; | 7.26.2 |
Conjugation | Relationship | ~ (see note) | KerML 7.3.2.4 |
PortConjugation | Conjugation | created implicitly with every port def | 7.12.3 |
ConjugatedPortTyping | FeatureTyping | port <name> : ~<PortDef>; | 7.12.3 |
Disjoining | Relationship | disjoint from (KerML only) | KerML 7.3.2.5 |
Unioning | Relationship | unions (KerML only) | KerML 7.3.2.7 |
Intersecting | Relationship | intersects (KerML only) | KerML 7.3.2.7 |
Differencing | Relationship | differences (KerML only) | KerML 7.3.2.7 |
FeatureChaining | Relationship | . in SysML; chains in KerML | 7.6.6, KerML 7.3.4.6 |
FeatureInverting | Relationship | inverse of (KerML only) | KerML 7.3.4.7 |
TypeFeaturing | Relationship | featured by (KerML only) | KerML 7.3.4.8 |
Conjugation is a general KerML relationship that flips the direction of every feature of a type, and KerML writes it as ~ or conjugates on any type declaration. SysML exposes only the port-specific slice of it: every port def silently acquires a ConjugatedPortDefinition via a PortConjugation, and you reach it by writing ~ in front of the port definition’s name when typing a port. There is no general conjugates keyword in SysML, and conjugates is not in the SysML keyword list.
The last four rows – chains, inverse of, featured by, and the set operators – are the clearest example of a real kind with no SysML notation. All four classes are in the SysML vocabulary, because SysML inherits KerML’s metamodel wholesale, but none of the keywords appears in the SysML reserved-keyword list in clause 8.2.2.1.2, and the SysML specification text uses phrases like “featured by” only as prose describing semantics. In SysML you get FeatureChaining by writing a dotted path, and you do not get FeatureInverting or TypeFeaturing at all.
In a
.sysmlfile use SysML notation. Where the construct exists only in KerML, use a.kermlmodel rather than relying on an implementation extension.
Membership kinds
A membership is the relationship between a namespace and something inside it. Almost all of them are created structurally – you write a nested declaration and the parser decides which membership class it produced – but a surprising number do have a keyword, and those are the ones worth memorising.
| Metamodel class | Specializes | Textual form | Clause |
|---|---|---|---|
Membership | Relationship | none; created by nesting. Visibility via public / private / protected | KerML 7.2.5.2 |
OwningMembership | Membership | none; created by nesting | KerML 7.2.5.2 |
FeatureMembership | OwningMembership | none; created by nesting a feature in a body | KerML 7.3.2.6 |
EndFeatureMembership | FeatureMembership | end | 7.13.2 |
ParameterMembership | FeatureMembership | in / out / inout | 7.6.3 |
ReturnParameterMembership | ParameterMembership | return | 7.19.2 |
ResultExpressionMembership | FeatureMembership | none; the trailing bare expression of a body | 7.19.2 |
ElementFilterMembership | OwningMembership | filter <booleanExpr>; | 7.5.4 |
SubjectMembership | ParameterMembership | subject | 7.22.2 |
ActorMembership | ParameterMembership | actor | 7.21.2 |
StakeholderMembership | ParameterMembership | stakeholder | 7.21.2 |
ObjectiveMembership | FeatureMembership | objective | 7.22.2 |
RequirementConstraintMembership | FeatureMembership | assume or require | 7.21.2 |
FramedConcernMembership | RequirementConstraintMembership | frame | 7.21.2 |
RequirementVerificationMembership | RequirementConstraintMembership | verify | 7.24.2 |
StateSubactionMembership | FeatureMembership | entry / do / exit | 7.18.2 |
TransitionFeatureMembership | FeatureMembership | accept (trigger) / if (guard) / do (effect) | 7.18.3 |
VariantMembership | OwningMembership | variant; also each enum literal | 7.6.7 |
ViewRenderingMembership | FeatureMembership | render | 7.26.2 |
ReturnParameterMembership and ResultExpressionMembership are the two most commonly doubted names on this list, and both are real KerML metaclasses, each with its own abstract-syntax subclause – KerML 8.3.4.7.8 and 8.3.4.7.7 respectively. They are the mirror image of message: where message is a keyword with no class behind it, these are classes, and only one of them has a keyword. The normative notation in KerML 8.2.5.7.1 shows the difference in two lines:
ReturnFeatureMember : ReturnParameterMembership = MemberPrefix 'return' ownedRelatedElement += FeatureElement
ResultExpressionMember : ResultExpressionMembership = MemberPrefix ownedRelatedElement += OwnedExpression
One has 'return' between the prefix and the element; the other has nothing at all. A calc def body can carry both at once – a named, typed return parameter, and a trailing expression that supplies its value:
package ResultExample {
calc def RectangleArea {
in width : ScalarValues::Real;
in height : ScalarValues::Real;
return area : ScalarValues::Real;
width * height
}
}
The return area : ScalarValues::Real; line is the ReturnParameterMembership. The bare width * height on the last line is the ResultExpressionMembership: there is no keyword to write, and the only thing that marks it is its position as the final expression in the body. If you go looking for a result keyword, you will not find one.
Relationship-shaped usages
SysML’s connectors, flows and behavioural references are relationships and usages at the same time. That double life is visible in the Specializes column, where you will often see two parents.
| Metamodel class | Specializes | Textual form | Clause |
|---|---|---|---|
Connector | Feature, Relationship | connect <a> to <b> | 7.13.2 |
BindingConnector | Connector | bind <a> = <b>; | 7.13.3 |
BindingConnectorAsUsage | BindingConnector, ConnectorAsUsage | binding <name> bind <a> = <b>; | 7.13.3 |
Succession | Connector | first <a> then <b>; / then <b>; | 7.13.5 |
SuccessionAsUsage | ConnectorAsUsage, Succession | succession <name> first <a> then <b>; | 7.13.5 |
Flow | Connector, Step | flow <src> to <tgt>; | 7.16.2 |
FlowUsage | ActionUsage, ConnectorAsUsage, Flow | flow or message (see below) | 7.16.2 |
SuccessionFlow | Flow, Succession | succession flow <src> to <tgt>; | 7.16.2 |
SuccessionFlowUsage | FlowUsage, SuccessionFlow | succession flow | 7.16.2 |
AllocationUsage | ConnectionUsage | allocate <a> to <b>; | 7.15.2 |
TransitionUsage | ActionUsage | transition [<name>] first <src> ... then <tgt>; | 7.18.3 |
AssignmentActionUsage | ActionUsage | assign <target> := <expr>; | 7.17.9 |
PerformActionUsage | ActionUsage, EventOccurrenceUsage | perform action <name> or perform <ref> | 7.17.6 |
ExhibitStateUsage | PerformActionUsage, StateUsage | exhibit state <name> or exhibit <ref> | 7.18.4 |
IncludeUseCaseUsage | PerformActionUsage, UseCaseUsage | include use case <name> or include <ref> | 7.25.3 |
EventOccurrenceUsage | OccurrenceUsage | event occurrence <name> or event <ref> | 7.9.5 |
AssertConstraintUsage | ConstraintUsage, Invariant | assert constraint { ... } or assert <ref> | 7.20.3 |
SatisfyRequirementUsage | AssertConstraintUsage, RequirementUsage | satisfy requirement <ref> by <part>; | 7.21.4 |
Notice the pattern in the last several rows: each has a long form that declares something new, and a short form that just names an existing element. That short form is not a special case per construct – it is always the same mechanism. perform a;, exhibit s;, include u;, assume c;, require c;, verify r;, assert c;, event e;, and a bare entry a; all attach the named element by a ReferenceSubsetting, which is why ::> and references appear so far from the connection chapter that introduces them. The specification says so explicitly in clauses 7.9.5, 7.17.6, 7.18.2, 7.18.4, 7.20.3, 7.21.2 and 7.24.2.
Messages
message is the clean worked example of the principle above, and it is worth spelling out because two apparently contradictory statements about it are both true:
messageis real, normative SysML v2 syntax. It is in the reserved-keyword list in clause 8.2.2.1.2, it has a normative grammar production in clause 8.2.2.16, and the specification uses it in its own examples.- There is no
Messageclass in the metamodel. SearchingSysML-vocab.ttlandKerml-Vocab.ttlfor one returns nothing, and that is the correct result, not a gap in the search.
The reconciliation is in the production’s return type. Clause 8.2.2.16 (Flows Textual Notation) declares:
Message : FlowUsage =
OccurrenceUsagePrefix 'message'
MessageDeclaration DefinitionBody
{ isAbstract = true }
Message : FlowUsage – the name on the left is the grammar rule, and the class it constructs is FlowUsage. So message is concrete syntax for an existing metaclass, not the name of a new one. Anyone who says the keyword is real is right; anyone who says the metaclass does not exist is also right; and Message is a production name that never becomes a class.
Two further things exist under the same name, which is what makes it such reliable bait:
Flows::Message, anabstract flow defin the shipped Systems library, described there as “the base type of all FlowUsages”.Flows::Flowspecializes it directly, andFlows::SuccessionFlowspecializesFlows::Flowin turn. This is a library type, not a metaclass.Transfers::MessageTransfer, a KerML libraryinteraction, whichFlowTransferis declareddisjoint from. Also a library element.
So the way to think about message is as one of the three kind keywords for a flow usage, alongside flow and succession flow (clause 7.16.2). A message differs from a streaming flow in what it identifies at its ends: a flow names an out feature of the source and an in feature of the target, whereas a message names the source and target events between which a transfer may happen. The { isAbstract = true } in the production above is why a message is always abstract whether or not you write abstract.
package MessageExample {
attribute def ControlSignal;
part def Vehicle {
part controller {
event occurrence sendControl;
}
part engine {
event occurrence receiveControl;
}
message throttleCmd of ControlSignal
from controller.sendControl
to engine.receiveControl;
}
}
The declaration parts are all optional, and this is the general shape:
message [<name>] [of [<payloadName> :] <PayloadType>] [from <sourceEvent> to <targetEvent>];
message <sourceEvent> to <targetEvent>;
The name, the of payload clause, and the from/to event pair are each independently omissible. The payload clause can also carry a multiplicity, and the : before the payload type is dropped along with the payload name when you omit it, which is why of ControlSignal above needs no colon. The second line is a separate grammar alternative: with no name and no payload you may drop from and write the two events with only to between them. If you omit the payload specification entirely, the message places no constraint on what may be transferred; and if you omit the source and target events instead, you may supply a feature value for the message in their place (clause 7.16.2).
The two endpoint forms differ in what the author supplies. message command from sent to received; gives the transfer a name. message sent to received; uses the short endpoint form. message of ControlSignal from sent to received; constrains the payload explicitly. message; supplies neither a name nor endpoints; even if admitted by the grammar it tells a reader very little.
For contrast, the streaming-flow sibling. Note what changes: a flow def declares its ends and can constrain the payload by redefining it, and the usage names an out feature on one side and an in feature on the other, rather than a pair of events.
package FlowPair {
item def Fuel;
part def FuelTank { out fuelOut : Fuel; }
part def Engine { in fuelIn : Fuel; }
flow def FuelFlow {
ref item :>> payload : Fuel;
end tank : FuelTank;
end eng : Engine;
}
part def Vehicle {
part tank : FuelTank;
part eng : Engine;
flow supply : FuelFlow from tank.fuelOut to eng.fuelIn;
}
}
FlowDefinition, FlowUsage and SuccessionFlowUsage are all real metaclasses, unlike Message – which is why the flow rows in the table above carry class names and the message row does not.
Names that do not exist
Each of the following is a plausible-sounding name that is not a metamodel class. They are listed rather than omitted because they circulate in tutorials, in tool output, and in earlier drafts of this book, and a confirmed negative is more useful than silence. Every one was checked against Kerml-Vocab.ttl, SysML-vocab.ttl, KerML-shapes.ttl, SysML-shapes.ttl, both specification texts, and the reference grammar.
| Name you may see | Verdict | What actually exists |
|---|---|---|
Message | Not a metamodel class – but a real grammar rule name | The keyword message, normative in clause 8.2.2.16, producing a FlowUsage; plus Flows::Message in the standard library |
Trace | Does not exist anywhere in the language | Nothing. trace appears only as jazz_am:trace, an OSLC interchange property in the API shapes files – not a SysML relationship and not a keyword |
Assignment | Not a metamodel class | AssignmentActionUsage |
Allocation | Not a metamodel class | AllocationDefinition and AllocationUsage |
Transition | Not a metamodel class | TransitionUsage |
Perform | Not a metamodel class | PerformActionUsage |
Exhibit | Not a metamodel class | ExhibitStateUsage |
Include | Not a metamodel class | IncludeUseCaseUsage |
Frame | Not a metamodel class | FramedConcernMembership |
RequireConstraintUsage | Not a metamodel class | RequirementConstraintMembership, whose kind is require or assume |
AssumeConstraintUsage | Not a metamodel class | as above |
Composition | Not a metamodel class | Feature::isComposite, a Boolean property. A usage is composite unless you write ref (clause 7.6.3) |
Portion | Not a metamodel class | PortionKind, an enumeration on OccurrenceUsage, written snapshot or timeslice (clause 7.9.3) |
OwningFeatureMembership | Not a metamodel class | FeatureMembership, which already specializes OwningMembership |
MessageTransfer | Not a metamodel class | Transfers::MessageTransfer, a KerML library interaction. FlowTransfer is declared disjoint from it |
ReturnParameterMembership and ResultExpressionMembership have also been challenged, and they are the opposite case to Message: both do exist as metaclasses, each with its own dedicated abstract-syntax subclause in the KerML specification (ResultExpressionMembership at KerML 8.3.4.7.7, ReturnParameterMembership at KerML 8.3.4.7.8). See the membership table above, and the worked example below it.
Definition and usage pairs
Most SysML element kinds come as a matched pair: a def that declares a reusable type, and a usage that places one in a context. The definition keyword is always the usage keyword plus def.
| Definition | Usage keyword | Metamodel class | Covered? |
|---|---|---|---|
attribute def | attribute | AttributeDefinition | ch05 |
enum def | enum | EnumerationDefinition (specializes AttributeDefinition) | ch05 |
item def | item | ItemDefinition | ch05 |
part def | part | PartDefinition | ch05 |
port def | port | PortDefinition | ch05 |
occurrence def | occurrence | OccurrenceDefinition | reference only |
connection def | connection | ConnectionDefinition | ch06 |
interface def | interface | InterfaceDefinition | ch06 |
allocation def | allocation | AllocationDefinition | ch06 |
flow def | flow | FlowDefinition | ch06 |
action def | action | ActionDefinition | ch07 |
state def | state | StateDefinition | ch08 |
calc def | calc | CalculationDefinition | ch09 |
constraint def | constraint | ConstraintDefinition | ch09 |
requirement def | requirement | RequirementDefinition | ch10 |
concern def | concern | ConcernDefinition | ch10 |
case def | case | CaseDefinition | ch10 |
analysis def | analysis | AnalysisCaseDefinition | ch10 |
verification def | verification | VerificationCaseDefinition | ch10 |
use case def | use case | UseCaseDefinition | ch10 |
view def | view | ViewDefinition | ch13 |
viewpoint def | viewpoint | ViewpointDefinition | ch13 |
rendering def | rendering | RenderingDefinition | ch13 |
metadata def | metadata, or the symbol @ | MetadataDefinition | ch13 |
That is the complete set. The vocabulary declares exactly one more *Definition class, ConjugatedPortDefinition, and it has no keyword of its own because you never declare one – every port def generates its conjugate automatically, and you reach it as ~<PortDef>.
Two things that look like they belong in this table but do not:
- There is no
package def.PackagespecializesNamespace, notDefinition, so there is no definition/usage split to have. You writepackage <Name> { ... }and that is the whole story. connectis not the connection usage keyword. The usage keyword isconnection;connectintroduces the ends. Both of these are valid, and the second is the short form you get when the declaration part is empty:
connection <name> : <ConnectionDef> connect <a> to <b>;
connect <a> to <b>;
The same shape applies to allocations (allocation <name> : <Def> allocate <a> to <b>;, or just allocate <a> to <b>;) and to bindings (binding <name> bind <a> = <b>;, or just bind <a> = <b>;).
Metadata is worth one extra note, because it has two notations that are easy to confuse and only one of them is a @:
@<MetadataDef> [{ <body> }] // a metadata usage, as a member
#<MetadataDef> <declaration> // a user-defined keyword, as a prefix
The @ form is a metadata usage attached to the element that owns it, and @ is simply the symbolic equivalent of metadata ... defined by ... (clause 7.27.2). The # form is different in kind: it is a user-defined keyword, placed immediately before the reserved keyword of a declaration, and if the named metadata definition specializes SemanticMetadata it also implies a specialization (clause 7.27.4). So #situation occurrence def Failure; declares an OccurrenceDefinition that implicitly subclassifies whatever situation’s base type names. With semantic metadata you may even drop the language keyword entirely and write #situation def Failure;.
Verifying the examples
Validate the model in context with sysml -strict -validate model.sysml. To inspect the elements produced, use sysml -convert api-json -o elements.json model.sysml and examine their metaclasses and relationships. A syntax token need not map to a metaclass of the same name. The exported element representation is experimental and is not a replacement for the normative abstract syntax.
Source anchors
Consult the SysML 2.0 language and machine-readable artifacts, the KerML 1.0 artifacts and the release models.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/appendix-g.sysml.
Appendix H: Lexical Reference
The chapters teach constructs. This appendix covers the smaller rules underneath them – how names, literals, and comments are actually written – and in particular the two forms the chapters use without stopping to explain: root-qualified names and quoted names.
Names
An ordinary name is an identifier: CoffeeMachine, grindSize, waterTank.
The book’s convention, and a common one, is UpperCamelCase for definitions and
lowerCamelCase for usages and attributes. Nothing in the language enforces
that, but a reader scanning a model relies on it.
Qualified and root-qualified names
<Package>::<Member>
$::<Package>::<Member>
part grinder : CoffeeMachineDomain::Definitions::Grinder;
A qualified name walks down from a visible namespace. Reach for one when a bare name would be ambiguous across packages.
Prefixing $:: makes it a root-qualified name: lookup starts at the model
root rather than the enclosing scope. It is the escape hatch for the case where
a local name shadows the one you meant.
Quoted names, for names that are not identifiers
<'<short-name>'> '<long name>'
requirement def <'REQ-TEMP-01'> 'Extraction Temperature' {
doc /* Water temperature shall remain within operating range. */
}
Read it as: this requirement’s short name is REQ-TEMP-01 and its name is
Extraction Temperature.
A name in single quotes is an unrestricted name, and it may contain
characters an identifier cannot – spaces, hyphens, punctuation. Angle brackets
declare a short name, which is why requirement identifiers like REQ-TEMP-01
are written <'REQ-TEMP-01'>: the hyphens would otherwise be read as
subtraction. To put a quote inside such a name, escape it: 'REQ\'TEMP-02'.
This is the form Chapter 10 and Chapter 11 use for requirement identifiers.
Use quoted names where they earn their keep – requirements and cases that carry an external identifier or a human-readable title – and plain identifiers everywhere else.
Literals
attribute grindSize : Real = 0.4;
attribute enabled : Boolean = true;
attribute label : String = "Main Grinder";
- Booleans are
trueandfalse. - Strings are double-quoted.
- Reals may lead with a dot –
.5is valid – and may use scientific notation:1e3,9.8e-2. nullis the null literal.()is an equivalent spelling of the same empty value, which is worth recognising when you meet it in library sources.*is the infinity literal. It is what makes[0..*]mean “any number of” in a multiplicity, and it is the same token as multiplication – position tells them apart.
Comments, and why doc is different
part def Brewer {
doc /* Heats and pressurizes water for extraction. */
// A note to whoever is editing this file next.
attribute waterTemp : Real = 93.0;
}
doc creates a documentation element in the model. It survives into the
model itself, so tools can show it on hover, carry it into a generated document,
and export it through the API.
The example’s // line note and a //* … */ block note do not. Per the specification’s own grammar they are hidden
tokens, discarded during parsing in the same way whitespace is. They never
become part of the model.
So the choice is not stylistic. If the sentence explains what an element is,
it belongs in doc, where a reviewer who never opens the source file will still
see it. If it is a message to the next person editing the file, use a // line note or close a multiline //* note with */.
The most common mistake here is writing model meaning into a note and then wondering why it does not appear anywhere in the tooling.
Marking the language of documentation
part def Brewer {
doc locale "en-GB" /* Heats and pressurises water for extraction. */
}
A doc may carry a locale – a string naming the natural language the
documentation is written in. It is optional, and worth setting on a model whose
documentation is translated or whose readership is mixed, because it lets a tool
pick the right text rather than guessing. Comments take the same modifier.
Embedding another language
The specification also provides a way to carry a fragment of some other language inside a model element:
[rep <name>] language "<language-name>" /* <the fragment> */
This is a textual representation (SysML §8.2.2.4.3). The intent is that a constraint expressed in OCL, a formula in MathML, or a snippet of source can travel with the element it belongs to, tagged with what language it is in, so a tool that understands that language can pick it up and one that does not can leave it alone.
Embedding a representation does not imply that an evaluator executes its language. Use it to carry the tagged text; use an appropriate interpreter if the text must actually run.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/appendix-h.sysml.
Appendix I: Modeling Review Checklists
Model review is a team activity, not a solo exercise. You bring a model to a review gate, a group of peers asks hard questions about completeness and correctness, and the model either passes or goes back for revision. The problem is that “completeness” is vague. Without a written standard, reviewers focus on whatever they happen to notice, and different reviewers notice different things.
This appendix gives you four copy-ready checklists, one for each major review type: Architecture, Requirements, Behavior, and Verification. Each checklist is a set of yes/no questions phrased so that “yes” means the model is correct in that dimension. A “no” or “unsure” answer identifies a specific gap that needs attention before the review can pass.
How to Use These Checklists
Copy the relevant checklist into your review document, pull request description, or team wiki page before the review meeting. Work through each item independently: read the question, inspect the model, and mark it. Do not answer from memory – open the .sysml files and check.
The checklist items are sequenced so that earlier items catch structural problems that would make later items meaningless. If item 1 fails, fix it before assessing item 3.
Each item includes a chapter reference in parentheses. If a question is unclear, that chapter explains the underlying construct in full.
Not every item is a language rule. Items marked Convention: or Style: describe review heuristics – a model is perfectly legal either way. They earn their place because they catch review pain later, but a team can consciously adapt or waive them.
Note: These checklists target model completeness and structural consistency. They are not a substitute for domain correctness review. A model can pass every checklist item and still describe a system that does not work in the real world. Use domain experts alongside these checklists.
The Coffee Machine example developed throughout this book is a useful validation target. After reading this appendix, you can apply each checklist to the files in src/examples/coffee-machine/ and observe which items pass immediately and which require model elaboration.
Checklist 1: Architecture Review
Use this checklist during a structural architecture review, typically at the end of the definition phase, before behavioral modeling begins. It verifies that the structural model has enough completeness and internal consistency to serve as a scaffold for behaviors, requirements, and connections.
-
Convention: does every
part defhave at least onepartusage that instantiates it within the model? The language does not require this – an uninstantiated definition is perfectly legal, and library or catalogue definitions legitimately have no usage in the package that declares them. The review question is whether each unused definition is intentional (a library entry, work in progress) or dead weight that nothing verifies, connects, or simulates. (Chapter 3, Chapter 5) -
Convention: is every connection across a
port defgoverned by a namedinterface defthat specifies the connection contract? There is nothing to check on the conjugate side – everyport defautomatically carries a conjugated form (~PortDef); the language creates it for you. The heuristic is about the contract: when connections across a port have nointerface def, reviewers and tools have no stated agreement to check the two ends against. (Chapter 5, Chapter 6) -
Style: are load-bearing
connectusages typed by a namedconnection def? Anonymous connections are fully normative – they parse, carry flows, and are queryable like any other usage. Naming the definition is a reuse and traceability convention: a namedconnection defcan be instantiated again elsewhere and gives allocations and satisfaction links a stable target. (Chapter 6) -
Does every
partusage that can have more than one instance declare an explicit multiplicity? Omitting multiplicity implies exactly one instance. If a coffee machine can have between one and four heating elements, that constraint belongs in the model, not in a comment or document. (Chapter 5, Chapter 3) -
Convention: are all
importstatements explicit rather than wildcard in production packages? Wildcard imports (private import SomePkg::*;) are convenient during drafting but create invisible name dependencies. In a reviewed package, each imported name should be traceable to a specific definition. (Chapter 4) -
Does every behavioral action that is assigned to a structural part have a corresponding
allocationlinking the action to that part? Without explicit allocation, the model declares behavior in the abstract but does not commit it to any physical or logical element. Reviewers and analysis tools need this link to check feasibility. (Chapter 6, Chapter 5) -
Convention: does the package structure separate domain definitions from contextual usages, with no definitions buried inside usage packages? Definitions mixed into context packages cannot be reused elsewhere and are harder to find during review. The canonical pattern is a definitions package imported by one or more context packages. (Chapter 4, Chapter 5)
Checklist 2: Requirements Review
Use this checklist during a requirements review, typically after the requirements package has been baselined and before the architecture team begins assigning satisfaction links. It verifies that every requirement is well-formed, bounded, and connected to the rest of the model.
-
Does every
requirementusage have asubjectmember declaring what the requirement constrains? A requirement without a subject is a floating assertion. The subject tells every reader – and every automated tool – exactly which element of the model must satisfy the requirement. (Chapter 10) -
Convention: does every leaf requirement usage (one with no child requirements) have at least one
require constraintor explicit constraint expression? A requirement with only adocannotation is legal, but it is an English sentence rather than a formal constraint. This convention asks leaf requirements to carry a verifiable condition that a constraint solver or test can evaluate. (Chapter 9, Chapter 10) -
Is every leaf requirement either satisfied by a
satisfyusage, or explicitly deferred with a documented rationale? An orphan requirement – one that exists in the model without a satisfaction link and without a deferral note – is an invisible gap. Reviewers cannot tell whether it was overlooked or intentionally left open. (Chapter 10) -
Does every
satisfyusage name a specific requirement usage rather than a requirement definition? Satisfying a definition claims to satisfy all possible instances of it, which is almost never the intent. The satisfaction link must point to the specific requirement usage in its context. (Chapter 10) -
Convention: is the requirement hierarchy no deeper than four levels? A hierarchy deeper than four levels usually indicates scope creep: requirements at the bottom level are design decisions, not stakeholder needs. Inspect any branch deeper than four levels and ask whether the lowest items belong in a design document instead. (Chapter 10, Chapter 15)
-
Convention: does every requirement have a
docannotation with rationale text explaining why the requirement exists? A requirement without rationale cannot be prioritized, traded off, or defended to a stakeholder. Rationale also guides verification: it tells you what evidence would actually satisfy the requirement. (Chapter 13, Chapter 10) -
Does every stakeholder concern raised during elicitation appear as a named
concernusage orrequirementin the model? A concern that was raised during review but never captured in the model is a hidden risk. Even concerns that do not yet have a formal requirement should appear asconcernusages so that the model tracks them explicitly. (Chapter 10)
Checklist 3: Behavior Review
Use this checklist during a behavior review, typically after action flows and state machines have been drafted. It verifies that behavioral elements are internally consistent, properly connected, and grounded in the structural model.
-
Does every
state defhave at least one entry transition and at least one exit condition? A state with no entry transition is unreachable. A state with no exit condition is a dead end. Either situation represents a logical error in the behavioral model. Check every state node, including nested parallel states. (Chapter 8, Chapter 7) -
Does every
transitionusage have an explicit guard, trigger, or both – with the only exception being the initial pseudo-transition? An unguarded, untriggered transition (other than the initial transition from the initial state) fires unconditionally on entry to its source state, which almost always indicates a modeling error. Verify the intent before approving. (Chapter 8) -
Are all
actionusages within a sequence model connected bysuccessionlinks, with no disconnected action nodes? An action node with no incoming succession and no outgoing succession is an island: it never executes in the sequence and will not appear in simulation or analysis. Every non-initial action needs at least one incoming succession link. (Chapter 7) -
Do all control-flow fork nodes have a corresponding join node that synchronizes the same branches? A fork without a join creates parallel branches that never converge. This may be intentional in some models, but it should be explicit: if there is no join, add a comment explaining why the branches are designed to diverge permanently. (Chapter 7)
-
Does every
accept actionandsend actionreference a port or flow definition that is declared in the structural model? Behavioral elements that send or receive across ports must reference the same port type used in the structural layer. A mismatch – for example, an action that sends aWaterFlowon a port typed forElectricalPower– is a semantic error that the structural review should have caught but the behavior review must confirm. (Chapter 6, Chapter 7) -
Style: does every
exhibitusage in an action definition reference a namedstate defrather than an anonymous inline state? Inline anonymous states are legal, but they cannot be referenced from other actions, tested in isolation, or carry documentation. Prefer a named state definition for any state that has more than trivial logic. (Chapter 8, Chapter 3) -
Do action parameter types match the item types declared on the ports or flows they read from or write to? A
performaction that reads aCoffeeGroundsitem but whose input parameter is typed asWaterwill pass a parser but fail during simulation or analysis. Parameter types must match the flow types at every boundary. (Chapter 7, Chapter 6)
Checklist 4: Verification Review
Use this checklist during a verification review, typically after the verification cases package has been drafted and before formal test planning begins. It verifies that every requirement has a path to objective evidence and that no verification case exists without a purpose.
-
Does every leaf requirement usage have at least one
verifyusage inside averification casethat references it? A requirement with no verification case cannot be closed. Requirements without objective evidence are assumptions. This item should be checked against the same list of leaf requirements identified in Checklist 2 item 3. (Chapter 10) -
Convention: is every
verification caseusage annotated with a verification method metadata tag – one of: analysis, test, inspection, or demonstration? Without a method tag, the verification case is unscheduled: you do not know who performs it, what evidence it produces, or when it runs. Method classification is also required for V&V plan traceability. (Chapter 13, Chapter 10) -
Does every
verification caseusage contain at least oneverifyusage that references a named requirement? A verification case that contains noverifyusages is a placeholder with no executable content. It may pass a parser but it contributes nothing to requirement closure. These orphan cases must either be populated or removed. (Chapter 10) -
Style: does every
assert constraintusage inside a verification case reference a namedconstraint defrather than an inline anonymous constraint? An anonymous inline constraint inside a verification case cannot be reused, named, or referenced from a test script or analysis tool. Named constraint definitions allow the same constraint to appear in both the requirement and the verification case, making the link explicit. (Chapter 9, Chapter 10) -
Convention: is every verification case annotated with a responsible stakeholder or team via a metadata usage? An unassigned verification case will not be executed. Ownership metadata can be as simple as a
#Responsible { team = "Systems Test"; }annotation; the convention asks that it be present so that test planning tools and project managers can schedule the work. (Chapter 13) -
Does the coverage matrix show every requirement at the leaf level mapped to at least one verification case? Individual checklist items verify individual connections. This item asks you to look at the whole picture: generate or inspect the requirement-to-verification-case coverage matrix and confirm no leaf requirement appears as uncovered. The Systems Modeling API supports this as a graph query. (Chapter 10, Appendix C)
-
Are verdict expressions in verification cases written using named
calculation defresults rather than literal boolean constants? A verification case whose verdict isassert true;is always passing and provides no information. Verdicts must evaluate observable conditions: parameter values, measured outputs, or constraint evaluations drawn from a named calculation. (Chapter 9, Chapter 10) -
Has a
view def <Milestone>ReviewView(carrying thefilter <viewCondition>;) plus a view usage (carryingexpose <package>::*;) been authored to scope the milestone review? A milestone review pulls a particular slice of the model — the requirements affected by this gate, the parts touched by this design phase, the verification cases due this iteration. Authoring that slice as a named view (rather than relying on each reviewer to remember which packages to inspect) makes the scope explicit, reviewable, and re-runnable for the next milestone. Thefilterclause lives in the view definition and narrows the slice to the relevant element kinds; theexpose ... ::*lives in the view usage (aview defbody does not admitexpose) and keeps the view fresh as the underlying packages grow. (Chapter 13: Metadata and Views)
Appendix J: Occurrences, Time Slices, and Snapshots
The chapters model a coffee machine: what it is made of, what it does, what it must satisfy. What they do not dwell on is that a machine, a brew, and a fault are all things that happen over time, and that SysML v2 has a specific family of constructs for saying so.
You can build a great deal without them. Reach for them when time itself becomes part of what you are modelling – phases of an operation, the state of something at an instant, or one particular real-world unit as opposed to the kind.
Occurrences
occurrence def <Name>;
occurrence <name> : <OccurrenceDef>;
occurrence def BrewCycle;
An occurrence is something that happens or exists over an interval of time.
occurrence is its kind keyword, and it works like every other kind keyword you
have met – occurrence def for the definition, occurrence for a usage
(SysML §7.9.2).
You have been using occurrences all along without naming them. Actions and states are occurrence usages of more specialized kinds: that is what lets a state have a duration and an action have a start and an end. This appendix is about the layer underneath them.
An occurrence usage may only be typed by an occurrence definition of some kind, or by a KerML class.
Time slices and snapshots
timeslice <name>; // equivalent to `timeslice occurrence <name>`
snapshot <name>; // equivalent to `snapshot occurrence <name>`
timeslice <kind> <name>; // e.g. `timeslice part activeSection`
occurrence def BrewCycle {
timeslice grinding;
timeslice heating;
timeslice extracting;
snapshot extractionStart;
}
Read it as: a brew cycle has three phases and one instant worth naming.
A time slice is a portion of an occurrence over an interval – the grinding
phase of a brew. A snapshot is a portion at a single instant – the moment
extraction begins. Both are written by putting the keyword immediately before the
kind keyword of the declaration, and both may stand in place of the kind
keyword, in which case they mean timeslice occurrence and snapshot occurrence
(SysML §7.9.3).
One rule to remember: a time slice or snapshot must be declared inside the body of an occurrence definition or usage. It is a portion of something, so there has to be a something.
The distinction is worth keeping straight because it is the difference between a duration and an instant. “While heating” is a time slice. “At the moment the pump started” is a snapshot. A constraint on a temperature rise belongs to the former; a constraint on a temperature reading belongs to the latter.
Individuals
individual def <Name> :> <OccurrenceDef>;
individual <kind> def <Name> :> <Def>;
part def Grinder;
individual part def Grinder_SN0417 :> Grinder;
occurrence def BrewCycle;
individual def BrewCycle_20260821_0730 :> BrewCycle;
An individual definition describes exactly one thing in the world, rather
than a kind of thing. Grinder is a kind; Grinder_SN0417 is the grinder on the
bench with that serial number. BrewCycle is a kind of operation; the second
declaration is the brew that ran at half past seven.
Like timeslice and snapshot, the keyword goes immediately before the kind
keyword, or in place of it (SysML §7.9.4).
A usage counts as an individual usage when its definition is an individual definition – you do not have to mark the usage. And a usage may not have more than one individual definition, which follows from what an individual is: two “exactly one thing” claims about the same usage would contradict each other.
This is the construct to reach for when the model has to talk about real units – a serial-numbered part, a specific test run, an incident that actually happened – rather than the design.
Event occurrences
occurrence def BrewCycle {
event occurrence pumpOn;
}
An event occurrence marks a point of interest within an occurrence
(SysML §7.9.5). It is what the from and to ends of a message name, which is
why Appendix G mentions them under flows: a
message runs between two events rather than between two features.
Where this shows up elsewhere
- Successions and the
HappensBeforeassociation order occurrences in time. Chapter 7 covers successions. - States and actions are occurrence usages, which is why they have durations and boundaries. Chapter 8, Chapter 7.
- The standard library’s
Occurrencespackage declares the machinery – includingHappensBefore, and thestartShot/endShot/snapshotsstructure that gives every occurrence its boundaries. Chapter 14.
Model context: chapter listings and shared vocabulary. From the edition root: sysml -strict -validate src/examples/lessons/vocabulary.sysml src/examples/lessons/appendix-j.sysml.
About this edition
Adapted from The SysML v2 Book, by the sysml-rs contributors, revision 87d74b3. This English edition retains the book’s coffee-machine study, sixteen chapters and appendices A–J. The source edition remains available unchanged. The original generated Language Reference is linked rather than reproduced: its implementation matrix measures a different tool.
What changed
- The worked examples use Open-MBEE OpenSysML MDK 0.12.1. The program name is
sysml. Commands, diagnostics and example outputs describe this implementation, not the language standard. - Examples specify import visibility, declare the signals and features they reference, and distinguish a bound value from an initial value. Control nodes, calculation results, filter predicates and verification objectives use standard notation. Code shown in its surrounding model is distinguished from grammar templates and deliberate counterexamples.
- The figures are static renderings of the supplied model views, not captures of the original viewer. The same model sources are distributed with the book.
- Chapters 15 and 16 and appendices D–F use OpenSysML’s project loading, checking, evaluation, state execution and diagnostic facilities. The chapter on physical models distinguishes a differential equation from a numerical solver; it does not assume an automatic integrator or implicit conservation laws.
The original prose and diagrams and their adaptations are distributed under Creative Commons Attribution 4.0 International. The model snippets and example models are dual licensed under MIT or Apache-2.0. The original authors have not endorsed the changes. See the original license notice.
Where to find the porting changes
| Lesson or appendix | Change in the worked material |
|---|---|
| 2: first model, 4: imports | Use explicit visibility. Check a file or load both sides of an import together; a package import is not a filesystem lookup. |
| 3: definitions, 5: structure, 6: connections | Separate a role from an instance, distinguish undirected ref item from a composite port member, and name the payload feature at each end of a transfer. The connection between two definitions is marked as a counterexample. |
| 7: actions, 8: states | Declare control nodes before wiring them; write each succession between two endpoints. Type the loop variable, declare signal types and separate absolute times from durations. |
| 9: expressions | Bind the calculation result once, supply expression inputs, import the sequence operators and distinguish a rate from integration. |
| 10: verification, 11: integrated model | Put result expressions in their proper bodies. Bind and instantiate the subject. Check a returned verdict separately from a design’s satisfaction claim. Chapter 11’s six displayed packages run together without the lesson vocabulary: the same temperature case passes at 96 °C and fails at 97 °C. |
| 12: variants, 13: views | Replace a reserved variant name. Identify metadata targets, filter on modeled metaclasses/metadata, and use viewpoint usages rather than satisfying a definition by name. |
| 14: libraries | Separate KerML library source from SysML input, and duration and temperature units from scalar magnitudes. |
| 15: projects, 16: running | Load a workspace, round-trip an archive, instantiate a machine, run a timed controller and compare input powers under one heating model. |
| A: syntax, B: migration, G: relationships, H: lexical forms | Provide the owning model context, preserve directions in redefinitions, distinguish grammar from tool diagnostics, and correctly close lexical notes. |
| C: API, D: tools, E: dynamics, F: diagnostics | Replace product-specific commands, diagnostic identifiers, interactive workbenches and solver claims. Keep the standard interchange concepts, state-space model and physical limitations. |