0% found this document useful (0 votes)
23 views600 pages

Systemcomposer Ug

The System Composer™ User's Guide for R2024a provides comprehensive instructions on using the software for architecture modeling, including templates, component management, and requirements tracing. It outlines features such as visual architecture composition, programmatic model building, and interface management. The guide also includes contact information for MathWorks and details on software licensing and trademark information.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views600 pages

Systemcomposer Ug

The System Composer™ User's Guide for R2024a provides comprehensive instructions on using the software for architecture modeling, including templates, component management, and requirements tracing. It outlines features such as visual architecture composition, programmatic model building, and interface management. The guide also includes contact information for MathWorks and details on software licensing and trademark information.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 600

System Composer™

User's Guide

R2024a
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

Technical support: www.mathworks.com/support/contact_us

Phone: 508-647-7000

The MathWorks, Inc.


1 Apple Hill Drive
Natick, MA 01760-2098
System Composer™ User's Guide
© COPYRIGHT 2019–2024 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied
only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form
without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through
the federal government of the United States. By accepting delivery of the Program or Documentation, the government
hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer
software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014.
Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain
to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and
Documentation by the federal government (or other entity acquiring for or through the federal government) and shall
supersede any conflicting contractual terms or conditions. If this License fails to meet the government's needs or is
inconsistent in any respect with federal procurement law, the government agrees to return the Program and
Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be
trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see www.mathworks.com/patents for
more information.
Revision History
March 2019 Online only New for Version 1.0 (Release 2019a)
September 2019 Online only Revised for Version 1.1 (Release 2019b)
March 2020 Online only Revised for Version 1.2 (Release 2020a)
September 2020 Online only Revised for Version 1.3 (Release 2020b)
March 2021 Online only Revised for Version 2.0 (Release 2021a)
September 2021 Online only Revised for Version 2.1 (Release 2021b)
March 2022 Online only Revised for Version 2.2 (Release 2022a)
September 2022 Online only Revised for Version 2.3 (Release 2022b)
March 2023 Online only Revised for Version 2.4 (Release 2023a)
September 2023 Online only Revised for Version 23.2 (R2023b)
March 2024 Online only Revised for Version 24.1 (R2024a)
Contents

Architecture Model Editing


1
Choose Architecture Template for System Design . . . . . . . . . . . . . . . . . . . 1-2
Core Modeling Capabilities of Architectures in System Composer . . . . . . . 1-2
Using Architecture Model Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Using Software Architecture Model Template . . . . . . . . . . . . . . . . . . . . . . 1-3
Using AUTOSAR Blockset Software Architecture Template . . . . . . . . . . . . 1-3

Compose Architectures Visually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5


Create Architecture Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14

Decompose and Reuse Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19


Decompose Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19
Create Architecture Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-21
Create Variants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-26
Add Variant Choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27
Convert Variant Component to Variant Assembly Component . . . . . . . . . 1-27
Create Software Architecture from Component . . . . . . . . . . . . . . . . . . . . 1-28
Create AUTOSAR Architecture from Component . . . . . . . . . . . . . . . . . . . 1-28

Build Architecture Models Programmatically . . . . . . . . . . . . . . . . . . . . . . 1-29

Modeling System Architecture of Small UAV . . . . . . . . . . . . . . . . . . . . . . 1-37

Model-Based Systems Engineering for Space-Based Applications . . . . . 1-43

Use Property Inspector in System Composer . . . . . . . . . . . . . . . . . . . . . . 1-60


Property Inspector Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-60

Export Architecture to Software or AUTOSAR Architecture . . . . . . . . . . 1-66


Export Architecture to Different Architecture Template . . . . . . . . . . . . . 1-66
Architecture Template Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-67

Add or Remove Variant Choices of Variant Assembly Component Blocks


Using External File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-68

Requirements
2
Allocate and Trace Requirements from Design to Verification . . . . . . . . . 2-2

iii
Link and Trace Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4

Manage Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9


Open Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
Manage Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
Trace Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
Use Requirements Traceability Diagram . . . . . . . . . . . . . . . . . . . . . . . . . 2-11
Link Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12
Analyze Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14

Verify and Validate Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15


Use Test Harnesses to Verify System Design . . . . . . . . . . . . . . . . . . . . . . 2-15
Create Test Harness for Airframe Component . . . . . . . . . . . . . . . . . . . . . 2-15
Combine Subsystems for Integration Testing . . . . . . . . . . . . . . . . . . . . . 2-16

Redirect Reference Requirement Links from Imported File . . . . . . . . . . 2-17

Establish Traceability Between Architectures and Requirements . . . . . 2-22


Define Requirements and Requirement Links . . . . . . . . . . . . . . . . . . . . . 2-23
Define Allocations and Directed Relationships . . . . . . . . . . . . . . . . . . . . 2-25

Interface Management
3
Define Port Interfaces Between Components . . . . . . . . . . . . . . . . . . . . . . . 3-2

Create Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6


Open Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6
Open Interface Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6
Create Composite Data Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
Create Value Types as Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8
Nest Interfaces to Reuse Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9

Assign Interfaces to Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11


Mobile Robot Architecture Model with Interfaces . . . . . . . . . . . . . . . . . . 3-11
Associate Ports with Interfaces in Property Inspector . . . . . . . . . . . . . . . 3-11
Assign Interfaces to Ports Using the Context Menu . . . . . . . . . . . . . . . . . 3-12
Define Owned Interfaces Local to Ports . . . . . . . . . . . . . . . . . . . . . . . . . 3-12
Select Multiple Ports and Assign Data Interface . . . . . . . . . . . . . . . . . . . 3-14
Specify Source Element or Destination Element for Ports . . . . . . . . . . . . 3-15
Enable Interface Compatibility Edit-Time Check . . . . . . . . . . . . . . . . . . . 3-16

Interface Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-18

Manage Interfaces with Data Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . 3-24


Mobile Robot Architecture Model with Interfaces . . . . . . . . . . . . . . . . . . 3-24
Save, Attach, and Delete Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-24

Reference Data Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-27


Add Referenced Data Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-27
Use Referenced Data Dictionaries for Projects with Multiple Models . . . . 3-29

iv Contents
Define Parameters
4
Author Parameters in System Composer Using Parameter Editor . . . . . . 4-2

Use Parameters to Store Instance Values with Components . . . . . . . . . . . 4-7

Define Architectural Properties


5
Extend System Composer Language Elements Using Profiles . . . . . . . . . . 5-2

Define and Style Stereotypes in Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5


Create Profile and Add Stereotypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
Add Properties with Stereotypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6
Define Default Stereotypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8
Use Stereotype-Based Styling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9

Apply Stereotypes to Extend Model Elements . . . . . . . . . . . . . . . . . . . . . . 5-13


Import Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13
Apply Stereotypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15
Change Stereotypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22
Remove Stereotypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22

Best Practices for Profile Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-24


Role of Profiles in System Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-24
Extend Stereotypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-25
Using Multiple Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-27

Change Stereotype Order Using Manage Profiles Tool . . . . . . . . . . . . . . . 5-31

Simulate Mobile Robot with System Composer Workflow . . . . . . . . . . . . 5-35

Organize and Link Requirements for Mobile Robot . . . . . . . . . . . . . . . . . 5-38


Link Stakeholder Requirements to System Requirements . . . . . . . . . . . . 5-38

Design Architectures and Activity Diagram for Mobile Robot . . . . . . . . . 5-42


Design, Specify, and Allocate Architecture Models . . . . . . . . . . . . . . . . . 5-42

Define Stereotypes and Perform Analysis for Mobile Robot . . . . . . . . . . 5-53


Define Stereotypes and Perform Analysis . . . . . . . . . . . . . . . . . . . . . . . . 5-53

Simulate Architectural Behavior for Mobile Robot . . . . . . . . . . . . . . . . . 5-63


Simulate Architectural Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-63

Change Stereotypes Based on Stereotype Hierarchy in Portable Blender


Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-68

v
Describe System Behavior with Diagrams
6
Describe System Behavior Using Sequence Diagrams . . . . . . . . . . . . . . . . 6-2

Author Sequence Diagrams Interactively . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5


Traffic Light Architecture Model and Sequence Diagram . . . . . . . . . . . . . 6-5
Traffic Light Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6
Add Lifelines and Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7
Add Fragments and Operands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-12

Author Sequence Diagrams to Co-Create Architecture Models . . . . . . . 6-19


Traffic Light Example with Hierarchy for Sequence Diagrams . . . . . . . . . 6-19
Create Sequence Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-20
Add Child Lifelines to Sequence Diagram . . . . . . . . . . . . . . . . . . . . . . . . 6-21
Create Sequence Diagram Gates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-23
Co-Create Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-24
Synchronize Sequence Diagram and Model . . . . . . . . . . . . . . . . . . . . . . . 6-25
Create Messages in Sequence Diagram . . . . . . . . . . . . . . . . . . . . . . . . . 6-25
Modify Sequence Diagram Using Model Browser . . . . . . . . . . . . . . . . . . 6-28
Use Annotations to Describe Elements of Sequence Diagram . . . . . . . . . 6-29
Create Sequence Diagram from View . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-30
Link Elements of Sequence Diagram to Requirements . . . . . . . . . . . . . . 6-31

Author Sequence Diagram Fragments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-35


Sequence Diagram Fragments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-35
Fragment Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-36
Messages with Ambiguous Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-44

Synchronize Sequence Diagrams and Architecture Models . . . . . . . . . . 6-46

Simulate Sequence Diagrams for Traffic Light Example . . . . . . . . . . . . . 6-51

Author and Simulate Basic Colors Sequence Diagram with Enumerations


......................................................... 6-72

Describe System Behavior Using Activity Diagrams . . . . . . . . . . . . . . . . . 6-75


Create New Activity Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-76
Authoring, Simulating, and Visualizing Activity Diagrams . . . . . . . . . . . . 6-77

Author Activity Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-78


Open Activity Diagram for Mobile Robot Functional Flow . . . . . . . . . . . . 6-78
Token Flow in Activity Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-79
Author Activity Diagram Action Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . 6-80
Use Control Nodes to Manipulate Token Flows . . . . . . . . . . . . . . . . . . . . 6-86

Simulate, Visualize, and Validate Activity Diagrams . . . . . . . . . . . . . . . . 6-91


Open Activity Diagram for Mobile Robot Functional Flow . . . . . . . . . . . . 6-91
Simulate Activity Diagram and Review Results . . . . . . . . . . . . . . . . . . . . 6-92
Validate Activity Diagram Behavior Using Animations . . . . . . . . . . . . . . . 6-93
Log Data from Activity Diagram Using Simulation Data Inspector . . . . . . 6-95
View Token Data Using Pin Value Display . . . . . . . . . . . . . . . . . . . . . . . . 6-97
Step Through the Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-97

vi Contents
Use Simulink Models with System Composer
7
Implement Component Behavior Using Simulink . . . . . . . . . . . . . . . . . . . . 7-2
Create Simulink Behavior with Robot Arm Model . . . . . . . . . . . . . . . . . . . 7-3
Create Referenced Simulink Behavior Model . . . . . . . . . . . . . . . . . . . . . . 7-5
Create Simulink Behavior Using Subsystem Component . . . . . . . . . . . . . . 7-7
Link to Existing Simulink Behavior Model . . . . . . . . . . . . . . . . . . . . . . . . 7-10
Access Model Arguments as Parameters on Reference Components . . . . 7-10
Create Simulink Behavior from Template for Component . . . . . . . . . . . . 7-11

Extract Architecture of Simulink Model Using System Composer . . . . . 7-13

Implement Component Behavior Using Stateflow Charts . . . . . . . . . . . . 7-15


Add State Chart Behavior to Component . . . . . . . . . . . . . . . . . . . . . . . . . 7-15
Remove Stateflow Chart Behavior from Component . . . . . . . . . . . . . . . . 7-17

Extract Architecture from Simulink Model . . . . . . . . . . . . . . . . . . . . . . . . 7-19

Implement Component Behavior Using Simscape . . . . . . . . . . . . . . . . . . 7-23


Architecture Model with Simscape Behavior for a DC Motor . . . . . . . . . . 7-23
Define Physical Ports on Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-24
Specify Physical Interfaces on Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-24
Create Simulink Subsystem Component . . . . . . . . . . . . . . . . . . . . . . . . . 7-25
Describe Component Behavior Using Simscape . . . . . . . . . . . . . . . . . . . 7-26

Merge Message Lines for Architectures Using Adapter Block . . . . . . . . 7-29

Allocate Architecture Models


8
Create and Manage Allocations Interactively . . . . . . . . . . . . . . . . . . . . . . . 8-2
Create and Manage Allocations Interactively Using Tire Pressure
Monitoring System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2

Create and Manage Allocations Programmatically . . . . . . . . . . . . . . . . . . 8-11


Create and Manage Allocations Using Tire Pressure Monitoring System
..................................................... 8-11

Allocate Architectures in Tire Pressure Monitoring System . . . . . . . . . . 8-14

Systems Engineering Approach for SoC Applications . . . . . . . . . . . . . . . 8-20

Analyze Architecture Model


9
Analyze Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Set Properties for Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2

vii
Create a Model Instance for Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Write Analysis Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5
Run Analysis Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7

Analysis Function Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-9


Roll-Up Analysis for Quadcopter Design . . . . . . . . . . . . . . . . . . . . . . . . . . 9-9
Class-Based Analysis for Battery Sizing . . . . . . . . . . . . . . . . . . . . . . . . . 9-10
Allocation-Based Analysis for Tire Pressure Monitoring . . . . . . . . . . . . . 9-11
Remaining Useful Life Analysis for Mobile Robot Design . . . . . . . . . . . . . 9-11
Variant Analysis for Insulin Infusion Pump Design . . . . . . . . . . . . . . . . . . 9-12

Battery Sizing and Automotive Electrical System Analysis . . . . . . . . . . . 9-15

Calculate Endurance Using Quadcopter Architectural Design . . . . . . . . 9-17

Design Insulin Infusion Pump Using Model-Based Systems Engineering


......................................................... 9-24

Simple Roll-Up Analysis Using Robot System with Properties . . . . . . . . 9-38

Software Architectures
10
Author Software Architectures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Create New Software Architecture Model . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Build a Simple Software Architecture Model . . . . . . . . . . . . . . . . . . . . . . 10-4
Import and Export Software Architectures . . . . . . . . . . . . . . . . . . . . . . . 10-6
Export Architecture to Software Architecture . . . . . . . . . . . . . . . . . . . . . 10-6

Simulate and Deploy Software Architectures . . . . . . . . . . . . . . . . . . . . . 10-10

Model Software Architecture of Throttle Position Control System . . . . 10-16

Class Diagram View of Software Architectures . . . . . . . . . . . . . . . . . . . . 10-22


Software Architecture with Class Diagram View . . . . . . . . . . . . . . . . . . 10-22
Interact with Class Diagram View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-22
Client-Server Interfaces in Class Diagram View . . . . . . . . . . . . . . . . . . 10-24

Author and Extend Functions for Software Architectures . . . . . . . . . . . 10-27


Author and Visualize Functions Using Functions Editor . . . . . . . . . . . . 10-27
Author Functions Programmatically . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-31
Implement Behaviors for Functions in the Architecture Level . . . . . . . . 10-32
Apply Stereotypes to Functions of Software Architectures . . . . . . . . . . 10-32
Import and Export Functions of Software Architectures . . . . . . . . . . . . 10-34

Merge Message Lines Using Adapter Block . . . . . . . . . . . . . . . . . . . . . . 10-36

Author Functions for Software Components of Adaptive Cruise Control


........................................................ 10-39

Service Interfaces Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-46


Structure of Service-Oriented Architectures . . . . . . . . . . . . . . . . . . . . . 10-47

viii Contents
Modeling Service-Oriented Communication Using System Composer . . 10-47

Model Service-Oriented Communication Between Sensors . . . . . . . . . . 10-52

Simulate Asynchronous Services for Vehicle Headlight Management


........................................................ 10-66

Create Custom Views


11
Create Custom Views Using Architecture Views Gallery . . . . . . . . . . . . . 11-2

Create Spotlight Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-5


Mobile Robot Architecture Model with Properties . . . . . . . . . . . . . . . . . . 11-5
Create Spotlight Views from Components . . . . . . . . . . . . . . . . . . . . . . . . 11-6

Create Architecture Views Interactively . . . . . . . . . . . . . . . . . . . . . . . . . . 11-9


Create Views with Component Filters and Port Filters . . . . . . . . . . . . . . 11-9
Add Group By Criteria to Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-16
Edit Views Interactively . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-17
Add or Remove Requirements Links from Views . . . . . . . . . . . . . . . . . . 11-18
Add Custom Clauses to Component Filters and Port Filters . . . . . . . . . . 11-20

Create Architecture Views Programmatically . . . . . . . . . . . . . . . . . . . . . 11-23


Create Architecture Views in System Composer with Keyless Entry System
.................................................... 11-23
Find Elements in Model Using Queries . . . . . . . . . . . . . . . . . . . . . . . . . 11-25

Display Component Hierarchy and Architecture Hierarchy Using Views


........................................................ 11-29
Robot Computer Systems Architecture . . . . . . . . . . . . . . . . . . . . . . . . . 11-29
Switch Between Component Diagram View and Hierarchy Views . . . . . 11-30

Modeling System Architecture of Keyless Entry System . . . . . . . . . . . . 11-33

Pivot Between Lifelines and Components in Views Gallery . . . . . . . . . . 11-46

Use Interface Editor in Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-49

Group Ports in Component Diagram Views . . . . . . . . . . . . . . . . . . . . . . . 11-52

Manage Architecture Models


12
Organize System Composer Files in Projects . . . . . . . . . . . . . . . . . . . . . . 12-2
Use Projects to Organize Files and Folders . . . . . . . . . . . . . . . . . . . . . . . 12-2
Export Models and Model Dependencies to Previous Version of System
Composer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-3

ix
Compare Model Differences Using System Composer Comparison Tool
......................................................... 12-5

Resolve Conflicts in Project Using System Composer Three-Way Merge


........................................................ 12-10
Architecture Model Changes and Conflicts . . . . . . . . . . . . . . . . . . . . . . 12-10
Open System Composer Three-Way Merge . . . . . . . . . . . . . . . . . . . . . . 12-10
View Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-10
Review Automatic Merges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-11
Resolve Conflicts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-11
Accept Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-11

Graphically Manage Shared Interfaces, Data Types, and Constants . . . 12-12


Create Simulink Data Dictionary and Open Architectural Data Section for
Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-12
Design Data Types, Interfaces, and Constants Using Architectural Data
Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-13
Link Data Dictionary to Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-14
Use Interface Editor to Apply Interfaces to Architecture Model . . . . . . . 12-15

Programmatically Manage Shared Interfaces, Data Types, and Constants


of Architecture Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-17
Create or Open Simulink Data Dictionary Programmatically . . . . . . . . . 12-17
Design Data Types, Interfaces, and Constants Programmatically . . . . . . 12-17
Link a Data Dictionary Programmatically . . . . . . . . . . . . . . . . . . . . . . . 12-18
Apply Data Changes Programmatically . . . . . . . . . . . . . . . . . . . . . . . . . 12-19

Resolve Conflicts in Projects Using System Composer Three-Way Merge


Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-20

Import and Export Architecture Models


13
Import and Export Architectures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-2

Import and Export Architecture Models . . . . . . . . . . . . . . . . . . . . . . . . . . 13-5


Define Basic Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-5
Import Basic Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-7
Extend Basic Architecture Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-8
Export Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-13

Import System Composer Architecture Using ModelBuilder Class . . . . 13-15

System Composer Report Generation for System Architectures . . . . . . 13-21

System Composer Report Generation for Software Architectures . . . . 13-26

x Contents
1

Architecture Model Editing

• “Choose Architecture Template for System Design” on page 1-2


• “Compose Architectures Visually” on page 1-5
• “Decompose and Reuse Components” on page 1-19
• “Build Architecture Models Programmatically” on page 1-29
• “Modeling System Architecture of Small UAV” on page 1-37
• “Model-Based Systems Engineering for Space-Based Applications” on page 1-43
• “Use Property Inspector in System Composer” on page 1-60
• “Export Architecture to Software or AUTOSAR Architecture” on page 1-66
• “Add or Remove Variant Choices of Variant Assembly Component Blocks Using External File”
on page 1-68
1 Architecture Model Editing

Choose Architecture Template for System Design


System Composer™ enables you to specify and analyze architectures. You can allocate requirements
while refining an architecture model that you can then design and simulate in Simulink®. To
investigate specific design or analysis concerns, you can create custom live views of the model. You
can use architecture models to analyze requirements, capture properties via stereotyping, perform
trade studies, and produce specifications and interface control documents (ICDs).

Core Modeling Capabilities of Architectures in System Composer


System Composer provides three template architecture models that address different domains in
systems engineering and software architecture modeling. All architecture models provide the same
structural capabilities with some domain-specific extensions.

With any architecture template, you can:

• Describe the structure of a system or software.


• Create profiles with stereotypes to extend your architectures and conduct trade studies using
analysis tools.
• Link model elements to requirements.
• Create custom views by filtering model elements based on criteria.
• Define component behavior by creating or linking Simulink models.
• Specify interfaces on ports to represent information exchange between components.
• Establish traceability using requirements management and model-to-model allocations.

Using Architecture Model Template


You can use the Architecture Model template for system architecture modeling.

In addition to the core capabilities of architectures, with an architecture model, you can:

• Author physical models using subsystem components and Simscape™ behaviors with physical
ports, connectors, and interfaces.
• Describe component behavior using Stateflow® charts to represent modes of operation.

For more information, see “Architectures, Requirements, and Allocations”.

For more information on how to export your model to a software or an AUTOSAR software
architecture model, see, “Export Architecture to Software or AUTOSAR Architecture” on page 1-66.

1-2
Choose Architecture Template for System Design

Using Software Architecture Model Template


You can use the Software Architecture Model template for generic software architecture modeling.
The software architecture applies software domain-specific extensions.

In addition to the core capabilities of architectures, with a software architecture model, you can:

• Author software architectures composed of software components, ports, and interfaces.


• Specify service interfaces on ports to represent component-to-component communication.

• You can represent component interactions as data interfaces and service interfaces. Service
interfaces allow you to define the interface between client and server components. For more
information, see “Service Interfaces Overview” on page 10-46.
• Define the execution order of your component software functions.
• Visualize the structure of a software architecture model using class diagrams.
• Generate deployable code.

To learn more about software architecture models, see “Design Software Architectures”.

For more information on how to export your software architecture model to an AUTOSAR software
architecture model, see, “Export Architecture to Software or AUTOSAR Architecture” on page 1-66.

Using AUTOSAR Blockset Software Architecture Template


The AUTOSAR Blockset Software Architecture template applies AUTOSAR domain-specific
extensions. In the AUTOSAR architecture model, you can author software compositions, components
with interfaces, data types, profiles, and stereotypes. You can add simulation behaviors, including
BSW service components. Alternatively, you can round-trip (import and export) software descriptions
via ARXML files. AUTOSAR Blockset supports C and C++ production code generation (with
Embedded Coder®) and is qualified for use with the ISO® 26262 standard (with IEC Certification Kit).

1-3
1 Architecture Model Editing

In addition to the core capabilities of architectures, with an AUTOSAR software architecture, you
can:

• Add and connect AUTOSAR compositions and components, or import a composition from ARXML
files.
• Configure scheduling and simulation.
• Export composition and component ARXML descriptions and generate production code.

To learn more about AUTOSAR architectures, see “Software Architecture Modeling” (AUTOSAR
Blockset).

See Also
systemcomposer.arch.Architecture | systemcomposer.createModel |
systemcomposer.exportToSoftwareArchitecture |
systemcomposer.exportToAUTOSARArchitecture

Related Examples
• “Compose Architectures Visually” on page 1-5
• “Author Software Architectures” on page 10-2
• “Create AUTOSAR Architecture Models” (AUTOSAR Blockset)
• “Modeling System Architecture of Small UAV” on page 1-37
• “Model Software Architecture of Throttle Position Control System” on page 10-16
• “Author AUTOSAR Compositions and Components in Architecture Model” (AUTOSAR Blockset)

1-4
Compose Architectures Visually

Compose Architectures Visually


In this section...
“Create Architecture Model” on page 1-5
“Components” on page 1-8
“Ports” on page 1-11
“Connections” on page 1-14

You can create and edit visual diagrams to represent architectures in System Composer. Use
architectural elements including components, ports, and connections in the system composition.
Model hierarchy in architecture by decomposing components. Navigate through the hierarchy.

With MATLAB® code and the functions importModel and exportModel, you can import external
architecture descriptions into System Composer. For more information, see “Import and Export
Architecture Models” on page 13-5.

Alternatively, you can use MATLAB programming to create and customize the various architectural
elements. For details, see “Build Architecture Models Programmatically” on page 1-29.

Note When you load existing interface data dictionaries, Simulink automatically migrates them to
the Architectural Data section of the Simulink data dictionary. In addition to the Interface Editor, you
can also use the Architectural Data Editor and Simulink.dictionary.ArchitecturalData
programmatic interfaces to manage and modify interfaces and value types. For more information on
managing architectural data, see “Graphically Manage Shared Interfaces, Data Types, and
Constants” on page 12-12 and “Programmatically Manage Shared Interfaces, Data Types, and
Constants of Architecture Models” on page 12-17.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Create Architecture Model


A System Composer architecture represents a system of components and how they interface with
each other structurally and behaviorally.

Different types of architectures describe different aspects of systems. You can use views to visualize a
subset of components in an architecture. You can define parameters on the architecture level using
the Parameter Editor.

A System Composer model is the file that contains architectural information, such as components,
ports, connectors, interfaces, and behaviors.

An architecture model includes a top-level architecture that holds the composition of the system. This
top-level architecture also allows definition of interfaces of this system with other systems.

Start with a blank architecture model to model the physical and logical architecture of a system. Use
one of these three methods to create an architecture model:

• At the MATLAB Command Window, enter this command.

1-5
1 Architecture Model Editing

systemcomposer

Select Architecture Model.

System Composer provides template architecture models that address different domains in
systems engineering and software architecture modeling: Architecture Model and Software
Architecture Model. All architecture models provide the same structural capabilities with some
domain and platform specific constraints. For more information on architecture templates, see
“Choose Architecture Template for System Design” on page 1-2.
• From a Simulink model or a System Composer architecture model. On the Simulation tab, select

New , and then select Architecture .

1-6
Compose Architectures Visually

• At the MATLAB Command Window, enter this command.

archModel = systemcomposer.createModel("modelName");
systemcomposer.openModel("modelName");

The argument modelName is the name of the new model.

Save the architecture model. On the Simulation tab, select Save . The architecture model is
saved as an SLX file.

The architecture model includes a top-level architecture that holds the composition of the system.
This top-level architecture also allows definition of interfaces of this system with other systems. The
composition represents a structured parts list — a hierarchy of components with their interfaces and
interconnections. Edit the composition in the Composition Editor.

1-7
1 Architecture Model Editing

This example shows a motion control architecture, where a sensor obtains information from a motor,
feeds that information to a controller, which in turn processes this information to send a control
signal to the motor so that it moves in a certain way. You can start with this rough description and
add component properties, interface definitions, and requirements as the design progresses.

Components
A component is a replaceable part of a system that fulfills a clear function in the context of an
architecture. A component defines an architectural element, such as a function, another system,
hardware, software, or other conceptual entity. A component can also be a subsystem or subfunction.

The Component element in System Composer can represent a component at any level of the system
hierarchy, whether it is a major system component that encompasses many subsystems, such as a
controller with its hardware and software, or a component at the lowest level of hierarchy, such as a
software module for messaging.

Represented as a block, a component is a part of an architecture model that can be separated into
reusable artifacts. Transfer information between components with:

• Port interfaces using the Interface Editor


• Parameters using the Parameter Editor

Add Components

Use one of these methods to add components to the architecture:

1-8
Compose Architectures Visually

• Draw a component — In the canvas, left-click and drag the mouse to create a rectangle. Release
the mouse button to see the component outline. Select the Component block option to commit.
• Create a single component from the palette —

• Create multiple components from the palette —

Name Component

Each component must have a name that is unique within the same architecture level. The name of the
component is highlighted upon creation so you can directly type the name. To change the name of a
component, click the component and then click its name.

Move Component

Move a component simply by clicking and dragging it. Blue guidelines may appear to help align the
component with other components.

1-9
1 Architecture Model Editing

Resize Component

Resize a component by dragging corners.

1 Pause the pointer over a corner to see the double arrow.

2 Click the corner and drag while holding the mouse button down. If you want to resize the
component proportionally, hold the Shift button as well.

3 Release the mouse button when the component reaches the size you want.

1-10
Compose Architectures Visually

Delete Component

Click a component and press Delete to delete it. To delete multiple components, select them while
holding the Shift key down, then press Delete.

Add Mask Icon on Component

You can use mask icons to mask System Composer components with an image that covers the
component body and header. Mask icons allow for more visually expressive architecture diagrams.

1 Select a Component or Variant Component block.


2 To open the Add mask icon image dialog box, from the toolstrip, select Format > Add Image
to Block.
3 Click Browse to select an image from your file directory. The directory must be on the MATLAB
path.
4 To remove the mask image, from the toolstrip, select Format > Edit Image > Remove Image.

To inspect component names or port names after applying a mask icon, use the Property Inspector. To
configure additional options such as mask transparency, use the setMaskImage function.

For an example of using mask icons on Component and Variant Component blocks, see “Calculate
Endurance Using Quadcopter Architectural Design” on page 9-17.

Ports
A port is a node on a component or architecture that represents a point of interaction with its
environment. A port permits the flow of information to and from other components or systems.

• Component ports are interaction points on the component to other components.


• Architecture ports are ports on the boundary of the system, whether the boundary is within a
component or the overall architecture model. The root architecture has a boundary defined by its
ports.

For example, a sensor might have data ports to communicate with a motor and a controller. Its input
port takes data from the motor, and the output port delivers data to the controller. You can specify
data values by defining an interface as described in “Define Port Interfaces Between Components” on
page 3-2.

Note New ports by default use <inherit> mode to support unknown interface specifications in
early stages of architectural design. If an interface is specified on another port, the <inherit>
specification propagates that interface across connections to your original port.

Add Component Port

Represent the relationship between components by defining directional interface ports. You can
organize the diagram by positioning ports on any edge of the component, in any position.

1 Pause over the side of a component. A + sign and a port outline appear.

1-11
1 Architecture Model Editing

2 Click the port outline. A set of options appear for an Input, Output, or Physical port.

3 Select Output to commit the port. You can also name the port at this point.

An output port is shown with the icon, an input port is shown with the icon, and a physical
port is shown with the icon and is nondirectional.

You can move any port to any component edge after creation.

Add Architecture Port

You can also create a port for the architecture that contains components. These system ports on the
boundary carry the interface of the system to other systems.

The root is at the top of an architecture hierarchy. A root architecture has a boundary defined by its
architecture ports surrounding the system of interest.

The root architecture has a system boundary surrounding your architecture model. You can add
architecture ports that define interfaces across the boundary.

Pause on any edge of the system box and click when the + sign appears. Click the left side to create
input ports and click the right side to create output ports.

1-12
Compose Architectures Visually

Name Port

Every port is created with a name. To change the name, click it and edit.

Ports of a component must have unique names.

Move Port

You can move a port to any side of a component. Select the port and use arrow keys.

Arrow Key Original Port Edge Port Movement


Up Left or right If below other ports on the same
edge, move up, if not, move to
the top edge
Top or bottom No action
Right Top or bottom If to the left of other ports on
the same edge, move right, if
not, move to the right edge
Left or right No action
Down Left or right If above other ports on the same
edge, move down, if not, move
to the bottom edge
Top or bottom No action

1-13
1 Architecture Model Editing

Arrow Key Original Port Edge Port Movement


Left Top or bottom If to the right of other ports on
the same edge, move left, if not,
move to the left edge
Left or right No action

The spacing of the ports on one side is automatic. There can be a combination of input and output
ports on the same edge.

Delete Port

Delete a port by selecting it and pressing the Delete button.

Change Port Type

To change a port type, right-click a port and select Change port action, then select either Input,
Output, or Physical. You can also change port types in the Property Inspector. In the Interface
section, from the Action list, select the appropriate port action.

Use the systemcomposer.arch.PortDirection enumeration to change port action. In this


example, compPort represents a systemcomposer.arch.ComponentPort object, and archPort
represents a systemcomposer.arch.ArchitecturePort object. Each object uses a Direction
property to identify port action.
compPort.Direction = systemcomposer.arch.PortDirection.Input
compPort.Direction = systemcomposer.arch.PortDirection.Physical

archPort.Direction = systemcomposer.arch.PortDirection.Output
archPort.Direction = systemcomposer.arch.PortDirection.Physical

For an Input port or an Output port, you can change a port type to its conjugate after right-clicking
a port and selecting Conjugate port from the context menu. An Input port is converted into an
Output port, and an Output port is converted into an Input port.

Connections
Connectors are lines that provide connections between ports. Connectors describe how information
flows between components or architectures.

A connector allows two components to interact without defining the nature of the interaction. Set an
interface on a port to define how the components interact.

Connections are visual representations of data flow from an output port to an input port. For
example, a connection from a motor to a sensor carries positional information.

Connect Existing Ports

Connect two ports by dragging a line:

1 Click one of the ports.


2 Keep the mouse button down while dragging a line to the other port.
3 Release the mouse button at the destination port. A black line indicates the connection is
complete. A red-dotted line appears if the connection is incomplete.

1-14
Compose Architectures Visually

You can take these steps in both directions — input port to output port, or output port to input port.
You cannot connect ports that have the same direction.

A connection between an architecture port and a component port is shown with tags instead of lines.

Connect Components Without Ports

To quickly create ports and connections at the same time, drag a line from one component edge to
another. The direction of this connection depends on which edges of the components are used - left
and top edges are considered inputs, right and bottom edges are considered outputs. You can also
perform this operation from an existing port to a component edge.

You can create a connection between an edge that is assumed to be an input only with an edge that is
assumed to be an output. For example, you cannot connect a top edge, which is assumed to be an
input, with another top edge, unless one of them already has an output port.

1-15
1 Architecture Model Editing

Branch Connections

Connect an output port to multiple input ports by branching a connection. To branch, right-click an
existing connection and drag to an input port while holding the mouse button down. Release the
button to commit the new connection.

Create New Components Through Connections

If you start a connection from an output port and release the mouse button without a destination
port, a new component tentatively appears. Accept the new component by clicking it.

Auto-Connect Ports With Same Name

You can automatically connect ports with the same name between components on the model canvas.

• Highlight a component with the ports to connect from.


• Press Ctrl and right-click another component whose ports to which you would like to connect
using the same name rule.

For more information, see “Connect Blocks”.

To connect same name ports using programmatic interfaces, use the connect function and specify
"name" for the Rule name-value argument. To identify your ports and components, use the lookup
function with the getQualifiedName function.

1-16
Compose Architectures Visually

Change Line Crossing Style for Overlapping Connections

In complex architectural diagrams, connectors can overlap. You can improve the readability of your
diagram by choosing another line crossing style. Navigate to Modeling > Environment > Simulink
Preferences. In Simulink Preferences, select Editor, then select a Line crossing style. The
default line crossing style, Tunnel, is shown below.

Another option, Line Hop, is shown below.

1-17
1 Architecture Model Editing

For more information on line crossing style parameters, see “Line crossing style”.

See Also
Functions
createModel | addComponent | addPort | connect | setMaskImage | exportModel |
importModel

Blocks
Component

More About
• “Decompose and Reuse Components” on page 1-19
• “Add Images in Masks”
• “Define Port Interfaces Between Components” on page 3-2
• “Author Parameters in System Composer Using Parameter Editor” on page 4-2
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35

1-18
Decompose and Reuse Components

Decompose and Reuse Components


Every component in an architecture model can have its own design, or even several design
alternatives. These designs can be architectures modeled in System Composer or behaviors modeled
in Simulink. Engineering systems often use the same component design in multiple places. A common
component, such as power switch, can be part of all electrical components. You can reuse a
component in System Composer within the same model as well as across architecture models.

Architecture How to Use More Information


Reference
System Composer Define component hierarchy with a “Create Architecture Model Reference”
model reference linked architecture model to easily on page 1-21
reuse these definitions across
architectural components.
System Composer Define component hierarchy with a “Create Architecture Subsystem
subsystem linked architecture subsystem to easily Reference” on page 1-23
reference reuse these definitions across
architectural components.

Subsystems support root-level physical


ports to use with Simscape physical
behaviors.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Decompose Component
A component can have its own architecture. Double-click a component to view or edit its architecture.
When you view the component at this level, its ports appear as architecture ports. Use the Model
Browser to view component hierarchy.

1-19
1 Architecture Model Editing

You can add components, ports, and connections at this level to define the architecture.

You can also make a new Component block from a group of components.

1 Select the components. Either click and drag a rectangle, or select multiple components by
holding the Shift button down.

1-20
Decompose and Reuse Components

2 Create a component from the selected elements by right-clicking and selecting Create
Component from Selection.

As a result, the new component has the selected components, their ports, and connections as part of
its architecture. Any unconnected ports and connections to components outside of the selection
become ports on the new component.

Any component that has its own architecture displays a preview of its contents.

Create Architecture Reference


An architecture reference provides a structure to create a hierarchical architectural system and
further define subsystems using the component, port, connector paradigm in System Composer. Some
projects use the same, detailed component in multiple places. The design of such a component must
be tightly managed. You can create an architecture reference to reuse the architectural definition of a
component in the same architecture model or across several architecture models.

Create Architecture Model Reference

Create an architecture reference model using this procedure:

1 Right-click the Sensor component and select Save as Architecture Model. Then, from the
Type list, select Model Reference.
2 Provide a name for the model. By default, the referenced architecture model is saved in the same
folder as the architecture model. Browse for or enter the full path if you want to save the
referenced model in a different folder.

1-21
1 Architecture Model Editing

3 The software creates an architecture model with the provided name, and links the component to
the new model. The linked model is indicated in the name of the component between the <>
signs.

All architecture models can reference this new architecture model through linked components.

1-22
Decompose and Reuse Components

Create Architecture Subsystem Reference

You can link architecture subsystem references to components. Unlike a model reference, a
subsystem reference supports top-level physical ports. Subsystems improve top-down editing
workflows because inherited ports are flexible. An architecture subsystem reference contains
sharable architecture models with optional Simscape behaviors. For more information about
implementing Simscape behaviors, see “Implement Component Behavior Using Simscape” on page 7-
23.

Note To type ports on architecture subsystems with interfaces, you must link an external interface
data dictionary. Architecture subsystems do not contain a model workspace. For more information,
see “Manage Interfaces with Data Dictionaries” on page 3-24.

Create an architecture subsystem reference by linking an existing System Composer architecture


subsystem file to a component or saving a new architecture subsystem from the converted
component. The subsystem reference is saved in a separate file from the parent System Composer
architecture model. Save a new architecture subsystem from the converted component using this
procedure:

1 Right-click the Motor component and select Save as Architecture Model. Then, from the Type
list, select Subsystem Reference.
2 Provide a name for the subsystem. By default, the referenced architecture subsystem is saved in
the same folder as the architecture model. Browse for or type the full path if you want to save the
referenced subsystem in a different folder.

3 System Composer creates an architecture subsystem with the provided name, and links the
component to the new model. The linked subsystem is indicated in the name of the component
between the <> signs, and the component has a icon on the upper right.

1-23
1 Architecture Model Editing

All architecture models can reference this new architecture subsystem through linked
components.

An architecture subsystem reference component can be implemented as a reference to a separate


System Composer subsystem file and reused multiple times in the architecture model. Each
component linked to an architecture subsystem is unique, so when a physical port is set to inherited,
each instance of a physical port can use a different physical domain.

Architecture subsystem references support physical ports with physical interfaces. You can add
Simscape behaviors to child components that become Simulink subsystem references or Simulink
subsystem components. For more information, see “Implement Component Behavior Using Simscape”
on page 7-23.

Use Architecture Reference

You can use an architecture model reference, saved in a separate file, by linking to it from a
component. Right-click the component and select Link to Model. You can also use the Create
Reference option in the element palette directly to create a component that uses a reference
architecture.

To link a selected component to an existing architecture model, right-click the Trajectory


Planning component and select Link to Model.

Provide the full path to the referenced architecture model. If the linked component has its own ports
and components, this content is deleted during linking and is replaced by that of the referenced
architecture. The ports of the linked component become the architecture ports in the referenced
architecture.

1-24
Decompose and Reuse Components

Any change made in an architecture model reference is immediately reflected in the models that link
to it. If you move or rename the referenced architecture, the link becomes invalid and the linked
component displays an error. Link the component to a valid architecture model reference.

Remove Architecture Reference

In some cases, you have to deviate from the architecture model reference for a single component. For
example, a comprehensive sensor model, referenced from a local component, may include too many
features for the motion control architecture at hand and require simplification for that architecture
only. In this case, you can remove the reference architecture to make local changes possible. Right-
click a linked component and select Inline Model.

This operation provides two options:

• Interface and subcomponents — Ports, interfaces, and subcomponents of the reference


architecture are copied to the component.
• Interface only — The ports and designated interfaces of the reference architecture are reflected
on the component, but the composition is blank.

Once the architecture model reference is removed, you can make changes without affecting other
architectures. However, you cannot propagate local changes to the architecture model reference. If
you link to the referenced architecture again, local changes are lost.

1-25
1 Architecture Model Editing

Create Variants
A component can have multiple design alternatives, or variants.

A variant is one of many structural or behavioral choices in a variant component.

Use variants to quickly swap different architectural designs for a component while performing
analysis.

A variant control is a string that controls the active variant choice.

Set the variant control programmatically to control which variant is active.

You can model variations for any component in a single architecture model. You can define a mix of
behaviors (defined in a Simulink model) and architectures (defined in a System Composer
architecture model) as variant choices. For example, a component may have two variant options that
represent two alternate structural decompositions.

Convert a Component block to a Variant Component block by adding variant choices to the
component. Right-click the Sensor component and select Add Variant Choice.

The badge on the component indicates that it is a variant, and a variant choice is added to the
existing composition. Double-click the component to see variant choices.

1-26
Decompose and Reuse Components

Add Variant Choices


You can add more variant choices to a variant component using the Add Variant Choice option.

Open and edit the variant by right-clicking and selecting Variant > Open > Variant Name from the
component context menu.

You can also designate a component as a variant upon creation using the button in the toolstrip.
This creates two variant choices by default.

Activate a specific variant choice using the context menu of the block. Right-click and select Variant
> Label Mode Active Choice > Choice (Component). The active choice is displayed in the header
of the block.

Convert Variant Component to Variant Assembly Component


A “Variant Assembly Component” block enables you to add or remove its variant choices from
external sources without modifying the model. The Variant Assembly Component block can contain
Model blocks, “Subsystem Reference” blocks, or both as its variant choices. The choices are
maintained in corresponding model or subsystem files that are on the MATLAB path. The conversion
from Variant Component to Variant Assembly Component is not supported for software architecture
and AUTOSAR architecture.

Convert Variant Component to Variant Assembly Component Interactively

Consider a Variant Component block in a architecture model canvas with model reference or
subsystem reference or Simulink models as its variant choices and in label or expression mode
that is to be converted to a Variant Assembly Component block. For more information on the steps to

1-27
1 Architecture Model Editing

convert a Variant Component to a Variant Assembly Component interactively, see “Convert Variant
Subsystem Block with Expressions to Variant Assembly Subsystem Block Interactively” and “Convert
Variant Subsystem Block with Labels to Variant Assembly Subsystem Block Interactively”.

Convert Variant Component to Variant Assembly Component Programmatically

To convert a Variant Component block using the makeVariantAssembly function of the


systemcomposer.arch.VariantComponent object to programmatically convert to a Variant
Assembly Component block, see makeVariantAssembly.

Create Software Architecture from Component

You can create a software architecture model from a component in a System Composer architecture
model and reference the software architecture model from the component. You can use software
architectures to link Simulink export-function, rate-based, or JMAAB models to components in your
architecture model to simulate and generate code. For more information, see “Export Architecture to
Software Architecture” on page 10-6.

Create AUTOSAR Architecture from Component


You can create an AUTOSAR architecture model from a component in a System Composer
architecture or software architecture model and reference the AUTOSAR architecture model from the
component. For more information, see “Create AUTOSAR Architecture from System Composer
Model” (AUTOSAR Blockset).

See Also
Functions
createArchitectureModel | createArchitectureSubsystem | linkToModel |
inlineComponent | addVariantComponent | makeVariant | makeVariantAssembly |
addChoice | setActiveChoice

Blocks
Reference Component | Variant Component

More About
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Implement Component Behavior Using Simscape” on page 7-23
• “Organize System Composer Files in Projects” on page 12-2
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35

1-28
Build Architecture Models Programmatically

Build Architecture Models Programmatically

Build an architecture model programmatically using System Composer™.

To build a model, add a data dictionary with data interfaces, data elements, a value type, and a
physical interface, then add components, ports, and connections. Create a profile with stereotypes
and properties and then apply those stereotypes to model elements. Assign an owned interface to a
port. After the model is built, you can create custom views to focus on specific considerations. You
can also query the model to collect different model elements according to criteria you specify.

Add Components, Ports, Connections, and Interfaces

Create a model and extract its architecture.

model = systemcomposer.createModel("mobileRobotAPI");
arch = model.Architecture;

Create an interface data dictionary and add a data interface. Add a data element to the data
interface. Add a value type to the interface data dictionary. Assign the type of the data element to the
value type. Add a physical interface and physical element with a physical domain type. Attach the
data dictionary to the model.

dictionary = systemcomposer.createDictionary("SensorInterfaces.sldd");
interface = dictionary.addInterface("GPSInterface");
element = interface.addElement("SignalStrength");
valueType = dictionary.addValueType("SignalStrengthType",Units="dB",...
Description="GPS Signal Strength");
element.setType(valueType);
physicalInterface = dictionary.addPhysicalInterface("PhysicalInterface");
physicalElement = addElement(physicalInterface,"ElectricalElement",...
Type="electrical.electrical");
linkDictionary(model,"SensorInterfaces.sldd");

Save the changes to the interface data dictionary.

dictionary.save

Save the model.

model.save

Open the model.

systemcomposer.openModel("mobileRobotAPI");

View the interfaces in the Interface Editor.

1-29
1 Architecture Model Editing

Add components, ports, and connections. Set the physical interface to the physical ports, which you
will connect later.
componentSensor = addComponent(arch,"Sensor");
sensorPorts = addPort(componentSensor.Architecture,{'MotionData','SensorPower'},...
{'in','physical'});
sensorPorts(2).setInterface(physicalInterface)

componentPlanning = addComponent(arch,"Planning");
planningPorts = addPort(componentPlanning.Architecture,...
{'Command','SensorPower1','MotionCommand'},...
{'in','physical','out'});
planningPorts(2).setInterface(physicalInterface)

componentMotion = addComponent(arch,"Motion");
motionPorts = addPort(componentMotion.Architecture,{'MotionCommand','MotionData'},...
{'in','out'});

Create an owned interface on the 'MotionData' port. Add an owned data element under the owned
data interface. Assign the data element "Rotation" to a value type with units set to degrees.
ownedInterface = motionPorts(2).createInterface("DataInterface");
ownedElement = ownedInterface.addElement("Rotation");
subInterface = ownedElement.createOwnedType(Units="degrees");

View the interfaces in the Interface Editor. Select the 'MotionData' port on the Motion
component. In the Interface Editor, switch from Dictionary View to Port Interface View.

Connect components with an interface rule and the default name rule. The interface rule connects
ports on components that share the same interface. By default, the name rule connects ports on
components that share the same name.
c_sensorData = connect(arch,componentSensor,componentPlanning,Rule="interface");
c_motionData = connect(arch,componentMotion,componentSensor);
c_motionCommand = connect(arch,componentPlanning,componentMotion);

Add and Connect Architecture Port

Add an architecture port on the architecture.


archPort = addPort(arch,"Command","in");

The connect command requires a component port as an argument. Obtain the component port, then
connect.

1-30
Build Architecture Models Programmatically

compPort = getPort(componentPlanning,"Command");
c_Command = connect(archPort,compPort);

Save the model.

model.save

Arrange the layout by pressıng Ctrl+Shift+A or using this command.

Simulink.BlockDiagram.arrangeSystem("mobileRobotAPI");

Create and Apply Profile with Stereotypes

Profiles are XML files that can be applied to any model. You can add stereotypes with properties to
profiles and then populate the properties with specific values in the Profile Editor. Along with the
built-in analysis capabilities of System Composer, stereotypes help you optimize your system for
performance, cost, and reliability.

Create Profile and Add Stereotypes

Create a profile.

profile = systemcomposer.createProfile("GeneralProfile");

Create a stereotype that applies to all element types.

elemSType = addStereotype(profile,"projectElement");

Create stereotypes for different types of components. You can select these types are based on your
design needs.

pCompSType = addStereotype(profile,"physicalComponent",AppliesTo="Component");
sCompSType = addStereotype(profile,"softwareComponent",AppliesTo="Component");

Create a stereotype for connections.

sConnSType = addStereotype(profile,"standardConn",AppliesTo="Connector");

1-31
1 Architecture Model Editing

Add Properties

Add properties to the stereotypes. You can use properties to capture metadata for model elements
and analyze nonfunctional requirements. These properties are added to all elements to which the
stereotype is applied, in any model that imports the profile.
addProperty(elemSType,'ID',Type="uint8");
addProperty(elemSType,'Description',Type="string");
addProperty(pCompSType,'Cost',Type="double",Units="USD");
addProperty(pCompSType,'Weight',Type="double",Units="g");
addProperty(sCompSType,'develCost',Type="double",Units="USD");
addProperty(sCompSType,'develTime',Type="double",Units="hour");
addProperty(sConnSType,'unitCost',Type="double"',Units="USD");
addProperty(sConnSType,'unitWeight',Type="double",Units="g");
addProperty(sConnSType,'length',Type="double",Units="m");

Save Profile
profile.save;

Apply Profile to Model

Apply the profile to the model.


applyProfile(model,"GeneralProfile");

Apply stereotypes to components. Some components are physical components, while others are
software components.
applyStereotype(componentPlanning,"GeneralProfile.softwareComponent")
applyStereotype(componentSensor,"GeneralProfile.physicalComponent")
applyStereotype(componentMotion,"GeneralProfile.physicalComponent")

Apply the connector stereotype to all connections.


batchApplyStereotype(arch,'Connector',"GeneralProfile.standardConn");

Apply the general element stereotype to all connectors and ports.


batchApplyStereotype(arch,'Component',"GeneralProfile.projectElement");
batchApplyStereotype(arch,'Connector',"GeneralProfile.projectElement");

Set properties for each component.


setProperty(componentSensor,'GeneralProfile.projectElement.ID','001');
setProperty(componentSensor,'GeneralProfile.projectElement.Description',...
'Central unit for all sensors');
setProperty(componentSensor,'GeneralProfile.physicalComponent.Cost','200');
setProperty(componentSensor,'GeneralProfile.physicalComponent.Weight','450');
setProperty(componentPlanning,'GeneralProfile.projectElement.ID','002');
setProperty(componentPlanning,'GeneralProfile.projectElement.Description',...
'Planning computer');
setProperty(componentPlanning,'GeneralProfile.softwareComponent.develCost','20000');
setProperty(componentPlanning,'GeneralProfile.softwareComponent.develTime','300');
setProperty(componentMotion,'GeneralProfile.projectElement.ID','003');
setProperty(componentMotion,'GeneralProfile.projectElement.Description',...
'Motor and motor controller');
setProperty(componentMotion,'GeneralProfile.physicalComponent.Cost','4500');
setProperty(componentMotion,'GeneralProfile.physicalComponent.Weight','2500');

1-32
Build Architecture Models Programmatically

Set the properties of connections to be identical.


connections = [c_sensorData c_motionData c_motionCommand c_Command];
for k = 1:length(connections)
setProperty(connections(k),'GeneralProfile.standardConn.unitCost','0.2');
setProperty(connections(k),'GeneralProfile.standardConn.unitWeight','100');
setProperty(connections(k),'GeneralProfile.standardConn.length','0.3');
end

Add Hierarchy

Add two components named Controller and Scope inside the Motion component. Define the ports.
Connect the components to the architecture and to each other, applying a connector stereotype.
Hierarchy in an architecture diagram creates an additional level of detail that specifies how
components behave internally.
motionArch = componentMotion.Architecture;

motionController = motionArch.addComponent('Controller');
controllerPorts = addPort(motionController.Architecture,{'controlIn','controlOut'},...
{'in','out'});
controllerCompPortIn = motionController.getPort('controlIn');
controllerCompPortOut = motionController.getPort('controlOut');

motionScope = motionArch.addComponent('Scope');
scopePorts = addPort(motionScope.Architecture,{'scopeIn','scopeOut'},{'in','out'});
scopeCompPortIn = motionScope.getPort('scopeIn');
scopeCompPortOut = motionScope.getPort('scopeOut');

c_planningController = connect(motionPorts(1),controllerCompPortIn);

For outport connections, the data element must be specified.


c_planningScope = connect(scopeCompPortOut,motionPorts(2),DestinationElement="Rotation");
c_planningConnect = connect(controllerCompPortOut,scopeCompPortIn,...
"GeneralProfile.standardConn");

Save the model.


model.save

Arrange the layout by pressıng Ctrl+Shift+A or using this command.


Simulink.BlockDiagram.arrangeSystem("mobileRobotAPI/Motion");

1-33
1 Architecture Model Editing

Create Model Reference

Model references can help you organize large models hierarchically and define architectures or
behaviors once that you can then reuse. When a component references another model, any existing
ports on the component are removed, and ports that exist on the referenced model will appear on the
component.

Create a new System Composer model. Convert the Controller component into a reference
component to reference the new model. To add additional ports on the Controller component, you
must update the referenced model "mobileMotion".
referenceModel = systemcomposer.createModel("mobileMotion");
referenceArch = referenceModel.Architecture;
newComponents = addComponent(referenceArch,"Gyroscope");
referenceModel.save

linkToModel(motionController,"mobileMotion");

Save the models.


referenceModel.save
model.save

Make Variant Component

You can convert the Planning component to a variant component using the makeVariant function.
The original component is embedded within a variant component as one of the available variant
choices. You can design other variant choices within the variant component and toggle the active
choice. Variant components allow you to choose behavioral designs programmatically in an
architecture model to perform trade studies and analysis.
[variantComp,choice1] = makeVariant(componentMotion);

Add an additional variant choice named MotionAlt. The second argument defines the name, and the
third argument defines the label. The label identifies the choice. The active choice is controlled by the
label.
choice2 = addChoice(variantComp,{'MotionAlt'},{'MotionAlt'});

Create the necessary ports on MotionAlt.


motionAltPorts = addPort(choice2.Architecture,{'MotionCommand','MotionData'},{'in','out'});

Make MotionAlt the active variant.

1-34
Build Architecture Models Programmatically

setActiveChoice(variantComp,"MotionAlt")

Arrange the layout by pressıng Ctrl+Shift+A or using this command.

Simulink.BlockDiagram.arrangeSystem("mobileRobotAPI/Planning");

Save the model.

model.save

Clean Up

Run this script to remove generated artifacts before you run this example again.

cleanUpArtifacts

See Also
Functions
createModel | createDictionary | addInterface | addPhysicalInterface | addValueType
| addElement | setType | createOwnedType | linkDictionary | addComponent | addPort |
setInterface | connect | save | getPort | createProfile | addStereotype | addProperty |
save | applyProfile | applyStereotype | batchApplyStereotype | setProperty |
linkToModel | makeVariant | addChoice | setActiveChoice | closeAll

Blocks
Component | Reference Component | Variant Component

Tools
Interface Editor | Profile Editor | Property Inspector

More About
• “Compose Architectures Visually” on page 1-5
• “Decompose and Reuse Components” on page 1-19

1-35
1 Architecture Model Editing

• “Extend System Composer Language Elements Using Profiles” on page 5-2


• “Define Port Interfaces Between Components” on page 3-2
• “Organize System Composer Files in Projects” on page 12-2

1-36
Modeling System Architecture of Small UAV

Modeling System Architecture of Small UAV

Overview

This example shows how to use System Composer™ to set up the architecture for a small unmanned
aerial vehicle, composed of six top-level components. Learn how to refine your architecture design by
authoring interfaces, inspect linked textual requirements, define profiles and stereotypes, and run a
static analysis on such an architecture model.

Each top-level component is decomposed into its subcomponents. Navigate through the hierarchy to
view the composition for each component. The root component, scExampleSmallUAVModel, has
input and output ports that represent data exchange between the system and its environment.

Author Interfaces

Define interfaces for domain-specific data between connections. The information shared between two
ports defined by interface element property values further enhances the specification. To open the
Interface Editor, in the Modeling tab in the toolstrip, click Interface Editor.

Click the GS Commands port on the architecture model to highlight the


architecture_gsCommands interface and indicate the assignment of the interface.

1-37
1 Architecture Model Editing

Inspect Requirements

A Requirements Toolbox™ license is required to inspect requirements in a System Composer


architecture model.

1-38
Modeling System Architecture of Small UAV

Components in the architecture model link to system requirements defined in


scExampleSmallUAVModel.slreqx. Open the Requirements Manager. In the bottom right
corner of the model pane, click Show Perspectives views. Then, click Requirements.

Select components on the model to see the requirement they link to, or, conversely, select items in the
Requirements view to see which components implement them. Requirements can also be linked to
connectors or ports to allow traceability throughout your design artifacts. To edit the requirements in
smallUAVReqs.slreqx, select the Requirements Editor (Requirements Toolbox) from the menu.

The Carrying Capacity requirement highlights the total mass able to be carried by the aircraft.
This requirement, along with the weight of the aircraft, is part of the mass rollup analysis performed
for early verification and validation.

Define Profiles and Stereotypes

To complete specifications and enable analysis later in the design process, stereotypes add custom
metadata to architecture model elements. This model has stereotypes for these elements:

• On-board element, applicable to components


• RF connector, applicable to ports
• RF wiring, applicable to connectors

1-39
1 Architecture Model Editing

Stereotypes are defined in XML files by using profiles. The profile UAVComponent.xml is attached to
this model. Edit a profile by using the Profile Editor. On the Modeling tab, click Profile Editor.

The display appears below.

Analyze the Model

To run static analyses on your system, create an analysis model from your architecture model. An
analysis model is a tree of instances generated from the elements of the architecture model in which
all referenced models are flattened out, and all variants are resolved.

To open the Instantiate Architecture Model tool, click Analysis Model on the Views menu.

Run a mass rollup on this model. In the dialog, select the stereotypes that you want to include in your
analysis. Select the analysis function by browsing to utilities/massRollUp.m. Set the model
iteration mode to Bottom-up.

1-40
Modeling System Architecture of Small UAV

Uncheck Strict Mode so that all components can have a Mass property instantiated to facilitate
calculation of total mass. Click Instantiate to generate an analysis.

1-41
1 Architecture Model Editing

Once on the Analysis Viewer screen, click Analyze. The analysis function iterates through model
elements bottom up, assigning the Mass property of each component as a sum of the Mass properties
of its subcomponents. The overall weight of the system is assigned to the Mass property of the top
level component, scExampleSmallUAVModel.

See Also
setInterface | createProfile | addStereotype | addProperty | applyStereotype |
instantiate

More About
• “Define Port Interfaces Between Components” on page 3-2
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Define and Style Stereotypes in Profiles” on page 5-5
• “Analyze Architecture” on page 9-2
• “Organize System Composer Files in Projects” on page 12-2
• “System Composer Concepts”

1-42
Model-Based Systems Engineering for Space-Based Applications

Model-Based Systems Engineering for Space-Based


Applications

This example provides an overview of the CubeSat Model-Based System Engineering Project
template, available from the Simulink® start page, under Aerospace Blockset™. It demonstrates how
to model a space mission architecture in Simulink with System Composer™ and Aerospace Blockset
for a 1U CubeSat in low Earth orbit (LEO). The CubeSat's mission is to image MathWorks
Headquarters in Natick, Massachusetts, at least once per day. The project references the Aerospace
Blockset CubeSat Simulation Project, reusing the vehicle dynamics, environment models, data
dictionaries, and flight control system models defined in that project.

This project demonstrates how to:

• Define system level requirements for a CubeSat mission in Simulink


• Compose a system architecture for the mission in System Composer
• Link system-level requirements to components in the architecture with Requirements Toolbox™
• Model vehicle dynamics and flight control systems with Aerospace Blockset
• Validate orbital requirements using mission analysis tools and Simulink Test™

Open the Project

To create a new instance of the CubeSat Model-Based System Engineering Project, select
Create Project in the Simulink start page. When the project is loaded, an architecture model for the
CubeSat opens.

open("asbCubeSatMBSEProject.sltx");

1-43
1 Architecture Model Editing

Define System-Level Requirements

Define a set of system-level requirements for the mission. You can import these requirements from
third-party requirement management tools such as ReqIF (Requirements Interchange Format) files or
author them directly in the Requirements Editor.

This example contains a set of system-level requirements stored in SystemRequirements.slreqx. Open


this requirement specification file in the Requirements Editor. Access the Requirements Editor
from the Apps tab or by double-clicking on SystemRequirements.slreqx in the project folder browser.

Our top level requirement for this mission is:

1 The system shall provide and store visual imagery of MathWorks® headquarters [42.2775 N,
71.2468 W] once daily at 10 meters resolution.

Additional requirements are decomposed from this top-level requirement to create a hierarchy of
requirements for the architecture.

1-44
Model-Based Systems Engineering for Space-Based Applications

Compose a System Architecture

System Composer enables the specification and analysis of architectures for model-based systems
engineering. Use the system-level requirements defined above to guide the creation of an
architecture model in System Composer. The architecture in this example is based on CubeSat
Reference Model (CRM) developed by the International Council on Systems Engineering (INCOSE)
Space Systems Working Group (SSWG) [1].

1-45
1 Architecture Model Editing

The architecture is composed of components, ports, and connectors. A component is a part of a


system that fulfills a clear function in the context of the architecture. It defines an architectural
element, such as a system, subsystem, hardware, software, or other conceptual entity.

Ports are nodes on a component or architecture that represent a point of interaction with its
environment. A port permits the flow of information to and from other components or systems.
Connectors are lines that provide connections between ports. Connectors describe how information
flows between components in an architecture.

Extend the Architecture with Stereotypes and Interfaces

You can add additional levels of detail to an architecture using stereotypes and interfaces.

Stereotypes

Stereotypes extend the architectural elements by adding domain-specific metadata to each element.
Stereotypes are applied to components, connectors, ports, and other architectural elements to
provide these elements with a common set of properties such as mass, cost, power, etc.

Packages of stereotypes used by one or more architectures are stored in profiles. This example
includes a profile of stereotypes called CubeSatProfile.xml. To view, edit, or add new stereotypes to
the profile, open this profile in the Profile Editor from the Modeling Tab.

This profile defines a set of stereotypes that are applied to components and connectors in the
CubeSat architecture.

1-46
Model-Based Systems Engineering for Space-Based Applications

Stereotypes can also inherit properties from abstract base stereotypes. For example,
BaseSCComponent in the profile above contains properties for size, mass, cost, and power demand.
We can add another stereotype to the profile, CubeSatTotal, and define BaseSCComponent as its
base stereotype. CubeSatTotal adds in its own property, nominalVoltage, but also inherits
properties from its base stereotype.

1-47
1 Architecture Model Editing

In the architecture model, apply the CubeSatTotal stereotype to CubeSat system component
(asbCubeSatArchModel/CubeSat Mission Enterprise/Space Segment/CubeSat). Select
the component in the model. In the Property Inspector, select the desired stereotype from the drop-
down window. Next, set property values for the CubeSat component.

1-48
Model-Based Systems Engineering for Space-Based Applications

Interfaces

Data interfaces define the kind of information that flows through a port. The same interface can be
assigned to multiple ports. A data interface can be composite, meaning that it can include data
elements that describe the properties of an interface signal. Create and manage interfaces from the
Interface Editor. Existing users of Simulink can draw a parallel between interfaces in System
Composer and buses in Simulink. In fact, buses can be used to define interfaces (and vice versa). For
example, the data dictionary asbCubeSatModelData.sldd contains several bus definitions, including
ACSOutBus, that can be viewed in the Interface Editor and applied to architecture ports.

1-49
1 Architecture Model Editing

Visualize the System with Architecture Views

Now that we have implemented our architecture using components, stereotypes, ports, and
interfaces, we can visualize our system with an architecture view. In the Modeling Tab, select Views.

Use the Component Hierarchy view to show our system component hierarchy. Each component also
lists its stereotype property values and ports.

1-50
Model-Based Systems Engineering for Space-Based Applications

You can also view the hierarchy at different depths of the architecture. For example, navigate to the
Power System Plant component of the architecture by double-clicking the component in the View
Browser.

1-51
1 Architecture Model Editing

1-52
Model-Based Systems Engineering for Space-Based Applications

Link Requirements to Architecture Components

To link requirements to the architectural elements that implement them, use the Requirements
Manager. Drag the requirement onto the corresponding component, port, or interface. Using this
linking mechanism, we can identify how requirements are met in the architecture model. The column
labeled "Implemented" in the Requirements Manager shows whether a textual requirement has
been linked to a component in the given model. For example, our top-level requirement "Provide
visual imagery" is linked to our top-level component CubeSat Mission Enterprise with
decomposed requirements linked to respective decomposed architectural components.

1-53
1 Architecture Model Editing

Connecting the Architecture to Design Models

As the design process matures through analysis and other systems engineering processes, we can
begin to populate our architecture with dynamics and behavior models. System Composer is built as a
layer on top of Simulink, which enables Simulink models to be directly referenced from the
components we have created. We can then simulate our architecture model as a Simulink model and
generate results for analysis. For example, the GNC subsystem component contains 3 Simulink
model references that are part of the CubeSat Simulation Project.

Double-click these reference components to open the underlying Simulink models. Notice that the
interfaces defined in the architecture map to bus signals in the Simulink model.

1-54
Model-Based Systems Engineering for Space-Based Applications

This example uses the Spacecraft Dynamics block from Aerospace Blockset to propagate the
CubeSat orbit and rotational states.

1-55
1 Architecture Model Editing

Simulate System Architecture to Validate Orbital Requirements

We can use simulation to verify our system-level requirements. In this scenario, our top level
requirement states that the CubeSat onboard camera captures an image of MathWorks Headquarters
at [ 42.2775 N, 71.2468 W] once daily at 10 meters resolution. We can manually validate this
requirement with various mission analysis tools. For examples of these analyses, click on the project
shortcuts Analyze with Mapping Toolbox and Analyze with Satellite Scenario.

1-56
Model-Based Systems Engineering for Space-Based Applications

The satellite scenario created in the Analyze with Satellite Scenario shortcut example is shown above.

Validate Orbital Requirements Using Simulink Test

Although we can use MATLAB to visualize and analyze the CubeSat behavior, we can also use
Simulink Test to build test cases. This test case automates the requirements-based testing process by
using the testing framework to test whether our CubeSat orbit and attitude meet our high-level
requirement. The test case approach enables us to create a scalable, maintainable, and flexible
testing infrastructure based on our textual requirements.

This example contains a test file systemTests.mldatx. Double-click this file in the project folder
browser to view it in the Test Manager. Our test file contains a test to verify our top-level
requirement. The "Verify visual imagery" testpoint is mapped to the requirement "Provide visual
imagery" and defines a MATLAB function to use as custom criteria for the test. While this test case is
not a comprehensive validation of our overall mission, it is useful during early development to
confirm our initial orbit selection is reasonable, allowing us to continue refining and adding detail to
our architecture.

1-57
1 Architecture Model Editing

Run the test point in the Test Manager and confirm that the test passes. Passing results indicate that
the CubeSat onboard camera as visibility to the imaging target during the simulation window.

1-58
Model-Based Systems Engineering for Space-Based Applications

References

[1] “Space Systems Working Group.” INCOSE, 2019, https://www.incose.org/communities/working-


groups-initiatives/space-systems.

See Also
Orbit Propagator | Spacecraft Dynamics | Attitude Profile

Related Examples
• “Compose Architectures Visually” on page 1-5
• “Define and Style Stereotypes in Profiles” on page 5-5
• “Allocate and Trace Requirements from Design to Verification” on page 2-2

1-59
1 Architecture Model Editing

Use Property Inspector in System Composer


The Property Inspector allows you to access and edit properties for different elements in System
Composer.

To open the tool, from the System Composer toolstrip, navigate to Modeling > Property Inspector.
Alternatively, press Ctrl+Shift+I. On macOS, press command+option+O instead.

Use the Property Inspector to inspect properties based on context. When you select a component,
port, connector, interface, function, or requirement, the structure of the Property Inspector adapts to
accommodate the given element.

Property Inspector Modes


This table explains where to find more information about authoring properties.

Property Tool
Stereotypes Profile Editor
Parameters Parameter Editor
Interfaces Interface Editor
Requirements Requirements Editor
Functions Functions Editor

View and Edit Stereotypes and Parameters

Launch the small unmanned aerial vehicle (UAV) project.

scExampleSmallUAV

In the Property Inspector, on the root architecture layer of the architecture model, you can view and
edit stereotypes and parameters.

1-60
Use Property Inspector in System Composer

When you select a component, you can view and edit the stereotypes or parameters assigned to the
component.

When you select a connector, you can view and edit the stereotypes assigned to the connector.

1-61
1 Architecture Model Editing

When you select a port, you can view and edit the stereotypes or interfaces assigned to the port. You
can also change the port action between Input, Output, and Physical.

1-62
Use Property Inspector in System Composer

From the Stereotype list, choose an option to apply a stereotype to the model element. Select the
fully qualified name of a stereotype, <profile>.<stereotype>, or create or edit new stereotypes
in the Profile Editor. Use <Add/Edit> when no stereotypes are applied or <New/Edit> when at least
one stereotype is applied. Choose <Remove All> from the Stereotype list to remove all
stereotypes from a model element.

Once you choose a stereotype, select from the list next to the stereotype name. Options include
Remove to remove the stereotype from the element and Reset to default values to reset the
values of the stereotype properties to their defaults. Expand the stereotype to view and edit its
property values.

Use the Parameters list to open the Parameter Editor using the Open Editor option. Reset a
specific parameter to its default value using the Reset to default option. Find the source of the
parameter using Highlight source of parameter. Since parameters can be promoted to higher
parts of the hierarchy, the source of the parameter is not always clear.

View and Edit Interfaces

When you select a data interface on the Interface Editor, you can view and edit the stereotypes in the
Property Inspector.

Select the edit hyperlink to open the interface in the Interface Editor.

When you select a data element on the Interface Editor, you can view and edit the type, dimension,
unit, complexity, minimum, maximum, and description in the Property Inspector.

1-63
1 Architecture Model Editing

View and Edit Requirements

When you select a requirement with the Requirements Perspective open, you can view and edit the
type, summary, description, and links for the requirement in the Property Inspector.

View and Edit Functions

Launch the adaptive cruise control example.


openExample('systemcomposer/ACCSoftwareCompositionExample')

1-64
Use Property Inspector in System Composer

When you select a function on the Functions Editor, you can view and edit the stereotypes for the
function in the Property Inspector.

See Also
applyStereotype | removeStereotype | createInterface | setInterface | addFunction |
Property Inspector

Related Examples
• “Modeling System Architecture of Small UAV” on page 1-37
• “Author Functions for Software Components of Adaptive Cruise Control” on page 10-39
• “Define and Style Stereotypes in Profiles” on page 5-5
• “Define Port Interfaces Between Components” on page 3-2
• “Allocate and Trace Requirements from Design to Verification” on page 2-2

1-65
1 Architecture Model Editing

Export Architecture to Software or AUTOSAR Architecture

The full system life cycle can be a long process where stakeholder requirements may change and
design decisions may not be finalized. When starting with a high-level architectural design, you may
not know which components will be in the system or software. Component behavior and
implementation models can be updated and changed during the design process.

If the desired domain for a component or architecture model changes, you can export the component
or model to a different architecture template. This topic describes how to export an architecture
model to a different architecture template.

• You can export your system architecture to a software architecture or an AUTOSAR architecture.
• You can export your software architecture to an AUTOSAR architecture.

Export Architecture to Different Architecture Template


To export your model to a different architecture template, use one of these methods:

• In the toolstrip, on the Simulation tab, click the Save button arrow, then select Software
Architecture Model or AUTOSAR Architecture Model. The model types available to export to
are dependent on which type of architecture model you are exporting.

Once you select architecture template type, you can specify the New model name and the
Destination folder. If you are saving your model as an AUTOSAR architecture model, you must
also specify Platform and Configure behavior models for AUTOSAR.
• Export your model programmatically using the appropriate function.

• To export to a software architecture, use the


systemcomposer.exportToSoftwareArchitecture function.
• To export to an AUTOSAR architecture, use the
systemcomposer.exportToAUTOSARArchitecture function.

1-66
Export Architecture to Software or AUTOSAR Architecture

Architecture Template Limitations


All architecture models provide the same structural capabilities with some domain-specific
extensions. The Software Architecture Model template applies software domain-specific extensions.
The AUTOSAR Software Architecture template applies AUTOSAR domain-specific extensions.

These elements are not supported when you export your architecture model to a software
architecture.

• Adapter blocks with UnitDelay or RateTransition as the applied interface conversion. The
applied interface conversion changes to None for these Adapter blocks.
• Physical ports.

• A component with Stateflow chart behavior.


• A Reference Component block linked to a Simulink subsystem, subsystem reference, or model
containing an FMU block.

In addition to the previous elements, these elements are not supported when you export your
architecture model to an AUTOSAR software architecture.

• Client ports or server ports in AUTOSAR classic architecture models.


• Adapter blocks with UnitDelay, RateTransition, or Merge as the applied interface
conversion. The applied interface conversion changes to None for these Adapter blocks.
• Reference components referencing a system or software architecture.
• systemcomposer.arch.Function objects. System Composer functions are not supported in
AUTOSAR Software Composition blocks.

• A nonunique short name.


• Local interfaces.

For more information about choosing an architecture template, see “Choose Architecture Template
for System Design” on page 1-2.

See Also
systemcomposer.exportToSoftwareArchitecture |
systemcomposer.exportToAUTOSARArchitecture |
systemcomposer.extractArchitectureFromSimulink

Related Examples
• “Author Architecture Models”
• “Author Software Architectures” on page 10-2
• “Create AUTOSAR Architecture Models” (AUTOSAR Blockset)

1-67
1 Architecture Model Editing

Add or Remove Variant Choices of Variant Assembly


Component Blocks Using External File

A Variant Assembly Component block can use Model blocks, “Subsystem Reference” blocks, or both
as its variant choices. The variant choices are maintained in a separate model and subsystem files
that are on the MATLAB®path. You can add or remove the variant choices from the Variant Assembly
Component block without modifying the model. You use an external source such as an enumeration
class or a MATLAB function to manage the variant choices of the Variant Assembly Component block.
Unlike when you use Variant Component blocks, you are not required to navigate inside the Variant
Assembly Component block to add or remove the variant choices from the block. For more
information, see Variant Assembly Component in Variant Component. This example explains how to
manipulate Variant Choices of Variant Assembly Component Block in Label and Expression Modes.

Open Model

The model slexVariantAssemblyComponent contains two Variant Assembly Component blocks


Controller1 in label mode and Controller2 in expression mode.In this example, the
vacLinearController1 and vacLinearController2 are Model Reference blocks. The
vacNonLinearController1 and vacNonLonlinearController2 are Subsystem Reference
blocks. The choices are saved as subsystem or model files in your current working folder.

systemcomposer.openModel('slexVariantAssemblyComponent.slx');

1-68
Add or Remove Variant Choices of Variant Assembly Component Blocks Using External File

Manipulate Variant Choices of Variant Assembly Component Block in Label Mode

To add variant choices to the Controller1 block, right-click the variant badge on the block icon and
select Block Parameters. Specify this MATLAB expression in the “Variant choices specifier”
parameter.

{'*Controller*'}

Explore the Controller1 block to observe the four variant choices vacLinearController1,
vacLinearController2, vacNonLinearController1, and vacNonLinearController2 that are
added to the Controller1 block. The file name and the path of the newly added variant choices are
displayed in the Variant Choices table in the Reference tab.

From Label mode active choice, select vacLinearController1 and simulate the model. Observe
that the vacLinearController1 choice becomes active.

You can modify the expression in the Variant choices specifier parameter as described in “Specify
Variant Choices of Variant Assembly Subsystem Block in Variant Choices Specifier Parameter”, then
simulate the model again.

Manipulate Variant Choices of Variant Assembly Component Block in Expression Mode

The vacLinearController1 and vacNonLinearController1 blocks are added as choices to the


Controller2 block using enumerations. Explore the Controller2 block to observe the two
variant choices vacLinearController1, and vacNonLinearController1 are added to the
Controller2 block.

To configure the Controller2 block, set the Variant control variable parameter to 'V' and the
Variant choices enumeration parameter to ControllersEnum in the Block Parameters dialog box.
For more information on how the enumerations are defined, see “Manipulate Variant Choices of
Variant Assembly Subsystem Block in Expression Mode”.

mdl = 'slexVariantAssemblyComponent';
open_system(mdl)
vacBlkPath = [mdl,'/Controller2'];

To configure the Controller block, set the Variant control variable parameter to
variantCtrlVar and the Variant choices enumeration parameter to controllerTypesMFile in
the Block Parameters dialog box.

set_param(vacBlkPath, 'VariantChoicesEnumeration','ControllersEnum')
set_param(vacBlkPath, 'VariantControlVariable','V')

To activate the vacLinearController1 choice, set 'V' to


ControllersEnum.vacLinearController1 and then simulate the model. During simulation, the V
== ControllersEnum.vacLinearController1 expression evaluates to true. Subsequently, the
vacLinearController1 choice becomes active.

V = ControllersEnum.vacLinearController1;
sim(mdl);

Similarly, to activate the vacNonLinearController1 choice, set 'V' to


ControllersEnum.vacNonLinearController1 and simulate the model again.

1-69
1 Architecture Model Editing

V = ControllersEnum.vacNonLinearController1;
sim(mdl);

See Also
Blocks
Variant Component | Component

Objects
systemcomposer.arch.VariantComponent | systemcomposer.arch.Component

Functions
addChoice | addVariantComponent | getActiveChoice | getChoices | getCondition |
makeVariant | makeVariantAssembly | setActiveChoice | setCondition |
updatePortsFromChoices

More About
• “Decompose and Reuse Components” on page 1-19
• “Calculate Endurance Using Quadcopter Architectural Design” on page 9-17
• “Design Insulin Infusion Pump Using Model-Based Systems Engineering” on page 9-24

1-70
2

Requirements

• “Allocate and Trace Requirements from Design to Verification” on page 2-2


• “Link and Trace Requirements” on page 2-4
• “Manage Requirements” on page 2-9
• “Verify and Validate Requirements” on page 2-15
• “Redirect Reference Requirement Links from Imported File” on page 2-17
• “Establish Traceability Between Architectures and Requirements” on page 2-22
2 Requirements

Allocate and Trace Requirements from Design to Verification


Systems engineering design is an iterative process. Design engineers author, link, and refine
requirements then use thorough test coverage to test that system design accurately implements each
requirement.

Requirements are a collection of statements describing the desired behavior and characteristics of a
system. Requirements help ensure system design integrity and should be achievable, verifiable,
unambiguous, and consistent with each other. Each level of design should have appropriate
requirements.

A Requirements Toolbox™ license is required to link, trace, and manage requirements in System
Composer.

To update reference requirement links from an imported file and integrate with Requirements
Toolbox, see “Redirect Reference Requirement Links from Imported File” on page 2-17.

To enhance traceability of requirements, link system, functional, customer, performance, or design


requirements to components and ports. Link requirements to each other to represent derived or
allocated requirements. Manage requirements from the Requirements Perspective on an architecture
model or through custom views. Assign test cases to requirements using the Simulink Test Manager
for verification and validation.

A Simulink Test™ license is required to use the Simulink Test Manager and to create test harnesses
for components. For more information, see “Create a Test Harness” (Simulink Test).

A requirement set is a collection of requirements. You can structure the requirements hierarchically
and link them to components or ports.

Use the Requirements Editor to edit and refine requirements in a requirement set. Requirement sets
are stored in SLREQX files. You can create a new requirement set and author requirements using
Requirements Toolbox, or import requirements from supported third-party tools.

A link is an object that relates two model-based design elements. A requirement link is a link where
the destination is a requirement. You can link requirements to components or ports.

View links by using the Requirements Perspective in System Composer. Select a requirement in the
Requirements Browser to highlight the component or the port to which the requirement is assigned.
Links are stored externally as SLMX files.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Use requirements to establish traceability from system design to verification. The table lists topics
about using requirements.

Topic Description
“Link and Trace Requirements” on page 2-4 Define requirements for your architecture model,
then allocate functional requirements to
components to establish traceability.

2-2
Allocate and Trace Requirements from Design to Verification

Topic Description
“Manage Requirements” on page 2-9 Manage requirements using the Requirements
Editor, trace requirements using a traceability
diagram, and analyze requirements using the
Requirements Table block.
“Verify and Validate Requirements” on page 2- Create test harnesses around components, link
15 test cases to requirements using the Simulink
Test Manager, and verify that the requirements
satisfy design needs.

This Variant Component block has a requirements badge. The requirement and requirement link is
visible in the Requirements Perspective.

See Also

More About
• “Compose Architectures Visually” on page 1-5
• “Establish Traceability Between Architectures and Requirements” on page 2-22
• “Organize System Composer Files in Projects” on page 12-2
• “View Requirements Toolbox Links Associated with Model Elements”
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35

2-3
2 Requirements

Link and Trace Requirements

This example shows how to work with requirements in an architecture model.

Define requirements for your architecture model using the Requirements Editor (Requirements
Toolbox). For more information, see “Author Requirements in MATLAB or Simulink” (Requirements
Toolbox). A Requirements Toolbox™ license is required to link, trace, and manage requirements in
System Composer™.

Allocate functional requirements to components to establish traceability. By creating a link between a


component and the related requirement, you can track whether all requirements are represented in
the architecture. You can also keep requirements and design in sync, for example, if a requirement
changes or if the design warrants a revision of the requirements. You can link components to
requirements in Requirements Toolbox, test cases in Simulink® Test™, or selections in MATLAB®,
Microsoft® Excel®, or Microsoft Word.

Open Model

Open the model exMobileRobot.

systemcomposer.openModel("exMobileRobot");

Launch Requirements Perspective

Manage requirements and architecture together in the Requirements Manager from Requirements
Toolbox. Navigate to Apps > Requirements Manager. You are now in the Requirements Perspective
in System Composer.

2-4
Link and Trace Requirements

Links can be created and managed through the Requirements Perspective. For more information, see
“Manage Requirements” on page 2-9. This example shows an alternative approach using the
Requirements Editor.

Use Requirements Editor to Link Requirements to Components

Open the requirements in the Requirements Editor (Requirements Toolbox).

slreq.load('MobileRobotRequirements');

slreq.editor

Select the requirement to be linked.

2-5
2 Requirements

Select the component to be linked in the architecture model. Right-click and select Requirements >
Link to Selection in Requirements Browser.

When you first link a requirement in an architecture model, a link set file with extension .slmx is
created to store requirement links. The Requirements context menu displays the linked
requirements.

You can also create a link using the Requirements Editor. First, select the component in the
architecture model. Then, in the Requirements Editor, right-click the requirement and select Link
from "<Component Name>" (Component).

2-6
Link and Trace Requirements

You can also create requirement links with blocks and subsystems in Simulink models. For more
information, see “View and Link Requirements in Simulink” (Requirements Toolbox).

Use Open Outgoing Links Dialog to Trace Requirement Links to Components

The badge on a component indicates that it is linked to a requirement. This badge also shows at
the lower-left corner of the architecture model.

2-7
2 Requirements

To trace requirement links to a component, right-click the Command component and select
Requirements > Open Outgoing Links dialog. Here, you can create new requirements, delete
existing ones, and change their order.

See Also

More About
• “Redirect Reference Requirement Links from Imported File” on page 2-17
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Organize System Composer Files in Projects” on page 12-2
• “View Requirements Toolbox Links Associated with Model Elements”
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35

2-8
Manage Requirements

Manage Requirements
In this example, you will use a mobile robot architecture model to manage and trace requirements.
You can also view traceability of requirements using a traceability diagram.

For more information about requirements terminology, see “Allocate and Trace Requirements from
Design to Verification” on page 2-2.

Open Model

Open the mobile robot platform architecture model.

Manage Requirements
Manage requirements and architecture together in the Requirements Perspective from Requirements
Toolbox. Navigate to Apps > Requirements Manager. You are now in the Requirements Perspective
in System Composer.

2-9
2 Requirements

Trace Requirements
When you click a component in the Requirements Perspective, linked requirements are highlighted.
Conversely, when you click a requirement, the linked components are shown.

2-10
Manage Requirements

Use Requirements Traceability Diagram


Visualize traceability of requirements and how they are related using a traceability diagram.

Change the View option on the Requirements Perspective from Requirements to Links. Right-click
the Trajectory Planning requirement link and select View Traceability Diagram.

2-11
2 Requirements

According to this traceability diagram, the Command component implements the three requirements
Trajectory Planning, Sensing, and Obstacle reaction.

Change the View option on the Requirements Manager from Links back to Requirements.

For more information, see “Visualize Links with Traceability Diagrams” (Requirements Toolbox).

Link Requirements
To directly create a link, drag a requirement onto a component or port.

2-12
Manage Requirements

You can close the annotation that shows the link as necessary. This action does not delete the link.

You can exit the Requirements Perspective by clicking the perspectives menu on the lower-right
corner of the architecture model and selecting Exit perspective.

2-13
2 Requirements

For more information on managing requirements from external documents, see “Manage Navigation
Backlinks in External Requirements Documents” (Requirements Toolbox). To integrate the
requirement links to the model, see “Redirect Reference Requirement Links from Imported File”.

Analyze Requirements
You can analyze requirements to maintain completeness and consistency using the Requirements
Table block. After you identify the issues, you can adjust the requirements.

For more information, see “Use a Requirements Table Block to Create Formal Requirements”
(Requirements Toolbox) and “Identify Inconsistent and Incomplete Formal Requirement Sets”
(Requirements Toolbox).

See Also

More About
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Compose Architectures Visually” on page 1-5
• “Establish Traceability Between Architectures and Requirements” on page 2-22
• “Organize System Composer Files in Projects” on page 12-2

2-14
Verify and Validate Requirements

Verify and Validate Requirements


Using Simulink Test and Requirements Toolbox, you can verify requirements by linking to test cases.
For more information, see “Link Test Cases to Requirements” (Requirements Toolbox).

You can author an architecture model in System Composer and then link requirements to model
elements that satisfy those requirements. For more information, see “Allocate and Trace
Requirements from Design to Verification” on page 2-2.

Use Test Harnesses to Verify System Design


A test harness is a model that isolates the component under test with inputs, outputs, and verification
blocks configured for testing scenarios. You can create a test harness for a model component or for a
full model. A test harness gives you a separate testing environment for a model or a model
component.

A Simulink Test license is required to use the Simulink Test Manager and to create test harnesses for
components. For more information, see “Create a Test Harness” (Simulink Test).

Create a test harness for a System Composer component to validate simulation results and verify
design. To edit the interfaces while you are testing the behavior of a component in a test harness, use
the Interface Editor.

Use Simulink Test to perform requirement-based testing workflows that include inputs, expected
outputs, and acceptance criteria. For more information on using Simulink Test with Requirements
Toolbox, see “Link Test Cases to Requirements” (Requirements Toolbox). Test harnesses are not
supported for Adapter blocks in architecture models or for Component blocks that contain a
Reference Component in software architecture models.

Create Test Harness for Airframe Component


This example uses the architecture model for an unmanned aerial vehicle (UAV) to create a test
harness for a System Composer component. In the MATLAB Command Window, enter this command.

scExampleSmallUAV

To create a test harness for the Airframe component:

1 Right-click the component.


2 Select Test Harness > Create for 'Airframe'.
3 In the Create Test Harness dialog box, specify the name of your test harness and click OK.

Your test harness opens in a new window, and the Harness menu is available in the toolstrip.

Tip If the model component is in an early step in the design process and not fully wired, then in the
Create Test Harness dialog box, you can select the Advanced Properties tab and select Create
without compiling the model.

2-15
2 Requirements

Use the Simulink Test Manager with the test harness to create test files and test cases. For more
information, see “Test Harness and Model Relationship” (Simulink Test) and “Create or Import Test
Harnesses and Select Properties” (Simulink Test).

Combine Subsystems for Integration Testing


To test whether combined systems as a whole function as designed, you can create test harnesses
around progressively larger systems or subsystems. Once these subsystems are connected, use a
testing framework to confirm that requirements are satisfied.

See Also

More About
• “Redirect Reference Requirement Links from Imported File” on page 2-17
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Establish Traceability Between Architectures and Requirements” on page 2-22
• “Organize System Composer Files in Projects” on page 12-2
• “Design Insulin Infusion Pump Using Model-Based Systems Engineering” on page 9-24

2-16
Redirect Reference Requirement Links from Imported File

Redirect Reference Requirement Links from Imported File

After importing requirement links from a file, redirect links to reference requirements in the model.
When you convert the links to reference requirement links, the links are contained in the model in an
SLREQX file to make full use of Requirements Toolbox™ functionality.

Import Requirement Links from Word File

Before running the code, follow these steps to prepare your workspace.

Note: Importing or linking requirements from an imported file is only supported on Windows®. A
web-based Microsoft® Office file stored in SharePoint® or OneDrive does not work. Save this file and
supporting files in a local folder to continue.

1. Open the Microsoft Word file Functional_Requirements.docx with the requirements listed.
Highlight the requirement to link. For example, highlight these lines.

1.1.2 Flight Computer


ID: 25
Description: Aircraft shall provide a flight computer to autonomously
conduct safe flight operations from launch to recovery

2. Open the reqImportExample.slx model.

model = systemcomposer.openModel("reqImportExample");

3. In the model, select the FlightComputer component to which to link the requirement. Right-click
the FlightComputer component and select Requirements > Link to Selection in Word. Keep the
Word file Functional_Requirements.docx open for the next steps.

2-17
2 Requirements

2-18
Redirect Reference Requirement Links from Imported File

Before requirement links are integrated within the model, the links depend on the source document,
the Word file Functional_Requirements.docx. To view the requirement links, open the
Requirements Perspective from the bottom-right corner of the reqImportExample.slx model
palette.

Redirect Links to Reference Requirements

Follow these steps to redirect requirement links to integrate with and reference from within the
model.

1. Export the reqImportExample.slx model and save to an external file: exportedModel.xls


exportedSet = systemcomposer.exportModel("reqImportExample");
SaveToExcel("exportedModel",exportedSet);

2. Use the external file exportedModel.xls to import requirement links into another model:
reqNewExample.slx
structModel = ImportModelFromExcel("exportedModel.xls","Components","Ports", ...
"Connections","PortInterfaces","RequirementLinks");

2-19
2 Requirements

structModel.readTableFromExcel

systemcomposer.importModel("reqNewExample",structModel.Components, ...
structModel.Ports,structModel.Connections,structModel.Interfaces,structModel.RequirementLinks);

3. To integrate the requirement links to the new model reqNewExample.slx, redirect references
within the model.

systemcomposer.updateLinksToReferenceRequirements("reqNewExample",...
"linktype_rmi_word","Functional_Requirements.docx")

4. Open the Requirements Perspective from the bottom right corner of the model palette to view the
new Flight Computer requirement on the FlightComputer component by setting View to
Requirements.

This requirement is saved in a requirement set Functional_Requirements.slreqx and used


directly in the requirement link. Change the View to Links to view the requirement link.

2-20
Redirect Reference Requirement Links from Imported File

See Also
importModel | exportModel | updateLinksToReferenceRequirements

More About
• “Link Directly to Requirements in Third-Party Applications” (Requirements Toolbox)
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Establish Traceability Between Architectures and Requirements” on page 2-22
• “Import and Export Architecture Models” on page 13-5
• “Migrating Requirements Management Interface Data to Requirements Toolbox” (Requirements
Toolbox)

2-21
2 Requirements

Establish Traceability Between Architectures and


Requirements
Traceability in system design allows systems engineers to go from stakeholder requirements to
individual design elements to overall system integrity. Create links to establish traceability between
architectures and requirements. Use model-to-model allocations to show directed relationships
between model elements from a source model to a target model. Link requirements to each other, to
model elements, and to architecture models. Verify and validate requirements by linking
requirements to test cases.

A Requirements Toolbox license is required to link, trace, and manage requirements in System
Composer.

A Simulink Test license is required to use the Simulink Test Manager and to create test harnesses for
components. For more information, see “Create a Test Harness” (Simulink Test).

This image shows a typical methodology to establish traceability.

First, define requirements for the system based on stakeholder needs. Then, decompose those
requirements to functional, system, and hardware requirements. Functional requirements can be
linked to architectural elements in the functional architecture model of the system. From the
functional requirements, allocate system requirements that link to parts of the logical architecture
model of the system. Using these system requirements, allocate hardware requirements that link to
parts of the physical architecture model of the system. You can also allocate elements from the
functional architecture to the logical architecture and from the logical architecture to the physical
architecture.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

2-22
Establish Traceability Between Architectures and Requirements

Define Requirements and Requirement Links


Define Requirements in the Requirements Editor

Requirements are a collection of statements describing the desired behavior and characteristics of a
system. Requirements help ensure system design integrity and should be achievable, verifiable,
unambiguous, and consistent with each other. Each level of design should have appropriate
requirements.

You can use the Requirements Editor app to author requirements and link between them. For more
information, see “Link and Trace Requirements” on page 2-4 and “Manage Requirements” on page 2-
9.

After you update your requirements, they are stored in a requirement set that you can open with your
System Composer architecture model.

Define Requirement Links and Link Types

You can link requirements to model elements.

A link is an object that relates two model-based design elements. A requirement link is a link where
the destination is a requirement. You can link requirements to components or ports.

For more information, see “View and Link Requirements in Simulink” (Requirements Toolbox) and
“Create and Store Links” (Requirements Toolbox).

You can enhance your requirements by assigning the appropriate link type. For more information, see
“Define Custom Requirement and Link Types” (Requirements Toolbox).

Visualize Traceability Between Requirements and Links

To visualize the requirement links between requirements and model elements, use a traceability
diagram or a traceability matrix. For more information, see “Visualize Links with Traceability
Diagrams” (Requirements Toolbox) and “Track Requirement Links with a Traceability Matrix”
(Requirements Toolbox).

This traceability diagram focuses on the stakeholder requirements and how they are linked to other
requirements and models.

2-23
2 Requirements

In this traceability matrix, the source is the functional architecture of a mobile robot, and the targets
are the stakeholder needs.

2-24
Establish Traceability Between Architectures and Requirements

Each of these requirements can be linked to and verified using test cases in further stages of the
design process. For more information, see “Verify and Validate Requirements” on page 2-15.

Define Allocations and Directed Relationships


After defining requirements and linking them to model elements, you can link these model elements
to each other. Use directed relationships for model elements from one model to another to establish
traceability between models.

An allocation establishes a directed relationship from architectural elements — components, ports,


and connectors — in one model to architectural elements in another model.

You can define allocations between model elements from a source model to a target model. For
example, your source model might be a physical architecture and your target model might be a
logical architecture. Use the Allocation Editor to manage allocations, and the in-model workflow to
create allocations interactively. For more information, see “Create and Manage Allocations
Interactively” on page 8-2.

First, create an allocation scenario to define the source and target model. Allocate between model
elements in an allocation scenario. The default allocation scenario is called Scenario 1. Then, save
your allocations in an allocation set to group your allocation scenarios. Create an allocation set with
allocation scenarios in the Allocation Editor. The result is an allocation matrix that describes the full
set of allocations from a source model to a target model.

2-25
2 Requirements

For this allocation matrix, the source model is the logical architecture of a mobile robot and the
target model is the physical architecture.

See Also

More About
• “Compose Architectures Visually” on page 1-5
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Create and Manage Allocations Interactively” on page 8-2
• “Organize System Composer Files in Projects” on page 12-2

2-26
3

Interface Management

• “Define Port Interfaces Between Components” on page 3-2


• “Create Interfaces” on page 3-6
• “Assign Interfaces to Ports” on page 3-11
• “Interface Adapter” on page 3-18
• “Manage Interfaces with Data Dictionaries” on page 3-24
• “Reference Data Dictionaries” on page 3-27
3 Interface Management

Define Port Interfaces Between Components


A systems engineering solution in System Composer includes a formal definition of the interfaces
between components. A connection shows that two components have an output-to-input relationship,
and an interface defines the type, dimensions, units, and structure of the data.

Note When you load existing interface data dictionaries, Simulink automatically migrates them to
the Architectural Data section of the Simulink data dictionary. In addition to the Interface Editor, you
can also use the Architectural Data Editor and Simulink.dictionary.ArchitecturalData
programmatic interfaces to manage and modify interfaces and value types. For more information on
managing architectural data, see “Graphically Manage Shared Interfaces, Data Types, and
Constants” on page 12-12 and “Programmatically Manage Shared Interfaces, Data Types, and
Constants of Architecture Models” on page 12-17.

These concepts are relevant for port interface workflows:

• An interface data dictionary is a consolidated list of interfaces and value types in an architecture
and where you use them in the architecture.

You can save local interfaces on a System Composer model in an interface data dictionary using
the Interface Editor. You can reuse data dictionaries between models that need to use a given set
of interfaces, elements, and value types. Data dictionaries that you attach to models are stored in
separate SLDD files.
• A data interface defines the kind of information that flows through a port. The same interface can
be assigned to multiple ports. A data interface can be composite, meaning that it can include data
elements that describe the properties of an interface signal.

Data interfaces represent the information that is shared through a connector and enters or exits a
component through a port. Use the Interface Editor to create and manage data interfaces and
data elements and store them in an interface data dictionary for reuse between models.
• A data element describes a portion of an interface, such as a communication message, a
calculated or measured parameter, or other decomposition of that interface.

Data interfaces are decomposed into data elements:

• Pins or wires in a connector or harness.


• Messages transmitted across a bus.
• Data structures shared between components.
• A value type can be used as a port interface to define the atomic piece of data that flows through
that port and has a top-level type, dimension, unit, complexity, minimum, maximum, and
description.

You can also assign the type of data elements in data interfaces to value types. Add value types to
data dictionaries using the Interface Editor so that you can reuse the value types as interfaces or
data elements.
• An owned interface is an interface that is local to a specific port and not shared in a data
dictionary or the model dictionary.

Create an owned interface to represent a value type or data interface that is local to a port.

3-2
Define Port Interfaces Between Components

• An adapter connects two components with incompatible port interfaces by mapping between the
two interfaces. An adapter can act as a unit delay, rate transition, or merge. You can also use an
adapter for bus creation. Use the Adapter block to implement an adapter.

With an adapter, you can perform functions on the “Interface Adapter” on page 3-18 dialog box:

• Create and edit mappings between input and output interfaces.


• Apply an interface conversion UnitDelay to break an algebraic loop.
• Apply an interface conversion RateTransition to reconcile different sample time rates for
reference models.
• Apply an interface conversion Merge to merge two or more message or signal lines.
• When output interfaces are undefined, you can use input interfaces in bus creation mode to
author owned output interfaces.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Use interfaces to describe information transmitted across connections through ports between
components. The table lists topics about using interfaces.

Topic Description
“Create Interfaces” on page 3-6 Design interfaces and nested interfaces in the
Interface Editor with data interfaces, data
elements, and value types.
“Assign Interfaces to Ports” on page 3-11 Assign data interfaces and data elements to
ports. Define owned interfaces local to ports.
“Manage Interfaces with Data Dictionaries” on Save external interface data dictionaries to reuse
page 3-24 between different models, attach data
dictionaries to architecture models, and delete
data interfaces from data dictionaries.
“Reference Data Dictionaries” on page 3-27 Reference data dictionaries so you can selectively
share interface definitions among models.
Manage referenced data dictionaries in the
Model Explorer.
“Interface Adapter” on page 3-18 Use an Adapter block to help connect two
components with incompatible port interfaces by
mapping between the two interfaces.

Note Connected ports in System Composer are compatible if they share a compatible interface type
and structure. Ports without assigned interfaces automatically inherit from other ports on the
connection. To activate compile-time checks for interface compatibility, click Update Diagram on the
toolstrip. You can reconcile incompatible interfaces on either end of a connection with an Adapter
block using the “Interface Adapter” on page 3-18.

The architecture model below represents an adapter, an interface data dictionary, a data interface, a
data element, and a value type.

3-3
3 Interface Management

Note System Composer interfaces mirror Simulink interfaces that use buses and value types. When
you plan to link Simulink behaviors to System Composer components, consider these resources:

• For buses at Simulink interfaces, see “Composite Interface Guidelines”.


• To use model interfaces with bus element ports, see “Simplify Subsystem and Model Interfaces
with Bus Element Ports”.
• For value types at Simulink interfaces, see “Specify Common Set of Signal Properties as Value
Type”.

3-4
Define Port Interfaces Between Components

See Also

More About
• “Specify Physical Interfaces on Ports” on page 7-24
• “Service Interfaces Overview” on page 10-46
• “Modeling System Architecture of Small UAV” on page 1-37
• “Modeling System Architecture of Keyless Entry System” on page 11-33
• “Use Interface Editor in Views” on page 11-49

3-5
3 Interface Management

Create Interfaces
In this section...
“Open Model” on page 3-6
“Open Interface Editor” on page 3-6
“Create Composite Data Interfaces” on page 3-7
“Create Value Types as Interfaces” on page 3-8
“Nest Interfaces to Reuse Data” on page 3-9

You can create interfaces between components in System Composer to structure transmitted data.
Use composite data interfaces with data elements or value types to manage data defined on ports.
Assign a data interface or value type to a data element so the data element inherits attributes and
reuses data. Use the model below as a starting point before adding interfaces using the Interface
Editor.

For interfaces terminology, see “Define Port Interfaces Between Components” on page 3-2.

To manage interfaces shared between models in data dictionaries, see “Manage Interfaces with Data
Dictionaries” on page 3-24. For information on physical interfaces, see “Specify Physical Interfaces
on Ports” on page 7-24.

Open Model

Open the mobile robot platform architecture model.

Open Interface Editor


To open the Interface Editor, navigate to Modeling > Interface Editor. The Interface Editor will
open at the bottom of the canvas.

3-6
Create Interfaces

Note The System Composer Interface Editor is a web-based widget and might appear blank when
you first launch it. If this occurs, save the model and relaunch MATLAB with the command line option
-cefdisablegpu.

Create Composite Data Interfaces

To add a new data interface definition, click the icon. Name the data interface sensordata.

To add a data element to the data interface, click the icon. Data interface and data element
names must be valid MATLAB variable names.

3-7
3 Interface Management

You can delete data interfaces and data elements in the Interface Editor using the button.

You can view and edit the properties of an element in the Property Inspector. Right-click the data
element and select Inspect Properties. For data interfaces, use the Property Inspector to apply
stereotypes.

For a comparative view, you can edit data element properties from the relevant Interface Editor
columns.

Create Value Types as Interfaces

To add a value type in the Interface Editor, select the down arrow next to the icon and select
Value Type. Name the value type motorSpeedType. Value type names must be valid MATLAB
variable names.

Right-click the motorSpeed data element and select Set 'Type' > motorSpeedType. The data
element motorSpeed is assigned to the value type motorSpeedType.

3-8
Create Interfaces

Any data changes on the motorSpeedType value type is propagated to the motorSpeed data
element. You can reuse value types any number of times. Data changes on a value type will propagate
to each data element that uses the value type.

Nest Interfaces to Reuse Data


A nested interface contains another data interface. Create a nested data interface by assigning a data
interface as the type of a data element. For information about the corresponding buses, see “Define
Multilevel Bus Hierarchy Using Type Editor”.

For example, let coordinates be a data interface that consists of x, y, and z coordinates. The
GPSdata data interface includes location and a timestamp. If the location data element is in
the same format as the coordinates interface, you can set its type to coordinates. Right-click
location and select Set 'Type' > coordinates. The available interface options include all value
types and all data interfaces in the model, except the parent of the data element.

The nested data interface displays the inherited data elements.

3-9
3 Interface Management

Note To change the number of columns that display in the Interface Editor, click the icon.
Select or clear the desired columns to show or hide them.

See Also
Functions
addInterface | removeInterface | addElement | removeElement | connect | setInterface |
addValueType

Blocks
Component

More About
• “Define Port Interfaces Between Components” on page 3-2
• “Specify Physical Interfaces on Ports” on page 7-24
• “Modeling System Architecture of Small UAV” on page 1-37
• “Use Interface Editor in Views” on page 11-49

3-10
Assign Interfaces to Ports

Assign Interfaces to Ports


In this section...
“Mobile Robot Architecture Model with Interfaces” on page 3-11
“Associate Ports with Interfaces in Property Inspector” on page 3-11
“Assign Interfaces to Ports Using the Context Menu” on page 3-12
“Define Owned Interfaces Local to Ports” on page 3-12
“Select Multiple Ports and Assign Data Interface” on page 3-14
“Specify Source Element or Destination Element for Ports” on page 3-15
“Enable Interface Compatibility Edit-Time Check” on page 3-16

A port interface transmits data between ports in a System Composer architecture model. Data
elements within the interface describe characteristics of the data transmitted across the interface.
Data elements can describe the composition of a data interface, messages transmitted, or data
structures shared between components.

Note Connected ports in System Composer are compatible if they share a compatible interface type
and structure. Ports without assigned interfaces automatically inherit from other ports on the
connection. To activate compile-time checks for interface compatibility, click Update Diagram on the
toolstrip. You can reconcile incompatible interfaces on either end of a connection with an Adapter
block using the “Interface Adapter” on page 3-18.

For interfaces terminology, see “Define Port Interfaces Between Components” on page 3-2.

This topic shows how to:

• Assign data interfaces to a single port using the Property Inspector or multiple ports using the
Interface Editor.
• Manage owned interfaces that are local to a port and not shared in a data dictionary.
• Assign interfaces to multiple ports at the same time.
• Connect components through ports and specify the source element or the destination element for
the connection.
• Use the interface compatibility edit-time check.

To manage interfaces shared between models in data dictionaries, see “Manage Interfaces with Data
Dictionaries” on page 3-24. For information on physical interfaces, see “Specify Physical Interfaces
on Ports” on page 7-24.

Mobile Robot Architecture Model with Interfaces

This example shows a mobile robot hardware architecture with interfaces defined.

Associate Ports with Interfaces in Property Inspector


To assign data interfaces or value types to one port at a time, use the Property Inspector. To open the
Property Inspector, navigate to Modeling > Property Inspector. To show the SensorData port

3-11
3 Interface Management

properties, select the port in the model. Expand Interface, and from the Name list, select
sensordata to associate the sensordata interface with the SensorData port.

Note New ports by default use <inherit> mode to support unknown interface specifications in
early stages of architectural design. If an interface is specified on another port, the <inherit>
specification propagates that interface across connections to your original port.

Assign Interfaces to Ports Using the Context Menu


After you select an interface from the Interface Editor, right-click a port. If the selected interface is
compatible with the port, select Apply selected interface: <interface name> to assign the
interface to the port. If a port already has an interface assigned, when you right click the port, you
can select Clear interface: <interface name> to remove the interface.

After you select a port from the architecture canvas, right-click an interface on the Interface Editor.
To assign the interface to the port, select Assign to selected port(s).

Define Owned Interfaces Local to Ports


You can select a value type or data interface from the model data dictionary in the Property Inspector,
or you can create an owned interface.

An owned interface is an interface that is local to a specific port and not shared in a data dictionary
or the model dictionary.

Create an owned interface to represent a value type or data interface that is local to a port.

Note Owned interfaces and value types do not have their own names because they are local to a port
and not shared. The name of the owned interface is derived from the port name.

3-12
Assign Interfaces to Ports

Manage Owned Interfaces Using Property Inspector

You can edit the data for the owned interface in the Property Inspector. Select the Docking
architecture port. In the Property Inspector, under Interface, from the Name list, select <owned>.

By default, the owned interface Docking becomes an owned value type. Edit interface attributes
directly in the Property Inspector, or select Open in Interface Editor to edit the owned value
type interface.

To convert the owned value type into an owned data interface, click to add a data element.

Manage Owned Interfaces Using Interface Editor

You can also work exclusively from the Interface Editor. Select the component port named Feedback.
In the Interface Editor, change from Dictionary View to Port Interface View.

Click to add data elements to the owned data interface.

3-13
3 Interface Management

To convert the owned data interface to an owned value type, change the Type for Feedback to a valid
MATLAB data type, such as double.

Make Owned Interfaces into Shared Interfaces

To convert an owned interface into a shared interface, right-click the port with the owned interface
and select Convert to shared interface. Alternatively, use the makeOwnedInterfaceShared
function.

Select Multiple Ports and Assign Data Interface


Multiple ports, whether they are connected or not, can use the same data interface definition. When
you assign a data interface to a port, the interface is automatically propagated to connected ports,
provided they do not already have assignments. To simplify batch assignments, select multiple ports,
right-click the data interface, and select Assign to selected port(s).

To highlight the ports that use a data interface definition, in the Interface Editor, right-click the
interface name and select Highlight port(s) using this interface. To highlight only the
source interfaces explicitly assigned to the ports, not including inherited interfaces on ports, select
the interface in the Interface Editor.

3-14
Assign Interfaces to Ports

Specify Source Element or Destination Element for Ports


For connections between the root architecture and a component within the architecture model, you
can add a source element or destination element to the ports.

1 Create a component called Motor and connect it to the root architecture with ports named
MotionData and SpeedData.
2 Define the data interface Wheel with the data elements RotationSpeed and MaxSpeed.
3 Assign the Wheel data interface to the ports on the connection.
4 Select the MotionData port name on the component. A dot and a list of data elements appear.
From the list, select the source element RotationSpeed.
5 Assign the MaxSpeed destination element to the SpeedData port.

3-15
3 Interface Management

Enable Interface Compatibility Edit-Time Check


Edit-time checks report warnings as you build the model and require a Simulink Check™ license.
Types of warnings for interface compatibility include:

• Shared interfaces defined in an interface data dictionary are incompatible across ports on a
connection if different interfaces are assigned to different ports.
• Owned interfaces defined locally on ports are incompatible across ports on a connection if the
value type or data elements do not have the same structure.

To enable edit-time checks on your architecture model, navigate to Modeling > Model Advisor >
Edit-Time Checks. Select the Edit-Time Checks check box.

Connectors highlighted in yellow signify an interface mismatch between different ports on the same
connector. If you click the warning symbol, you see the edit-time check message and a suggestion for
what to do.

3-16
Assign Interfaces to Ports

For incompatible interfaces on different ports on the same connection, such as different data
interfaces, you can fix the problem by adding an Adapter block to define interface mappings.

See Also
Functions
connect | getDestinationElement | getSourceElement | createOwnedType |
createInterface | makeOwnedInterfaceShared

Blocks
Component | Adapter

More About
• “Define Port Interfaces Between Components” on page 3-2
• “Specify Physical Interfaces on Ports” on page 7-24
• “Modeling System Architecture of Small UAV” on page 1-37
• “Use Interface Editor in Views” on page 11-49

3-17
3 Interface Management

Interface Adapter

A source port and its destination port can be defined by different data interfaces in System
Composer™. Such a connection can represent an intermediate point in design, where components
from different sources come together. To connect components that have different data interfaces, use
an Adapter block and the Interface Adapter dialog box. For interfaces terminology, see “Define Port
Interfaces Between Components” on page 3-2.

An adapter helps connect two components with incompatible port interfaces by mapping between the
two interfaces. Use the Adapter block to implement an adapter. Open the Interface Adapter dialog
box by double-clicking an Adapter block on the connection between the ports.

With an adapter, you can perform functions on the Interface Adapter dialog box:

• Create and edit mappings between input and output interfaces.


• Apply an interface conversion UnitDelay to break an algebraic loop.
• Apply an interface conversion RateTransition to reconcile different sample time rates for
reference models.
• Apply an interface conversion Merge to merge two or more message or signal lines.
• When output interfaces are undefined, you can use input interfaces in bus creation mode to author
owned output interfaces.

systemcomposer.openModel("exMobileRobotInterfaces");

Map Incompatible Interfaces

When two connected components with Simulink® behaviors have incompatible interfaces, use an
Adapter block and the Interface Adapter to define the port connections.

1 Add an Adapter block on the connection between the two components Sensor and Motor.
2 Rename the port on the Motor component MotorData.
3 Assign the coordinates interface to the MotionData port. In the Interface Editor, select the
coordinates interface. Then, right-click the port on the System Composer canvas and select
Apply selected interface coordinates.
4 Open the Interface Adapter by double-clicking the Adapter block.
5 In the Select input box, select the MotorData data element. In the Select output box, select
the x data element.
6 Click the Map and Overwrite button.

You have mapped the MotorData port to the MotionData port by mapping to the data element x
from the coordinates data interface.

3-18
Interface Adapter

You can use an Adapter block to map similar interfaces for an N:1 connection, which is an Adapter
with more than one input port and a single output port. A data element from each input connection
maps to the output connection data elements.

1 Create a Motor output port on the top of the Motor component. Add an Adapter block on the
connection between the Sensor, Motor, and Command components. Change the number of input
ports on an Adapter block in the same way you add and remove component ports. For more
information, see “Compose Architectures Visually” on page 1-5.
2 Click the name of each port to edit and rename them. Rename the port on the Sensor
component Sensor, the port on the Motor component Motor, and the port on the Command
component Command.
3 Assign the sensorData interface to the Sensor port. In the Interface Editor, select the
sensorData interface. Then, right-click the port on the System Composer canvas and select
Apply selected interface sensorData.
4 Assign the GPSData interface to the Command port. In the Interface Editor, select the
GPSData interface. Then, right-click the port on the System Composer canvas and select Apply
selected interface GPSData.
5 Open the Interface Adapter by double-clicking the Adapter block.

3-19
3 Interface Management

6 In the Select input box, select the location data element. In the Select output box, select the
coordinates data element.
7 Click the Map button.

On the Adapter block, the data element location associated with the input port Command is now
mapped to the data element coordinates associated with the output port Sensor. Now, the Sensor
port on the Sensor component can communicate with the Command port on the Command
component.

Use Unit Delay to Break Algebraic Loop

When connecting two components with port connections in both directions, an algebraic loop can
occur. To break the algebraic loop, use an Adapter block to insert a unit delay between the
components.

1 Add an Adapter block on the connection between the two components.

3-20
Interface Adapter

2 Open the Interface Adapter by double-clicking the Adapter block.


3 From the Apply interface conversion list, select UnitDelay.

You can configure unit delays by clicking the icon. Options include:

• Initial conditions — Default 0

For more information, see “Remove Algebraic Loops”.

Use Rate Transition Between Simulink Behaviors

When connecting two reference components, the Simulink models that the components reference can
have different sample time rates. For compatibility, use an Adapter block to insert a rate transition
between the components.

1 Add an Adapter block on the connection between the two components.


2 Open the Interface Adapter by double-clicking the Adapter block.
3 From the Apply interface conversion list, select RateTransition.

You can configure rate transitions by clicking the icon. Options include:

• Ensure data integrity during data transfer — Default true


• Ensure deterministic data transfer (maximum delay) — Default true
• Initial conditions — Default 0

For more information, see “Handle Rate Transitions” (Simulink Coder).

Use Adapter Block as Merge Block

Use an Adapter block as a Merge block to merge multiple message lines for system architecture
models or merge multiple message lines or multiple signal and message lines for software
architecture models.

1 Add an Adapter block on the connection between the two components.


2 Open the Interface Adapter by double-clicking the Adapter block.
3 From the Apply interface conversion list, select Merge.

For more information, see “Merge Message Lines for Architectures Using Adapter Block” on page 7-
29.

Use Bus Creation Mode to Author Owned Interfaces

When input ports for an Adapter block are typed by interfaces from incoming connections and no
interfaces are defined on the output ports of the adapter, you can use the interface elements from the
input ports to author owned interfaces for outgoing connections. An owned interface is an interface
that is local to a specific port and not shared in a data dictionary or the model dictionary. Instead of
predefining interface structures, you can create the bus structure.

systemcomposer.openModel("SewingMachine");

1. Open the Interface Adapter in bus creation mode by double-clicking the Adapter block.

3-21
3 Interface Management

2. Click the button to add the input data element Torque to the output port interface for the
port named Signal.

3. Select the Displacement element from the Select output box. Click the button to remove
the output data element Displacement from the output port interface for the port named Signal.

4. Click OK to apply the changes.

3-22
Interface Adapter

The owned interface on the output port of the Adapter block propagates to the connected input port
Signal on the Controller component. The owned interface contains one element, Torque.

To convert an owned interface into a shared interface, right-click the port with the owned interface
and select Convert to shared interface.

See Also
Blocks
Adapter | Message Merge | Rate Transition | Unit Delay

Functions
makeOwnedInterfaceShared

More About
• “Define Port Interfaces Between Components” on page 3-2
• “Merge Message Lines for Architectures Using Adapter Block” on page 7-29
• “Merge Message Lines Using Adapter Block” on page 10-36

3-23
3 Interface Management

Manage Interfaces with Data Dictionaries

In this section...
“Mobile Robot Architecture Model with Interfaces” on page 3-24
“Save, Attach, and Delete Interfaces” on page 3-24

Engineering systems often share interface definitions across multiple components or subsystems.
Data interfaces in System Composer can be stored either locally in a model or in a data dictionary,
depending on the maturity of your system.

For interfaces terminology, see “Define Port Interfaces Between Components” on page 3-2.

An interface data dictionary is a consolidated list of interfaces and value types in an architecture and
where you use them in the architecture.

You can save local interfaces on a System Composer model in an interface data dictionary using the
Interface Editor. You can reuse data dictionaries between models that need to use a given set of
interfaces, elements, and value types. Data dictionaries that you attach to models are stored in
separate SLDD files.

For more advanced data dictionary referencing techniques, see “Reference Data Dictionaries” on
page 3-27.

Note When you load existing interface data dictionaries, Simulink automatically migrates them to
the Architectural Data section of the Simulink data dictionary. In addition to the Interface Editor, you
can also use the Architectural Data Editor and Simulink.dictionary.ArchitecturalData
programmatic interfaces to manage and modify interfaces and value types. For more information on
managing architectural data, see “Graphically Manage Shared Interfaces, Data Types, and
Constants” on page 12-12 and “Programmatically Manage Shared Interfaces, Data Types, and
Constants of Architecture Models” on page 12-17.

Mobile Robot Architecture Model with Interfaces

This example shows a mobile robot hardware architecture with interfaces defined.

Save, Attach, and Delete Interfaces


By default, interfaces are stored within the architecture model and are not visible outside the model.
If you are in the initial stages of building a system model, store interfaces locally to limit the number
of files that need to be managed. However, if your model is mature to the point of leveraging
componentization workflows like reference architectures and behaviors, storing interfaces in a data
dictionary gives you the ability to share interface definitions across the model hierarchy.

Use the menu to save a data interface to a new or existing data dictionary. To create a new data
dictionary, select Save to new dictionary. Provide a data dictionary name.

3-24
Manage Interfaces with Data Dictionaries

You can also add interface definitions in the model from an existing data dictionary by selecting Link
existing dictionary to attach the data dictionary to the model.

Use the button to import interface definitions from a Simulink bus object, either from a MAT-file or
the workspace.

Delete a data interface from a data dictionary using the button. If the data interface is already
being used by ports in a currently open model, the software returns a warning message. The data
interface is then removed from any ports in the open model that are associated with the data
interface.

If a data interface is deleted from a data dictionary upon opening another model that shares the data
dictionary, a warning will be presented on startup if the deleted interface is used by ports in that
model. The Diagnostic Viewer offers an option to remove the deleted interface from all ports that are
still using it. You can also select ports individually and delete their missing interfaces.

A System Composer model and a data dictionary are separate artifacts. Even when you attach the
data dictionary to the model, you must save changes to the data dictionary (an SLDD file) separately
from changes to the model (an SLX file). To save changes to an attached data dictionary, use the
button and select Save dictionary. Once you save a data dictionary, other models can use its
interface definitions if you attach the data dictionary to those models, which allows multiple models
to share the same interface definitions.

See Also
createDictionary | moveInterface | openDictionary | saveToDictionary |
linkDictionary | unlinkDictionary | makeOwnedInterfaceShared

3-25
3 Interface Management

More About
• “Specify Physical Interfaces on Ports” on page 7-24
• “Define Port Interfaces Between Components” on page 3-2
• “Use Interface Editor in Views” on page 11-49

3-26
Reference Data Dictionaries

Reference Data Dictionaries


In this section...
“Add Referenced Data Dictionaries” on page 3-27
“Use Referenced Data Dictionaries for Projects with Multiple Models” on page 3-29

Referenced dictionaries in System Composer can be useful when:

• Multiple models need to share some, but not all, interface definitions.
• Multiple models need to communicate with one another.

A data dictionary can reference one or more other data dictionaries. The interface definitions in the
referenced dictionaries are visible in the parent data dictionary and can be used by a model for which
the parent data dictionary is attached.

For interfaces terminology, see “Define Port Interfaces Between Components” on page 3-2.

To create a data dictionary from interfaces in a model dictionary, see “Manage Interfaces with Data
Dictionaries” on page 3-24.

Add Referenced Data Dictionaries

To add a data dictionary reference, open the Model Explorer by clicking , or by navigating to
Modeling > Model Explorer.

On the right side of the Model Explorer app, click Add, then select the file name of the data
dictionary to add as a referenced data dictionary. To remove a data dictionary reference, highlight the
referenced data dictionary, then click Remove.

3-27
3 Interface Management

The Interface Editor shows all interfaces accessible to a model, grouped based on their data
dictionary files. In this example, myDictionary.sldd is the data dictionary attached to the model,
and otherDictionary.sldd is a referenced data dictionary.

The model can use any of the interfaces listed. You can modify the contents of referenced data
dictionaries in the Interface Editor.

Note Referenced data dictionaries can reference other data dictionaries. A model with an attached
data dictionary has access to all interface definitions in referenced data dictionaries, including
indirectly referenced data dictionaries.

3-28
Reference Data Dictionaries

Use Referenced Data Dictionaries for Projects with Multiple Models


A project may contain multiple models, and it may be useful for the models to share interface
definitions that are relevant to data flows and other communications between models. For more
information, see “Organize System Composer Files in Projects” on page 12-2.

At the same time, each model may have interface definitions that are relevant only to its internal
operations. For example, different components of a system may be represented by different models,
with different teams or different suppliers working on each model, with a system integrator working
on the "top" model that incorporates the various components. Referenced data dictionaries provide a
way for models to share some but not all interface definitions.

In such a multiple-team project, set up a "shared artifacts" data dictionary to store interface
definitions that will be shared by different teams, then set up a data dictionary for each model within
the project to store its own interface definitions. Each data dictionary can then add the shared data
dictionary as a referenced data dictionary. Alternatively, if a model does not need its own interface
definitions, you can attach the shared data dictionary to the model.

To generate a dependency graph between models and data dictionaries, use the Dependency
Analyzer.

3-29
3 Interface Management

The above diagram depicts a project with three models. The model mSystem.slx represents a
system integration model, and mSupplierA.slx and mSuppierB.slx represent supplier models.
The data dictionary dShared.sldd contains interface definitions shared by all the models. The
system integration model is attached to the data dictionary dSystem.sldd, and the Supplier A model
is attached to the data dictionary dSupplierA.sldd; each data dictionary contains interface
definitions relevant to the corresponding model's internal workflow. The data dictionaries
dSystem.sldd and dSupplierA.sldd both reference the shared data dictionary dShared.sldd.
The mSuppierB.slx model, by contrast, is attached directly to the shared data dictionary
dShared.sldd. In this way, all three models have access to the interface definitions in
dShared.sldd.

The following diagrams show the system integration model mSystem, along with the Interface Editor.
Interface definitions contained in the referenced data dictionary dShared are associated with the
ports used to communicate between the models mSupplierA and mSupplierB and the rest of the
system integration model.

The following diagrams show the supplier model mSupplierA, along with the Interface Editor.
Interface definitions contained in the referenced data dictionary dShared are associated with the
ports used to communicate externally, while interface definitions in the private data dictionary
dSupplierA are associated with ports whose use is internal to the mSupplierA model.

3-30
Reference Data Dictionaries

See Also
addReference | removeReference | moveInterface

More About
• “Define Port Interfaces Between Components” on page 3-2
• “Specify Physical Interfaces on Ports” on page 7-24
• “Organize System Composer Files in Projects” on page 12-2
• “Use Interface Editor in Views” on page 11-49

3-31
4

Define Parameters

• “Author Parameters in System Composer Using Parameter Editor” on page 4-2


• “Use Parameters to Store Instance Values with Components” on page 4-7
4 Define Parameters

Author Parameters in System Composer Using Parameter


Editor

This example shows how to add and modify parameters for a System Composer™ architecture model
of a propeller by using a top-down authoring workflow available in the Parameter Editor. System
Composer parameters synchronize with Simulink® for seamless simulation and code generation.This
example also shows how to export and import a System Composer architecture model of a propeller
with set parameters.

1. Create an architecture model named Propeller. Add a component to the model and name it Hub.

2. Click the Hub component, then open the Property Inspector. Pin the Property Inspector for easy
access. To open the Parameter Editor, in the Property Inspector, next to Parameters, from the Select
list, select Open Editor.

3. In the Parameters tab, click Add parameter. Define a parameter named bladePitch with
default value 45 and unit degrees.

4-2
Author Parameters in System Composer Using Parameter Editor

4. Click the Propeller root architecture. Open the Parameter Editor. Add a parameter named
advanceSpeed. Set Value as 500 and Unit as mph.

5. Define a parameter named spinningRate. Set Value as 3 and Unit as Hz.

6. To open the Parameter Promotion: One-To-One section, click Promote parameter. Under the
component Hub, select the bladePitch parameter. To promote the parameter, click Promote.

Parameter promotion provides easy access to parameter values and preserves distinct parameter
values inside the model during simulation or code generation. Parameter promotion also removes
unnecessary duplication of parameters defined on lower levels of an architectural hierarchy.

4-3
4 Define Parameters

7. From the source component Hub, change the default value of the promoted parameter
bladePitch to 72. The new value of the bladePitch parameter now appears for the architecture
Propeller.

4-4
Author Parameters in System Composer Using Parameter Editor

Export Architecture With Parameters

In addition to components, ports, connections, interfaces, and requirement links, you can export the
Propeller architecture with parameters to MATLAB® tables.

exportedSet = systemcomposer.exportModel("Propeller");

The output of the function is a structure that contains the components table, ports table, connections
table, port interfaces table, requirement links table, and parameters table.

Import Architecture With Parameters

The parameters table in the exportedSet structure includes parameters information. You can
import those parameters into a new model. Specify a name for the imported architecture model.

modelName = "ImportedPropellerArchitecture";

4-5
4 Define Parameters

You can import an architecture into System Composer when components, ports, connections, port
interfaces, requirement links, and parameters information is defined in or converted into MATLAB
tables.

model = systemcomposer.importModel(modelName,exportedSet.components,...
exportedSet.ports,exportedSet.connections,exportedSet.portInterfaces,...
exportedSet.requirementLinks,exportedSet.parameters);

Auto-arrange blocks in the generated model.

Simulink.BlockDiagram.arrangeSystem(modelName)

See Also
Tools
Parameter Editor

Objects
systemcomposer.arch.Parameter

Functions
addParameter | getParameter | resetToDefault | getParameterPromotedFrom |
getEvaluatedParameterValue | getParameterNames | getParameterValue |
setParameterValue | setUnit | resetParameterToDefault | importModel | exportModel

More About
• “Promote Block Parameters on a Mask”
• “Use Parameters to Store Instance Values with Components” on page 4-7
• “Use Property Inspector in System Composer” on page 1-60
• “Import and Export Architectures” on page 13-2
• “Compose Architectures Visually” on page 1-5

4-6
Use Parameters to Store Instance Values with Components

Use Parameters to Store Instance Values with Components

This example shows how to add value types as model arguments to a System Composer™
architecture model of a wheel, mWheelArch.slx, using the Model Explorer. Then, on the System
Composer architecture model mAxleArch.slx, these model arguments are exposed as instance-
specific parameter values that can be changed independently across each component that references
mWheelArch.

Use Model Explorer to Add MATLAB Variables as Model Arguments

Open the mWheelArch model.


systemcomposer.openModel("mWheelArch");

Navigate to Modeling > Model Explorer or enter Ctrl+H. The Model Explorer opens. Expand the
mWheelArch model and select Model Workspace. View the contents of the model workspace. The
workspace contains three Simulink Parameters named Diameter, Pressure, and Wear.

To add a new MATLAB® variable to the model workspace, on the toolstrip menu, click . You can
rename your variable from the default name Var and set its starting value. If you select the
Argument check box, the MATLAB variable becomes a model argument. As a model argument, the
variable can later be exposed as an instance-specific parameter value in an architecture model.
Rename the variable to TreadDepth and set its value to 1, then select it as a model argument.

Use Model Explorer to Add Simulink Parameters as Model Arguments

In the Model Explorer, you can also add Simulink® parameters as model arguments. To add a new

Simulink parameter to the model workspace, on the toolstrip menu, click . You can edit the
attributes of a Simulink parameter including: Name, Value, DataType, Dimensions, Complexity,
Min, Max, and Unit. These attributes contribute to the parameter definition when the parameter is

4-7
4 Define Parameters

specified as a model argument. Select the Argument check box to specify a parameter as a model
argument. Rename the variable to PressureBar, set its value to 2000, set its units to mbar, then
select it as a model argument.

Right-click the mWheel model in the Model Explorer. Save these changes to the model workspace,
then close the Model Explorer.

View and Edit Parameters on Components in Architecture Model

Open the mAxleArch architecture model.

systemcomposer.openModel("mAxleArch");

Select the LeftWheel component that references the mWheel model. The parameters appear on the
Property Inspector with default values.

You can expose these parameters as model arguments and then edit the parameters as instance-
specific parameters independently for each component that references the same model. Right-click
the RightWheel component and select Block Parameters (Model Reference). Click the
Instance parameters tab and select the Argument check box for the new parameters Pressure
and TreadDepth.

4-8
Use Parameters to Store Instance Values with Components

Once selected, these parameters are treated as model arguments of the mAxleArch model and can
be changed independently for each instance the model.

Edit the parameters for the RightWheel component so that Pressure and PressureBar are now
31 psi and 2100 mbar, respectively.

4-9
4 Define Parameters

The corresponding parameter values for the LeftWheel component remain unchanged.

See Also
systemcomposer.arch.Parameter | addParameter | getParameter | resetToDefault |
getParameterPromotedFrom | getEvaluatedParameterValue | getParameterNames |
getParameterValue | setParameterValue | setUnit | resetParameterToDefault

More About
• “Author Parameters in System Composer Using Parameter Editor” on page 4-2
• “Specify Instance-Specific Parameter Values for Reusable Referenced Model” (Simulink Coder)
• “Implement Component Behavior Using Simulink” on page 7-2
• “Compose Architectures Visually” on page 1-5
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35

4-10
5

Define Architectural Properties

• “Extend System Composer Language Elements Using Profiles” on page 5-2


• “Define and Style Stereotypes in Profiles” on page 5-5
• “Apply Stereotypes to Extend Model Elements” on page 5-13
• “Best Practices for Profile Design” on page 5-24
• “Change Stereotype Order Using Manage Profiles Tool” on page 5-31
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35
• “Organize and Link Requirements for Mobile Robot” on page 5-38
• “Design Architectures and Activity Diagram for Mobile Robot” on page 5-42
• “Define Stereotypes and Perform Analysis for Mobile Robot” on page 5-53
• “Simulate Architectural Behavior for Mobile Robot” on page 5-63
• “Change Stereotypes Based on Stereotype Hierarchy in Portable Blender Architecture”
on page 5-68
5 Define Architectural Properties

Extend System Composer Language Elements Using Profiles


You can use System Composer profiles to define stereotypes, then apply these stereotypes to core
elements that represent an architectural modeling language used to describe a system. To verify
structural and functional requirements, use stereotypes to capture nonfunctional properties on
elements in the architecture model.

For example, if there is a limit on the total power consumption of a system, the model must be able to
capture the power rating of each electrical component. To define component-specific property values,
you must extend built-in model element types with properties that correspond to requirements. In
this case, an electrical component type as an extension of components is a stereotype. By extending
the definition of regular components, you introduce a custom modeling language and framework that
includes specific concepts and terminologies important for the architecture model. Capturing the
individual properties also sets the scene for early parametric analyses and to define custom views.

These concepts are relevant for extend architectural elements workflows:

• Stereotypes provide a mechanism to extend the core language elements and add domain-specific
metadata.

Apply stereotypes to core element types. An element can have multiple stereotypes. Stereotypes
allow you to style different elements. Stereotypes provide elements with a common set of
properties, such as mass, cost, and power.
• A property is a field in a stereotype. You can specify property values for each element to which the
stereotype is applied.

Use properties to store quantitative characteristics, such as weight or speed, that are associated
with a model element. Properties can also be descriptive or represent a status. You can view and
edit the properties of each element in the architecture model using the Property Inspector.
• A profile is a package of stereotypes.

You can use profiles to create a domain of specialized element types. Author profiles and apply
profiles to a model using the Profile Editor. You can store stereotypes for a project in one or
several profiles. When you save profiles, they are stored in XML files.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Use profiles to extend your modeling language to represent your specific modeling environment. The
table lists topics about using profiles.

Topic Description
“Define and Style Stereotypes in Profiles” on Author a profile using the Profile Editor by
page 5-5 defining stereotypes, stereotype styling, and
properties.

5-2
Extend System Composer Language Elements Using Profiles

Topic Description
“Apply Stereotypes to Extend Model Elements” on Import an existing profile to your System
page 5-13 Composer architecture model, Requirements
Toolbox requirement set, or interface data
dictionary, then apply stereotypes to architectural
elements, and add property values.
“Best Practices for Profile Design” on page 5-24 Design profiles to maintain consistency and
optimize your stereotype definitions as your
system grows.

Create a profile in the Profile Editor and add stereotypes to it with properties. Apply the stereotype to
a component, and set the property value in the Property Inspector. Open the Property Inspector by
navigating to Modeling > Property Inspector.

5-3
5 Define Architectural Properties

See Also

More About
• “Analyze Architecture” on page 9-2
• “Analysis Function Constructs” on page 9-9
• “Modeling System Architecture of Small UAV” on page 1-37
• “Create and Manage Allocations Interactively” on page 8-2
• “Apply Stereotypes to Functions of Software Architectures” on page 10-32
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35

5-4
Define and Style Stereotypes in Profiles

Define and Style Stereotypes in Profiles


Author a profile by defining stereotypes, stereotype styling, and properties in the Profile Editor tool.
You can later apply stereotypes from your profile to architectural elements to extend your system
modeling language.

In this topic, you will learn how to:

1 Create a profile and define stereotypes with properties.


2 Define default stereotypes in a profile to be added to any new element in a model with that
applied profile.
3 Use stereotype-based styling that enhances the appearance of the model based upon specific
features each element represents.

For more information about profiles terminology, see “Extend System Composer Language Elements
Using Profiles” on page 5-2.

Create Profile and Add Stereotypes


Create a profile to define a set of component, port, and connection types to be used in an architecture
model. For example, a profile for an electromechanical system, such as a robot, could consist of these
types.

• Component types

• Electrical component
• Mechanical component
• Software component
• Connection types

• Analog signal connection


• Data connection
• Port types

• Data port

Define a profile using the Profile Editor by navigating to Modeling > Profile Editor. Click New
Profile. Select the new profile to start editing.

Note Before you move, copy, or rename a profile to a different directory, you must close the profile in
the Profile Editor or by using the close function. If you rename a profile, follow the example for the
renameProfile function.

5-5
5 Define Architectural Properties

Name the profile and provide a description. Add stereotypes by clicking New Stereotype. You can

delete stereotypes by clicking the button in their respective menus.

Save the profile. The file name is the same as the profile name.

For more information on optimizing profile design, see “Best Practices for Profile Design” on page 5-
24.

Add Properties with Stereotypes


Select a stereotype in a profile to define it:

• Name — The name of the stereotype, for example, ElectricalComponent.


• Applies to — The model element type to which the stereotype applies. This option can be:

• <all> to apply stereotype to all element types.


• Component.
• Port.
• Connector.
• Interface.
• Allocation. For more information, see “Create and Manage Allocations Interactively” on
page 8-2.
• Function, which is only available for software architectures. For more information, see “Apply
Stereotypes to Functions of Software Architectures” on page 10-32.
• Requirement, to be used with a Requirements Toolbox license. For more information, see
“Customize Requirements and Links by Using Stereotypes” (Requirements Toolbox).

5-6
Define and Style Stereotypes in Profiles

• Link, to be used with a Requirements Toolbox license.


• Icon — Icon to be shown on the model element with color, if applicable.
• Connector Style — Line style of the connector to be shown on the model with color, if applicable.
• Base stereotype — Other stereotype on which this stereotype is based. This option can be empty.
• Abstract stereotype — A stereotype that is not intended to be applied directly to a model
element. You can use abstract stereotypes only as the base stereotype for other stereotypes.

Add properties to a stereotype using the button. Define these fields for each property:

• Property name — Valid variable name


• Type — Numeric, string, or enumeration data type
• Name — Name of the enumerated type, if applicable
• Default — Default value
• Unit — Value units as a string
• Min — Minimum value
• Max — Maximum value

Use the property toolstrip to add , delete , reorder properties up , and reorder properties
down .

5-7
5 Define Architectural Properties

You can create a stereotype that applies to all model element types by setting the Applies to field to
<all>. With these stereotypes, you can add properties to elements regardless of whether they are
components, ports, connectors, interfaces, functions, requirements, or links.

Define Default Stereotypes


Each profile can have a set of default stereotypes. Use default stereotypes when each new element of
a certain type must assume the same stereotype. System Composer applies a default stereotype to
the root architecture when you import the profile. To set this default in the Profile Editor for the
Stereotype applied to root on import field, select ProjectComponent.

This default stereotype is for the top-level architecture. If a model imports multiple profiles, the
default component stereotype for all profiles apply to the architecture.

5-8
Define and Style Stereotypes in Profiles

Each component stereotype can also have defaults for the components, ports, and connectors added
to its architecture. For example, if you want all new connectors in a project component to be analog
connections, for the ProjectComponent stereotype, set Connector stereotype to
AnalogConnection.

When you import the profile ProjectProfile into a model:

• The ProjectComponent stereotype is automatically applied to the root architecture.


• The ElectricalComponent stereotype is automatically applied to all new components in the
architecture model.
• The SignalPort stereotype is automatically applied to all new ports.
• The AnalogConnection stereotype is automatically applied to all new connections.

Use Stereotype-Based Styling


Profiles and stereotypes are used to apply custom metadata on the architecture model elements.
Element styling is an additional visual cue that indicates applied stereotypes.

You can use provided icons for the component stereotypes or use you own custom icon images.
Custom icons support .png, .jpeg, or .svg image files of size 16-by-16 pixels. The custom icons are
displayed as badges on the components for which the stereotypes are applied.

5-9
5 Define Architectural Properties

You can associate a color with component stereotypes. Element styling is an additional visual cue that
indicates applied stereotypes.

Use a preconfigured set of color options for component stereotypes to style the architecture
component headers. See “Apply Stereotypes to Extend Model Elements” on page 5-13 to learn how
to use stereotypes in your model.

Similarly, you can style architecture connectors using the stereotype settings. You can style
connectors by using connector, port, or port interface stereotypes. Customize styling provides various
color and line style choices. Connector styles are also reflected in architecture and spotlight views.

5-10
Define and Style Stereotypes in Profiles

Note Connector styling is sourced from the highest-priority stereotype that defines style information.
Connector stereotypes have the highest priority, followed by port stereotypes and then interface
stereotypes. When two connectors with different styling merge, if the styling is incompatible, the
resulting connector is displayed in black.

5-11
5 Define Architectural Properties

See Also
Tools
Profile Editor | Manage Profiles

Blocks
Component | Reference Component | Variant Component

Objects
systemcomposer.profile.Profile | systemcomposer.profile.Stereotype |
systemcomposer.profile.Property

Functions
systemcomposer.profile.Profile.createProfile | systemcomposer.loadProfile |
applyProfile | removeProfile | renameProfile | systemcomposer.profile.editor |
systemcomposer.profile.Profile.find | systemcomposer.profile.Profile.load | save
| open | close | systemcomposer.profile.Profile.closeAll |
systemcomposer.profile.Stereotype.find | getDefaultStereotype |
setDefaultStereotype | getDefaultElementStereotype | setDefaultElementStereotype
| addStereotype | removeStereotype | getStereotype | applyStereotype |
batchApplyStereotype | getStereotypes | changeStereotype | removeStereotype |
hasStereotype | addProperty | removeProperty | hasProperty | setProperty |
getProperty | getPropertyValue | getEvaluatedPropertyValue |
getStereotypeProperties | applyStereotypeOrder | getStereotypeNamesByOrder |
increaseStereotypeOrder | decreaseStereotypeOrder

More About
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Analyze Architecture” on page 9-2
• “Change Stereotype Order Using Manage Profiles Tool” on page 5-31
• “Change Stereotypes Based on Stereotype Hierarchy in Portable Blender Architecture” on page
5-68
• “Create and Manage Allocations Programmatically” on page 8-11
• “Apply Stereotypes to Functions of Software Architectures” on page 10-32

5-12
Apply Stereotypes to Extend Model Elements

Apply Stereotypes to Extend Model Elements


Use profiles to add properties to components, ports, and connectors in System Composer. Import an
existing profile, apply stereotypes, and add property values.

In this topic, you will learn how to:

1 Import profiles into a model or a dictionary.


2 Apply a stereotype to a model element and add property values.
3 Remove stereotypes using the Property Inspector.

For more information about profiles terminology, see “Extend System Composer Language Elements
Using Profiles” on page 5-2.

Import Profiles
The Profile Editor is independent from the model that opens it, so you must explicitly import a new
profile into a model. The profile must first be saved with an .xml extension. Navigate to Modeling >

Profiles > Import . Select the profile to import. An architecture model can use multiple profiles
at once.

Alternatively, open the Profile Editor by navigating to Modeling > Profile Editor. You can import a
profile into any open dictionaries or models.

5-13
5 Define Architectural Properties

To import profiles into Simulink models linked to a Reference Component, open the Profile Editor and
select the linked model from Import into.

Note For a System Composer component linked to a Simulink behavior model, the profile must be
imported into the Simulink model before applying a stereotype to the component. Since the Property
Inspector on the Simulink side does not display stereotypes, this workflow is not finalized.

To manage profiles after they have been imported, open the Manage Profiles tool by navigating to

Modeling > Profiles > Manage .

5-14
Apply Stereotypes to Extend Model Elements

You can click the Manage Stereotype Order button to change the priority order of stereotypes on
imported profiles. For more information, see “Change Stereotype Order Using Manage Profiles Tool”
on page 5-31.

Apply Stereotypes
Apply stereotypes to architecture model elements using the Property Inspector or the Apply
Stereotypes dialog. You can also quick-insert a new component with the stereotype applied. For
information about applying stereotypes to functions in software architectures, see “Apply Stereotypes
to Functions of Software Architectures” on page 10-32.

Apply Stereotype Using Property Inspector

Once the profile is available in the model, open the Property Inspector by navigating to Modeling >
Property Inspector. Select a model element.

5-15
5 Define Architectural Properties

Select the stereotype from the Stereotype list. Only the stereotypes that apply to the current
element type (for example, a port) are available for selection. If no stereotype exists, you can use the
<new / edit> option to open the Profile Editor and create one.

5-16
Apply Stereotypes to Extend Model Elements

When you apply a stereotype to an element, a new set of properties appears in the Property Inspector
under the name of the stereotype. To edit the properties, expand this set.

You can set multiple stereotypes for each element.

5-17
5 Define Architectural Properties

Use Apply Stereotypes Dialog to Batch Apply Stereotypes

You can also apply component, port, connector, and interface stereotypes to all applicable elements at
the same architecture level. Navigate to Modeling > Apply Stereotypes. In the Apply Stereotypes
dialog box, from Apply stereotype(s) to, select Top-level architecture, All elements,
Components, Ports, Connectors, or Interfaces.

Note The Interfaces option is only available if interfaces are defined in the Interface Editor. For
more information, see “Create Interfaces” on page 3-6.

You can also apply stereotypes by selecting a single model element. From Scope, select Selection,
This layer, or Entire model.

5-18
Apply Stereotypes to Extend Model Elements

You can also apply stereotypes to data interfaces or value types. When interfaces are locally defined
and you select one or more interfaces in the Interface Editor, the options for Scope are Selection
and Local interfaces.

5-19
5 Define Architectural Properties

When interfaces are stored and shared across a data dictionary and you select one or more interfaces
in the Interface Editor, the options for Scope are Selection and either dictionary.sldd or the
name of the dictionary currently in use.

5-20
Apply Stereotypes to Extend Model Elements

Note For the stereotypes to display for interfaces in a dictionary, in the Apply Stereotypes dialog box,
the profile must be imported into the dictionary.

Quick-Insert New Component With Stereotype Applied

You can also create a new component with an applied stereotype using the quick-insert menu. Select
the stereotype as a fully qualified name. A component with that stereotype is created.

5-21
5 Define Architectural Properties

Change Stereotypes
To change stereotypes applied to model elements on the model canvas, first create a hierarchy of
stereotypes. Assign a Base Stereotype value in the Profile Editor for a given stereotype to inherit all
properties from the base stereotype. For more information about base stereotypes, see “Extend
Stereotypes” on page 5-25. Expand your hierarchy as needed to add detail to your system
description.

Use the System Composer model canvas context menu and Property Inspector to change stereotypes,
without changing shared property values. You can move one level up and down the stereotype
hierarchy defined in the Profile Editor. For more information about changing stereotypes, see
“Change Stereotypes Based on Stereotype Hierarchy in Portable Blender Architecture” on page 5-
68.

You can also use the changeStereotype function to change stereotypes you assign to model
elements by any number of levels up and down the hierarchy.

Remove Stereotypes
If a stereotype is no longer required for an element, remove it using the Property Inspector. Next to
the stereotype, click Select, then select Remove.

5-22
Apply Stereotypes to Extend Model Elements

See Also
Tools
Profile Editor | Manage Profiles

Blocks
Component | Reference Component | Variant Component

Objects
systemcomposer.profile.Profile | systemcomposer.profile.Stereotype |
systemcomposer.profile.Property

Functions
systemcomposer.profile.Profile.createProfile | systemcomposer.loadProfile |
applyProfile | removeProfile | renameProfile | systemcomposer.profile.editor |
systemcomposer.profile.Profile.find | systemcomposer.profile.Profile.load | save
| open | close | systemcomposer.profile.Profile.closeAll |
systemcomposer.profile.Stereotype.find | getDefaultStereotype |
setDefaultStereotype | getDefaultElementStereotype | setDefaultElementStereotype
| addStereotype | removeStereotype | getStereotype | applyStereotype |
batchApplyStereotype | getStereotypes | changeStereotype | removeStereotype |
hasStereotype | addProperty | removeProperty | hasProperty | setProperty |
getProperty | getPropertyValue | getEvaluatedPropertyValue |
getStereotypeProperties | applyStereotypeOrder | getStereotypeNamesByOrder |
increaseStereotypeOrder | decreaseStereotypeOrder

More About
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Analyze Architecture” on page 9-2
• “Change Stereotype Order Using Manage Profiles Tool” on page 5-31
• “Change Stereotypes Based on Stereotype Hierarchy in Portable Blender Architecture” on page
5-68
• “Create and Manage Allocations Programmatically” on page 8-11
• “Apply Stereotypes to Functions of Software Architectures” on page 10-32

5-23
5 Define Architectural Properties

Best Practices for Profile Design


You should design your profiles in System Composer as your system grows. You can optimize your
stereotype definitions by placing a shared set of properties in a base stereotype and maintain
consistent definitions between specialized groups of model elements.

In this topic, you will learn how to:

• Clarify the role of profiles in systems engineering design.


• Structure your stereotypes so common properties can be shared through an inherited mechanism.
For example, a UserInterface stereotype can be an extension of a SoftwareComponent
stereotype, and you can add a property called ScreenResolution.
• Decide how to use multiple profiles based on what each profile represents.

For more information about profiles terminology, see “Extend System Composer Language Elements
Using Profiles” on page 5-2.

Role of Profiles in System Design


Profiles in System Composer are used to define a framework for stereotypes. In a profile, stereotypes,
which can apply to a certain element type, include property definitions. Stereotypes extend model
elements after you apply a stereotype to the elements and define property values for each element
type. You can apply stereotypes to these model elements:

• <all> to apply stereotype to all element types.


• Component.
• Port.
• Connector.
• Interface.
• Allocation. For more information, see “Create and Manage Allocations Interactively” on page 8-
2.
• Function, which is only available for software architectures. For more information, see “Apply
Stereotypes to Functions of Software Architectures” on page 10-32.
• Requirement, to be used with a Requirements Toolbox license. For more information, see
“Customize Requirements and Links by Using Stereotypes” (Requirements Toolbox).
• Link, to be used with a Requirements Toolbox license.

In this example, the profile MyCustomProfile contains multiple stereotypes. The


PhysicalComponent stereotype applies to Component elements and includes the DeviceID
property. The BluetoothLink stereotype applies to Connector elements. You can further specialize
the PhysicalComponent stereotype by using the SensorComponent stereotype, which inherits the
DeviceID property and includes the additional property FailureProb.

5-24
Best Practices for Profile Design

Extend Stereotypes
You can extend a stereotype by creating a new stereotype based on the existing one, allowing you to
control properties in a structural manner. For example, all components in a project may have a part
number, but only electrical components have a power rating, and only electronic components — a
subset of electrical components — have manufacturer information. You can use an abstract
stereotype to serve solely as a base for other stereotypes and not as a stereotype for any architecture
model elements.

For example, in the Profile Editor, create a new stereotype called ElectronicComponent. For Base
stereotype, select ProjectProfile.ElectricalComponent. Define properties you want to add to
those of the base stereotype. Select Show inherited properties (read-only) at the bottom of the
property list to show the properties of the base stereotype. You can edit only the properties of the
selected stereotype, not the base stereotype.

5-25
5 Define Architectural Properties

When you apply the new stereotype, it carries its defined properties in addition to those of its base
stereotype.

5-26
Best Practices for Profile Design

When you use a base stereotype and shared property definitions across your profile, you optimize
your stereotype definitions as your model grows.

Using Multiple Profiles


Profiles provide a way to extend a modeling language. In System Composer, profiles allow you to
clarify which domain-specific language to use to specialize your system. Domain-specific languages
include definitions for safety, logic, or company information.

Suppose your system has a physical domain and a safety domain with separate definitions. You can
create the PhysicalProfile and SafetyProfile profiles in the Profile Editor.

5-27
5 Define Architectural Properties

On the model canvas, after importing both profiles into the model, you can apply both the
PhysicalComponent and SafetyComponent stereotypes from the two different profiles to the
PressureSensorLeft component, then populate the respective property values for the component.

5-28
Best Practices for Profile Design

When you work with multiple profiles, use Simulink projects with source control to organize your files
and folders and collaborate with other contributors. For more information, see “Organize System
Composer Files in Projects” on page 12-2.

Multiple profiles help to maintain consistent definitions between specialized groups of model
elements in separate domains.

See Also
Tools
Profile Editor | Manage Profiles

Blocks
Component | Reference Component | Variant Component

Objects
systemcomposer.profile.Profile | systemcomposer.profile.Stereotype |
systemcomposer.profile.Property

Functions
systemcomposer.profile.Profile.createProfile | systemcomposer.loadProfile |
applyProfile | removeProfile | renameProfile | systemcomposer.profile.editor |
systemcomposer.profile.Profile.find | systemcomposer.profile.Profile.load | save
| open | close | systemcomposer.profile.Profile.closeAll |
systemcomposer.profile.Stereotype.find | getDefaultStereotype |
setDefaultStereotype | getDefaultElementStereotype | setDefaultElementStereotype
| addStereotype | removeStereotype | getStereotype | applyStereotype |
batchApplyStereotype | getStereotypes | changeStereotype | removeStereotype |
hasStereotype | addProperty | removeProperty | hasProperty | setProperty |
getProperty | getPropertyValue | getEvaluatedPropertyValue |
getStereotypeProperties | applyStereotypeOrder | getStereotypeNamesByOrder |
increaseStereotypeOrder | decreaseStereotypeOrder

5-29
5 Define Architectural Properties

More About
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Analyze Architecture” on page 9-2
• “Change Stereotype Order Using Manage Profiles Tool” on page 5-31
• “Change Stereotypes Based on Stereotype Hierarchy in Portable Blender Architecture” on page
5-68
• “Create and Manage Allocations Programmatically” on page 8-11
• “Apply Stereotypes to Functions of Software Architectures” on page 10-32

5-30
Change Stereotype Order Using Manage Profiles Tool

Change Stereotype Order Using Manage Profiles Tool

This example shows how to change the stereotype order for stereotypes applied to a component after
importing the RGBColors profile.

Open the model.

model = systemcomposer.openModel("OrderingStereotypes");

The Door component has the Green, Red, and Blue stereotypes applied. Since the Green stereotype
is first in priority, the color of the component is green.

To open the Manage Profiles tool, navigate to Modeling > Profile Editor > Manage.

5-31
5 Define Architectural Properties

Select the OrderingStereotypes.slx model, then click Manage Stereotype Order to rearrange
the priority of the stereotypes in imported profiles.

Select RBGColors.Blue, then click the up arrow until RBGColors.Blue is the top priority. Accept
changes by clicking OK.

5-32
Change Stereotype Order Using Manage Profiles Tool

Navigate back to the model canvas. The Door component is now colored blue.

5-33
5 Define Architectural Properties

See Also
Tools
Profile Editor | Manage Profiles

Blocks
Component | Reference Component | Variant Component

Objects
systemcomposer.profile.Profile | systemcomposer.profile.Stereotype |
systemcomposer.profile.Property

Functions
systemcomposer.profile.Profile.createProfile | systemcomposer.loadProfile |
applyProfile | removeProfile | renameProfile | systemcomposer.profile.editor |
systemcomposer.profile.Profile.find | systemcomposer.profile.Profile.load | save
| open | close | systemcomposer.profile.Profile.closeAll |
systemcomposer.profile.Stereotype.find | getDefaultStereotype |
setDefaultStereotype | getDefaultElementStereotype | setDefaultElementStereotype
| addStereotype | removeStereotype | getStereotype | applyStereotype |
batchApplyStereotype | getStereotypes | changeStereotype | removeStereotype |
hasStereotype | addProperty | removeProperty | hasProperty | setProperty |
getProperty | getPropertyValue | getEvaluatedPropertyValue |
getStereotypeProperties | applyStereotypeOrder | getStereotypeNamesByOrder |
increaseStereotypeOrder | decreaseStereotypeOrder

More About
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Analyze Architecture” on page 9-2
• “Change Stereotypes Based on Stereotype Hierarchy in Portable Blender Architecture” on page
5-68
• “Create and Manage Allocations Programmatically” on page 8-11
• “Apply Stereotypes to Functions of Software Architectures” on page 10-32

5-34
Simulate Mobile Robot with System Composer Workflow

Simulate Mobile Robot with System Composer Workflow

Along with other tools, System Composer™ can help you organize and link requirements, design and
allocate architecture models, analyze the system, and implement the design in Simulink®. This
tutorial shows the early phases of development of an autonomous mobile robot.

This example shows the model-based systems engineering (MBSE) process from specification and
iterative design to simulation and verification. In Step 4, the robot navigates around a barrier in its
path meeting the high-level functional requirements.

Navigate through these phases of design to explore system design by following the link to each step.

Step 1: “Organize and Link Requirements for Mobile Robot” on page 5-38: Create requirements and
requirement links based on market research using Requirements Toolbox™. Link stakeholder
requirements to system requirements.

Step 2: “Design Architectures and Activity Diagram for Mobile Robot” on page 5-42: Create
architecture models to help organize algorithms and hardware. Use an activity diagram to elaborate
on the functional flow behavior of the robot. Link requirements to components in the architecture
models, then allocate element-to-element from the activity diagram to the logical architecture and
from one architecture to another.

Step 3: “Define Stereotypes and Perform Analysis for Mobile Robot” on page 5-53: Define
stereotypes and perform system analysis to ensure that the life expectancy of the durable
components in the robot meets the customer-specified mean time before repair. Use stereotype-based
filters to create architecture views. Export your physical architecture to a web view.

Step 4: “Simulate Architectural Behavior for Mobile Robot” on page 5-63: Create a Simulink model
to simulate realistic behavior of the mobile robot. Add behaviors to components in your logical
architecture model. Then, simulate the logical architecture using Simscape™ Multibody™.

This workflow is represented by the left side of the model-based systems engineering (MBSE) design
diagram.

5-35
5 Define Architectural Properties

References
[1] Rahman, Mohd Azizi Abdul, Katsuhiro Mayama, Takahiro Takasu, Akira Yasuda, and Makoto
Mizukawa. “Model-Driven Development of Intelligent Mobile Robot Using Systems Modeling
Language (SysML).” In Mobile Robots: Control Architectures, Bio-Interfacing, Navigation,
Multi Robot Motion Planning and Operator Training, edited by Janusz Będkowski. InTech
Open, 2011. https://doi.org/10.5772/26906.

See Also

More About
• “Model-Based Design with Simulink”

5-36
Simulate Mobile Robot with System Composer Workflow

• “Organize System Composer Files in Projects” on page 12-2


• “System Composer Concepts”

5-37
5 Define Architectural Properties

Organize and Link Requirements for Mobile Robot


The first step in model-based systems engineering (MBSE) design using System Composer is to set up
requirements. This functionality requires a Requirements Toolbox license.

Requirements are a collection of statements describing the desired behavior and characteristics of a
system. Requirements ensure system design integrity and are achievable, verifiable, unambiguous,
and consistent with each other. Each level of design should have appropriate requirements. This
mobile robot example has three sets of requirements.

1 Stakeholder needs — A set of end-user needs. Stakeholders are interested in attributes of the
mobile robot associated with endurance, payload, speed, autonomy, and reliability.
2 System requirements — A set of requirements that are linked closely with system-level design.
System requirements include the derived requirements that describe how the system responds to
stakeholder needs.
3 Implementation requirements — A set of requirements that specify subsystems in the model.
Implementation requirements include specifications for the battery, structure, propulsion, path
generation, position, controller, and component life for individual subsystems.

By linking one requirement set to another, each high-level requirement can be traced to
implementation. As the MBSE design evolves, you can use iterative requirements analysis to enhance
requirement traceability and coverage. You can use the traceability diagram to visualize requirement
traceability. See “Visualize Links with Traceability Diagrams” (Requirements Toolbox).

Note This example uses Simscape blocks. If you do not have a Simscape license, you can open and
simulate the model but can only make basic changes, such as modifying block parameters.

Link Stakeholder Requirements to System Requirements

The mobile robot example includes a functional, logical, and physical architecture that fulfills
stakeholder needs, system requirements, and implementation requirements.

1. Launch the project.

openProject("scMobileRobotExample");

2. Load these systems in memory to view their requirement links.

• Functional architecture model

systemcomposer.loadModel("RobotFunctionalArchitecture");

• Logical architecture model

systemcomposer.loadModel("scMobileRobotLogicalArchitecture");

• Physical architecture model

systemcomposer.loadModel("scMobileRobotHardwareArchitecture");

3. Load these requirement sets into memory.

5-38
Organize and Link Requirements for Mobile Robot

• Stakeholder needs

slreq.load("scMobileRobotStakeholderNeeds");

• System requirements

slreq.load("scMobileRobotRequirements");

• Implementation requirements

slreq.load("scMobileRobotSubsystemRequirements");

4. Open the Requirements Editor (Requirements Toolbox).

slreq.editor

You can link stakeholder needs to derived requirements to keep track of high-level goals. The Mean
Time Before Repair (MTBR) requirement, STAKEHOLDER-07, is refined by the Battery Life
requirement, SYSTEM-REQ-09.

5-39
5 Define Architectural Properties

You can set a specific link type. To change link types, in the Requirements Editor (Requirements
Toolbox), select Show Links. For more information, see “Create and Store Links” (Requirements
Toolbox).

5-40
Organize and Link Requirements for Mobile Robot

To return to interacting with requirements, in the Requirements Editor (Requirements Toolbox),


select Show Requirements. The Transportation stakeholder needs requirement, STAKEHOLDER-04,
will be implemented by the Localization system requirement, SYSTEM-REQ-05. The robot must be
able to determine its current position with a specified tolerance. Right-click SYSTEM-REQ-05 and
select Select for Linking with Requirement. Then, right-click STAKEHOLDER-04 and select
Create a link from SYSTEM-REQ-05 to STAKEHOLDER-04.

References
[1] Rahman, Mohd Azizi Abdul, Katsuhiro Mayama, Takahiro Takasu, Akira Yasuda, and Makoto
Mizukawa. “Model-Driven Development of Intelligent Mobile Robot Using Systems Modeling
Language (SysML).” In Mobile Robots: Control Architectures, Bio-Interfacing, Navigation,
Multi Robot Motion Planning and Operator Training, edited by Janusz Będkowski. InTech
Open, 2011. https://doi.org/10.5772/26906.

See Also
slreq.editor | slreq.load | systemcomposer.loadModel

More About
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Design Insulin Infusion Pump Using Model-Based Systems Engineering” on page 9-24
• “Establish Traceability Between Architectures and Requirements” on page 2-22
• “System Composer Concepts”

5-41
5 Define Architectural Properties

Design Architectures and Activity Diagram for Mobile Robot


Architecture models in System Composer describe a system at different levels of abstraction. This
mobile robot example presents three architectures:

1 Functional architecture — Describes high-level functions and the relationships between those
functions
2 Logical architecture — Describes data exchange between electronic hardware and software
components in each subsystem
3 Physical architecture — Describes the physical hardware or platform needed for the robot

In addition to these architecture models, you can generate the functional flow as an activity diagram.
To describe the element-to-element directed relationship from one architecture to another or from an
activity diagram to an architecture, use the Allocation Editor.

Note This example uses Simscape blocks. If you do not have a Simscape license, you can open and
simulate the model but can only make basic changes, such as modifying block parameters.

Design, Specify, and Allocate Architecture Models

This mobile robot example includes architecture models where you can link requirements to
components and define allocations. It also includes an activity diagram to elaborate on the functional
design and explore alternative options.

Launch the project.

openProject("scMobileRobotExample");

Functional Architecture Model for Mobile Robot

The functional architecture model describes functional dependencies: controlling a mobile robot
autonomously, localization, path-planning, and path-following. To open the functional architecture
model, double-click the file or run this command.

systemcomposer.openModel("RobotFunctionalArchitecture");

5-42
Design Architectures and Activity Diagram for Mobile Robot

Functional Flow Activity Diagram for Mobile Robot

The functional flow activity diagram describes an operational scenario with a random start point and
random end point between which the mobile robot moves. The algorithm plans the path. If the path is
too long and the robot does not have enough battery life, the process ends early. If the path is
feasible, the robot begins at a set angular orientation, traverses in the x-direction, traverses in the y-
direction, and then sets its final angular orientation.

systemcomposer.openModel("RobotActivity");

5-43
5 Define Architectural Properties

Logical Architecture Model for Mobile Robot

The logical architecture model describes the behavior of the mobile robot system for simulation:
trajectory generator, trajectory follower, motor controller, sensor algorithm, and robot and
environment. The connections represent the interactions in the system. To open the logical
architecture model, double-click the file or run this command.

systemcomposer.openModel("scMobileRobotLogicalArchitecture");

5-44
Design Architectures and Activity Diagram for Mobile Robot

Physical Architecture Model for Mobile Robot

The physical architecture model describes the hardware components and their connections: the
sensor, actuators, and embedded processor. The colors and icons indicate the stereotypes used for
each element. To open the physical architecture model, double-click the file or run this command.

systemcomposer.openModel("scMobileRobotHardwareArchitecture");

5-45
5 Define Architectural Properties

Link Requirements to Components

Requirement traceability involves linking technical requirements to components and ports in


architecture models, thereby allowing the connection between an early requirements phase and
system-level design. You can easily track whether a requirement is met by connecting components
back to stakeholder needs. You can add requirement links by dragging requirements to a component.

To view requirements, open the Requirements Manager by navigating to Apps > Requirements
Manager.

The Identify Target Position component in the functional architecture model implements the
Autonomous Charging requirement, STAKEHOLDER-05. To show or hide linked requirements, click
the requirement icon on the top-right corner of a component.

5-46
Design Architectures and Activity Diagram for Mobile Robot

5-47
5 Define Architectural Properties

You can view the requirements linked to the hardware architecture model in the Requirements
Browser. After selecting STAKEHOLDER-04, only components related to the Transportation
requirement are shown.

Allocate Architectures and Diagrams

You can allocate functional components to physical components using model-to-model allocations. To
open the Allocation Editor, navigate to Modeling > Allocation Editor, or run this command.
systemcomposer.allocation.editor

Load the allocation sets.


allocSetFunc = systemcomposer.allocation.load("FunctionalToLogicalAllocation");
allocSetPhys = systemcomposer.allocation.load("LogicalToPhysicalAllocation");
allocSetAct = systemcomposer.allocation.load("DiagramToModel");

Allocate Functional to Logical Architectures

Click Scenario 1 under the FunctionalToLogicalAllocation allocation set.

Select the Component in the Row Filter and Column Filter sections. The Allocation Editor tool
allows you to link components between different architecture models to establish traceability for your
project. Double-click the boxes in the allocation matrix to allocate or deallocate two elements.

5-48
Design Architectures and Activity Diagram for Mobile Robot

In the functional architecture, the trajectory generator requires components Identify Target
Postion, User Input, and Compute Self Position, so these components are allocated to the
Trajectory Generator component in the logical architecture.

Allocate Functional Activity Diagram to Logical Architecture

Click Scenario 1 under the DiagramToModel allocation set.

5-49
5 Define Architectural Properties

From the activity diagram, allocate action nodes Initialize Path Follower, Apply Path
Limits, Select Target Position, and Error out to the Alignment Algorithm component

5-50
Design Architectures and Activity Diagram for Mobile Robot

on the logical architecture model to indicate that these actions are controlled by the contents of that
logical component.

Allocate Logical to Physical Architectures

Click Scenario 1 under the LogicalToPhysicalAllocation allocation set.

The autonomy of a vehicle is mostly handled by a target machine, which is an embedded computer
responsible for processing sensor readings to calculate control inputs. Therefore, many functional

5-51
5 Define Architectural Properties

components like Robot Body, Sensor Fusion, and Trajectory Generator are allocated to the
Target Machine component in the physical architecture model.

References
[1] Rahman, Mohd Azizi Abdul, Katsuhiro Mayama, Takahiro Takasu, Akira Yasuda, and Makoto
Mizukawa. “Model-Driven Development of Intelligent Mobile Robot Using Systems Modeling
Language (SysML).” In Mobile Robots: Control Architectures, Bio-Interfacing, Navigation,
Multi Robot Motion Planning and Operator Training, edited by Janusz Będkowski. InTech
Open, 2011. https://doi.org/10.5772/26906.

See Also
allocate | addComponent | addPort | connect

More About
• “Compose Architectures Visually” on page 1-5
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Create and Manage Allocations Programmatically” on page 8-11
• “Establish Traceability Between Architectures and Requirements” on page 2-22
• “System Composer Concepts”

5-52
Define Stereotypes and Perform Analysis for Mobile Robot

Define Stereotypes and Perform Analysis for Mobile Robot


Stereotypes add an additional layer of metadata to components, ports, and connectors in System
Composer. A stereotype is a custom extension of the modeling language. Stereotypes provide a
mechanism to extend the architectural language elements by adding domain-specific metadata. The
hardware architecture model provides a basis to understand the stereotypes applied to model
elements, create filtered views based on the stereotypes, and perform a remaining useful life (RUL)
analysis on the model.

Define Stereotypes and Perform Analysis

This mobile robot example includes a profile applied to a physical architecture with stereotypes and
properties defined. You can use views to display stakeholder concerns. Perform a remaining useful
life (RUL) analysis on the life expectancy of the hardware components.

Launch the project.

openProject("scMobileRobotExample");

Hardware Architecture Model for Mobile Robot

The hardware architecture model describes the hardware components and their connections: the
sensor, actuators, and embedded processor. The colors and icons indicate the stereotypes used for
each element. To open the hardware architecture model, double-click the file or run this command.

systemcomposer.openModel("scMobileRobotHardwareArchitecture");

5-53
5 Define Architectural Properties

View Stereotypes and Properties in Profile Editor

In this example, the HardwareBaseStereotype stereotype is defined as an abstract stereotype and


is extended to connector and component stereotypes. For example, a DataConnector stereotype is a
connector stereotype that inherits the HardwareBaseStereotype.

To focus on expected time before first maintenance, define properties such as UsagePerDay,
UsagePerYear, and Life. Setting these properties allows you to analyze each hardware component
to make sure the mobile robot will last until first expected year of maintenance. To open the Profile
Editor, navigate to Modeling > Profile Editor.

5-54
Define Stereotypes and Perform Analysis for Mobile Robot

In addition to properties like name and mass, the DataConnector stereotype has a property of
enumeration type, TypeOfConnection, that describes which of the three connection types it uses:
RS232, Ethernet, or USB. To generate custom data types, create a script simlar to
ConnectorType.m. For more information, see “Simulink Enumerations”.

Apply Stereotypes to Elements in Model

Once you define stereotypes in the Profile Editor, you can apply them to components, ports, and
connectors. Apply stereotypes using the Property Inspector. To open the Property Inspector, navigate
to Modeling > Property Inspector.

To add stereotypes to elements, select the element in the diagram. In the Property Inspector, select
Main > Stereotype. You can apply multiple stereotypes to the same element. Apply the
MobileRobotProfile.Sensor stereotype to the Lidar Sensor component to add properties.

5-55
5 Define Architectural Properties

Some components remain in use for longer periods of time than others. The Lidar Sensor
component is used for obstacle avoidance in this scenario, so it is always in use except when it is
charging. The RGB Camera only aligns the robot to the charging station, so it is in use for a shorter
period per day. You can change values for the UsagePerDay, UsagePerYear, and Life properties to
determine the expected maintenance time for components that are each used with different
frequency.

5-56
Define Stereotypes and Perform Analysis for Mobile Robot

The property ExceedExpectedMaintenance is set to false by default. This property will update
when you run your analysis.

Architecture Views for Hardware Architecture Model

Use the Architecture Views Gallery to review changes you make in the architecture model.
Architecture views allow you to create filtered views and thereby focus on few elements of the model,
which enables you to navigate a complex model more easily.

1 To open the Architecture Views Gallery, navigate to Modeling > Architecture Views.
2 Select New > View to create a new view.
3 Name the view in the View Properties pane on the right.
4 In the bottom pane, under View Configurations > Filter, select from the list Add Component
Filter > Select All Components to show all components in the view. Select Apply .
5 Select the Component Hierarchy view. The hierarchy of the components is flattened to show all
subcomponents in one view.

5-57
5 Define Architectural Properties

7 You can apply a filter to view components with the Life Expectancy requirement. Select New >
View and name the view in the View Properties pane on the right.
8 In the bottom pane under View Configurations > Filter, select Add Component Filter.
9

5-58
Define Stereotypes and Perform Analysis for Mobile Robot

10
Select Apply . Observe the components with the Life property defined.
11

The components with the Life property defined are components for which expected time before first
maintenance is a concern.

Analyze Hardware Components for Life Expectancy

Analyze the system to check if the components and connectors will last longer than the expected time
before first maintenance. This value is set to two years in the analysis function. Navigate to
Modeling > Analysis Model to open the Instantiate Architecture Model tool.

Select all stereotypes to make them available on the instance model. Select
scMobileRobotAnalysis.m as the analysis function. The iteration order determines in what order
the component hierarchy is analyzed. However, since each component is analyzed separately, the
order does not matter. Select the default iteration order Pre-order.

5-59
5 Define Architectural Properties

Click Instantiate to instantiate the model and open the Analysis Viewer tool. Relevant components
and connectors with stereotypes are shown. Since all stereotypes are selected, all elements with
stereotypes are shown in the instance model. Model analysis will calculate which components and
connectors will last longer than the expected two years. Click Analyze to perform the calculation.

5-60
Define Stereotypes and Perform Analysis for Mobile Robot

The components for which usage is not defined are components that last significantly longer than the
expected time and are therefore excluded from analysis. The analysis function calculates whether the
time before first maintenance for each component and connector will exceed Life, which is set to
two years. The unchecked boxes indicate that components and connectors will need maintenance
within two years.

To refresh the instance model in the Analysis Viewer, select Overwrite, then click Refresh. This
action will retrieve the values back from the source model, in this case, the hardware architecture
model. Since ExceedExpectedMaintenance was the only property changed, it reverts back to its
default value. Conversely, when you click Update the property values in the hardware architecture
source update according to the instance model.

Use Web View to Export Architecture Model

Web views are dynamic view-only HTML versions of a model. For an architecture model, web views
allow you to visualize port interfaces, element stereotypes and properties, and parameters on
components. In this example, you can interact with stereotypes and properties for the
scMobileRobotHardwareArchitecture model. For more information on web views, see “Web
Views” (Simulink Report Generator). A Simulink® Report Generator™ license is required to export
architecture models to web views.

Follow the instructions in “Export Models to Web View Files” (Simulink Report Generator) to export
the architecture model into a web view. To display your web view on your browser, follow the
instructions in “Display and Navigate Through Web Views” (Simulink Report Generator).

5-61
5 Define Architectural Properties

References
[1] Rahman, Mohd Azizi Abdul, Katsuhiro Mayama, Takahiro Takasu, Akira Yasuda, and Makoto
Mizukawa. “Model-Driven Development of Intelligent Mobile Robot Using Systems Modeling
Language (SysML).” In Mobile Robots: Control Architectures, Bio-Interfacing, Navigation,
Multi Robot Motion Planning and Operator Training, edited by Janusz Będkowski. InTech
Open, 2011. https://doi.org/10.5772/26906.

See Also
applyProfile | applyStereotype | openViews | instantiate

More About
• “Define and Style Stereotypes in Profiles” on page 5-5
• “Create Architecture Views Interactively” on page 11-9
• “Analyze Architecture” on page 9-2
• “Analysis Function Constructs” on page 9-9
• “System Composer Concepts”

5-62
Simulate Architectural Behavior for Mobile Robot

Simulate Architectural Behavior for Mobile Robot


To simulate the mobile robot logical architecture, link Simulink models to the components or add
Simulink subsystem components. For details, see “Implement Component Behavior Using Simulink”
on page 7-2. These models act as Simulink behaviors and can be simulated in System Composer by
clicking Run. The simulation shows how well the mobile robot follows a trajectory created by a
controller to avoid an obstacle.

Note This example uses Simscape blocks. If you do not have a Simscape license, you can open and
simulate the model but can only make basic changes, such as modifying block parameters.

Simulate Architectural Behavior

The mobile robot example includes a logical architecture with component behaviors defined. You can
run the simulation to watch the mobile robot avoid an obstacle.

Load the project.

openProject("scMobileRobotExample");

Add Behavior to Logical Architecture

The logical architecture model describes the behavior of the mobile robot system for simulation:
trajectory generator, trajectory follower, motor controller, sensor algorithm, and robot and
environment. The connections represent the interactions in the system. Open the logical architecture
model without any behaviors, double-click the file or run this command.

systemcomposer.openModel("scMobileRobotLogicalArchitecture_Initial");

5-63
5 Define Architectural Properties

The architecture model describes the behavior of the robot, but no behavior is actually added to the
architecture yet. By adding Simulink or Stateflow® behavior, the logical architecture can also be
simulated.

Create a new behavior based on the interface of a component. If a model or subsystem file already
exists for the behavior, use Link To Model to link to the exisiting model or subsystem. To create
new subsystem reference behavior for the Motor Controller component, right-click and select
Create Simulink Behavior, or, on the toolstrip, click Create Simulink Behavior. For more
information, see “Implement Component Behavior Using Simulink” on page 7-2.

You can create Simulink behaviors using mulitiple methods: Subsystem, Subsystem Reference,
and Model Reference. Use Subsystem to create a subsystem component behavior that is part of
the parent architecture model. Use the Subsystem Reference or Model Reference option to save
the behavior as a separate artifact and reuse the behavior. Physical ports can only cross subsystem
boundaries, so for physical systems, Subsystem Reference or Subsystem are recommended.

If you already have a behavior defined in a model file or subsystem file, use Link To Model to link a
component to the corresponding file. On the toolstrip, click Link to Model, or right-click the
Environment component and select Link to Model to link to the Environment.slx subsystem
file.

Logical Architecture Model for Mobile Robot

Open the final logical architecture where behavior is added to all the components.
systemcomposer.openModel("scMobileRobotLogicalArchitecture");

The Robot Body and Environment are Simulink subsystem reference components that support
physical ports. The Trajectory Generator is a Simulink subsystem component that also supports

5-64
Simulate Architectural Behavior for Mobile Robot

physical ports. The Trajectory Follower and Motion Controller components are represented
as Simulink models linked to the components as referenced models.

A behavior algorithm is created based on port information only. When designing a logical
architecture, you can set the interface of the port to define the information in more detail. For
example, if you know that 800 x 600 RGB images captured at 24 frames per second are transferred
from the camera sensor, then you can set the corresponding port interfaces accordingly to ensure
efficient data transfer. For more information about setting interfaces, see “Define Port Interfaces
Between Components” on page 3-2.

Run Simulation Using Logical Architecture

Once behavior models are linked, you can simulate the architecture model just like any other
Simulink model by clicking Run. Simulation verifies requirements such as Transportation,
Collision Avoidance, and Path Generation.

sim scMobileRobotLogicalArchitecture;

The scope from the MotorController component behavior shows how a simple P-gain controller
performs to follow the reference velocity for one of the wheels on the robot.

5-65
5 Define Architectural Properties

In the Mechanics Explorer (Simscape Multibody), switch to the isometric view by selecting .
Watch the mobile robot avoid an obstacle.

5-66
Simulate Architectural Behavior for Mobile Robot

References
[1] Rahman, Mohd Azizi Abdul, Katsuhiro Mayama, Takahiro Takasu, Akira Yasuda, and Makoto
Mizukawa. “Model-Driven Development of Intelligent Mobile Robot Using Systems Modeling
Language (SysML).” In Mobile Robots: Control Architectures, Bio-Interfacing, Navigation,
Multi Robot Motion Planning and Operator Training, edited by Janusz Będkowski. InTech
Open, 2011. https://doi.org/10.5772/26906.

See Also
createSimulinkBehavior

More About
• “Define Port Interfaces Between Components” on page 3-2
• “Explore Simulink Bus Capabilities”
• “Implement Component Behavior Using Simulink” on page 7-2
• “System Composer Concepts”

5-67
5 Define Architectural Properties

Change Stereotypes Based on Stereotype Hierarchy in


Portable Blender Architecture

This example shows how to change stereotypes to higher levels of the stereotype hierarchy in a
portable blender architecture in System Composer™. Stereotypes that are in a hierarchy inherit
properties from base stereotypes. Start by applying a generalized stereotype, then change to a
deeper stereotype in the hierarchy to further specify the component.

Open Architecture Model and Import Profile into Model

Open the simpleBlender model or enter this code into the Command Window.

archModel = systemcomposer.openModel("simpleBlender");

This model shows the hardware architecture of a simple portable blender, with the top-level
components that represent physical components to manufacture the blender. Ports represent power
sockets that send and receive power to and from these components.

5-68
Change Stereotypes Based on Stereotype Hierarchy in Portable Blender Architecture

Import the blenderProfile profile into the model. Click Profile Editor > Import on the Modeling
tab of the System Composer toolstrip or enter this code into the Command Window.

archModel.applyProfile("blenderProfile");

To view the contents of your imported profile, click Profile Editor to open the Profile Editor or enter
this code into the Command Window.

systemcomposer.profile.editor

In the Profile Editor, you can inspect the structure of the blenderProfile profile. The
BaseStereotype stereotype is the top-level stereotype. One level down is the HardwareComponent
stereotype that uses BaseStereotype as its base stereotype from which it inherits properties. The
PowerConsumer and PowerGenerator stereotypes inherit properties from the
HardwareComponent stereotype and are two levels down from the BaseStereotype stereotype.

Apply Stereotypes to All Components

To open the Apply Stereotypes dialog box, click Apply Stereotypes on the Modeling tab of the
System Composer toolstrip. Set Apply stereotype(s) to as Components. Set Scope as Entire
model. Select the blenderProfile.BaseStereotype stereotype.

5-69
5 Define Architectural Properties

To apply the BaseStereotype stereotype with a default value of 3 kg for the mass property to all
components, click Apply.

5-70
Change Stereotypes Based on Stereotype Hierarchy in Portable Blender Architecture

BaseStereotype now applies to the Housing component.

Change Stereotypes for Multiple Components in Model

Select the Housing component on the canvas. In the Property Inspector, click Select next to
BaseStereotype for the Housing component and select ↓
blenderProfile.HardwareComponent. The Housing component is now specified one-level
deeper in the BaseStereotype stereotype hierarchy to the HardwareComponent stereotype.

5-71
5 Define Architectural Properties

Further defining the Housing component as a hardware component adds the additional property,
material, which has a default value "titanium".

Double-click the Housing component to view the architecture within it. Select the Battery, Output
Shaft, and Blade Assembly components by clicking each of them while pressing Shift. Then,
right-click the Battery component, and select Change Stereotype, then select the ↓
blenderProfile.HardwareComponent stereotype from the list. The HardwareComponent
stereotype is now applied to these three components.

5-72
Change Stereotypes Based on Stereotype Hierarchy in Portable Blender Architecture

Deselect all components by clicking once in the model canvas. Right-click the Battery component
and select Change Stereotype, then select the ↓ blenderProfile.PowerGenerator stereotype.
Repeat for the Output Shaft and Blade Assembly components, but select the ↓
blenderProfile.PowerConsumer stereotype instead.

5-73
5 Define Architectural Properties

In the Property Inspector, you can now specify the powerIn and powerOut properties for the
Battery, Output Shaft, and Blade Assembly components as necessary.

See Also
Tools
Profile Editor | Manage Profiles

Blocks
Component | Reference Component | Variant Component

Objects
systemcomposer.profile.Profile | systemcomposer.profile.Stereotype |
systemcomposer.profile.Property

Functions
systemcomposer.profile.Profile.createProfile | systemcomposer.loadProfile |
applyProfile | removeProfile | renameProfile | systemcomposer.profile.editor |
systemcomposer.profile.Profile.find | systemcomposer.profile.Profile.load | save
| open | close | systemcomposer.profile.Profile.closeAll |
systemcomposer.profile.Stereotype.find | getDefaultStereotype |
setDefaultStereotype | getDefaultElementStereotype | setDefaultElementStereotype
| addStereotype | removeStereotype | getStereotype | applyStereotype |
batchApplyStereotype | getStereotypes | changeStereotype | removeStereotype |
hasStereotype | addProperty | removeProperty | hasProperty | setProperty |
getProperty | getPropertyValue | getEvaluatedPropertyValue |
getStereotypeProperties | applyStereotypeOrder | getStereotypeNamesByOrder |
increaseStereotypeOrder | decreaseStereotypeOrder

More About
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Analyze Architecture” on page 9-2
• “Change Stereotype Order Using Manage Profiles Tool” on page 5-31
• “Create and Manage Allocations Programmatically” on page 8-11
• “Apply Stereotypes to Functions of Software Architectures” on page 10-32

5-74
6

Describe System Behavior with


Diagrams

• “Describe System Behavior Using Sequence Diagrams” on page 6-2


• “Author Sequence Diagrams Interactively” on page 6-5
• “Author Sequence Diagrams to Co-Create Architecture Models” on page 6-19
• “Author Sequence Diagram Fragments” on page 6-35
• “Synchronize Sequence Diagrams and Architecture Models” on page 6-46
• “Simulate Sequence Diagrams for Traffic Light Example” on page 6-51
• “Author and Simulate Basic Colors Sequence Diagram with Enumerations” on page 6-72
• “Describe System Behavior Using Activity Diagrams” on page 6-75
• “Author Activity Diagrams” on page 6-78
• “Simulate, Visualize, and Validate Activity Diagrams” on page 6-91
6 Describe System Behavior with Diagrams

Describe System Behavior Using Sequence Diagrams


You can use sequence diagrams integrated with System Composer to describe system behaviors as
the interaction between components in a sequence of message exchanges. While designing your
system, use sequence diagrams as a planning tool to envision your system and later validate that your
system works as designed.

These concepts are relevant for authoring sequence diagrams:

• A sequence diagram represents the expected interaction between structural elements of an


architecture as a sequence of message exchanges.

Use sequence diagrams to describe how the parts of a system interact.


• A lifeline is represented by a head and a timeline that proceeds down a vertical dotted line.

The head of a lifeline represents a component in an architecture model.


• A message sends information from one lifeline to another. Messages are specified with a message
label.

A message label has a trigger and a constraint. A trigger determines whether the message occurs.
A constraint determines whether the message is valid.
• A gate in a sequence diagram represents the root architecture of the corresponding architecture
model.

Connect messages to gates to represent architecture ports.


• An annotation describes the elements of a sequence diagram.

Use annotations to provide detailed explanations of elements or workflows captured by sequence


diagrams.
• A fragment indicates how a group of messages specified within execute or interact.

A fragment is used to model complex sequences, such as alternatives, in a sequence diagram.


• An operand is a region in a fragment. Fragments have one or more operands depending on the
kind of fragment. Operands can contain messages and additional fragments.

Each operand can include a constraint to specify whether the messages inside the operand
execute. You can express the precondition of an operand as a MATLAB Boolean expression using
the input signal of a lifeline.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Sequence diagrams are integrated with architecture models in System Composer. The table lists
topics about using sequence diagrams.

Topic Description
“Author Sequence Diagrams Interactively” on Interactively create and edit a sequence diagram
page 6-5 and learn terminology.

6-2
Describe System Behavior Using Sequence Diagrams

Topic Description
“Author Sequence Diagram Fragments” on page Learn how to implement fragments and more
6-35 about fragment semantics.
“Author Sequence Diagrams to Co-Create Create and use sequence diagrams with
Architecture Models” on page 6-19 architecture models.
“Synchronize Sequence Diagrams and Learn how to synchronize sequence diagrams
Architecture Models” on page 6-46 with architecture models.
“Simulate Sequence Diagrams for Traffic Light Simulate a sequence of message exchanges as
Example” on page 6-51 interactions between lifelines.
“Author and Simulate Basic Colors Sequence Author and simulate a sequence diagram
Diagram with Enumerations” on page 6-72 containing a basic colors enumeration class.

Create a sequence diagram in the Architecture Views Gallery by clicking New > Sequence
Diagram.

See Also
Tools
Architecture Views Gallery | Sequence Viewer

Functions
openViews | sim | getInteraction | getInteractions | open | next | current | reset

Objects
systemcomposer.arch.Model | systemcomposer.interaction.Interaction |
systemcomposer.interaction.Iterator | systemcomposer.interaction.Lifeline |
systemcomposer.interaction.MessageEvent | systemcomposer.interaction.FormalGate
| systemcomposer.interaction.Message | systemcomposer.interaction.Fragment |

6-3
6 Describe System Behavior with Diagrams

systemcomposer.interaction.RootFragment |
systemcomposer.interaction.AltFragment | systemcomposer.interaction.OptFragment
| systemcomposer.interaction.LoopFragment |
systemcomposer.interaction.SeqFragment |
systemcomposer.interaction.StrictFragment |
systemcomposer.interaction.ParFragment | systemcomposer.interaction.Operand |
systemcomposer.interaction.Annotation | Simulink.SimulationInput |
Simulink.SimulationOutput

More About
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Compose Architectures Visually” on page 1-5
• “Define Port Interfaces Between Components” on page 3-2
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Implement Component Behavior Using Simscape” on page 7-23

6-4
Author Sequence Diagrams Interactively

Author Sequence Diagrams Interactively


You can create, edit, and simulate sequence diagrams in System Composer by accessing the
Architecture Views Gallery. Sequence diagrams describe operational system behavior. Use a sequence
diagram to validate an expected sequence of events as system design proceeds. You will learn about
the basic terminology and functions of a sequence diagram:

• Add lifelines and messages with message labels including triggers and constraints to represent
interactions.
• Include fragments and operands with constraints to further specify the behavior of the interaction.

A lifeline in a sequence diagram represents a component in the architecture. A message represents a


communication across a path between the source lifeline and destination lifeline. The path for a
message must consist of at least two ports and one connector from the architecture model. With
nested messages, the path is more complex due to the hierarchy to be navigated.

For a roadmap of the sequence diagram topics, see “Describe System Behavior Using Sequence
Diagrams” on page 6-2.

Traffic Light Architecture Model and Sequence Diagram


This figure shows a traffic light architecture model and a corresponding sequence diagram that
describes one operative scenario. The traffic light model describes a cycling traffic light, the
pedestrian crossing button being pressed, and the lights changing so pedestrians can cross.

6-5
6 Describe System Behavior with Diagrams

To learn how to execute this sequence diagram to simulate the model, see “Simulate Sequence
Diagrams for Traffic Light Example” on page 6-51.

Note This example uses Stateflow blocks. If you do not have a Stateflow license, you can open and
simulate the model but can only make basic changes, such as modifying block parameters.

To access the example files, open the example below.

Traffic Light Example

6-6
Author Sequence Diagrams Interactively

This traffic light example contains sequence diagrams to describe pedestrians crossing an
intersection. The model describes these steps:

1 The traffic signal cycles from red to green to yellow.


2 When the pedestrian crossing button is pressed, if the traffic signal is green, the traffic signal
transitions from yellow to red for a limited time.
3 The pedestrians cross while the walk signal is active.

Open the System Composer model that contains the sequence diagrams.

model = systemcomposer.openModel('TLExample');

Open the Architecture Views Gallery to view the sequence diagrams.

openViews(model)

Add Lifelines and Messages


A lifeline is represented by a head and a timeline that proceeds down a vertical dotted line.

The head of a lifeline represents a component in an architecture model.

A message sends information from one lifeline to another. Messages are specified with a message
label.

1 Navigate to Modeling > Sequence Diagram to open sequence diagrams in the Architecture
Views Gallery.
2 To create a new sequence diagram, click New > Sequence Diagram.
3 A new sequence diagram called SequenceDiagram1 is created in the View Browser, and the
Sequence Diagram tab becomes active. Under Sequence Diagram Properties, rename the
sequence diagram Inhibit.
4 Select Component > Add Lifeline to add a lifeline. A new lifeline with no name is created and
is indicated by a dotted line.

6-7
6 Describe System Behavior with Diagrams

5 Click the down arrow and select source. The source lifeline detects when the pedestrian
presses the crossing button. Add four more lifelines using the down arrow named poller,
switch, controller, and lampController. The poller lifeline checks if the pedestrian
crossing button has been pressed, switch processes the signal, controller determines which
color the pedestrian lamp and traffic light should display, and lampController changes the
traffic light colors.

6 Draw a line from the source lifeline to the poller lifeline. Start to type sw in the To box, which
will automatically fill in as you type. Once the text has filled in, select sw.

6-8
Author Sequence Diagrams Interactively

Since the switchout port and sw port are connected in the model, a message is created from
the switchout port to the sw port in the sequence diagram.
7 A message label has a trigger and a constraint. A trigger determines whether the message
occurs. A constraint determines whether the message is valid.

An informal message label is written in natural language. A formal message label is in the form of
trigger[constraint] where trigger represents the identifying event for this message, and
constraint represents additional expressions that are expected to be true when this message
occurs.

• For signal-based communication, a trigger is also called an edge and can described in the
format direction(signal [+|-] value). You can enter a condition that specifies a
triggering edge with a direction and an expression. The direction can be:

• rising — The edge expression is rising from strictly below zero to a value equal to or
greater than zero.
• falling — The edge expression is falling from strictly above zero.
• crossing — The edge expression is either rising or falling past zero.
• For message-based communication, a trigger can be described simply by using the name of
the input message port, and represents the arrival of a message.
• For both signal and message-based communication, a constraint expression in square
brackets on the message label is an optional MATLAB Boolean expression involving the names
of the inputs to the destination lifeline.

Click on the message and double-click on the empty message label that appears. Enter this
condition and constraint.

rising(sw-1)[sw==1]

The message will be triggered when the sw signal rises from below 1 to a value of 1 or above.
The constraint in square brackets indicates that if sw is not equal to 1, the message is invalid.

6-9
6 Describe System Behavior with Diagrams

Note Only destination elements are supported for message labels. In this example, switchout
is a source element and cannot be included.

The signal name sw is valid input data on the port for a Stateflow chart behavior. The poller
component with state chart behavior has sw in the Symbols pane.

Note The signal name can also be a data element on a data interface on a port. Enter Tab to
autocomplete the port and data element names. For more information, see “Represent System
Interaction Using Sequence Diagrams”.

6-10
Author Sequence Diagrams Interactively

In this example, when the sw signal becomes 1, the pedestrian crossing button has been pressed,
and a message to the poller lifeline is recognized.
8 In addition to signal-based communication, sequence diagrams also support message-based
communication, or message events. Create a message by drawing a line from the poller lifeline
to the switch lifeline. Start typing switchEvent in the To box until switchEvent is available
to select.

Since there is an existing connection in the architecture model, a message is created from source
port switchEvent.
9 Click the message and double-click the empty message label that appears. Enter this condition
representing the port and constraint.

switchEvent[switchEvent==1]

6-11
6 Describe System Behavior with Diagrams

When the message event switchEvent is received and its value is 1, the message has occurred
in the corresponding architecture model and validates the architectural design.

Add Fragments and Operands


A fragment indicates how a group of messages specified within execute or interact.

A fragment is used to model complex sequences, such as alternatives, in a sequence diagram.

An operand is a region in a fragment. Fragments have one or more operands depending on the kind
of fragment. Operands can contain messages and additional fragments.

Each operand can include a constraint to specify whether the messages inside the operand execute.
You can express the precondition of an operand as a MATLAB Boolean expression using the input
signal of a lifeline.

To access the menu of fragments:

1 Click and drag to select two messages.

6-12
Author Sequence Diagrams Interactively

2 Pause on the ellipsis (...) that appears to access the action bar.

3 A list of fragments appears:

• Alternative (“Alt Fragment” on page 6-41)


• Optional (“Opt Fragment” on page 6-38)
• Loop (“Loop Fragment” on page 6-39)
• Weak sequencing (“Seq Fragment” on page 6-36)
• Strict sequencing (“Strict Fragment” on page 6-37)
• Parallel (“Par Fragment” on page 6-42)

For more information, see “Author Sequence Diagram Fragments” on page 6-35.

6-13
6 Describe System Behavior with Diagrams

Select the “Alt Fragment” on page 6-41 fragment.

4 The “Alt Fragment” on page 6-41 fragment is added to the sequence diagram with a single
operand that contains the selected messages.

6-14
Author Sequence Diagrams Interactively

5 Select the fragment to enter an operand condition. Choose a fully qualified name for input data
and use a constraint condition relation.

switch/inhibit==0

This constraint is a precondition that determines when the operand is active. This constraint
specifies that the inhibit flag is set to 0. Thus, pedestrian crossing is allowed at this
intersection using a pedestrian lamp.

6-15
6 Describe System Behavior with Diagrams

The messages inside an operand can only be executed if the constraint condition is true.
6 Highlight the first operand under the “Alt Fragment” on page 6-41 fragment and select from the
toolstrip Fragment > Add Operand > Insert After. A second operand is added.

Add a constraint condition relation to the second operand. The second operand in an “Alt
Fragment” on page 6-41 fragment represents an elseif condition for which the message will
be executed.

switch/inhibit==1

This constraint represents when the inhibit flag is set to 1. Thus, pedestrian crossing is not
controlled by a walk signal on that intersection.

Create a message with a message label inside the second operand.

6-16
Author Sequence Diagrams Interactively

For the first operand in the “Alt Fragment” on page 6-41 fragment, since the inhibit flag is set
to 0, the first message to the controller lifeline is recognized and validates the pedRequest
message. Then, when the switchPed message value is 1, the lampController component
behavior allows pedestrians to cross.

For the second operand in the “Alt Fragment” on page 6-41 fragment, since the inhibit flag is
set to 1, the switch bypasses the controller. The message switchPed with a value of 2 goes
directly to the lampcontroller which does not affect the traffic signal. Pedestrian crossing is
not specifically supported in this traffic intersection.

See Also
Tools
Architecture Views Gallery | Sequence Viewer

Functions
openViews | sim | getInteraction | getInteractions | open | next | current | reset

Objects
systemcomposer.arch.Model | systemcomposer.interaction.Interaction |
systemcomposer.interaction.Iterator | systemcomposer.interaction.Lifeline |
systemcomposer.interaction.MessageEvent | systemcomposer.interaction.FormalGate

6-17
6 Describe System Behavior with Diagrams

| systemcomposer.interaction.Message | systemcomposer.interaction.Fragment |
systemcomposer.interaction.RootFragment |
systemcomposer.interaction.AltFragment | systemcomposer.interaction.OptFragment
| systemcomposer.interaction.LoopFragment |
systemcomposer.interaction.SeqFragment |
systemcomposer.interaction.StrictFragment |
systemcomposer.interaction.ParFragment | systemcomposer.interaction.Operand |
systemcomposer.interaction.Annotation | Simulink.SimulationInput |
Simulink.SimulationOutput

More About
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Compose Architectures Visually” on page 1-5
• “Define Port Interfaces Between Components” on page 3-2
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Implement Component Behavior Using Simscape” on page 7-23

6-18
Author Sequence Diagrams to Co-Create Architecture Models

Author Sequence Diagrams to Co-Create Architecture Models


You can author sequence diagrams to describe expected system behavior as a sequence of
interactions between components of a System Composer architecture model. Lifelines correspond to
components in an architecture model, and messages correspond to the connectors between the
components. You can create multiple sequence diagrams to represent different operational scenarios
of the system. Sequence diagrams are integrated into the Architecture Views Gallery in System
Composer.

For a roadmap of the sequence diagram topics, see “Describe System Behavior Using Sequence
Diagrams” on page 6-2.

This traffic light example will show you how to:

• Create a sequence diagram.


• Add child lifelines in a sequence diagram.
• Interact with root architecture ports in a sequence diagram using gates.
• Co-create components and keep the architecture model and the sequence diagram in sync.
• Create messages in a sequence diagram.
• Use the model browser to add components.
• Link elements of a sequence diagram to requirements.

Note This example uses Stateflow blocks. If you do not have a Stateflow license, you can open and
simulate the model but can only make basic changes, such as modifying block parameters.

Traffic Light Example with Hierarchy for Sequence Diagrams

This traffic light example contains sequence diagrams to describe pedestrians crossing an
intersection. The model describes these steps:

1 The traffic signal cycles from green to yellow to red.


2 When the pedestrian crossing button is pressed, if the traffic signal is green, the traffic signal
transitions from yellow to red for a limited time.
3 The pedestrians cross while the walk signal is active.

Open the System Composer model that contains the sequence diagrams.

model = systemcomposer.openModel("TrafficLight");

Open the Architecture Views Gallery to view the sequence diagrams.

openViews(model)

The sequence diagram in this example represents an operative scenario in the architecture model.

InputPollNested sequence diagram: When the poller recognizes a signal event as inValue rises
to 1, the pedestrian crossing button is pressed. Next, the switch lifeline recognizes a signal event to
lampcontroller as switchPed rises to 1, which activates the pedestrian crossing signal.

6-19
6 Describe System Behavior with Diagrams

Create Sequence Diagram


Use an architecture model in System Composer to represent how a traffic light system operates.

1 Navigate to Modeling > Sequence Diagram to open sequence diagrams in the Architecture
Views Gallery.
2 To create a new sequence diagram, click New > Sequence Diagram.
3 In Sequence Diagram Properties on the right, enter the name PedLoop.
4 Select Component > Add Lifeline from the menu. A box with a vertical dotted line appears on
the canvas. This is the new lifeline.
5 Click the down arrow on the lifeline to view available options. Select the component named
lampSubsystem to be represented by the lifeline.

6-20
Author Sequence Diagrams to Co-Create Architecture Models

Add Child Lifelines to Sequence Diagram


You can add child lifelines to a sequence diagram to represent model hierarchy and describe the
interactions between lifelines.

1 From the menu, select Component > Add Lifeline. From the list that appears, select the
Controller component.

2 Child components called lampcontroller and controller are located inside the
lampSubsystem and Controller components, respectively.

6-21
6 Describe System Behavior with Diagrams

3 Select the lampSubsystem lifeline. Navigate to Component > Add Lifeline > Add Child
Lifeline. Select lampcontroller. The lampcontroller child lifeline is now situated below
lampSubsystem in the hierarchy.
4 Repeat these steps for the Controller lifeline to add the controller child lifeline.

6-22
Author Sequence Diagrams to Co-Create Architecture Models

Create Sequence Diagram Gates


A gate in a sequence diagram represents the root architecture of the corresponding architecture
model.

Connect messages to gates to represent architecture ports.

1 Select the lampcontroller lifeline, then click and drag it to the gutter region. Start typing
tSwitch into the To box and select tSwitch from the list. See that a gate called tSwitch has
been created with a message from the lampcontroller lifeline at the port tSwitch.

6-23
6 Describe System Behavior with Diagrams

2 Return to the architecture diagram. Observe that tSwitch is a root architecture port connected
to the lampcontroller component in the hierarchy through the lampSubsystem component.

Co-Create Components
The co-creation workflow between the sequence diagram and the architecture model keeps the model
synchronized as you make changes to the sequence diagram. Adding both lifelines and messages in a
sequence diagram results in updates to the architecture model. This example shows component co-
creation.

1 From the toolstrip menu, select Component > Add Lifeline. Another box with a vertical dotted
line appears on the canvas to represent a lifeline. In the box, enter the name of a new component
named Machine.

2 Observe that the Machine component is co-created in the architecture diagram.

6-24
Author Sequence Diagrams to Co-Create Architecture Models

Synchronize Sequence Diagram and Model


1 Remove the Machine component from the architecture diagram.
2 Return to the sequence diagram and select Synchronize > Check Consistency. See that the
Machine lifeline is highlighted, as it does not correspond to a component.

3 To restore consistency, either remove the Machine lifeline or click Undo in the architecture
model to restore the Machine component.
4 Click Check Consistency again.

For advanced sequence diagram synchronization techniques, see “Synchronize Sequence Diagrams
and Architecture Models” on page 6-46.

Create Messages in Sequence Diagram


You can create a message from an existing connection.

1 Draw a line from the controller lifeline to the lampcontroller lifeline. Start to type
traffic in the To box, which fills in automatically as you type. Once the text fills in, select
traffic.

6-25
6 Describe System Behavior with Diagrams

2 Since the trafficColor port and traffic port are connected in the model, a message is
created from the traffic port to the trafficColor port in the sequence diagram.

3 You can modify the source and destination of a message after the message has been created.
Click the trafficColor message end to select it.

6-26
Author Sequence Diagrams to Co-Create Architecture Models

4 Click and drag the trafficColor message end to the Controller parent lifeline, then select
the trafficColor port.

5 Once the trafficColor port is selected, the message end moves from the controller child
lifeline to the Controller parent lifeline.

6-27
6 Describe System Behavior with Diagrams

You can also rename message ends and the associated ports by double-clicking the name of a
message end.

Modify Sequence Diagram Using Model Browser


1 The Views Gallery model browser located on the bottom left of the canvas is called Model
Components. Click and drag the switch child component into the sequence diagram.

2 The sequence diagram is updated with a new lifeline.

6-28
Author Sequence Diagrams to Co-Create Architecture Models

3 Click and drag to reorder the lampSubsystem and the Controller lifelines.

Use Annotations to Describe Elements of Sequence Diagram


An annotation describes the elements of a sequence diagram.

Use annotations to provide detailed explanations of elements or workflows captured by sequence


diagrams.

You can add plain-text annotations to a sequence diagram to describe elements, such as lifelines,
messages, and fragments.

To create an annotation, double-click the canvas at the desired location. Then, enter the annotation
text in the text box that appears on the canvas.

6-29
6 Describe System Behavior with Diagrams

Press Esc or click anywhere outside the text box to apply the changes.

Create Sequence Diagram from View


1 In the MATLAB Command Window, enter scKeylessEntrySystem. The architecture model
opens in the Simulink Editor.
2 To open the Architecture Views Gallery for the model, navigate to Modeling > Views >
Architecture Views.
3 Right-click the Sound System Supplier Breakdown view and select New Sequence
Diagram.

6-30
Author Sequence Diagrams to Co-Create Architecture Models

4 A new sequence diagram of lifelines is created with all the components from the view.

Link Elements of Sequence Diagram to Requirements


You can link a sequence diagram as a whole or individual elements of a sequence diagram to
requirements in the Architecture Views Gallery. A Requirements Toolbox license is required.
1 On the Views tab, in the Requirement section, click Open Requirements Editor to open the
Requirements Editor. From here, you can author requirements, create requirement sets, and
organize requirements into hierarchies.
2 With the Requirements Editor open, select the sequence diagram element that you want to link
to a requirement. To select a lifeline, gate, fragment, or message, click the element on the
sequence diagram canvas. To select the sequence diagram as a whole, click the name of the
sequence diagram in the View Browser pane.
3 In the Requirements Editor, click the requirement that you want to link the selected sequence
diagram element to.

6-31
6 Describe System Behavior with Diagrams

4 You can link from the selected sequence diagram element to the requirement in three ways.

• In the Architecture Views Gallery, on the Views tab, in the Requirement section, click Link
to selected requirement.
• In the Requirements Editor, right-click the selected requirement and click Link from for the
specific sequence diagram element.
• In the Requirements Editor, click Add Link and select Link from for the specific sequence
diagram element.

Note In a sequence diagram, links from lifelines and gates to requirements connect to the
respective elements in the underlying architecture diagram. This type of link is called an
implemented link. If you delete an architecture diagram element corresponding to a lifeline or
gate, then the option to link a requirement from this element is disabled. If you delete an element
after linking to a requirement, then the link is invalid.

On the other hand, requirement links from sequence diagrams, messages, and fragments link
locally to the respective element in the sequence diagram. This type of link is a verified link.

To view the requirements linked from sequence diagram elements, select a particular element on the
sequence diagram canvas and click Requirements Manager in the Requirement section of the
Views tab. The requirements linked from the selected element are listed in the Requirement Links
pane that appears at the bottom of the window.

6-32
Author Sequence Diagrams to Co-Create Architecture Models

If the Requirements Manager button is selected, gray badges appear over sequence diagram
elements that are linked to requirements. To display the corresponding requirement ID and the
requirement Summary text, point to the badge.

To view these requirements in the Requirements Editor, point to the requirements in the
Requirement Links pane and click the Show in Links View button. You can delete requirement
links from sequence diagram elements by pausing your cursor on the requirement name, and clicking
the Delete Link button.

6-33
6 Describe System Behavior with Diagrams

See Also
Tools
Architecture Views Gallery | Sequence Viewer

Functions
openViews | sim | getInteraction | getInteractions | open | next | current | reset

Objects
systemcomposer.arch.Model | systemcomposer.interaction.Interaction |
systemcomposer.interaction.Iterator | systemcomposer.interaction.Lifeline |
systemcomposer.interaction.MessageEvent | systemcomposer.interaction.FormalGate
| systemcomposer.interaction.Message | systemcomposer.interaction.Fragment |
systemcomposer.interaction.RootFragment |
systemcomposer.interaction.AltFragment | systemcomposer.interaction.OptFragment
| systemcomposer.interaction.LoopFragment |
systemcomposer.interaction.SeqFragment |
systemcomposer.interaction.StrictFragment |
systemcomposer.interaction.ParFragment | systemcomposer.interaction.Operand |
systemcomposer.interaction.Annotation | Simulink.SimulationInput |
Simulink.SimulationOutput

More About
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Compose Architectures Visually” on page 1-5
• “Define Port Interfaces Between Components” on page 3-2
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Implement Component Behavior Using Simscape” on page 7-23

6-34
Author Sequence Diagram Fragments

Author Sequence Diagram Fragments


A sequence diagram describes an expected order of the events logged during execution of a Simulink
model. There are four event types:

1 Signal read
2 Signal write
3 Message send
4 Message receive

These four events cover the two interaction styles described by sequence diagrams: signal-based and
Simulink message-based. You can specify events in a sequence diagram using messages between
lifelines. Each sequence diagram message describes a pair of events. For signal-based
communication, the pair of events is write followed by read. For message-based communication, the
pair of events is send followed by receive.

To learn more about simulating sequence diagrams, see “Simulate Sequence Diagrams for Traffic
Light Example” on page 6-51.

A fragment indicates how a group of messages specified within execute or interact.

A fragment is used to model complex sequences, such as alternatives, in a sequence diagram.

To add a fragment to a sequence diagram, click and drag around a group of messages or other
fragments. A blue box appears. Pause on the ellipsis (…) menu to select from a list of possible
fragments.

The fragment you select is added in the sequence diagram. For more information, see “Add
Fragments and Operands” on page 6-12.

For a roadmap of the sequence diagram topics, see “Describe System Behavior Using Sequence
Diagrams” on page 6-2.

Sequence Diagram Fragments

This example shows an intersection control system to demonstrate how composite fragments are
used in sequence diagrams.

Open the System Composer™ model that contains the sequence diagrams.

model = systemcomposer.openModel("IntersectionControlSystemS");

6-35
6 Describe System Behavior with Diagrams

Open the Architecture Views Gallery to view the sequence diagrams.

openViews(model)

Fragment Semantics
Fragments in a sequence diagram execute messages in a specific order based on the kind of
fragment. The following fragments are supported:

• Alternative (“Alt Fragment” on page 6-41)


• Optional (“Opt Fragment” on page 6-38)
• Loop (“Loop Fragment” on page 6-39)
• Weak sequencing (“Seq Fragment” on page 6-36)
• Strict sequencing (“Strict Fragment” on page 6-37)
• Parallel (“Par Fragment” on page 6-42)

An operand is a region in a fragment. Fragments have one or more operands depending on the kind
of fragment. Operands can contain messages and additional fragments.

Each operand can include a constraint to specify whether the messages inside the operand execute.
You can express the precondition of an operand as a MATLAB Boolean expression using the input
signal of a lifeline.

Seq Fragment

The Seq fragment contains one operand and represents weak sequencing. The Seq fragment
specifies the same ordering constraints as a sequence of messages with no fragment.

Weak sequencing means that the sequence of events on each lifeline is respected, but the sequencing
of events between lifelines can differ from the order shown in the operand.

6-36
Author Sequence Diagram Fragments

• On any given lifeline, any event must occur after the event immediately above it on the lifeline. If
a message send or write event occurs from the same lifeline, the order is determined by from how
far down the lifeline the event occurs.
• The send or write event for a message must occur before the corresponding receive or read event.
• If two different message send and receive events or write and read events occur on the same
lifeline, then the first message can be received before or after the second message is sent.

This sequence diagram specifies that after the sensor signal from its hardware interface rises
through 1, the MainStreetController sends a PedButtonMain Simulink message to
LightSequencer, which controls the intersection. LightSequencer then tells the hardware
interface to turn the pedestrian lamp red, indicating that pedestrians should wait.

Strict Fragment

The Strict fragment contains one operand and represents strict sequencing.

Strict sequencing follows the weak sequencing found in a “Seq Fragment” on page 6-36 with the
additional constraint that the order of the events in the operand be followed exactly. If messages are
sent from the same lifeline, the order is determined by how far down the lifeline they are sent.
Messages are received in the order on the operand regardless of which lifeline receives them.

6-37
6 Describe System Behavior with Diagrams

This sequence diagram is an example of strict sequencing for an intersection controller. The traffic
lights on the side street should be set to red before the traffic lights on the main street are set to
green. Without strict sequencing, the order in which the street controllers perform their tasks would
be undefined.

You can use the “Seq Fragment” on page 6-36 for a subset of the messages in a Strict fragment if
all the messages do not require strict ordering.

Opt Fragment

The Opt fragment includes a single operand and indicates that the events described might occur or
not. A constraint determines whether the group of messages are valid. If the group of messages are
valid, they can execute, otherwise, this fragment is skipped. If no constraint is specified, the
messages in the Opt fragment are executed only if the messages become valid.

The events in an Opt fragment occur if all of these conditions are met:

• The current event is a valid first event for the operand.


• The condition expressed by the operand constraint evaluates to true.

6-38
Author Sequence Diagram Fragments

In this sequence diagram, the LightSequencer knows the state of each controller due to the state
signal. The LightSequencer issues a Stop command to a controller if it is in the flowing (Green)
state, which is indicated by the value 2. The operand in the Opt fragment is executed only if a Stop
command is present and its mainState signal has the value 2. After the Stop command, the
mainState signal falls to 1, indicating a stopping (Yellow) state.

Loop Fragment

A Loop fragment has a single operand with a constraint and an expression describing the minimum
(lower bound) and maximum (upper bound) number of times that the operand repeats. The upper
bound can be *, indicating that there is no maximum. The lower bound can be 0, indicating that the
operand is optional. The default is a lower bound of 0 and an upper bound of *. With the default
lower and upper bounds, the Loop fragment repeats a certain number of times according to the
simulation time or the lower and upper bounds of the architecture model.

6-39
6 Describe System Behavior with Diagrams

The single operand in the Loop fragment repeats if all of these conditions are met:

• The current event is a valid first event for the operand.


• The condition expressed by the operand constraint evaluates to true.
• The number of iterations is less than or equal to the upper bound.

The lower bound (1) is the minimum number of iterations of the loop. The upper bound (3) is the
maximum. You can also define a constraint on a Loop fragment operand that determines whether the
loop executes. When the Boolean expression is false, the loop is skipped.

6-40
Author Sequence Diagram Fragments

This sequence diagram describes the default cycle of the main street traffic lamps. The
LightSequencer issues a Go command so that the MainStreetController tells the
MainHWInterface to turn the green lamps on. The controller then cycles the lights repeatedly
through yellow, red, and green lamps, as indicated by the Loop fragment. The lower and upper
bounds of the loop fragment are the default values of 0 and *, respectively, indicating that it allows
any number of iterations.

Alt Fragment

The Alt fragment is like an “Opt Fragment” on page 6-38 except that it has two or more operands,
each describing a different message order.

The events for each operand in an Alt fragment occur if all of these conditions are met:

• The current event is a valid first event for the operand.

6-41
6 Describe System Behavior with Diagrams

• The condition expressed by the operand constraint evaluates to true.

This sequence diagram shows that there are crossing buttons on the main street and the side street
and either may be pressed. For a description of the first operand, see the sequence diagram for the
“Seq Fragment” on page 6-36.

Par Fragment

Par stands for parallel. A Par fragment can have two or more operands. In a Par fragment, the order
of events in each operand is enforced, but there is no constraint on the order of events in different
operands. You should use Par fragments wherever order between messages is not important because
this fragment imposes few constraints on system design.

6-42
Author Sequence Diagram Fragments

6-43
6 Describe System Behavior with Diagrams

No matter which crossing button the pedestrian presses, the controller stops traffic on both streets.
This sequence diagram specifies this state using an Alt fragment for the red lamp color. The green
light that indicates safety in crossing, is shown on both streets. The Par fragment indicates that both
the main and side streets show the green color, but order does not matter.

Messages with Ambiguous Order

Due to the nature of signal semantics in block diagrams, predicting the ordering between signal
edges and other events that occur in the same simulation step can be difficult. Signal edges are
where a signal value passes through a threshold indicated by the rising, falling, or crossing keywords.
Small changes to the architecture model can change the order of signal events represented by
sequence diagrams. When a signal edge occurs in the same simulation step as another event, both
messages are marked with an symbol. You can examine both the sequence diagram and
underlying architecture model for potential ambiguity.

To specify that these messages may occur in any order within the same time step, place each
message in separate operands of a “Par Fragment” on page 6-42. The simulation interprets these
messages to occur in any order. Alternatively, change the behavior of the underlying system so these
events happen on different time steps.

See Also
Tools
Architecture Views Gallery | Sequence Viewer

6-44
Author Sequence Diagram Fragments

Functions
openViews | sim | getInteraction | getInteractions | open | next | current | reset

Objects
systemcomposer.arch.Model | systemcomposer.interaction.Interaction |
systemcomposer.interaction.Iterator | systemcomposer.interaction.Lifeline |
systemcomposer.interaction.MessageEvent | systemcomposer.interaction.FormalGate
| systemcomposer.interaction.Message | systemcomposer.interaction.Fragment |
systemcomposer.interaction.RootFragment |
systemcomposer.interaction.AltFragment | systemcomposer.interaction.OptFragment
| systemcomposer.interaction.LoopFragment |
systemcomposer.interaction.SeqFragment |
systemcomposer.interaction.StrictFragment |
systemcomposer.interaction.ParFragment | systemcomposer.interaction.Operand |
systemcomposer.interaction.Annotation | Simulink.SimulationInput |
Simulink.SimulationOutput

More About
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Compose Architectures Visually” on page 1-5
• “Define Port Interfaces Between Components” on page 3-2
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Implement Component Behavior Using Simscape” on page 7-23

6-45
6 Describe System Behavior with Diagrams

Synchronize Sequence Diagrams and Architecture Models

This example shows how to maintain consistency between sequence diagrams and an architecture
model.

Open the model.

model = systemcomposer.openModel("mRetargetElements");

Open the Architecture Views Gallery.

openViews(model)

Pull Changes from Architecture Model to Sequence Diagram

1. In the View Browser, select the RepairExample sequence diagram. Inspect the lifeline named
ChildComponent.

2. Return to the model canvas. Marquee select the ChildComponent component. Pause on the
ellipses (...) menu and select Create Subsystem. Specify the name of the new component as
Component. The ChildComponent component is now the child of the Component component.

3. Click Check Consistency on the sequence diagram RepairExample. The sequence diagram has
become inconsistent and the ChildComponent lifeline is highlighted because it is no longer at the
root level of the diagram.

6-46
Synchronize Sequence Diagrams and Architecture Models

4. Select the ChildComponent lifeline and, on the toolstrip, click Repair. The sequence diagram
RepairExample is updated after changes are pulled from the architecture model
mRetargetElements.

Push Changes from Sequence Diagram to Architecture Model

1. In the View Browser, select the CreateInArchitecture sequence diagram.

2. Marquee select the contents of the sequence diagram, including the two lifelines and the message.

6-47
6 Describe System Behavior with Diagrams

3. In the toolstrip, click Create in Architecture. The architecture model mRetargetElements is


updated after changes are pushed from the sequence diagram.

Retarget Lifeline and Create New Connection in Architecture Model

1. In the View Browser, select the RetargetThenCocreate sequence diagram.

2. Select the B lifeline on the sequence diagram and, from the Architecture Element menu, select C
from the list. The sequence diagram becomes inconsistent, and the message is highlighted.

6-48
Synchronize Sequence Diagrams and Architecture Models

3. Select the message and, in the toolstrip, click Create in Architecture. A new connection is
created in the architecture model mRetargetElements.

See Also
Tools
Architecture Views Gallery | Sequence Viewer

Functions
openViews | sim | getInteraction | getInteractions | open | next | current | reset

Objects
systemcomposer.arch.Model | systemcomposer.interaction.Interaction |
systemcomposer.interaction.Iterator | systemcomposer.interaction.Lifeline |
systemcomposer.interaction.MessageEvent | systemcomposer.interaction.FormalGate
| systemcomposer.interaction.Message | systemcomposer.interaction.Fragment |
systemcomposer.interaction.RootFragment |
systemcomposer.interaction.AltFragment | systemcomposer.interaction.OptFragment
| systemcomposer.interaction.LoopFragment |
systemcomposer.interaction.SeqFragment |
systemcomposer.interaction.StrictFragment |
systemcomposer.interaction.ParFragment | systemcomposer.interaction.Operand |
systemcomposer.interaction.Annotation | Simulink.SimulationInput |
Simulink.SimulationOutput

6-49
6 Describe System Behavior with Diagrams

More About
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Compose Architectures Visually” on page 1-5
• “Define Port Interfaces Between Components” on page 3-2
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Implement Component Behavior Using Simscape” on page 7-23

6-50
Simulate Sequence Diagrams for Traffic Light Example

Simulate Sequence Diagrams for Traffic Light Example

This demonstrates how to simulate a System Composer™ architecture model of a traffic light and
verify that the model simulation results match the interactions within the sequence diagrams of the
model. The example model uses blocks from Stateflow®. If you do not have a Stateflow license, you
can open and simulate the model but only make basic changes such as modifying block parameters.

This traffic light example uses sequence diagrams to describe the process of pedestrians crossing an
intersection.

1 The traffic signal cycles from red to green to yellow.


2 When the pedestrian crossing button is pressed, if the traffic signal is green, the traffic signal
transitions from yellow to red for a limited time.
3 The pedestrians cross while the walk signal is active.

Open the model.

model = systemcomposer.openModel("TLExample");

Open the Architecture Views Gallery to view the sequence diagrams.

openViews(model)

Simulate Inhibit Sequence Diagram

In the View Browser, select the Inhibit sequence diagram. For more information on how to
construct this sequence diagram, see “Author Sequence Diagrams Interactively” on page 6-5.

6-51
6 Describe System Behavior with Diagrams

To simulate the sequence diagram until the next message, select the Next Message option in the
toolstrip. When the message event switchEvent occurs, the switch lifeline activates.

6-52
Simulate Sequence Diagrams for Traffic Light Example

Select Continue to continue until the end. Since the inhibit flag is equal to 0, the first operand of
the Alt fragment activates. For more information on the Alt fragment, see “Author Sequence
Diagram Fragments” on page 6-35. The switch lifeline sends a message to the controller lifeline
to change the traffic lamp via the lampcontroller lifeline to stop traffic and allow the pedestrians
to cross the intersection.

6-53
6 Describe System Behavior with Diagrams

If the inhibit flag is set to 1, the switch lifeline bypasses the controller and sends the signal
directly to the lampcontroller lifeline. This action means that pedestrian crossing is not controlled
by a walk signal on this intersection.

Simulate PressDetection Sequence Diagram Programmatically

In the View Browser, select the PressDetection sequence diagram.

6-54
Simulate Sequence Diagrams for Traffic Light Example

Observe the PressDetection sequence diagram during model simulation using a


Simulink.SimulationInput object for the sim function. The ObservedSequenceDiagrams
model configuration parameter specifies which sequence diagram to simulate. You can
programmatically simulate only one sequence diagram at a time. To use sim to simulate a sequence
diagram, set ObservedSequenceDiagrams for the simulation.

simIn = Simulink.SimulationInput("TLExample");
simIn = setModelParameter(simIn,"ObservedSequenceDiagrams","PressDetection",...
"ObservedSequenceDiagramsOut","sequenceDiagramOutput");
simOut = sim(simIn);

ObservedSequenceDiagramsOut is a property of the Simulink.SimulationOutput object


captured in simOut. The object contains these properties:

• Name: Name of the sequence diagram being simulated.


• Completed: Whether the simulation was completed.
• NumErrors: Number of errors found, which counts the number of red exclamation marks next to
messages in your sequence diagram after simulation. The red marks indicate that the message
triggers were satisfied, but the constraints were not met.

For ease of use, you can rename the optional ObservedSequenceDiagramsOut parameter to
sequenceDiagramOutput, or any valid MATLAB® variable name.

sequenceDiagramOut = simOut.sequenceDiagramOutput

sequenceDiagramOut = struct with fields:


Name: 'PressDetection'
Completed: 1
NumErrors: 0

Messages where the trigger is satisfied and the constraints are met turn green with a check mark.
Since all message constraints are met, the number of errors is zero.

6-55
6 Describe System Behavior with Diagrams

When a pedestrian presses the crossing button, the value of the signal sw rises to 1. When this action
happens, the poller lifeline sends the message switchEvent to the switch lifeline. This action
alerts the switch lifeline that a pedestrian is waiting so the switch lifeline can alert the
controller lifeline. The traffic light then turns red to stop traffic, and the walk signal turns on.

Simulate PedestrianCross Sequence Diagram

In the View Browser, select the PedestrianCross sequence diagram.

6-56
Simulate Sequence Diagrams for Traffic Light Example

6-57
6 Describe System Behavior with Diagrams

To simulate the sequence diagram until the next message, select the Next Message option in the
toolstrip. The value of the message traffic is 1, which indicates that the traffic light color is red.

6-58
Simulate Sequence Diagrams for Traffic Light Example

6-59
6 Describe System Behavior with Diagrams

The Sequence Viewer describes the simulation events as they occur in the model as the sequence
diagram describes what is expected to occur. On the toolstrip, in the Simulation tab, select Log
Events, then launch the Sequence Viewer from the same location. See that the simulation pauses
when traffic is 1.

Select Next Message three more times to simulate until the traffic light completes one loop from
green to yellow to red again. For more information on the Loop fragment, see “Author Sequence
Diagram Fragments” on page 6-35.

6-60
Simulate Sequence Diagrams for Traffic Light Example

6-61
6 Describe System Behavior with Diagrams

View the corresponding message events in the Sequence Viewer.

6-62
Simulate Sequence Diagrams for Traffic Light Example

6-63
6 Describe System Behavior with Diagrams

Select Continue to continue until the end. The pedestrian crossing signal allows the pedestrians
cross by turning the traffic light red. Then, the traffic light continues its cycle.

6-64
Simulate Sequence Diagrams for Traffic Light Example

6-65
6 Describe System Behavior with Diagrams

View the corresponding message events for the pedestrian crossing messages in the Sequence
Viewer.

6-66
Simulate Sequence Diagrams for Traffic Light Example

6-67
6 Describe System Behavior with Diagrams

Simulate and Detect Errors with SignalSequence Sequence Diagram

In the View Browser, select the SignalSequence sequence diagram.

Click Run to simulate the sequence diagram to the end. Messages where the conditions are met turn
green with a checkmark.

This step requires a Stateflow license.

Return to the TLExample model. Double-click the lampController component to view the state
chart. In the ped subchart, introduce an error into model execution by changing
pedColor=trafficColors.RED to pedColor=trafficColors.YELLOW. Save the TLExample
model.

6-68
Simulate Sequence Diagrams for Traffic Light Example

Return to the View Browser. For the SignalSequence sequence diagram, click Clear Results to
clear the green checkmarks and reset sequence diagram simulation. Click Run to simulate the
SignalSequence sequence diagram again.

6-69
6 Describe System Behavior with Diagrams

For the first message from the lampController lifeline to the ped lamp lifeline, the constraints
specified by the sequence diagram are not met by the model execution.

See Also
Tools
Architecture Views Gallery | Sequence Viewer

Functions
openViews | sim | getInteraction | getInteractions | open | next | current | reset

Objects
systemcomposer.arch.Model | systemcomposer.interaction.Interaction |
systemcomposer.interaction.Iterator | systemcomposer.interaction.Lifeline |
systemcomposer.interaction.MessageEvent | systemcomposer.interaction.FormalGate
| systemcomposer.interaction.Message | systemcomposer.interaction.Fragment |
systemcomposer.interaction.RootFragment |
systemcomposer.interaction.AltFragment | systemcomposer.interaction.OptFragment
| systemcomposer.interaction.LoopFragment |
systemcomposer.interaction.SeqFragment |
systemcomposer.interaction.StrictFragment |
systemcomposer.interaction.ParFragment | systemcomposer.interaction.Operand |
systemcomposer.interaction.Annotation | Simulink.SimulationInput |
Simulink.SimulationOutput

More About
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Compose Architectures Visually” on page 1-5
• “Define Port Interfaces Between Components” on page 3-2
• “Implement Component Behavior Using Simulink” on page 7-2

6-70
Simulate Sequence Diagrams for Traffic Light Example

• “Implement Component Behavior Using Stateflow Charts” on page 7-15


• “Implement Component Behavior Using Simscape” on page 7-23

6-71
6 Describe System Behavior with Diagrams

Author and Simulate Basic Colors Sequence Diagram with


Enumerations

This example shows how to author and simulate a sequence diagram containing a variable of
datatype Simulink.IntEnumType.

Define BasicColors.m Enumeration

Create an enumeration class called BasicColors and define Red(0), Yellow(1), and Blue(2)
as the enumerated values.

classdef BasicColors < Simulink.IntEnumType


enumeration
Red(0)
Yellow(1)
Blue(2)
end

Open Enumeration Example Model

Open the EnumExample.slx architecture model that contains a sequence diagram that implements
the BasicColors enumeration.

model = systemcomposer.openModel("EnumExample");

Double-click the source component to inspect the Stateflow® Chart (Stateflow) block.

6-72
Author and Simulate Basic Colors Sequence Diagram with Enumerations

The output data port, data, is typed by the BasicColors enumeration in this state chart where the
color changes from Red to Yellow as the model simulates.

Open Enumeration Sequence Diagram

Navigate to Modeling > Sequence Diagram to open the Architecture Views Gallery and access the
EnumSequenceDiagram sequence diagram. Click Run to simulate the sequence diagram.

6-73
6 Describe System Behavior with Diagrams

As the inEnum destination port inherits a value of 1 from the BasicColors enumeration, indicating
a change from Red (0) to Yellow (1), the sequence diagram executes successfully.

See Also
Tools
Architecture Views Gallery | Sequence Viewer

Functions
openViews | sim | getInteraction | getInteractions | open | next | current | reset

Objects
systemcomposer.arch.Model | systemcomposer.interaction.Interaction |
systemcomposer.interaction.Iterator | systemcomposer.interaction.Lifeline |
systemcomposer.interaction.MessageEvent | systemcomposer.interaction.FormalGate
| systemcomposer.interaction.Message | systemcomposer.interaction.Fragment |
systemcomposer.interaction.RootFragment |
systemcomposer.interaction.AltFragment | systemcomposer.interaction.OptFragment
| systemcomposer.interaction.LoopFragment |
systemcomposer.interaction.SeqFragment |
systemcomposer.interaction.StrictFragment |
systemcomposer.interaction.ParFragment | systemcomposer.interaction.Operand |
systemcomposer.interaction.Annotation | Simulink.SimulationInput |
Simulink.SimulationOutput

More About
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Compose Architectures Visually” on page 1-5
• “Define Port Interfaces Between Components” on page 3-2
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Implement Component Behavior Using Simscape” on page 7-23

6-74
Describe System Behavior Using Activity Diagrams

Describe System Behavior Using Activity Diagrams


An activity diagram is the primary diagram to describe an activity. An activity describes system
behavior that models the flow of tokens from inputs to outputs through a controlled sequence of
actions. An activity diagram contains action nodes with pins connected by flow lines. Activity
diagrams represent the flow of tokens through various actions that describe the execution of
activities.

Actions are the building blocks of activities and describe what happens when activities execute. Each
action can accept inputs and produce outputs, called tokens.

Use activity diagrams to conceptualize a system, visualize functional flow through actions or
decisions, and understand how system components interact with one another. You can use activity
diagrams to describe the behavior of systems as a transformation of inputs to outputs through actions
that process token flows.

You can allocate activity diagram elements to elements of a System Composer architecture model
using the Allocation Editor to more fully describe your functional architectural design. For more
information, see “Design Architectures and Activity Diagram for Mobile Robot” on page 5-42.

These concepts are relevant for authoring activity diagrams:

• Tokens are objects that flow in the activity diagram. A token can represent data such as structures
and integers, or simply pass on the control.

Use a token to move data or control across the activity diagram. These are the types of tokens:

• Object token — Represents an object such as a piece of data.


• Control token — Represents a control or a triggering event that does not carry any data.
• A flow in an activity diagram connects two nodes. A dashed line represents a control flow and a
solid line represents an object flow.

You can use object flows to route input or output tokens to carry information or physical items
between object nodes. You can use control flows to model transfer of control from one Action
Node to another. These are the types of flows:

6-75
6 Describe System Behavior with Diagrams

• Object flow — Tokens in an object flow contains token data on which actions operate.
• Control flow — Tokens in a control flow trigger the execution of actions.
• An action node is a key building block in an activity diagram. An action node represents an action
to be executed. Action nodes consume input tokens and produce output tokens on pins.

Use a MATLAB function or a nested activity diagram to describe the behavior of an action node.
• A control node routes a logical flow of tokens through the system.

Use control nodes and flows to route tokens. Control nodes can be used to initialize, split, merge,
and terminate token flows.

These are the various types of control nodes in an activity:

• Initial Node — Dispatches a control token at the beginning of an activity.


• Decision or Merge Node — A decision node routes an input token to an output flow based on
the evaluation of guard expressions. A merge node routes tokens from multiple input flows to a
single output flow. A merge decision node routes tokens from multiple input flows to certain
output flows based on the evaluation of guard expressions.
• Join or Fork Node — A join node consolidates multiple input tokens to one output flow given
that a token is available at each input pin. A fork node replicates one input token on each
output flow.
• Flow Final Node — Terminates one object or control flow but not the entire activity.
• Activity Final Node — Terminates the incoming token and the entire activity.
• A pin directs tokens in or out of an action node. The directionality of the pin represents input or
output. You can connect pins by object flows.

Use pins to route an object token to or from an Action Node. Pins are also used to store object
tokens before or during execution. You can use pins only for object flows.

Create New Activity Diagram


Create an activity diagram by launching the System Composer Start Page. Enter in the MATLAB
Command Window:
systemcomposer

From the following dialog box, select Activity Diagram.

Alternatively, you can use the systemcomposer.createActivity function to create a new activity
diagram.

6-76
Describe System Behavior Using Activity Diagrams

Authoring, Simulating, and Visualizing Activity Diagrams


Activity diagrams are integrated with architecture models in System Composer. While designing a
system, you can use an activity diagram to conceptualize a system, and visualize the flow of actions or
decisions. Activity diagrams help you to understand how each element of your system interacts with
each other. In System Composer, you can also simulate and visualize activity diagrams to validate
system behavior.

Topic Description
“Author Activity Diagrams” on page 6-78 Interactively create and edit an activity diagram
and learn terminology.
“Simulate, Visualize, and Validate Activity Simulate and visualize an activity diagram to
Diagrams” on page 6-91 validate system behavior.

See Also
Functions
systemcomposer.createActivity

Tools
Types Editor | Interface Editor | Architectural Data Editor

Blocks
Initial Node | Action Node | Decision or Merge Node | Join or Fork Node | Flow Final Node | Activity
Final Node

More About
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Compose Architectures Visually” on page 1-5
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Implement Component Behavior Using Simscape” on page 7-23

6-77
6 Describe System Behavior with Diagrams

Author Activity Diagrams


Activity diagrams describe the functional flow behavior of an architectural system, used in early
phases of system design to elaborate on end system goals. To create an activity diagram, see “Create
New Activity Diagram” on page 6-76.

An activity diagram is the primary diagram to describe an activity. An activity describes system
behavior that models the flow of tokens from inputs to outputs through a controlled sequence of
actions. An activity diagram contains action nodes with pins connected by flow lines. Activity
diagrams represent the flow of tokens through various actions that describe the execution of
activities.

Use activity diagrams to conceptualize a system, visualize functional flow through actions or
decisions, and understand how system components interact with one another. You can use activity
diagrams to describe the behavior of systems as a transformation of inputs to outputs through actions
that process token flows.

In this topic, you will inspect different parts of an activity diagram and how to author each of the
nodes to describe a mobile robot following a randomly generated path.

You can allocate activity diagram elements to elements of a System Composer architecture model
using the Allocation Editor to more fully describe your functional architectural design. For more
information, see “Design Architectures and Activity Diagram for Mobile Robot” on page 5-42.

You will learn how to:

• Begin token flow in your activity diagram. You will use an initial node and a control flow.
• Represent actions in your activity diagram.

• Create an action node with MATLAB function behavior.


• Create an action node with a nested activity.
• Use MATLAB action nodes without MATLAB functions to initialize object tokens.
• Use control nodes to manipulate token flows.

• Use a fork node to replicate a control token in two control flows.


• Use a decision node to route the input token to one of the output flows.
• Create loops with control nodes.
• Consume tokens and terminate your activity with a flow final node and an activity final node.

For a roadmap of the activity diagram topics, see “Describe System Behavior Using Activity
Diagrams” on page 6-75.

Open the activity diagram used in this example below to follow along.

Open Activity Diagram for Mobile Robot Functional Flow

This example shows a functional flow diagram for modeling a mobile robot architecture that travels
between a randomized starting point and destination.

Open the project.

6-78
Author Activity Diagrams

openProject("scMobileRobotExample");

Open the activity diagram.

systemcomposer.openModel("RobotActivity");

First, the robot software calculates the path distance, and if the distance exceeds robot battery life to
traverse the distance, the token flows to Error out and the activity terminates, otherwise, the robot
follows the path.

Token Flow in Activity Diagrams


Tokens represent objects that travel along your activity diagram invoking activities while routed by
control nodes. To begin your activity, use an Initial Node to place a control token on the single
outgoing flow.

Tokens are objects that flow in the activity diagram. A token can represent data such as structures
and integers, or simply pass on the control.

Use a token to move data or control across the activity diagram. These are the types of tokens:

• Object token — Represents an object such as a piece of data.


• Control token — Represents a control or a triggering event that does not carry any data.

6-79
6 Describe System Behavior with Diagrams

Click the right side the initial node and drag to generate a control flow. Then, use marquee draw to
select the action node that appears to instantiate it. The control flow transports the control token to
the action node and begins execution.

A flow in an activity diagram connects two nodes. A dashed line represents a control flow and a solid
line represents an object flow.

You can use object flows to route input or output tokens to carry information or physical items
between object nodes. You can use control flows to model transfer of control from one Action Node to
another. These are the types of flows:

• Object flow — Tokens in an object flow contains token data on which actions operate.
• Control flow — Tokens in a control flow trigger the execution of actions.

Author Activity Diagram Action Nodes


In an activity diagram, you can generate tokens and read tokens using an Action Node.

An action node is a key building block in an activity diagram. An action node represents an action to
be executed. Action nodes consume input tokens and produce output tokens on pins.

Use a MATLAB function or a nested activity diagram to describe the behavior of an action node.

You can add an action node in your activity diagram by clicking and dragging the action node
icon from the left side palette to the canvas.

6-80
Author Activity Diagrams

Author Action Node with MATLAB Function Behavior

The first Action Node of an activity diagram with a MATLAB function behavior determines how the
control token that begins the action produces an object token on the action node output pin.

Change the Behavior Type parameter in the Property Inspector to MATLAB to implement MATLAB
function behavior, then populate the MATLAB Function Name text box with the name of your
function.

Double-click the Select Target Position action node to view the GeneratePosition.m
function file in the MATLAB editor.
function [TargetPos] = GeneratePosition()

close all;

6-81
6 Describe System Behavior with Diagrams

figure('Name','RobotPath');
set(gca, 'XLim', [0 100], 'YLim', [0 100]);
hold on;

pos = randi(100, [1 2]);


TargetPos(1) = pos(1); % x
TargetPos(2)= pos(2); % y
TargetPos(3) = floor(rand*360); % orientation

plot(pos(1), pos(2), 'go', 'MarkerSize', 12);

end

The GeneratePosition function calculates a random starting position and ending position on the
graph for the mobile robot. The GeneratePosition function contains no input arguments and one
output argument. The output argument TargetPos corresponds to the output pin on the action node
and represents a 3-dimensional vector with the starting position, ending position, and orientation of
the robot.

To create a pin on an action node, hover over the edge of an action node and click the blue pin, then
choose whether to create an input pin or an output pin.

You can select the TargetPos pin and view its types in the Types Editor to view the corresponding
PositionData type with expected dimensions [1,3].

6-82
Author Activity Diagrams

Note When you set Dimensions to 3, the Types Editor automatically interprets the dimensions as a
column vector [1,3].

A pin directs tokens in or out of an action node. The directionality of the pin represents input or
output. You can connect pins by object flows.

Use pins to route an object token to or from an Action Node. Pins are also used to store object tokens
before or during execution. You can use pins only for object flows.

Use Nested Activity to Describe Action

You can represent an Action Node in an activity diagram as a nested activity. The flow of tokens in a
nested activity execute as an invocation action. An invocation action can only be executed
sequentially and cannot have multiple concurrent invocations.

When an action starts, one instance of the action executes, and if new tokens arrive, new tokens will
wait in the input pin. The input pin is a queue. The Token Multiplicity parameter in the Property
Inspector for an input pin determines the size of the queue.

6-83
6 Describe System Behavior with Diagrams

Change the Behavior Type parameter in the Property Inspector to Activity to implement a nested
activity, then double-click your action node to author your nested activity.

The nested activity Plan Path executes normally according to the MATLAB function behaviors on
each of the serially connected action nodes Do Plan Path and Apply Path Limits. Path planning
calculates the path in steps:

1 Turn the robot to the starting orientation.


2 Move the robot in the x-direction.
3 Turn the robot from the x-direction to the y-direction.
4 Move the robot in the y-direction.

6-84
Author Activity Diagrams

5 Turn the robot to the ending orientation.

Use MATLAB Action Node without MATLAB Function to Initialize Object Token

When you author your activity diagram and connect flow lines between object pins on action nodes, to
describe the sequence of actions, a MATLAB action can be used without any MATLAB function.

Note For an action node where a MATLAB function is not defined, a default token with all attributes
set to 0 is created on the output pin.

The Initialize Path Follower action node with Behavior Type set to MATLAB, has no defined
MATLAB Function Name. You can specify the output pin type to initialize an object token type for
the next action node.

The output pin stores a token that travels down the flow line to the next action node input pin. For the
Initialize Path Follower action node, specify the type of the output pin Count as owned type
with type double and dimension of 1.

Note When you initialize a datatype in the Types Editor, the options include fixed point and
enumerations. Due to limited support, compile time checks are active. Compile your activity diagram
using CTRL+D to validate your datatypes.

6-85
6 Describe System Behavior with Diagrams

Use Control Nodes to Manipulate Token Flows


Control flows constrain the timing and ordering of the execution of actions in an activity diagram
using control nodes.

A control node routes a logical flow of tokens through the system.

Use control nodes and flows to route tokens. Control nodes can be used to initialize, split, merge, and
terminate token flows.

Use Fork Node to Split Control Flow

A Join or Fork Node node replicates an input control token on each output flow when implemented as
a fork node.

6-86
Author Activity Diagrams

The control flows transport the control tokens to two different action nodes and begins execution.

Use Decision Node to Create Conditional Flow

A Decision or Merge Node routes an input token to a particular output flow based on the evaluation
of decision conditions when implemented as a decision node. You can use a decision node to
manipulate token flow to demonstrate the following scenario: When there is enough battery life for
the robot to follow the calculated path distance, the robot can follow its path.

6-87
6 Describe System Behavior with Diagrams

When the function isBatteryLifeSufficient evaluates to true after taking the current token
value from the built in variable, token, the token continues to the Follow Path action node.
Otherwise, the token is routed to the Error out action node.

To access the token flowing through the flow, use the built in keyword token. When the
isBatteryLifeSufficient(token) function evaluates to true, the token continues to the
Follow Path action node. When the isBatteryLifeSufficient(token) function evaluates to
false, the token is routed to the Error out action node.

Create Loops with Decision and Merge Nodes

When you have an iterating function that uses a count variable to keep track of number of loops until
completion, you can use a Decision or Merge Node to route tokens to and from the same action node.

6-88
Author Activity Diagrams

In this example, the nested activity Follow Path contains an Issue Command action node that
loops five times before the mobile robot completes following the path.

End Flows and Activity with Final Nodes

You can use a Flow Final Node to terminate one object or control, but not the entire activity. Flow
final nodes are used in the Follow Path activity diagram above. You can use an Activity Final Node
to terminate the incoming token and the parent activity.

After the mobile robot path planning errors out, the activity ends via an activity final node.

Simulate and Validate Activity Diagrams

Now that you learned how to author an activity diagram for a mobile robot following a path, you can
simulate the activity diagram to visualize token flow. For more information, see “Simulate, Visualize,
and Validate Activity Diagrams” on page 6-91.

See Also
Functions
systemcomposer.createActivity

6-89
6 Describe System Behavior with Diagrams

Tools
Types Editor | Interface Editor | Architectural Data Editor

Blocks
Initial Node | Action Node | Decision or Merge Node | Join or Fork Node | Flow Final Node | Activity
Final Node

More About
• “Describe System Behavior Using Activity Diagrams” on page 6-75
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Compose Architectures Visually” on page 1-5
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Implement Component Behavior Using Simscape” on page 7-23

6-90
Simulate, Visualize, and Validate Activity Diagrams

Simulate, Visualize, and Validate Activity Diagrams


After you describe your system as an activity diagram, you can visualize the flow of your tokens and
track the execution of activities. To validate that your activity diagram satisfies your design goals,
simulate your model, use animations to validate diagram behavior, and visualize the output of your
model using Simulation Data Inspector. For more information about activity diagrams, see “Describe
System Behavior Using Activity Diagrams” on page 6-75.

In this example, the activity diagram represents a mobile robot path planning algorithm. The activity
diagram has:

• Select Target Position action node to represent the target position of the robot in the grid.
• Plan Path action node to compute the robot path based on the target position from Select
Target Position node and its initial position from Compute Self Position node.
• The decision node to check whether the computed path is feasible with respect to the planned
path and remaining robot battery life.

• If the path is feasible, in the Follow Path action node, the robot issues proper commands and
implement them to reach the target position.
• If the path is not feasible, the diagram errors out.

For more information about creating this activity diagram, see “Author Activity Diagrams” on page 6-
78.

Open Activity Diagram for Mobile Robot Functional Flow

This example shows a functional flow diagram for modeling a mobile robot architecture that travels
between a randomized starting point and destination.

Open the project.

openProject("scMobileRobotExample");

Open the activity diagram.

systemcomposer.openModel("RobotActivity");

6-91
6 Describe System Behavior with Diagrams

First, the robot software calculates the path distance, and if the distance exceeds robot battery life to
traverse the distance, the token flows to Error out and the activity terminates, otherwise, the robot
follows the path.

Simulate Activity Diagram and Review Results


To simulate activity diagrams, in the System Composer toolstrip, on the Modeling tab, use the
Simulate section.

After you simulate the activity diagram, observe that the robot follows the path and reaches its
destination when a path is feasible. In this simple path planning algorithm, the robot first moves in
the horizontal axis to align its x coordinate with the target and then moves in the vertical axis to align
its y coordinate with the target position. Then, the robot aligns its orientation with the target
position.

Observe that the simulation ends when a token arrives at the Activity Final Node node.

6-92
Simulate, Visualize, and Validate Activity Diagrams

Note An activity diagram simulation ends in two scenarios, if a token reaches an Activity Final node
or due to the final simulation time.

Validate Activity Diagram Behavior Using Animations


To track the flow of your tokens and the execution of activities, use animations. Animations highlight
the flow of your tokens and the sequence of actions in your activity diagram. To specify the speed of
your animation, in the System Composer toolstrip, on the Debug tab, select the animation speed as
Lightning Fast, Fast, Medium, Slow, or None.

If the animation is on, to stop the animation during simulation, press Ctrl+C or set the animation
speed to None.

6-93
6 Describe System Behavior with Diagrams

Animate the activity diagram representation of the robot. Observe that the animation highlights the
action nodes with colors that represent the state of the action node at that time of the simulation.

In an animation, there are two types of colors, fill colors and border colors.

Fill colors:

• Light Grey — Action node is in idle mode.


• Dark Grey — Action node completed its run.
• Green — Action node is running. When an action node is running, its main color is green but its
boundary can have three different colors to represent its token status:

Border colors when the fill color is green:

• Orange — Some tokens arrived at the node, but the node does not meet all the requirements to
run.
• Green — All the requirements regarding the tokens are satisfied and the node is running.
• Grey — All the output tokens have not yet departed the node.

6-94
Simulate, Visualize, and Validate Activity Diagrams

Log Data from Activity Diagram Using Simulation Data Inspector


To visualize the output tokens from a node and the data, right-click an object flow line, log your
signal, and use the Simulation Data Inspector.

In the activity diagram of the robot, in the Follow Path action node, log the issued commands.

6-95
6 Describe System Behavior with Diagrams

Simulate the diagram. In the toolstrip, on the Simulation tab, select Data Inspector and observe
that Simulation Data Inspector displays the logged data.

6-96
Simulate, Visualize, and Validate Activity Diagrams

View Token Data Using Pin Value Display


You can display the values and the structure of token data at the output pin of a node as a label that
floats over the flow line in the diagram. The value in the label is updated when a token departs an
output pin. You can add and remove pin value labels throughout your model before and during
simulation. You can use pin value labels along with other visualization options to understand, analyze,
and debug your diagram.

To display token data, in the robot example, right-click flow lines and select Show Port Value Label
on Selected Signal. Observe that during and after animation, the pin values are displayed.

Step Through the Simulation


You can step through major time steps of a simulation to analyze and debug the behavior of your
diagram. In the toolstrip, on the Debug tab, use the Step Forward and Step Back buttons. Observe
that the simulation pauses on every major time step.

Note You need to specify a nonzero duration of your nodes in your activity diagram to be able to step
through time steps. Otherwise, the simulation will end in one time step.

6-97
6 Describe System Behavior with Diagrams

See Also
Functions
systemcomposer.createActivity

Tools
Types Editor | Interface Editor | Architectural Data Editor

Blocks
Initial Node | Action Node | Decision or Merge Node | Join or Fork Node | Flow Final Node | Activity
Final Node

More About
• “Describe System Behavior Using Activity Diagrams” on page 6-75
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Compose Architectures Visually” on page 1-5
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15

6-98
Simulate, Visualize, and Validate Activity Diagrams

• “Implement Component Behavior Using Simscape” on page 7-23

6-99
7

Use Simulink Models with System


Composer

• “Implement Component Behavior Using Simulink” on page 7-2


• “Extract Architecture of Simulink Model Using System Composer” on page 7-13
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Extract Architecture from Simulink Model” on page 7-19
• “Implement Component Behavior Using Simscape” on page 7-23
• “Merge Message Lines for Architectures Using Adapter Block” on page 7-29
7 Use Simulink Models with System Composer

Implement Component Behavior Using Simulink


System design and architecture definitions can involve a behavior definition for some components,
such as the algorithm for a data processing component. Define components in System Composer
architecture models as behaviors using Simulink subsystem components that are part of the parent
model, or referenced behaviors by linking components to Simulink models or subsystems.

Behavior How to Use More Information


Simulink model Implement component behaviors with a “Create Reusable Simulink Behavior
reference linked Simulink model to define your Using Model Reference Component” on
system behavior and easily reuse these page 7-5
definitions across architectural
components.
Simulink Implement component behaviors with a “Create Reusable Simulink Behavior
subsystem linked Simulink subsystem to define Using Subsystem Reference
reference your system behavior and easily reuse Component” on page 7-6
these definitions across architectural
components.

Subsystems support root-level physical


ports to use with Simscape physical
behaviors.
Simulink Implement component behaviors with a “Create Simulink Behavior Using
subsystem Simulink subsystem that is part of the Subsystem Component” on page 7-7
component parent architecture model to define
your system behavior once.

Subsystems support root-level physical


ports to use with Simscape physical
behaviors.
Stateflow chart Implement component behaviors with a “Implement Component Behavior Using
component Stateflow chart that is part of the Stateflow Charts” on page 7-15
parent architecture model to define
your system behavior once.

Note System Composer interfaces mirror Simulink interfaces that use buses and value types. When
you plan to link Simulink behaviors to System Composer components, consider these resources:

• For buses at Simulink interfaces, see “Composite Interface Guidelines”.


• To use model interfaces with bus element ports, see “Simplify Subsystem and Model Interfaces
with Bus Element Ports”.
• For value types at Simulink interfaces, see “Specify Common Set of Signal Properties as Value
Type”.

You can simulate the Simulink component implementations in System Composer. Use the Simulation
Data Inspector to view and compare simulation results between model designs.

7-2
Implement Component Behavior Using Simulink

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Create Simulink Behavior with Robot Arm Model

This example shows how to use a robot arm model to create Simulink® behavior from the Motion
component.

1. Open the Robot.slx model.

model = systemcomposer.openModel('Robot');

7-3
7 Use Simulink Models with System Composer

The Robot model has an interface sensordata applied on the ports SensorData.

2. Look up the Motion component.

motionComp = lookup(model,'Path','Robot/Motion');

3. Create a Simulink behavior.

motionComp.createSimulinkBehavior('MotionSimulink');

7-4
Implement Component Behavior Using Simulink

Create Referenced Simulink Behavior Model


When a component does not require decomposition from an architecture standpoint, you can design
and define the behavior of the component in Simulink. When you link to a Simulink behavior, the
Component block becomes a Reference Component block.

A reference component is a component whose definition is a separate architecture model, Simulink


behavior model, or Simulink subsystem behavior. A reference component represents a logical
hierarchy of other compositions.

You can synchronize and reuse reference components as Reference Component blocks. There are
three types of reference components:

• Model references are Simulink models.


• Subsystem references are Simulink subsystems.
• Architecture references are System Composer architecture models or subsystems.

In this section, you will create a model reference and a subsystem reference. For more information on
architecture references, see “Create Architecture Model Reference” on page 1-21.

Referenced or linked models are useful for collaborative design with version control using Simulink
projects. For more information, see “Organize System Composer Files in Projects” on page 12-2.

Create Reusable Simulink Behavior Using Model Reference Component

Use Simulink model references to describe the implementation of System Composer components.

1 Select the Motion component. Navigate to Modeling > Create Simulink Behavior.
Alternatively, right-click the Motion component and select Create Simulink Behavior.
2 From the Type list, select Model Reference. Provide the model name MotionSimulink. The
default name is the name of the component.

3 A new Simulink model file with the provided name is created in the current folder. The root-level
ports of the Simulink model reflect the ports of the component. The component in the
architecture model is linked to the Simulink model. The icon on the component indicates that
the component has a Simulink behavior.

7-5
7 Use Simulink Models with System Composer

4 To view the interfaces on the SensorData port converted into Simulink bus elements, double-
click the port in Simulink.

5 To remove model behavior, right-click the linked Motion component and select Inline Model.

For more information on removing referenced behaviors, see “Remove Architecture Reference” on
page 1-25.

Create Reusable Simulink Behavior Using Subsystem Reference Component

Use subsystem references to author Simulink or Simscape behaviors with physical ports, connections,
and blocks. For more information, see “Implement Component Behavior Using Simscape” on page 7-
23.

1 Select the Motion component. Navigate to Modeling > Create Simulink Behavior.
Alternatively, right-click the Motion component and select Create Simulink Behavior.
2 From the Type list, select Subsystem Reference. Provide the model name MotionSubsystem.
The default name is the name of the component.

7-6
Implement Component Behavior Using Simulink

3 A new Simulink subsystem file with the provided name is created in the current folder. The root-
level ports of the Simulink subsystem reflect the ports of the component. The component in the
architecture model is linked to the Simulink subsystem. The icon on the component indicates
that the component has a Simulink subsystem behavior.

You can access and edit referenced Simulink models and subsystems by double-clicking the
Reference Component in the architecture model. When you save the architecture model, all unsaved
referenced Simulink behaviors are also saved, and all linked components are updated.

Create Simulink Behavior Using Subsystem Component


A subsystem component is a Simulink subsystem that is part of the parent System Composer
architecture model.

Add Simulink subsystem behavior to a component to author a subsystem component in System


Composer. You cannot synchronize and reuse subsystem components as Reference Component blocks
because the component is part of the parent model.

1 Right-click the Sensor component and select Create Simulink Behavior. Alternatively,
navigate to Modeling > Create Simulink Behavior.
2 From the Type list, select Subsystem.

7-7
7 Use Simulink Models with System Composer

3 The Sensor component is now a Simulink subsystem of the same name that is part of the parent
System Composer architecture model.

The root-level ports of the Simulink model reflect the ports of the component. The icon on the
component indicates that the component has a Simulink subsystem behavior.

4 You can continue to provide specific dynamics and algorithms in the Simulink subsystem
behavior model. Adding root-level ports in the subsystem behavior creates additional ports on the
subsystem component.
5 You can use subsystem components to author Simscape component behaviors with physical ports,
connections, and blocks. For example, this amplifier physical system uses electrical domain
blocks inside a subsystem component in a System Composer architecture model.

7-8
Implement Component Behavior Using Simulink

Convert Simulink Subsystem Component to Subsystem Reference Component

You can convert existing Simulink subsystem components that are part of the parent System
Composer model to subsystem reference components. The subsystem reference components are
saved separately as a reusable artifact.

1 Right-click the subsystem component block and select Block Parameters (Subsystem).
2 Click the Subsystem Reference tab.

3 Click Convert to open the Convert to Subsystem Reference dialog.


4 Choose a name for the new subsystem file. Optionally, select Transfer test harnesses to
transfer test harnesses. Click Convert to complete the conversion.

7-9
7 Use Simulink Models with System Composer

To convert a subsystem component to a subsystem reference programmatically, use the


createSimulinkBehavior function.

Link to Existing Simulink Behavior Model


You can link to an existing Simulink behavior model or subsystem from a System Composer
component, provided that the component is not already linked to a reference architecture. Right-click
the component and select Link to Model. Type in or browse for the name of a Simulink model or
subsystem.

Any subcomponents and ports in the components are deleted when the component links to a Simulink
model or subsystem. A prompt displays to continue and lose subcomponents and ports.

Note Linking a System Composer component to a Simulink model with root-level enable or trigger
ports is not supported.

You can link protected Simulink models (.slxp) to create component behaviors. You can also convert
an already linked Simulink behavior model to a protected model. The change is reflected when you
refresh the model.

Access Model Arguments as Parameters on Reference Components


System Composer exposes instance-specific parameter values for reusable referenced models.

A parameter is an instance-specific value of a value type.

Parameters are available for inlined architectures and components. Parameters are also available for
components linked to model, subsystem, or architecture references that specify model arguments.
You can specify independent values for a parameter on each component.

Instance-specific parameter values are visible on the component level. View and edit these values
using the Property Inspector.

7-10
Implement Component Behavior Using Simulink

Each parameter value can be specified independently for each component that references the model.

For more information, see “Use Parameters to Store Instance Values with Components” on page 4-7.

To add or modify parameters for architectures or components using the Parameter Editor, see “Author
Parameters in System Composer Using Parameter Editor” on page 4-2.

Create Simulink Behavior from Template for Component


To create user-defined templates for Simulink models, see “Create Template from Model”.

After creating and saving a user-defined template, you can link the template to a Simulink behavior.
Right-click the component and select Create Simulink Behavior, or, navigate to Modeling >
Create Simulink Behavior.

7-11
7 Use Simulink Models with System Composer

On the Create Simulink behavior dialog, choose the template and enter a new data dictionary
name if local interfaces are defined. Click OK. The component exhibits a Simulink behavior according
to the template with shared interfaces, if present. Blocks and lines in the template are excluded, and
only configuration settings are preserved. Configuration settings include annotations and styling.

Note that you can use architecture templates by right-clicking a component and selecting Save As
Architecture Model, or navigating to Modeling > Save As Architecture Model.

See Also
Functions
createSimulinkBehavior | linkToModel | inlineComponent | createArchitectureModel |
createArchitectureSubsystem | systemcomposer.parameter.ParameterDefinition

Blocks
Reference Component

More About
• “Decompose and Reuse Components” on page 1-19
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Implement Component Behavior Using Simscape” on page 7-23
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Organize System Composer Files in Projects” on page 12-2

7-12
Extract Architecture of Simulink Model Using System Composer

Extract Architecture of Simulink Model Using System


Composer

Export an existing Simulink® model to a System Composer™ architecture model. The algorithmic
sections of the original model are removed and structural information is preserved during this
process. Requirements links, if present, are also preserved.

Convert Simulink Model to System Composer Architecture

System Composer converts structural constructs in a Simulink model to equivalent architecture


model constructs:

• Subsystems to components
• Variant subsystems to variant components
• Bus objects to interfaces
• Referenced models to reference components

Open Model

Open the Simulink model of F-14 Flight Control.

open_system('f14')

7-13
7 Use Simulink Models with System Composer

Export Model

Extract an architecture model from the original model.

systemcomposer.extractArchitectureFromSimulink('f14','F14ArchModel');
Simulink.BlockDiagram.arrangeSystem('F14ArchModel');
systemcomposer.openModel('F14ArchModel');

See Also
extractArchitectureFromSimulink

More About
• “Extract Architecture from Simulink Model” on page 7-19
• “Compose Architectures Visually” on page 1-5
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Implement Component Behavior Using Simulink” on page 7-2
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35
• “Modeling System Architecture of Small UAV” on page 1-37

7-14
Implement Component Behavior Using Stateflow Charts

Implement Component Behavior Using Stateflow Charts


A state chart diagram demonstrates the state-dependent behavior of a component throughout its
state lifecycle and the events that can trigger a transition between states.

Add Stateflow chart behavior to describe a component using state machines. You cannot synchronize
and reuse Stateflow chart behaviors as Reference Component blocks because the component is part
of the parent model.

You can simulate the Stateflow component implementations in System Composer. Use the Simulation
Data Inspector to view and compare simulation results between model designs.

State charts consist of a finite set of states with transitions between them to capture the modes of
operation for the component. Charts allow you to design for different modes, internal states, and
event-based logic of a system. You can also use charts as stubs to mock a complex component
implementation during top-down integration testing. This functionality requires a Stateflow license.
For more information, see “Stateflow”.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Add State Chart Behavior to Component


A System Composer component with stereotypes, interfaces, requirement links, and ports, is
preserved when you add Stateflow Chart behavior.

1 This example uses the architecture model for an unmanned aerial vehicle (UAV) to add state
chart behavior to a component. In the MATLAB Command Window, enter the following command:

scExampleSmallUAV
2 Double-click the Airframe component. Select the LandingGear component on the System
Composer composition editor.
3 Select the Brake port. Open the Interface Editor from the toolstrip Modeling > Interface
Editor. Right-click the interface operatorCmds and select Assign to Selected Port(s).
4 Right-click the LandingGear component and select Create Behavior then select Stateflow
Behavior. Alternatively, navigate to Modeling > Create Stateflow Chart Behavior.

7-15
7 Use Simulink Models with System Composer

5 Double-click LandingGear, which has the Stateflow icon. Navigate to Modeling > Design Data
> Symbols Pane to view the Stateflow symbols. The input port Brake appears as input data in
the symbols pane.

Note Some Stateflow objects remain local to Stateflow charts. Input and output event ports are
not supported in System Composer. Only local events are supported.

Since Stateflow ports show up as input and output data objects, they must follow Stateflow
naming conventions. Ports are automatically renamed to follow Stateflow naming conventions.
For more information, see “Guidelines for Naming Stateflow Objects” (Stateflow).

7-16
Implement Component Behavior Using Stateflow Charts

6 Select the Brake input and view the interface in the Property Inspector. The interface can be
accessed like a Simulink bus signal. For information on how to use bus signals in Stateflow, see
“Index and Assign Values to Stateflow Structures” (Stateflow).

7 You can populate the Stateflow canvas to represent the internal states of the LandingGear.

Remove Stateflow Chart Behavior from Component


You can remove Stateflow chart behavior from a component to delete the contents inside the
Stateflow chart while preserving interfaces on the component.

1 Right-click the LandingGear component and select Inline Model.


2 To confirm the operation to delete all the content inside the Stateflow chart, click OK.

7-17
7 Use Simulink Models with System Composer

3 The Stateflow chart behavior on the component is removed. Interfaces on ports on the
component are preserved.

See Also
createStateflowChartBehavior | inlineComponent

More About
• “Compose Architectures Visually” on page 1-5
• “Decompose and Reuse Components” on page 1-19
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Simscape” on page 7-23
• “Describe System Behavior Using Sequence Diagrams” on page 6-2

7-18
Extract Architecture from Simulink Model

Extract Architecture from Simulink Model


You can use System Composer architecture editing and analysis capabilities on Simulink models. To
do so, extract the architecture from a Simulink model. Model and Subsystem blocks, as well as all
ports in a Simulink model represent architectural constructs, while all other blocks represent some
kind of dynamic or algorithmic behavior. In the architecture model that you obtain from a Simulink
model, you can choose to represent architectural constructs or link to behavior models.

1 Open an example model.

openExample('ReferenceFilesForCollaborationExample')
2 On the Simulation tab, click the Save arrow. From the Export Model To list, select
Architecture Model.

3 Provide a name and path for the architecture model.

7-19
7 Use Simulink Models with System Composer

4 Click Export. A System Composer Editor window opens with an architecture model
corresponding to the Simulink model.

7-20
Extract Architecture from Simulink Model

Each subsystem in the Simulink model corresponds to a component in the architecture model so that
the hierarchy in the architecture model reflects the hierarchy of the behavior model.

The requirements for subsystems and Model blocks in the Simulink model are preserved in the
architecture model.

Any Model block in the Simulink model that references another model corresponds to a component
that links to that same referenced model.

7-21
7 Use Simulink Models with System Composer

Buses at subsystem and Model block ports, as well as their dictionary links are preserved in the
architecture model.

You can use the exported model to add architecture-related information such as interface definitions,
nonfunctional properties for model elements and analyze the design.

See Also
extractArchitectureFromSimulink

More About
• “Extract Architecture of Simulink Model Using System Composer” on page 7-13
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Implement Component Behavior Using Simscape” on page 7-23
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “Compose Architectures Visually” on page 1-5

7-22
Implement Component Behavior Using Simscape

Implement Component Behavior Using Simscape


A physical subsystem is a Simulink subsystem with Simscape connections.

A physical subsystem with Simscape connections uses a physical network approach suited for
simulating systems with real physical components and represents a mathematical model.

Using Simscape behaviors for components in System Composer improves model simulation and
design for systems with physical components. This functionality requires a Simscape license. For
more information, see “Basic Principles of Modeling Physical Networks” (Simscape).

You can simulate the Simscape component implementations in System Composer. Use the Simulation
Data Inspector to view and compare simulation results between model designs.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

To describe component behavior in Simscape for a System Composer architecture model, follow these
steps:

1 “Define Physical Ports on Component” on page 7-24


2 “Specify Physical Interfaces on Ports” on page 7-24
3 “Create Simulink Subsystem Component” on page 7-25
4 “Describe Component Behavior Using Simscape” on page 7-26

Open this model to interact with a System Composer architecture model named Fan with Simscape
behavior on a component DC Motor. The steps in this tutorial will produce this model.

Note This example uses Simscape blocks. If you do not have a Simscape license, you can open and
simulate the model but can only make basic changes, such as modifying block parameters.

Architecture Model with Simscape Behavior for a DC Motor

This example shows a DC motor in an architecture model of a fan. The DC motor is modeled using a
Simscape behavior within a Simulink subsystem component.

7-23
7 Use Simulink Models with System Composer

Define Physical Ports on Component


A physical port represents a Simscape physical modeling connector port called a Connection Port.

Use physical ports to connect components in an architecture model or to enable physical systems in a
Simulink subsystem.

Create a new System Composer architecture model. Add a component called DC Motor to the
canvas. To add physical ports to the component, pause on the boundary of the component until a port
outline appears. Click the port outline and, from the options, select Physical.

Physical ports can also be used to connect to Simscape blocks.

Note Components with physical ports cannot be saved as architecture models, model references,
software architectures, or Stateflow chart behaviors. Components with physical ports can only be
saved as subsystem references or as subsystem component behaviors.

Specify Physical Interfaces on Ports


You can specify physical interfaces on the physical ports.

A physical interface defines the kind of information that flows through a physical port. The same
interface can be assigned to multiple ports. A physical interface is a composite interface equivalent to

7-24
Implement Component Behavior Using Simscape

a Simulink.ConnectionBus object that specifies a number of Simulink.ConnectionElement


objects.

Use a physical interface to bundle physical elements to describe a physical model using at least one
physical domain.

A physical element describes the decomposition of a physical interface. A physical element is


equivalent to a Simulink.ConnectionElement object.

Define the Type of a physical element as a physical domain to enable use of that domain in a physical
model.

1 To open the Interface Editor, navigate to Modeling > Interface Editor.


2
To add a new physical interface definition, click the list next to the icon and select Physical
Interface. Name the physical interface ElectricalInterface.
3
To add a physical element to the physical interface, click the icon. Physical interface and
physical element names must be valid MATLAB variable names. Create the physical elements
Positive and Negative.
4 In the Type column, define the Simscape domain to which these physical elements belong. In this
case, both belong to foundation.electrical.electrical.

5 Select the E port on the DC Motor component. Right-click the ElectricalInterface physical
interface on the Interface Editor and click Assign to Selected Port(s).

Note New ports by default use <inherit> mode to support unknown interface specifications in
early stages of architectural design. If an interface is specified on another port, the <inherit>
specification propagates that interface across connections to your original port.

Create Simulink Subsystem Component


You can create a Simulink subsystem in System Composer to enable direct Simscape integration. For
more information, see “Create Simulink Behavior Using Subsystem Component” on page 7-7.

Select the DC Motor component. Navigate to Modeling > Create Simulink Behavior, or use the
right-click menu on the component.

7-25
7 Use Simulink Models with System Composer

Click OK.

You can convert a subsystem component that is part of the parent System Composer model into a
subsystem reference behavior then save and reuse the subsystem as a separate artifact. For more
information, see “Create Simulink Behavior Using Subsystem Component” on page 7-7.

Describe Component Behavior Using Simscape


Double-click the subsystem component to describe component behavior using Simscape. For the DC
motor this example is based on, see “Evaluating Performance of a DC Motor” (Simscape).

The physical interface can be decomposed into physical elements using a Simscape bus. Each
physical element represents a conserving connection associated with a domain in Simscape.
Simscape buses bundle conserving connections. For more information, see Simscape Bus (Simscape).

Add a Simscape Bus block next to the E physical port. Double-click the Simscape Bus and select the
connection type Bus: ElectricalInterface. Connect the E physical port to the Simscape Bus
block. The domain foundation.electrical.electrical defined under the Type of the
Positive and Negative physical elements are used for any connections from these ports.

7-26
Implement Component Behavior Using Simscape

You can also use owned interfaces defined locally on ports to enable domain-specific lines on a
Simscape behavior model in System Composer. Edit the port interface through the Property
Inspector. Navigate to Modeling > Property Inspector. In this case, Simscape Bus blocks are not
needed, and the port can connect directly to the physical connection of the specified domain. Add an
owned physical interface to the physical port R with Type as a
foundation.mechanical.rotational.rotational domain. Selecting edit to Open in
Interface Editor enters the Port Interface View in the Interface Editor. For more information, see
“Define Owned Interfaces Local to Ports” on page 3-12.

Using the Library Browser, retrieve the following Simscape blocks and construct the DC Motor model
with electrical and rotational mechanical domain-specific connectors.

A physical connector can represent a nondirectional conserving connection of a specific physical


domain. Connectors can also represent physical signals.

Use physical connectors to connect physical components that represent features of a system to
simulate mathematically.

For more information, see “Domain-Specific Line Styles” (Simscape).

7-27
7 Use Simulink Models with System Composer

Physical modeling uses the network approach and is therefore different from regular Simulink
modeling. For more information, see “Modeling Best Practices” (Simscape) and “Troubleshooting
Simulation Errors” (Simscape).

See Also
createSimulinkBehavior | addPort | addPhysicalInterface | addElement | setInterface
| createInterface

More About
• “DC Fast Charging Station for Electric Vehicles with Solar Cogeneration” (Simscape Electrical)
• “Decompose and Reuse Components” on page 1-19
• “Implement Component Behavior Using Simulink” on page 7-2
• “Implement Component Behavior Using Stateflow Charts” on page 7-15
• “Define Port Interfaces Between Components” on page 3-2

7-28
Merge Message Lines for Architectures Using Adapter Block

Merge Message Lines for Architectures Using Adapter Block

This example shows how to use an Adapter block to merge multiple message lines in a System
Composer™ architecture model.

Open the model.

systemcomposer.openModel('mSysArchMessageMerge');

In this model, message-based communication is constructed between three software components: two
send components, SAC1 and SAC2, create messages and send them to a receive component, SAC3.

• The SAC1 component linked to the Simulink® behavior model mBottomupMsg1 generates
messages with value 1 with a 0.1 sample time.
• The SAC2 component linked to the Simulink behavior model mBottomupMsg2 generates messages
with value 8 with a 0.2 sample time.
• The SAC3 component linked to the Simulink behavior model mBottomupMsg3 receives the merged
messages using a rate-based Subsystem block with a 0.5 sample time.

A first-in, first-out (FIFO) queue is used as a message buffer between the components.

You can double-click the Adapter block to view the “Interface Adapter” on page 3-18 dialog box.
Confirm that the interface conversion Merge is applied. Mappings are now disabled.

7-29
7 Use Simulink Models with System Composer

Simulate the model to merge the messages from the send components SAC1 and SAC2 produced by
Simulink behaviors into a single destination, the receive component SAC3.

sim('mSysArchMessageMerge');

Launch the Simulation Data Inspector to view the three messages together on the same diagram.

Simulink.sdi.view

7-30
Merge Message Lines for Architectures Using Adapter Block

See Also
Simulation Data Inspector | Adapter | Send | Receive

Related Examples
• “Merge Message Lines Using Adapter Block” on page 10-36
• “Merge Message Lines Using a Message Merge Block”
• “Create Rate-Based Model”

7-31
8

Allocate Architecture Models

• “Create and Manage Allocations Interactively” on page 8-2


• “Create and Manage Allocations Programmatically” on page 8-11
• “Allocate Architectures in Tire Pressure Monitoring System” on page 8-14
• “Systems Engineering Approach for SoC Applications” on page 8-20
8 Allocate Architecture Models

Create and Manage Allocations Interactively


This example shows how to create and manage System Composer allocations interactively on the
model canvas and using the Allocation Editor.

In systems engineering, an architectural system is commonly described on different levels. Functional


architectures [1] describe the high-level functions of a system. Logical architectures [2] describe the
logical components of a system and how data is exchanged between them. You can use allocations to
establish relationships from functional components to logical components and to indicate deployment
strategies.

• An allocation establishes a directed relationship from architectural elements — components,


ports, and connectors — in one model to architectural elements in another model.

Resource-based allocation allows you to allocate functional architectural elements to logical


architectural elements and logical architectural elements to physical architectural elements.
• An allocation scenario contains a set of allocations between a source and a target model.

Allocate between model elements in an allocation scenario. The default allocation scenario is
called Scenario 1.
• An allocation set consists of one or more allocation scenarios that describe various allocations
between a source and a target model.

Create an allocation set with allocation scenarios in the Allocation Editor. Allocation sets are saved
as MLDATX files.

To create allocations programmatically, see “Create and Manage Allocations Programmatically” on


page 8-11.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Create and Manage Allocations Interactively Using Tire Pressure


Monitoring System

This example uses the Tire Pressure Monitoring System (TPMS) project. To open the project, use this
command.
openProject("scExampleTirePressureMonitorSystem");

Create Allocations Between Two Models

You can create allocations between a functional architecture and a logical architecture of the TPMS
to represent directed relationships between components, ports, and connectors.

1. Open the functional architecture model, which is the source model for allocations.
systemcomposer.openModel("TPMS_FunctionalArchitecture");

2. To create an allocation set for these models, launch the Allocation Editor by navigating to
Modeling > Allocation Editor from the toolstrip.

8-2
Create and Manage Allocations Interactively

The Allocation Editor has three parts: the toolstrip, the browser pane, and the allocation matrix.

• Use the toolstrip to create and manage allocation sets.


• Use the Allocation Set Browser pane to browse and open existing allocation sets.
• Use the allocation matrix to specify allocations between the source model elements in the first
column and target model elements in the first row. You can create allocations programmatically or
by double-clicking a cell in the matrix.

3. Click New Allocation Set to create a new allocation set between two models and set the name. In
this example, TPMS_FunctionalArchitecture.slx is the source model, and
TPMS_LogicalArchitecture.slx is the target model.

4. To create an allocation between two elements of the same type from the source model to the target
model, double-click the corresponding cell in the allocation matrix. Double-click the cell for the

8-3
8 Allocate Architecture Models

Report Low Tire Pressure component on the source model and the TPMS Reporting System
component on the target model.

5. To show allocations on model elements for the source model TPMS_FunctionalArchitecture,


on the toolstrip, navigate to Modeling > Allocation Editor > Show Allocations. Select the Report
Low Tire Pressure source component and click the allocated to symbol. You will see the full path
of the target component.

6. Click the target component to navigate to it on the target model.

8-4
Create and Manage Allocations Interactively

8-5
8 Allocate Architecture Models

7. Return to the source model TPMS_FunctionalArchitecture and create a new allocation from a
model element. Right-click the Calculate if pressure is low component, and from the tooltip
select Allocations, then select Select as allocation source.

8. On the target model TPMS_LogicalArchitecture, right-click the TPMS Reporting System


component, from the tooltip, select Allocations. Then, select Allocate to selected element.
Choose the active allocation scenario.

9. To show allocations on model elements for the target model TPMS_LogicalArchitecture, on the
toolstrip, navigate to Modeling > Allocation Editor > Show Allocations. Click the allocated from
symbol on the TPMS Reporting System component to view the full path of the two allocated-from
components. Click the icon on either component to delete the allocation and deallocate the
components. Click Confirm delete to continue deleting.

8-6
Create and Manage Allocations Interactively

Assign Stereotypes to Allocations

Stereotypes on allocations capture metadata on the relationship between model elements to map
from one environment to another.

1. Open the Profile Editor from the Allocation Editor. Create a stereotype called
FunctionalAllocation in your profile that applies to allocations. Then, define a property called
IsImplemented of type boolean.

8-7
8 Allocate Architecture Models

2. Return to the Allocation Editor and select the FunctionalAllocation allocation set. Import

the TPMSProfile profile on the Allocation Set Properties tab by clicking the button.

8-8
Create and Manage Allocations Interactively

3. Click Scenario 1 on the FunctionalAllocation allocation set. Select an allocation. From the
Allocation Properties tab, select the FunctionalAllocation stereotype.

8-9
8 Allocate Architecture Models

You can now check the IsImplemented property to indicate that the functional to logical allocation
is implemented. Properties represent a directed relationship from a source model to a target model
and extend the architectural modeling language.

References
[1] Carter, Jeffrey. “Functional Architecture.” Guide to the Systems Engineering Body of Knowledge
(SEBoK) v. 2.7, released October 31, 2022. https://sebokwiki.org/wiki/
Functional_Architecture.

[2] Faisandier, Alan, Garry Roedler, and Rick Adcock. “Logical Architecture.” Guide to the Systems
Engineering Body of Knowledge (SEBoK) v. 2.7, released October 31, 2022. https://
sebokwiki.org/wiki/Logical_Architecture.

See Also
Objects
systemcomposer.allocation.AllocationScenario |
systemcomposer.allocation.AllocationSet | systemcomposer.allocation.Allocation

Functions
editor | getScenario | allocate | synchronizeChanges | applyProfile | applyStereotype

More About
• “Create and Manage Allocations Programmatically” on page 8-11
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Allocate Architectures in Tire Pressure Monitoring System” on page 8-14
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35

8-10
Create and Manage Allocations Programmatically

Create and Manage Allocations Programmatically


This example shows how to create and manage System Composer allocations using the Allocation
Editor and programmatic interfaces.

In systems engineering, an architectural system is commonly described on different levels. Functional


architectures [1] describe the high-level functions of a system. Logical architectures [2] describe the
logical components of a system and how data is exchanged between them. You can use allocations to
establish relationships from functional components to logical components and to indicate deployment
strategies.

• An allocation establishes a directed relationship from architectural elements — components,


ports, and connectors — in one model to architectural elements in another model.

Resource-based allocation allows you to allocate functional architectural elements to logical


architectural elements and logical architectural elements to physical architectural elements.
• An allocation scenario contains a set of allocations between a source and a target model.

Allocate between model elements in an allocation scenario. The default allocation scenario is
called Scenario 1.
• An allocation set consists of one or more allocation scenarios that describe various allocations
between a source and a target model.

Create an allocation set with allocation scenarios in the Allocation Editor. Allocation sets are saved
as MLDATX files.

To create allocations interactively, see “Create and Manage Allocations Interactively” on page 8-2.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Create and Manage Allocations Using Tire Pressure Monitoring System

This example uses the Tire Pressure Monitoring System (TPMS) project. To open the project, use this
command.

openProject("scExampleTirePressureMonitorSystem");

Create New Allocation Set

You can create an allocation set using the Allocation Editor. In this example,
TPMS_FunctionalArchitecture.slx is the source model and
TPMS_LogicalArchitecture.slx is the target model.

To create an allocation set for these models, use this command.

allocSet = systemcomposer.allocation.createAllocationSet(...
'FunctionalToLogical', ...% Name of the allocation set
'TPMS_FunctionalArchitecture', ... % Source model
'TPMS_LogicalArchitecture' ... % Target model
);

8-11
8 Allocate Architecture Models

To see the allocation set, open the Allocation Editor by using this command.

systemcomposer.allocation.editor

Create Allocations Between Two Models

This example shows how to programmatically create allocations between two models in the TPMS
project.

Get systemcomposer.arch.Component objects for the reporting functions in the functional


architecture model.

functionalArch = systemcomposer.loadModel('TPMS_FunctionalArchitecture');
reportLevels = functionalArch.lookup('Path',...
'TPMS_FunctionalArchitecture/Report Tire Pressure Levels');
reportLow = functionalArch.lookup('Path',...
'TPMS_FunctionalArchitecture/Report Low Tire Pressure');

Get the systemcomposer.arch.Component object for the TPMS reporting system component in
the logical architecture model.

logicalArch = systemcomposer.loadModel('TPMS_LogicalArchitecture');
reportingSystem = logicalArch.lookup('Path',...
'TPMS_LogicalArchitecture/TPMS Reporting System');

Create the allocations in the default scenario that is created.

defaultScenario = allocSet.getScenario('Scenario 1');


alloc = defaultScenario.allocate(reportLevels,reportingSystem);
defaultScenario.allocate(reportLow,reportingSystem);

Optionally, you can delete the allocation between reporting low tire pressure and reporting system.

% defaultScenario.deallocate(reportLow,reportingSystem);

Use Stereotypes on Allocations

This example shows how to programmatically apply stereotypes to allocations and use stereotypes to
parameterize allocations.

allocSet.applyProfile("TPMSProfile")
alloc.applyStereotype("TPMSProfile.FunctionalAllocation")
setProperty(alloc,"TPMSProfile.FunctionalAllocation.IsImplemented","true")

References
[1] Carter, Jeffrey. “Functional Architecture.” Guide to the Systems Engineering Body of Knowledge
(SEBoK) v. 2.7, released October 31, 2022. https://sebokwiki.org/wiki/
Functional_Architecture.

[2] Faisandier, Alan, Garry Roedler, and Rick Adcock. “Logical Architecture.” Guide to the Systems
Engineering Body of Knowledge (SEBoK) v. 2.7, released October 31, 2022. https://
sebokwiki.org/wiki/Logical_Architecture.

8-12
Create and Manage Allocations Programmatically

See Also
Objects
systemcomposer.allocation.AllocationScenario |
systemcomposer.allocation.AllocationSet | systemcomposer.allocation.Allocation

Functions
editor | getScenario | allocate | synchronizeChanges | applyProfile | applyStereotype

More About
• “Create and Manage Allocations Interactively” on page 8-2
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Allocate Architectures in Tire Pressure Monitoring System” on page 8-14
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35

8-13
8 Allocate Architecture Models

Allocate Architectures in Tire Pressure Monitoring System

Use allocations to analyze a tire pressure monitoring system.

Overview

In systems engineering, it is common to describe a system at different levels of abstraction. For


example, you can describe a system in terms of its high-level functions. These functions may not have
any behavior associated with them but most likely trace back to some operating requirements the
system must fulfill. We refer to this layer (or architecture) as the functional architecture. In this
example, an automobile tire pressure monitoring system is described in three different architectures:
1 Functional Architecture — Describes the system in terms of its high-level functions. The
connections show dependencies between functions [1].
2 Logical Architecture — Describes the system in terms of its logical components and how data is
exchanged between them. Additionally, this architecture specifies behaviors for model simulation
[2].
3 Platform Architecture — Describes the physical hardware needed for the system at a high level
[3].

Note: This example illustrates allocations in System Composer™ using a specific methodology.
However, you can use other methodologies that fit your needs.

The allocation process is defined as linking these three architectures that fully describe the system.
The linking captures the information about each architectural layer and makes it accessible to the
others.

Use this command to open the project.


openProject("scExampleTirePressureMonitorSystem");

Open the FunctionalAllocation.mldatx file, which displays allocations from


TPMS_FunctionalArchitecture to TPMS_LogicalArchitecture in the Allocation Editor. The

8-14
Allocate Architectures in Tire Pressure Monitoring System

elements of TPMS_FunctionalArchitecture are displayed in the first column. The elements of


TPMS_LogicalArchitecture are displayed in the first row. The arrows indicate the allocations
between model elements.

The arrows display allocated components in the model. You can observe allocations for each element
in the model hierarchy.

The rest of the example shows how to use this allocation information to further analyze the model.

Functional to Logical Allocation and Coverage Analysis

This section shows how to perform coverage analysis to verify that all functions have been allocated.
This process requires using the allocation information specified between the functional and logical
architectures.

To start the analysis, load the allocation set.


allocSet = systemcomposer.allocation.load('FunctionalAllocation');
scenario = allocSet.Scenarios;

Verify that each function in the system is allocated.


import systemcomposer.query.*;
[~,allFunctions] = allocSet.SourceModel.find(HasStereotype(IsStereotypeDerivedFrom("TPMSProfile.F
unAllocatedFunctions = [];
ImplementedAllocations = [];
for i = 1:numel(allFunctions)
alloc = scenario.getAllocatedTo(allFunctions(i));
if isempty(alloc)
unAllocatedFunctions(end+1) = allFunctions(i);
end
end

allCompsSource = allocSet.SourceModel.find(AnyComponent);

8-15
8 Allocate Architecture Models

allCompsTarget = allocSet.TargetModel.find(AnyComponent);
for i = 1:numel(allCompsSource)
for j = 1:numel(allCompsTarget)
sourceComp = allocSet.SourceModel.lookup(Path=allCompsSource{i});
targetComp = allocSet.TargetModel.lookup(Path=allCompsTarget{j});
allocated = scenario.getAllocation(sourceComp,targetComp);
if ~isempty(allocated)
if allocated.getPropertyValue("TPMSProfile.FunctionalAllocation.IsImplemented")
ImplementedAllocations(end+1) = strcat(sourceComp.Name," to ",targetComp.Name);
end
end
end
end

if isempty(unAllocatedFunctions)
fprintf('All functions are allocated');
else
fprintf('%d Functions have not been allocated',numel(unAllocatedFunctions));
end

All functions are allocated

if isempty(ImplementedAllocations)
fprintf('No allocations are implemented');
else
fprintf('%d Allocations have been implemented',numel(ImplementedAllocations));
end

6 Allocations have been implemented

The result displays All functions are allocated to verify that all functions in the system are
allocated and lists the allocations that have not been implemented.

Analyze Suppliers Providing Functions

This section shows how to identify which functions will be provided by which suppliers using the
specified allocations. Since suppliers will be delivering these components to the system integrator,
the supplier information is stored in the logical model.

suppliers = {'Supplier A','Supplier B','Supplier C','Supplier D'};


functionNames = arrayfun(@(x) x.Name, allFunctions,'UniformOutput',false);
numFunNames = length(allFunctions);
numSuppliers = length(suppliers);
allocTable = table('Size',[numFunNames,numSuppliers],'VariableTypes',...
repmat("double",1,numSuppliers));
allocTable.Properties.VariableNames = suppliers;
allocTable.Properties.RowNames = functionNames;
for i = 1:numFunNames
elem = scenario.getAllocatedTo(allFunctions(i));
for j = 1:numel(elem)
elemSupplier = getEvaluatedPropertyValue(elem(j),"TPMSProfile.LogicalComponent.Supplier");
allocTable{i,strcmp(elemSupplier,suppliers)} = 1;
end

end

The table shows which suppliers are responsible for the corresponding functions.

8-16
Allocate Architectures in Tire Pressure Monitoring System

allocTable

allocTable=8×4 table
Supplier A Supplier B Supplier C Supplier D
__________ __________ __________ __________

Measure Tire Pressure 0 0 0 0


Measure pressure on tire 0 0 1 0
Report Tire Pressure Levels 1 0 0 0
Report Low Tire Pressure 1 0 0 0
Measure temprature of tire 0 0 0 1
Calculate if pressure is low 1 0 0 0
Calculate Tire Pressure 0 1 0 0
Measure rotations 0 1 0 0

Analyze Software Deployment Strategies

You can determine if the Engine Control Unit (ECU) has enough capacity to house all the software
components. The software components are allocated to the cores themselves, but the ECU is the
component that has the budget property.

Get the platform architecture.


platformArch = systemcomposer.loadModel('PlatformArchitecture');

Load the allocation.


softwareDeployment = systemcomposer.allocation.load('SoftwareDeployment');

frontECU = platformArch.lookup('Path','PlatformArchitecture/Front ECU');


rearECU = platformArch.lookup('Path','PlatformArchitecture/Rear ECU');

scenario1 = softwareDeployment.getScenario('Scenario 1');


scenario2 = softwareDeployment.getScenario('Scenario 2');
frontECU_availMemory = getEvaluatedPropertyValue(frontECU,"TPMSProfile.ECU.MemoryCapacity");
rearECU_availMemory = getEvaluatedPropertyValue(rearECU,"TPMSProfile.ECU.MemoryCapacity");

frontECU_memoryUsed1 = getUtilizedMemoryOnECU(frontECU,scenario1);
frontECU_isOverBudget1 = frontECU_memoryUsed1 > frontECU_availMemory;
rearECU_memoryUsed1 = getUtilizedMemoryOnECU(rearECU,scenario1);
rearECU_isOverBudget1 = rearECU_memoryUsed1 > rearECU_availMemory;

frontECU_memoryUsed2 = getUtilizedMemoryOnECU(frontECU,scenario2);
frontECU_isOverBudget2 = frontECU_memoryUsed2 > frontECU_availMemory;
rearECU_memoryUsed2 = getUtilizedMemoryOnECU(rearECU,scenario2);
rearECU_isOverBudget2 = rearECU_memoryUsed2 > rearECU_availMemory;

Build a table to showcase the results.


softwareDeploymentTable = table([frontECU_memoryUsed1;frontECU_availMemory;...
frontECU_isOverBudget1;rearECU_memoryUsed1;rearECU_availMemory;rearECU_isOverBudget1],...
[frontECU_memoryUsed2; frontECU_availMemory; frontECU_isOverBudget2;rearECU_memoryUsed2;...
rearECU_availMemory; rearECU_isOverBudget2],...
'VariableNames',{'Scenario 1','Scenario 2'},...
'RowNames',{'Front ECUMemory Used (MB)','Front ECU Memory (MB)','Front ECU Overloaded',...
'Rear ECU Memory Used (MB)','Rear ECU Memory (MB)','Rear ECU Overloaded'})

softwareDeploymentTable=6×2 table
Scenario 1 Scenario 2

8-17
8 Allocate Architecture Models

__________ __________

Front ECUMemory Used (MB) 110 90


Front ECU Memory (MB) 100 100
Front ECU Overloaded 1 0
Rear ECU Memory Used (MB) 0 20
Rear ECU Memory (MB) 100 100
Rear ECU Overloaded 0 0

function memoryUsed = getUtilizedMemoryOnECU(ecu, scenario)

For each component in the ECU, accumulate the binary size required for each allocated software
component.

coreNames = {'Core1','Core2','Core3','Core4'};
memoryUsed = 0;
for i = 1:numel(coreNames)
core = ecu.Model.lookup('Path',[ecu.getQualifiedName '/' coreNames{i}]);
allocatedSWComps = scenario.getAllocatedFrom(core);
for j = 1:numel(allocatedSWComps)
binarySize = getEvaluatedPropertyValue(allocatedSWComps(j),"TPMSProfile.SWComponent.BinaryS
memoryUsed = memoryUsed + binarySize;
end
end
end

References
[1] Carter, Jeffrey. “Functional Architecture.” Guide to the Systems Engineering Body of Knowledge
(SEBoK) v. 2.7, released October 31, 2022. https://sebokwiki.org/wiki/
Functional_Architecture.

[2] Faisandier, Alan, Garry Roedler, and Rick Adcock. “Logical Architecture.” Guide to the Systems
Engineering Body of Knowledge (SEBoK) v. 2.7, released October 31, 2022. https://
sebokwiki.org/wiki/Logical_Architecture.

[3] Faisandier, Alan, and Rick Adcock. “Physical Architecture.” Guide to the Systems Engineering
Body of Knowledge (SEBoK) v. 2.7, released October 31, 2022. https://sebokwiki.org/wiki/
Physical_Architecture.

See Also
Objects
systemcomposer.allocation.AllocationScenario |
systemcomposer.allocation.AllocationSet | systemcomposer.allocation.Allocation

Functions
editor | getScenario | allocate | synchronizeChanges | applyProfile | applyStereotype

More About
• “Create and Manage Allocations Interactively” on page 8-2
• “Create and Manage Allocations Programmatically” on page 8-11

8-18
Allocate Architectures in Tire Pressure Monitoring System

• “Extend System Composer Language Elements Using Profiles” on page 5-2


• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Analysis Function Constructs” on page 9-9
• “Organize System Composer Files in Projects” on page 12-2

8-19
8 Allocate Architecture Models

Systems Engineering Approach for SoC Applications

This example shows how to design a sample signal detector application on a System on Chip (SoC)
platform using a systems engineering approach. The workflow in this example maps the application
functions onto the selected hardware architecture.

The signal detector application continuously processes the signal data and classifies the signal as
either high or low frequency. The signal cannot change between high- and low-frequency classes
faster than 1 ms. The signal is sampled at the rate of 10 MHz.

Functional Architecture

Define the functional architecture of the application. At this stage, the implementation of the
application components is not known. You can use the System Composer™ software to capture the
functional architecture.

This model represents the functional architecture with its main software components and their
connections.
systemcomposer.openModel('soc_signaldetector_func');

The functional architecture of the application consists of these top-level components:


1 Generate Signal
2 Preprocess Signal
3 Classify Signal
4 Activate LEDs

Hardware Architecture

Select the hardware architecture. Due to the anticipated application complexity, choose an SoC
device. The chosen SoC device has a hardware programmable logic (FPGA) core and an embedded
processor (ARM) core. You can use the System Composer software to capture the details of the
hardware architecture.

8-20
Systems Engineering Approach for SoC Applications

This model represents the hardware architecture with its main hardware components and their
connections.
systemcomposer.openModel('soc_signaldetector_arch');

Behavioral Modeling

If the implementations for functional components are available, you can add them to the functional
architecture as behaviors. In System Composer, for each functional component, you can link the
implementation behaviors as Simulink® models. To review the component implementations, double-
click each component in the functional architecture model.

After you define the behavior of each component, you can simulate the behavior of the entire
application and verify its functional correctness. Select Run in the functional architecture model.
Then, analyze the signals classification results in the Simulation Data Inspector. To change the
signal type, select the Generate Signal component and then select the Manual Switch block.
Confirm that the source signal is classified correctly.

Allocation of Functional and Hardware Elements

After refining the functional and hardware architecture, allocate different functional components to
different hardware elements to meet desired system performance benchmarks. In this case, some
functional components are constrained as to where in the hardware architecture they can be
implemented. You must implement the Generate Signal and Activate LEDs components on the
FPGA core in the chosen hardware architecture due to input output (I/O) connections. Comparatively,
you can implement the Preprocess Signal and Classify Signal components on either the
FPGA or on the processor core.
Component Constraint
Generate Signal FPGA

8-21
8 Allocate Architecture Models

Preprocess Signal -
Classify Signal -
Activate LEDs FPGA

This example shows how to use three possible scenarios for allocating the application functional
architecture to the hardware architecture.

• The FPGA handles preprocessing and classification.


• The FPGA handles preprocessing and the processor handles classification.
• The processor handles preprocessing and classification.

System Composer captures these scenarios as Scenario 1, Scenario 2, and Scenario 3 using
the Allocation Editor.

allocSet = systemcomposer.allocation.load('soc_signaldetector_allocation');
systemcomposer.allocation.editor

Choosing an allocation scenario requires finding an implementation that optimally meets the
application requirements. Often you can find this implementation via static analysis without detailed
simulation. In this example, use static analysis to analyze the computational costs of implementing
different functional components on the processor and on the FPGA.

Implementation Cost

The implementation cost of a component depends on the required computation operations. To


determine the implementation costs, consider these typical approaches.

• Component implementation is not available: Obtain the computational cost from the available
reference implementations.
• The implementation and the hardware are available: Measure or profile the implementation cost
on the candidate hardware.
• The implementation is available, but the hardware is not: Estimate the implementation cost by
using the SoC Blockset™ algorithm analyzer function socAlgorithmAnalyzerReport.

8-22
Systems Engineering Approach for SoC Applications

The socModelAnalyzer function estimates the number of operations in a Simulink model and
generates an algorithm analyzer report. To get the number of operations that a model executes to
then analyze the implementation cost on the processor, use the dynamic analysis function option. To
get the number of operators an algorithm requires to then analyze the implementation cost on the
FPGA, use the static analysis function option. For an example on how to use socModelAnalyzer, see
this sample function.

soc_signaldetector_costanalysis

*** Component: 'Preprocess Signal'


ADD(+) MUL(*)
______ ______

FPGA Implementation 15 16
Processor Implementation 15300 16320

*** Component: 'Classify Signal'


ADD(+) MUL(*)
______ ______

FPGA Implementation 32 18
Processor Implementation 32640 18360

The implementation costs for each functional component obtained in this code are entered in the
corresponding stereotypes in the functional architecture. To verify the values, select each component
in the functional architecture model and use the Property Inspector.

To learn more about socModelAnalyzer, see the “Compare FIR Filter Implementations Using
socModelAnalyzer” (SoC Blockset) example. This example shows how to analyze the computational
complexity of different implementations of a Simulink algorithm.

Allocation Choice

You can use the number of operators or operations that are required for implementing the application
functional components to decide how to allocate the functional components to the hardware
components. Analyze the candidate allocations by comparing the implementation cost against the
available resources of the FPGA and the processor. This example uses sample values in the FPGA and
the processor components in the hardware architecture model for the available computation
resources. Verify the values by using the Property Inspector.

Typically, the analysis does not use the number of operators or operations directly. Rather, the
number of operators or operations are multiplied by the cost of each operator or operation first. The
cost of the operator or operations is hardware dependent. Determining such costs is beyond the
scope of this example.

For an example on how to use the cost models, use this function. Observe that we require the
capacity of the FPGA and the processor be greater than the estimated implementation cost as well as
that the processor headroom be between 60 and 90 %.

soc_signaldetector_partitionanalysis

FPGA DSPs Used (out of 900) FPGA LUT Used (out of 218600) Processor Instr
___________________________ _____________________________ _______________

8-23
8 Allocate Architecture Models

Scenario 1 34 576
Scenario 2 16 192
Scenario 3 0 0

Based on the results Scenario 2 is feasible.

Data Path Design Between FPGA and Processor

The FPGA processes data sample-by-sample, and the processor processes frame-by-frame. Because
the duration of a processor task can vary, to prevent data loss, a queue is needed to hold the data
between the FPGA and processor. In this case you must set these parameters that are related to the
queue: frame size, number of frame buffers, and FIFO size (that is, the number of samples in the
FIFO). Also, in embedded applications, the task durations can vary between different task instances
(for example, due to different code execution paths or due to variations in OS switching time). As a
result, data might be dropped in the memory channel. The “Streaming Data from Hardware to
Software” (SoC Blockset) example shows a systematic approach to choosing the previously mentioned
parameters that satisfy the application requirements.

See Also
socAlgorithmAnalyzerReport | socModelAnalyzer | systemcomposer.allocation.editor

More About
• “Using the Algorithm Analyzer Report” (SoC Blockset)
• “Create and Manage Allocations Programmatically” on page 8-11
• “Analyze Architecture” on page 9-2
• “Compose Architectures Visually” on page 1-5
• “Implement Component Behavior Using Simulink” on page 7-2

8-24
9

Analyze Architecture Model

• “Analyze Architecture” on page 9-2


• “Analysis Function Constructs” on page 9-9
• “Battery Sizing and Automotive Electrical System Analysis” on page 9-15
• “Calculate Endurance Using Quadcopter Architectural Design” on page 9-17
• “Design Insulin Infusion Pump Using Model-Based Systems Engineering” on page 9-24
• “Simple Roll-Up Analysis Using Robot System with Properties” on page 9-38
9 Analyze Architecture Model

Analyze Architecture

Perform static analysis on a System Composer architecture to evaluate characteristics of the system.

Analysis is a method for quantitatively evaluating an architecture for certain characteristics. Static
analysis analyzes the structure of the system. Static analysis uses an analysis function and parametric
values of properties captured in the system model.

Use analyses to calculate overall reliability, mass roll-up, performance, or thermal characteristics of a
system, or to perform a size, weight, and power (SWaP) analysis to increase efficiency.

Write static analyses based on element properties to perform data-driven trade studies and verify
system requirements. Consider an electromechanical system where there is a trade-off between cost
and weight, and lighter components tend to cost more. The decision process involves analyzing the
overall cost and weight of the system based on the properties of its elements, and iterating on the
properties to arrive at a solution that is acceptable both from the cost and weight perspective.

The analysis workflow consists of these steps:

1 Define a profile containing a set of stereotypes that describe some analyzable properties (for
example, cost and weight).
2 Apply the profile to an architecture model and add stereotypes from that profile to elements of
the model (components, ports, or connectors).
3 Specify values for the properties on those elements.
4 Write an analysis function to compute values necessary for the trade study. This is a static
constraint solver for parametrics and values of related properties captured in the system model.
5 Create an instance of the architecture model, which is a tree of elements, corresponding to the
model hierarchy with all shared architectures expanded and a variant configuration applied. Use
the Instantiate Architecture Model tool.
6 Run the analysis function and then see analysis calculations and results in the Analysis Viewer
tool.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Set Properties for Analysis


This example shows how to enable analysis by adding stereotypes to model elements and setting
property values. The model provides the basis to analyze the trade-off between total cost and weight
of the components in a simple architecture model of a robot system. For more information, see
“Simple Roll-Up Analysis Using Robot System with Properties” on page 9-38.

Open the Model

Open the RobotPhysicalArchitecture architecture model.

9-2
Analyze Architecture

Import Profile

Enable analysis of properties by first importing a profile. In the toolstrip, navigate to Modeling >
Profiles > Import and browse to the profile to import it.

Apply Stereotypes to Model Elements

Apply stereotypes to all model elements that are part of the analysis. Use the Apply Stereotypes
dialog to apply stereotypes to all elements of a certain type. Navigate to Modeling > Apply
Stereotypes. In Apply Stereotypes, from Apply stereotype(s) to, select Components. From Scope,
select This layer. For more information, see “Use Apply Stereotypes Dialog to Batch Apply
Stereotypes” on page 5-18.

Tip Make sure you apply the stereotype to the top-level component if a cumulative value is to be
computed.

Set Property Values

Set property values for each model element in the Property Inspector. To open the Property Inspector,
navigate to Modeling > Property Inspector.

1 Select the model element.


2 In the Property Inspector, expand the stereotype name and type values for properties.

9-3
9 Analyze Architecture Model

Create a Model Instance for Analysis

Create an instance of the architecture model that you can use for analysis.

An instance is an occurrence of an architecture model element at a given point in time.

An instance freezes the active variant or model reference of the component in the instance model.

An instance model is a collection of instances.

You can update an instance model with changes to a model, but the instance model will not update
with changes in active variants or model references. You can use an instance model, saved in a MAT
file, of a System Composer architecture model for analysis.

Navigate to Modeling > Analysis Model to open the Instantiate Architecture Model tool. Specify all
the parameters required to create and view an analysis model.

9-4
Analyze Architecture

The Select Stereotypes tree lists the stereotypes of all profiles that have been loaded in the current
session and allows you to select those whose properties should be available in the instance model.
You can browse for an analysis function, create a new analysis function, or skip analysis at this point.
If the analysis function requires inputs other than elements in the model, such as an exchange rate to
compute cost, enter it in Function arguments. Select a mode for iterating through model elements,
for example, Bottom-up to move from the leaves of the tree to the root. Strict Mode ensures
elements in the instantiated model get properties only if the corresponding element in the
composition model has the stereotype applied.

Click Instantiate to create the instantiated architecture model and launch the Analysis Viewer tool.

The Analysis Viewer shows all elements in the first column. The other columns show properties for all
stereotypes chosen for the current instance. If a property is not part of a stereotype applied to an
element, that field is greyed out. You can use the Filter button to hide properties for certain
stereotypes. When you select an element, Instance Properties shows the stereotypes and property
values of the element. You can save an instance in a MAT-file and open it again in the Analysis Viewer.

If you make changes in the model while an instance is open, you can synchronize the instance with
the model. Update pushes the changes from the instance to the model. Refresh pulls changes to the
instance from the model. Unsynchronized changes are shown in a different color. Selecting a single
element enables the option to Update Element.

Note When you save an instance of a subsystem reference, it propagates to all other instances and
synchronizes. Model references continuously synchronize. In an analysis model, to ensure all unsaved
subsystem references synchronize, save your changes, and then click Refresh or Update in the
Analysis Viewer tool. For more information, see Edit and Save Subsystem Reference in “Reference
a Subsystem File in a Model”.

Write Analysis Function

9-5
9 Analyze Architecture Model

Write a function to analyze the architecture model using instances. An analysis function quantitatively
evaluates an architecture for certain characteristics.

An analysis function is a MATLAB function that computes values necessary to evaluate the
architecture using the properties of each element in the model instance.

Use an analysis function to calculate the result of an analysis.

For more information, see “Analysis Function Constructs” on page 9-9.

You can add an analysis function as you set up the analysis instance model. After you select the

stereotypes of interest, create a template function by clicking next to the Analysis function
field. The generated M-file includes the code to obtain all property values from all stereotypes that
are subject to analysis. The analysis function operates on a single element — aggregate values are
generated by iterating this function over all elements in the model when you run the analysis using
the Analysis Viewer tool.
function CostAndWeightRollupAnalysis(instance,varargin)
% Analysis function for the RobotPhysicalArchitecture.slx example

% Calculate total price


if instance.isComponent() && ~isempty(instance.Components)...
&& instance.hasValue('SystemProfile.PhysicalElement.UnitCost')
sysComponent_unitPrice = 0;
for child = instance.Components
if child.hasValue('SystemProfile.PhysicalElement.UnitCost')
comp_price = child.getValue('SystemProfile.PhysicalElement.UnitCost');
sysComponent_unitPrice = sysComponent_unitPrice + comp_price;
end
end
instance.setValue('SystemProfile.PhysicalElement.UnitCost',sysComponent_unitPrice);
end

In the generated file, instance is the instance of the element on which the analysis function runs
currently. You can perform these operations for analysis:

• Access a property of the instance:


instance.getValue("<profile>.<stereotype>.<property>")
• Set a property of an instance:
instance.setValue("<profile>.<stereotype>.<property>",value)
• Access the subcomponents of a component: instance.Components
• Access the connectors in component: instance.Connectors

The getValue function generates an error if the property does not exist. You can use hasValue to
query whether elements in the model have the properties before getting the value.

As an example, this code computes the weight of a component as a sum of the weights of its
subcomponents.
% Calculate total weight
if instance.isComponent() && ~isempty(instance.Components)...
&& instance.hasValue('SystemProfile.PhysicalElement.UnitWeight')
weight = 0;
for child = instance.Components
if child.hasValue('SystemProfile.PhysicalElement.UnitWeight')
subcomp_weight = child.getValue('SystemProfile.PhysicalElement.UnitWeight');
weight = weight + subcomp_weight;
end
end
instance.setValue('SystemProfile.PhysicalElement.UnitWeight',weight);
end

9-6
Analyze Architecture

Once the analysis function is complete, add it to the analysis under the Analysis function box. An
analysis function can take additional input arguments, for example, a conversion constant if the
weights are in different units in different stereotypes. When this code runs for all components
recursively, starting from the deepest components in the hierarchy to the top level, the overall weight
of the system is assigned to the weight property of the top-level component.

Run Analysis Function


Run an analysis function using the Analysis Viewer.

1 Select or change the analysis function using the Analyze menu.


2 Select the iteration method.

• Pre-order — Start from the top level, move to a child component, and process the
subcomponents of that component recursively before moving to a sibling component.
• Top-Down — Like pre-order, but process all sibling components before moving to their
subcomponents.
• Post-order — Start from components with no subcomponents, process each sibling, and
then move to parent.
• Bottom-up — Like post-order, but process all subcomponents at the same depth before
moving to their parents.

The iteration method depends on what kind of analysis is to be run. For example, for an analysis
where the component weight is the sum of the weights of its components, you must make sure
the subcomponent weights are computed first, so the iteration method must be bottom-up.
3 Click the Analyze button.

System Composer runs the analysis function over each model element and computes results. The
computed properties are highlighted yellow in the Analysis Viewer.

Here, the total cost of the system is 5100 dollars and the total weight is 55 kg.

See Also
Tools
Profile Editor | Instantiate Architecture Model | Analysis Viewer

Objects
systemcomposer.analysis.Instance

Functions
iterate | instantiate | deleteInstance | update | refresh | save | loadInstance | lookup
| getValue | setValue | hasValue

9-7
9 Analyze Architecture Model

More About
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Organize System Composer Files in Projects” on page 12-2
• “Simple Roll-Up Analysis Using Robot System with Properties” on page 9-38
• “Analysis Function Constructs” on page 9-9
• “Calculate Endurance Using Quadcopter Architectural Design” on page 9-17

9-8
Analysis Function Constructs

Analysis Function Constructs


Analyze architectures to choose between design alternatives or improve existing designs. You can use
analysis functions with System Composer architecture models to perform systems analysis and trade
studies.

An analysis function is a MATLAB function that computes values necessary to evaluate the
architecture using the properties of each element in the model instance.

Use an analysis function to calculate the result of an analysis and determine the optimal parameters
to use for behavior models to simulate the architectural system.

Type Section
Roll-up analysis “Roll-Up Analysis for Quadcopter Design” on page 9-9
Class-based analysis “Class-Based Analysis for Battery Sizing” on page 9-10
Allocation-based analysis “Allocation-Based Analysis for Tire Pressure Monitoring” on page
9-11
Remaining useful life (RUL) “Remaining Useful Life Analysis for Mobile Robot Design” on page
analysis 9-11
Variant analysis “Variant Analysis for Insulin Infusion Pump Design” on page 9-12

For more information on analysis functions and architecture instances, see “Analyze Architecture” on
page 9-2.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Roll-Up Analysis for Quadcopter Design


Use a roll-up analysis function to calculate a total or average of model element property values.
Assign properties to model elements using stereotypes. For more information, see “Define and Style
Stereotypes in Profiles” on page 5-5.

In this example, the analysis function CostAndWeightRollupAnalysis calculates the total cost of
all components in the model and is compatible with the Analysis Viewer tool.
function CostAndWeightRollupAnalysis(instance,varargin)
% Analysis function for the RobotPhysicalArchitecture.slx example

% Calculate total price


if instance.isComponent() && ~isempty(instance.Components)...
&& instance.hasValue('SystemProfile.PhysicalElement.UnitCost')
sysComponent_unitPrice = 0;
for child = instance.Components
if child.hasValue('SystemProfile.PhysicalElement.UnitCost')
comp_price = child.getValue('SystemProfile.PhysicalElement.UnitCost');
sysComponent_unitPrice = sysComponent_unitPrice + comp_price;
end
end
instance.setValue('SystemProfile.PhysicalElement.UnitCost',sysComponent_unitPrice);
end

This analysis function iterates through an architecture instance. First, the


sysComponent_unitPrice variable is set to zero so that every time the analysis is run, sums do not

9-9
9 Analyze Architecture Model

accumulate indefinitely. Each component instance is checked for a UnitCost property value. All
UnitCost property values are summed up and saved in the sysComponent_unitPrice variable.
Finally, the UnitCost property of the current component instance is updated with the value of
sysComponent_unitPrice. For more information, see “Write Analysis Function” on page 9-5 and
“Simple Roll-Up Analysis Using Robot System with Properties” on page 9-38.

In this example, a section of the analysis function calculateEndurance calculates endurance for a
quadcopter using component instance properties. The calculated endurance value is then set for the
architecture instance of the quadcopter with the setValue function.
if payloadBatteryCapacity == 0
totalPower = powerConsumption + hoverPower/efficiency;
endurance = (batteryCapacity/1000)/(totalPower/voltage)*60;
else
payloadEndurance = (payloadBatteryCapacity/1000)/(powerConsumption/voltage)*60;
flightEndurance = (batteryCapacity/1000)/((hoverPower/efficiency)/voltage)*60;
if flightEndurance < payloadEndurance
endurance = flightEndurance;
else
endurance = payloadEndurance;
warning('Endurance is limited by payload electronics.')
end
end
instance.setValue('AirVehicle.Endurance',endurance)

For more information and for the supporting files, see “Calculate Endurance Using Quadcopter
Architectural Design” on page 9-17.

Class-Based Analysis for Battery Sizing


Use MATLAB classes for an analysis function to iterate over an object, or instantiation of the class.

In this example, the class called computeBatterySizing involves properties and methods useful for
the analysis function computeLoad.
classdef computeBatterySizing < handle

properties
totalCrankingInrushCurrent;
totalCrankingCurrent;
totalAccesoriesCurrent;
totalKeyOffLoad;
batteryCCA;
batteryCapacity;
puekertcoefficient;
end

methods
function obj = computeBatterySizing(obj)
obj.totalCrankingInrushCurrent = 0;
obj.totalCrankingCurrent = 0;
obj.totalAccesoriesCurrent = 0;
obj.totalKeyOffLoad = 0;
obj.batteryCCA = 0;
obj.batteryCapacity = 0;
obj.puekertcoefficient = 1.2;
end

function obj = displayResults(obj)


tempNumdaysToDischarge = ...
(((obj.batteryCapacity/obj.puekertcoefficient)*0.3)/(obj.totalKeyOffLoad*1e-3))/24;
disp("Total KeyOffLoad: " + num2str(obj.totalKeyOffLoad) + " mA");
disp("Number of days required for KeyOffLoad to discharge 30% of battery: " + ...
num2str(tempNumdaysToDischarge) + ".");
disp("Total CrankingInRush current: " + num2str(obj.totalCrankingInrushCurrent) + " A");
disp("Total Cranking current: " + num2str(obj.totalCrankingCurrent) + " A");

9-10
Analysis Function Constructs

if(obj.totalCrankingCurrent > obj.batteryCCA)


disp("The Cold Cranking Amps of the specified battery is not sufficient to start the car 0 F.")
else
disp("CCA of the specified battery is sufficient to start the car at 0 F.")
end
end
end
end

For more information and for the supporting files, see “Battery Sizing and Automotive Electrical
System Analysis” on page 9-15.

Allocation-Based Analysis for Tire Pressure Monitoring


A functional-to-logical allocation matrix allocates components in a functional architecture to
components in a logical architecture. Coverage analysis is the most basic form of analysis to
determine whether all elements have been allocated.

First, open the project for this example. Then, load the allocation set and collect the scenarios.

scExampleTirePressureMonitorSystem
allocSet = systemcomposer.allocation.load('FunctionalAllocation');
scenario = allocSet.Scenarios;

Verify that each function in the system is allocated.


import systemcomposer.query.*;
[~, allFunctions] = ...
allocSet.SourceModel.find(HasStereotype(IsStereotypeDerivedFrom("TPMSProfile.Function")));
unAllocatedFunctions = [];
for i = 1:numel(allFunctions)
if isempty(scenario.getAllocatedTo(allFunctions(i)))
unAllocatedFunctions = [unAllocatedFunctions allFunctions(i)];
end
end

if isempty(unAllocatedFunctions)
fprintf('All functions are allocated');
else
fprintf('%d Functions have not been allocated', numel(unAllocatedFunctions));
end

All functions are allocated

The output verifies that all functions are allocated.

For more information and for the supporting files, see “Allocate Architectures in Tire Pressure
Monitoring System” on page 8-14.

Remaining Useful Life Analysis for Mobile Robot Design


Remaining useful life (RUL) analysis estimates the time remaining before different subsystems fail.
The goal is to anticipate maintenance and thus minimize system disruptions.

In this example, the analysis function scMobileRobotAnalysis is compatible with the Analysis
Viewer tool.
function scMobileRobotAnalysis(instance,varargin)

ExpectedYearsBeforeFirstMaintenance = 2;

if ~instance.isArchitecture()
if instance.hasValue("HardwareBaseStereotype.Life")

9-11
9 Analyze Architecture Model

Life = instance.getValue("HardwareBaseStereotype.Life");
UsagePerDay = instance.getValue("HardwareBaseStereotype.UsagePerDay");
UsagePerYear = instance.getValue("HardwareBaseStereotype.UsagePerYear");
WillSurvive = Life > UsagePerDay * UsagePerYear * ExpectedYearsBeforeFirstMaintenance;
instance.setValue("HardwareBaseStereotype.ExceedExpectedMaintenance", WillSurvive);
end
end
end

After running this analysis function, you can optimize the desired first expected maintenance time in
years. Each component that exceeds the expected maintenance time, in this case set to two years, is
flagged with a check box. Unchecked components should be optimized or replaced with longer-lasting
parts.

For more information and for the supporting files, see “Define Stereotypes and Perform Analysis for
Mobile Robot” on page 5-53.

Variant Analysis for Insulin Infusion Pump Design


Use variant analysis to choose one optimal combination of variants by comparing them with a
calculated metric.

In this example, the analysis function OutcomeAnalysis is used to determine the best configuration
for an insulin infusion pump. This standalone analysis function does not involve the Analysis Viewer
tool. Instead, the analysis function uses the iterate function and can be executed directly from the
MATLAB Command Window.

The OutcomeAnalysis function first gathers all variant choice components named Pump and
BGSensor.
function outcomes = OutcomeAnalysis()

modelname = 'InsulinInfusionPumpSystem';

therapyModel = systemcomposer.openModel(modelname);
components = therapyModel.Architecture.Components;
for idx = 1:numel(components)
if strcmp(components(idx).Name,'Pump')
pumps = components(idx).getChoices;
pumpNames = {};
for jdx = 1:numel(pumps)
pumpNames{end+1} = pumps(jdx).Name;
end
elseif strcmp(components(idx).Name,'BGSensor')
sensors = components(idx).getChoices;
sensorNames = {};
for jdx = 1:numel(sensors)
sensorNames{end+1} = sensors(jdx).Name;
end
end
end

The analysis function then collects all variant combinations to iterate over.
config.Sensor = sensorNames{1};
config.Pump = pumpNames{1};
configs = {};

for idx = 1:numel(sensorNames)

9-12
Analysis Function Constructs

for jdx = 1:numel(pumpNames)


config.Sensor = sensorNames{idx};
config.Pump = pumpNames{jdx};
configs{end+1} = config;
end
end

The analysis function activates the variants one by one, iterates over the model properties, and
collects outcomes. To set variant combinations, OutcomeAnalysis uses the setVariants function.
To compute the outcomes, OutcomeAnalysis uses the computeOutcome function.

outcomes = {};

for idx = 1:numel(configs)


hOutcome = OutcomeContainer(configs{idx});
therapyModel.iterate('Topdown',@setVariants,configs{idx});
therapyModel.iterate('BottomUp',@computeOutcome,hOutcome);
hOutcome.setWeights([1e-6 1 10 1 1000]');
outcomes{end+1} = hOutcome;
end

Finally, the analysis function plots the net outcome to reveal the optimal design choice.
properties = {'Lower NRE','Higher Accuracy','Better Compliance',...
'Sooner To Market','Lower Operating Cost'};
plotMatrix = zeros(numel(outcomes), numel(properties));
plotStrings = {};
for idx = 1:numel(outcomes)
plotStrings{idx} = [outcomes{idx}.Sensor '+' outcomes{idx}.Pump];
plotMatrix(idx,1) = 1/(outcomes{idx}.NRE);
plotMatrix(idx,2) = outcomes{idx}.Accuracy;
plotMatrix(idx,3) = outcomes{idx}.Compliance;
plotMatrix(idx,4) = 1/(outcomes{idx}.TimeToMarket);
plotMatrix(idx,5) = 1/(outcomes{idx}.AnnualCost);
end

colmin = zeros(1,5);
colmax = max(plotMatrix);
normalizedMatrix = rescale(plotMatrix,'InputMin',colmin,'InputMax',colmax);

if exist('spider_plot') == 2
fig = figure;
spider_plot(normalizedMatrix,'AxesLabels',properties,'FillOption','on',...
'FillTransparency',0.1,'AxesDisplay','one');

title(sprintf('Trade Study Outcome'),...


'FontSize', 14);
legend(plotStrings, 'Location', 'eastoutside');
pos = fig.Position;
pos(2) = pos(2) - pos(4);
pos(3) = 2*pos(3);
pos(4) = 2*pos(4);
fig.Position = pos;
else
vals = sum(normalizedMatrix,2)/5;
x_labels = categorical(plotStrings);
h = bar(x_labels,vals);
title('Net outcome');
ax = h.Parent;
ax.YLabel.String = 'Normalized units';
end

For more information and for the supporting files, see “Design Insulin Infusion Pump Using Model-
Based Systems Engineering” on page 9-24.

9-13
9 Analyze Architecture Model

See Also
systemcomposer.analysis.Instance | iterate | instantiate | deleteInstance | update |
refresh | save | loadInstance | lookup | getValue | setValue | hasValue

More About
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Simple Roll-Up Analysis Using Robot System with Properties” on page 9-38
• “Analyze Architecture” on page 9-2
• “Organize System Composer Files in Projects” on page 12-2

9-14
Battery Sizing and Automotive Electrical System Analysis

Battery Sizing and Automotive Electrical System Analysis

Overview

Model a typical automotive electrical system as an architectural model and run a primitive analysis.
The elements in the model can be broadly grouped as either a source or a load. Various properties of
the sources and loads are set as part of the stereotype. This example uses the iterate method of the
specification API to iterate through each element of the model and run analysis using the stereotype
properties.

Structure of Model

The generator charges the battery while the engine is running. The battery and the generator
support the electrical loads in the vehicle, like ECU, radio, and body control. The inductive loads like
motors and other coils have the InRushCurrent stereotype property defined. Based on the
properties set on each component, the following analyses are performed:

• Total KeyOffLoad.
• Number of days required for KeyOffLoad to discharge 30% of the battery.
• Total CrankingInRush current.
• Total Cranking current.
• Ability of the battery to start the vehicle at 0°F based on the battery cold cranking amps (CCA).
The discharge time is computed based on Puekert coefficient (k), which describes the relationship
between the rate of discharge and the available capacity of the battery.

Load Model and Run Analysis

archModel = systemcomposer.loadModel('scExampleAutomotiveElectricalSystemAnalysis');

Instantiate battery sizing class used by the analysis function to store analysis results.

objcomputeBatterySizing = computeBatterySizing;

Run the analysis using the iterator.

archModel.iterate('Topdown',@computeLoad,objcomputeBatterySizing)

Display analysis results.

objcomputeBatterySizing.displayResults

Total KeyOffLoad: 158.708 mA


Number of days required for KeyOffLoad to discharge 30% of battery: 55.789.
Total CrankingInRush current: 70 A
Total Cranking current: 104 A
CCA of the specified battery is sufficient to start the car at 0 F.

ans =
computeBatterySizing with properties:

totalCrankingInrushCurrent: 70
totalCrankingCurrent: 104
totalAccesoriesCurrent: 71.6667
totalKeyOffLoad: 158.7080

9-15
9 Analyze Architecture Model

batteryCCA: 500
batteryCapacity: 850
puekertcoefficient: 1.2000

Close Model

bdclose('scExampleAutomotiveElectricalSystemAnalysis');

See Also
systemcomposer.analysis.Instance | iterate | instantiate | deleteInstance | update |
save | loadInstance | getValue | setValue | hasValue | lookup

More About
• “Analyze Architecture” on page 9-2
• “Analysis Function Constructs” on page 9-9
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35
• “Allocate Architectures in Tire Pressure Monitoring System” on page 8-14
• “Calculate Endurance Using Quadcopter Architectural Design” on page 9-17

9-16
Calculate Endurance Using Quadcopter Architectural Design

Calculate Endurance Using Quadcopter Architectural Design

This example shows you how to create the physical architecture [1] of a quadcopter following a target
green ball using System Composer™ and Requirements Toolbox™ and following a model-based
systems engineering (MBSE) workflow. Start by defining requirements, then extend architectural
data using stereotypes and custom property values for model elements, and finally use analysis to
iteratively improve on the design.

Define Functional Requirements for Quadcopter Design

The first step in the MBSE methodology is to define requirements. The concept of operations, or
conops, define the overall idea of the system. You then derive functional requirements from conops
requirements and further define the logical and physical subsystems by linking requirements.

Open the project.

openProject("scExampleQuadcopterEndurance");

Load Simulink® customizations.

sl_refresh_customizations

Load the physical architecture model in memory to view its requirement links.

systemcomposer.loadModel("QuadArchPhysical");

Load the requirement sets.

• Concept of operations

slreq.load("conops");

• Functional requirements

slreq.load("FunctionalReqs_Quad");

• Logical requirements

slreq.load("LogicalReqs_Quad");

• Physical requirements

slreq.load("PhysicalReqs_Quad");

Open the Requirements Editor (Requirements Toolbox).

slreq.editor

Inspect the conops requirement Target Characteristics. The requirements under the
Decomposed by list represent the requirements contained in the top-level requirement. The
requirement Target Identification under the Derived from list represents requirements
derived from the conops requirement.

9-17
9 Analyze Architecture Model

To open the quadcopter physical architecture model, run this code.

systemcomposer.openModel("QuadArchPhysical");

Add mask icons to your components by selecting a component and then navigating on the tooltrip to
Format > Add Image to Block. Browse for a mask icon from the Tools folder. Click OK.

Manage requirements and architecture together in the Requirements Manager from Requirements
Toolbox. Navigate to Apps > Requirements Manager. You are now in the Requirements Perspective
in System Composer. In this perspective, you can see which requirements are associated with specific
components in the physical architecture.

9-18
Calculate Endurance Using Quadcopter Architectural Design

Specify Functional Design Using Stereotypes and Properties

Stereotypes, defined on a profile, include properties to specify metadata on model elements to which
stereotypes are applied.

To open the Profile Editor tool, on the System Composer toolstrip, navigate to Modeling > Profile
Editor. Alternatively, run this command.

systemcomposer.profile.editor

9-19
9 Analyze Architecture Model

The AirVehicle stereotype applies to components and inherits from the base stereotype
HW_Implementation. Each property under the AirVehicle stereotype is specified by a data type
defined by Type, and some properties include an engineering unit defined by Unit. You can apply the
AirVehicle stereotype to components in the quadcopter physical architecture to elaborate on these
components with specific property values. Define these property values for the RPiCam_RadioComms
component in the Property Inspector.

9-20
Calculate Endurance Using Quadcopter Architectural Design

Perform Roll-Up Analysis to Calculate Endurance for Quadcopter Design

To open the Instantiate Architecture Model tool, on the System Composer toolstrip, navigate to
Modeling > Analysis Model. Select all the stereotypes under the

QuadcopterPhysicalProperties profile. Click the open button, then open the analysis
function file calculateEndurance.m. Select Bottom-up for Iteration Order. Click Instantiate.

9-21
9 Analyze Architecture Model

In the Analysis Viewer tool, you can use an analysis function to calculate roll-up property values such
as BatteryCapacity, PayloadBatteryCapacity, PowerDraw, and TotalMass. The analysis
function also calculates the performance characteristics PowerDraw and Endurance. For more
information, see “Analysis Function Constructs” on page 9-9. Click Analyze to view the analysis
results highlighted in yellow.

9-22
Calculate Endurance Using Quadcopter Architectural Design

The Endurance property for this particular configuration is calculated as approximately 3.825 using
this equation.

batteryCapacity
1000
endurance = totalPower
* 60
voltage

You can change the variant configuration on the Variant Component blocks, GCS and Quadcopter,
then run the analysis function again to calculate Endurance and compare different proposed
designs.

References
[1] Faisandier, Alan, and Rick Adcock. “Physical Architecture.” Guide to the Systems Engineering
Body of Knowledge (SEBoK) v. 2.7, released October 31, 2022. https://sebokwiki.org/wiki/
Physical_Architecture.

See Also
Blocks
Variant Component

Tools
Profile Editor | Instantiate Architecture Model | Requirements Editor | Analysis Viewer

Functions
systemcomposer.profile.editor | slreq.editor | sl_refresh_customizations

More About
• “Analyze Architecture” on page 9-2
• “Compose Architectures Visually” on page 1-5
• “Analysis Function Constructs” on page 9-9
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35
• “Modeling System Architecture of Keyless Entry System” on page 11-33
• “Model-Based Systems Engineering for Space-Based Applications” on page 1-43

9-23
9 Analyze Architecture Model

Design Insulin Infusion Pump Using Model-Based Systems


Engineering

This example shows you how to use a model-based systems engineering (MBSE) workflow to
investigate optimal insulin infusion pump design. Insulin pumps are medical devices used by people
with diabetes that mimic the human pancreas by delivering insulin continuously and delivering
variable amounts of insulin with food intake.

The purpose of an insulin pump wearable device is to keep the blood glucose level of the wearer near
a healthy set point by infusing insulin as needed and in response to food intake. This example shows a
proposed insulin infusion pump system with two sensor and three pump variants that represent
alternate design choices.

Begin by determining system requirements, then create detailed design models with code generation
and verification tests. Finally, simulate the system architecture model that meets the evolving
requirements.

Insulin Pump System Architecture Model

This figure shows the System Composer™ architecture model for the insulin pump system. This
example uses Stateflow® blocks. If you do not have a Stateflow license, you can open and simulate
the model but can only make basic changes, such as modifying block parameters.

openProject("scExampleInsulinPumpSystem");
systemcomposer.openModel("InsulinInfusionPumpSystem.slx");

The BGSensor component measures the blood glucose level. The Controller component makes a
decision about the insulin rate. The Pump component provides insulin to the body using the
InfusionSet. The Patient receives the treatment. The BGMeter calibrates the BGSensor. Finally,
the HID (human interface device) component may be a mobile app on the phone for the patient to
communicate with the system. The HID provides information to the PatientDataServer
component, which sends analyses to the Clinician, Regulator, and Reimburser components.

9-24
Design Insulin Infusion Pump Using Model-Based Systems Engineering

System Requirements and Links

Use Requirements Toolbox™ to analyze the system requirements, further break them down into
subsystem requirements, and link derived requirements to architectural components that satisfy
them. A Requirements Toolbox license is required to link, trace, and manage requirements in System
Composer.

Manage requirements and architecture together in the Requirements Perspective from Requirements
Toolbox. Select Apps > Requirements Manager. To edit requirements, select Requirements >
Requirements Editor or enter these commands to open the Requirements Editor (Requirements
Toolbox).

slreq.open("Infusion_Pump_System");
slreq.open("Insulin_Pump_Controller_Software_Specification");
slreq.editor

9-25
9 Analyze Architecture Model

The requirements decomposition and analysis at this point represent these concerns:

• Accuracy of delivery
• Mitigations against over-infusion, which leads to dangerously low blood glucose levels
• Fault analysis to prevent negative outcomes, for example, when the battery is depleted or the
device runs out of medication

On the architecture model, select the requirements icon to see the requirements that are associated
with the component. For example, below are the requirements linked to the Pump component.

9-26
Design Insulin Infusion Pump Using Model-Based Systems Engineering

Conversely, select a requirement to see the highlighted component by which the requirement is
implemented. For example, the BGSensor component implements the Sense blood glucose
requirement.

9-27
9 Analyze Architecture Model

Outcome Analysis for Optimal Design Choice

Outcome analysis consists of a trade study where the goal is to maximize the business value of the
design options based on calculations that sum up different component properties with weighting
factors. Many are directly entered properties, such as non-recurring engineering (NRE) costs to
develop the component. Compliance score, however, is a derived property that is based on different
data for each type of component. These properties model the burden to an end user of the system.
The compliance score includes these considerations:

• Energy consumption
• Size and weight
• Accuracy
• Mean time between failures (MTBF)
• Sound level produced during operation
• Ease of use

Navigate to Modeling > Profiles > Profile Editor, or enter this command.
systemcomposer.profile.editor

A System Composer profile, defined in the Profile Editor, is composed of stereotypes with properties
defined. You can apply stereotypes to components in the model to assign specific property values to
each component.

9-28
Design Insulin Infusion Pump Using Model-Based Systems Engineering

The pump and sensor trade study includes these steps:

1 Collect all variant combinations.


2 Activate variants one by one to represent all the combinations.
3 Iterate over the model to calculate compliance and compute the outcome using the stored and
calculated parameters.
4 Collect outcomes and weight them using the same units.
5 Provide the optimized option.

A Variant Component block named BGSensor contains two different sensor variants representing
example sensors from different manufacturers.

The Variant Component block named Pump contains three different pumps in this example called
PeristalticPump, SyringePump, and PatchPump.

9-29
9 Analyze Architecture Model

To programmatically cycle between the different variant choice combinations, calculate compliance,
and monitor the outcome to determine the optimal design choice, run OutcomeAnalysis.m. For
more information on variant analysis, see “Analysis Function Constructs” on page 9-9.

run("OutcomeAnalysis.m")

9-30
Design Insulin Infusion Pump Using Model-Based Systems Engineering

The normalized outcome score is at a maximum for the SensorA + SyringePump combination. This
design choice is optimal for the insulin pump.

Controller Implementation Model

Implement the insulin infusion pump controller in Simulink®. To access the Controller model,
navigate to the InsulinInfusionPumpSystem architecture model and double-click the
Controller component. The input ports in this implementation include User input, with user
metrics that the insulin pump reads, and Hardware status, with information about the insulin
pump. The block named ModeControl deteremines in which mode the insulin pump must operate.

9-31
9 Analyze Architecture Model

The block named ModeControl contains a Stateflow chart with details on how to select the mode.

The three modes include:

• Alarm mode, where the system is be suspended, repaired, and restarted once clear
• Bolus delivery mode to deliver insulin quickly with food intake
• Basal delivery mode to deliver insulin over a longer period of time to keep glucose levels steady
throughout the day

After the mode is selected, this component behavior determines the insulin rate for the outport.

9-32
Design Insulin Infusion Pump Using Model-Based Systems Engineering

Verification and Validation Using Test Manager

You can use model-based design to verify architectural designs and system requirements. The
abstract architecture model and the detailed Simulink design model are connected with traceable
requirement links. This section requires a Simulink® Test™ license.

The Controller implementation model in Simulink demonstrates requirements traceability for the
Alarm handling requirement.

9-33
9 Analyze Architecture Model

Load and view the Simulink Test Manager (Simulink Test) using these commands.

sltest.testmanager.load("Controller_Tests.mldatx");
sltest.testmanager.view

The Alarm_Detection functional test verifies the Alarm handling requirement.

9-34
Design Insulin Infusion Pump Using Model-Based Systems Engineering

Click the icon to the right of the Harness box to open the test harness. In this example, the block
named Controller is isolated for unit testing using a test harness. For more information on creating
a test harness, see “Create or Import Test Harnesses and Select Properties” (Simulink Test).

Double-click the Test Sequence block to view the steps in the test sequence. The steps define a
scenario to verify the functioning of the alarm system.

9-35
9 Analyze Architecture Model

To run this test, go back into the Simulink Test Manager (Simulink Test).

sltest.testmanager.view

Right-click the test Alarm_Detection in the Test Browser and select Run. In the Results and
Artifacts section, view your test results. A passing test indicates that the system requirement Alarm
handling is verified by the conditions defined in the Test Assessment Block:

• Whether the alarm disables insulin delivery when there is low battery, occlusion (line blockage), or
low medication (insulin)
• Whether the system restarts after the issue has passed

See Also
Apps
Profile Editor | Simulink Test Manager | Requirements Editor

9-36
Design Insulin Infusion Pump Using Model-Based Systems Engineering

More About
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Compose Architectures Visually” on page 1-5
• “Analysis Function Constructs” on page 9-9
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35
• “Calculate Endurance Using Quadcopter Architectural Design” on page 9-17
• “Model-Based Systems Engineering for Space-Based Applications” on page 1-43

9-37
9 Analyze Architecture Model

Simple Roll-Up Analysis Using Robot System with Properties

This example shows a simple roll-up analysis of a robotic system to calculate the total weight and cost
of the system from its individual parts. You can perform roll-up calculations on any other system
metric, for example, total power. In System Composer™, you can use the analysis tools to iterate over
elements in an architecture instance, perform calculations, and display the results in a table.

Open Model and Modify Properties Using Property Inspector

To open the model, run this command.


model = systemcomposer.openModel("RobotPhysicalArchitecture");

In the physical architecture [1] model, select the Computer component. In the Property Inspector,
expand the PhysicalComponent stereotype, and view or modify the property values for the
individual weight, UnitWeight, and the individual cost, UnitCost.

Based on the property definition on the SystemProfile profile, you can change property values of
model elements in the Property Inspector. Use the Profile Editor to change property names and
units for the SystemProfile profile.

Perform Simple Roll-Up Analysis To Calculate Total Cost and Total Weight

To perform a roll-up analysis, instantiate the architecture model by navigating to Modeling >
Analysis Model and opening the Instantiate Architecture Model tool. An instance model is a
collection of instances of architectural elements. Use this instance to calculate a total weight and
total cost for the system by adding up the individual values for each model element.

In the Instantiate Architecture Model tool, select all stereotypes by selecting the SystemProfile
profile check box. Specify the Analysis function by clicking the folder icon then selecting
CostAndWeightRollupAnalysis.m. Then, for Iteration Order, select Bottom-up. Confirm that

9-38
Simple Roll-Up Analysis Using Robot System with Properties

Strict Mode is selected, so that elements in the instantiated model get properties only if the
corresponding element in the composition model has the stereotype applied.

To view the instance, click Instantiate to create the instantiated architecture model and launch the
Analysis Viewer tool. Click Analyze to execute the bottom-up analysis iterator. The iterator calls the
analysis function for each element in the instantiated architecture as an input argument as the
iterator works its way from the deepest level of the architecture to the top.

The total cost for the RobotPhysicalArchitecture architecture model is 5,100 dollars, and
the total weight of the components is 55 kg. Using these metrics, systems designers can change the
overall design to meet system requirements then analyze the system again. Adjust the property

9-39
9 Analyze Architecture Model

values in the Analysis Viewer and rerun the analysis to optimize the design to reach a solution that
is acceptable both from the cost and weight perspectives.

References
[1] Faisandier, Alan, and Rick Adcock. “Physical Architecture.” Guide to the Systems Engineering
Body of Knowledge (SEBoK) v. 2.7, released October 31, 2022. https://sebokwiki.org/wiki/
Physical_Architecture.

See Also
Tools
Profile Editor | Instantiate Architecture Model | Analysis Viewer

Objects
systemcomposer.analysis.Instance

Functions
iterate | instantiate | deleteInstance | update | refresh | save | loadInstance | lookup
| getValue | setValue | hasValue

More About
• “Compose Architectures Visually” on page 1-5
• “Analyze Architecture” on page 9-2
• “Analysis Function Constructs” on page 9-9
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Calculate Endurance Using Quadcopter Architectural Design” on page 9-17

9-40
10

Software Architectures

• “Author Software Architectures” on page 10-2


• “Simulate and Deploy Software Architectures” on page 10-10
• “Model Software Architecture of Throttle Position Control System” on page 10-16
• “Class Diagram View of Software Architectures” on page 10-22
• “Author and Extend Functions for Software Architectures” on page 10-27
• “Merge Message Lines Using Adapter Block” on page 10-36
• “Author Functions for Software Components of Adaptive Cruise Control” on page 10-39
• “Service Interfaces Overview” on page 10-46
• “Model Service-Oriented Communication Between Sensors” on page 10-52
• “Simulate Asynchronous Services for Vehicle Headlight Management” on page 10-66
10 Software Architectures

Author Software Architectures


Software architectures in System Composer provides capabilities to author software architecture
models composed of software components, ports, and interfaces. Use System Composer to design
your software architecture model, simulate your design in the architecture level, and generate code.

Use software architectures to link your Simulink export-function, rate-based, or JMAAB models to
components in your architecture model to simulate and generate code.

These are relevant concepts for software architecture workflows:

• A software architecture is a specialization of an architecture for software-based systems, including


the description of software compositions, component functions, and their scheduling.

Use software architectures in System Composer to author software architecture models composed
of software components, ports, and interfaces. Design your software architecture model, define
the execution order of your component functions, simulate your design in the architecture level,
and generate code.
• A software component is a specialization of a component for software entities, including its
interfaces.

Implement a Simulink export-function, rate-based, or JMAAB model as a software component,


simulate the software architecture model, and generate code.
• A software composition is a diagram of software components and connectors that represents a
composite software entity, such as a module or application.

Encapsulate functionality by aggregating or nesting multiple software components or


compositions.

Create New Software Architecture Model


The workflow for authoring software architecture models is similar to authoring system architectures.
Start with a blank software architecture template to model.

You can create a software architecture programmatically by using the function.


systemcomposer.createModel("mySoftwareArchitectureDesign","SoftwareArchitecture")

where mySoftwareArchitectureDesign is the name of the new model.

You can also use the provided template in the Simulink start page.

Select Software Architecture Model.

10-2
Author Software Architectures

System Composer provides template architecture models that address different domains in systems
engineering and software architecture modeling: Architecture Model and Software Architecture
Model. All architecture models provide the same structural capabilities with some domain and
platform specific constraints. For more information on architecture templates, see “Choose
Architecture Template for System Design” on page 1-2.

From a Simulink model or a System Composer architecture model, on the Simulation tab, select

New , and then select Architecture . Then, select Software Architecture Model.

System Composer opens a new empty software architecture model. Observe the icon on the upper
left corner that distinguishes the empty model from a system architecture.

10-3
10 Software Architectures

When you model software architectures, you can:

• Use model-building and visualization tools provided by System Composer such as components,
connections, and ports. For more information, see “Compose Architectures Visually” on page 1-5.
• Define interfaces. For more information, see Interface Editor.
• Define profiles and stereotypes. For more information, see Profile Editor.
• Create custom views and sequence diagrams. For more information, see Architecture Views
Gallery.
• Use tools to write analysis. For more information, see Instantiate Architecture Model and Analysis
Viewer.
• Create allocations. For more information, see Allocation Editor.
• Define parameters. For more information, see Parameter Editor.
• Compare differences between two models. For more information, see System Composer
Comparison Tool.

Build a Simple Software Architecture Model


1 Drag an empty component to the mySoftwareArchitectureDesign model.

10-4
Author Software Architectures

2 Link this simple Simulink Export-Function model, export_model_software_architecture to


your component by right-clicking the component and selecting Link to Model. For more
information about building this Simulink model, see “Create Export-Function Model”.

3 Connect component input port and output ports to architecture input ports and output ports.

10-5
10 Software Architectures

In this example, you start from a blank template and create a simple software architecture model. To
learn how to simulate a software architecture model and generate code, see “Simulate and Deploy
Software Architectures” on page 10-10.

Import and Export Software Architectures


You can import a software architecture model using the systemcomposer.importModel function.

archModel = systemcomposer.importModel(modelName,importStruct)

If the domain field of importStruct is "Software", the importModel function creates a new
software architecture based on the structure of the MATLAB tables.

To export a System Composer software architecture model, use the systemcomposer.exportModel


function.

exportedSet = systemcomposer.exportModel(modelName)

The exportModel function returns a structure containing MATLAB tables that contains
components, ports, connections, portInterfaces, requirementLinks, and a domain field
with value 'Software' to indicate that the exported architecture is a software architecture.

For more information on importing and exporting software architectures with functions, see “Import
and Export Functions of Software Architectures” on page 10-34.

Export Architecture to Software Architecture


Create Software Architecture Model from Component

You can create a software architecture model from an existing component in a System Composer
architecture model.

To create a software architecture model from a component:

1 Select an existing component from your architecture model. In this example, Component2 is
selected.

10-6
Author Software Architectures

2 To create a software architecture model from Component2, you can use any of these three
methods:

a Right-click the component and select Create Software Architecture Model.


b Select the component and, on the toolstrip, click Create Software Architecture Model.

c To create a software architecture programmatically, use the createArchitectureModel


function.
3 Observe the software architecture model icon in the upper left corner. The new software
architecture contains all elements from the component, including previously applied stereotypes.

10-7
10 Software Architectures

Export Architecture to Software Architecture Model

To export your model to a software architecture, use one of these methods:

• In the toolstrip, on the Simulation tab, click the Save button arrow, then select a model type.

Once you select model type, you can specify the New model name and the Destination folder.
• Export your model programmatically using the
systemcomposer.exportToSoftwareArchitecture function.

Software Architecture Constraints and Limitations

The benefit of using the Software Architecture template is the application of software domain specific
constraints. To allow for the completion of the model-based design workflow, the template does not
support the use of these elements:

10-8
Author Software Architectures

• Adapter blocks with UnitDelay or RateTransition as the applied interface conversion. The
applied interface conversion changes to None for these Adapter blocks.
• Physical ports.

Some model elements are not supported in the software architecture model template. These elements
include:

• A component with Stateflow chart behavior.


• A Reference Component block linked to a Simulink subsystem, subsystem reference, or model
containing an FMU block.

Note For more information regarding saving a component or architecture as an AUTOSAR


architecture, see “Create AUTOSAR Architecture from System Composer Model” (AUTOSAR
Blockset).

See Also
systemcomposer.createModel | createArchitectureModel | createSimulinkBehavior

More About
• “Compose Architectures Visually” on page 1-5
• “Export Architecture to Software or AUTOSAR Architecture” on page 1-66
• “Create Export-Function Model”
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Class Diagram View of Software Architectures” on page 10-22
• “Model Software Architecture of Throttle Position Control System” on page 10-16
• “Simulate and Deploy Software Architectures” on page 10-10

10-9
10 Software Architectures

Simulate and Deploy Software Architectures

This example shows how to build a multi-component software architecture model with a rate-based
and export-function components, how to simulate your design at the architecture level, and how to
generate code.

Open the Software Architecture Model

After opening the example, open the model below. This software architecture model has two software
components: Export_Function and Rate_Based.

open_system('RateBasedExportFunctionSoftwareArchitectureModel')

In the software architecture model, the Export_Function component is linked to a Simulink®


export-function behavior model, export_model_software_architecture.

In this Simulink behavior, two functions are modeled using Function-Call Subsystem blocks. The
inport blocks are connected to the function-call input ports and generate periodic function-call events
with sample times 10ms and 100ms. To learn how to model this behavior, see “Create Export-Function
Model”.

10-10
Simulate and Deploy Software Architectures

If the inport blocks that are connected to the function-call input ports with sample time specified as
-1, meaning the functions are aperiodic, use a Simulink test model with explicit scheduling blocks
such as a Stateflow® chart to simulate. For more information see Test Software Architecture on page
10-13.

The Rate_Based component is linked to rate_based_model_software_architecture as the


Simulink behavior model. To learn how to create this rate-based model, see “Create Rate-Based
Model”.

Simulate the Model with Default Execution Order

Simulate the model. Observe that the Simulation Data Inspector displays the output from the Rate-
Based component.

10-11
10 Software Architectures

Visualize and Edit Component Functions Using Functions Editor

Use the Functions Editor to edit simulation execution order of the functions in your software
architecture. You can also edit the sample time of the functions with inherited sample time (-1).

The Functions Editor is visible only when you model software architectures. To open the Functions
Editor, in the toolstrip on the Modeling tab, select Functions Editor.

To edit the functions in your software architecture:

1 Open the Functions Editor. When you open the Functions Editor, the model will automatically
update, and the table will display the functions populated from your model.
2 If there are changes in the software architecture model, the Update Model button becomes
yellow to signal that an update is required to refresh your functions table.
3 To arrange the execution order of the functions, use the up and down arrows or drag and drop
functions to sort them.
4 To edit sample times of the functions, specify their period in the table.

To order functions based on their data dependencies, select the Order functions by dependency
check box. To enable sorting of functions based on dependencies, you can set this parameter.

10-12
Simulate and Deploy Software Architectures

set_param('RateBasedExportFunctionSoftwareArchitectureModel','OrderFunctionsByDependency','on')

The default value for the parameter is off.

Alternatively, you can use the systemcomposer.arch.Function object to get the functions
programmatically.

Test Software Architecture

You can test a software architecture model and simulate different execution orders of functions by
referencing it from a Model block in a Simulink test model with explicit scheduling blocks such as
Stateflow® Chart (Stateflow).

In this example, a Model block that references a software architecture model has a function-call input
port for each function in the architecture model.

To simulate the architecture model with a Stateflow chart periodic scheduler, connect the Stateflow
chart function-call outputs to the Model block function-call inputs.

Deploy Software Architecture

You can generate code from the software architecture model for the functions of the export-function
and rate-based components.

To generate code, from the Apps tab, select Embedded Coder. On the C Code tab, select Generate
Code. The generated code contains an entry-point for each function of the component. For more
information, see “Generate Code for Export-Function Model”.

For the export-function component, it generated the two functions that correspond to the function-
call inport blocks inside the referenced export-function model.

10-13
10 Software Architectures

Observe that, each rate-based component has separate entry point functions that correspond to each
sample time in the referenced rate based model.

10-14
Simulate and Deploy Software Architectures

See Also
systemcomposer.createModel | createArchitectureModel | createSimulinkBehavior |
increaseExecutionOrder | decreaseExecutionOrder

More About
• “Author Software Architectures” on page 10-2
• “Compose Architectures Visually” on page 1-5
• “Create Export-Function Model”
• “Create Rate-Based Model”
• “Class Diagram View of Software Architectures” on page 10-22
• “Model Software Architecture of Throttle Position Control System” on page 10-16
• “Software Component Modeling”

10-15
10 Software Architectures

Model Software Architecture of Throttle Position Control


System

This example shows how to author the software architecture of a throttle position control system in
System Composer™, schedule and simulate the execution order of the functions from its components,
and generate code.

Throttle Control Composition

In this example, the software architecture of a throttle position control system is modeled in System
Composer using six components. The throttle position control component reads the throttle and pedal
positions and outputs the new throttle position. Two throttle position sensor components provide the
current position of the throttle, and a pedal position sensor component provides the applied pedal
position. A controller component uses these signals to determine the new throttle position as a
percent value. An actuator component then converts the percent value to the appropriate value for
the hardware.
model = systemcomposer.openModel('ThrottleControlComposition');

Simulate Model at Architecture Level

Simulate the software architecture model.


sim('ThrottleControlComposition');

To view the list of functions from the components and edit their properties, such as execution order,
use the Functions Editor. To open the Functions Editor, on the Modeling tab, in the Design section,

10-16
Model Software Architecture of Throttle Position Control System

click Functions Editor. For more information about the Functions Editor, see “Simulate and Deploy
Software Architectures” on page 10-10.

Simulate Model at System Level

To simulate the throttle control system with the throttle body, use a Model block to reference the
software architecture model in the system model. The ThrottleControlSystem model also
contains a Stateflow® Chart block to model a more complex scheduling of the functions of the
software architecture.

A Stateflow license is required for this functionality.

open_system('ThrottleControlSystem');

10-17
10 Software Architectures

To simulate the system model containing the plant and Stateflow scheduler, use this command.

sim('ThrottleControlSystem');

10-18
Model Software Architecture of Throttle Position Control System

View Component Types in Software Architecture

To view the unique component types in the software architecture, create a class diagram view and
add all components. To create a class diagram view, on the Modeling tab, in the Views section, click
Architecture Views, then click New to create a new class diagram. Select Class Diagram from the
Diagram section in the Views Gallery. From the list, select Add Component Filter > Select All
Components to add all components in the software architecture to the view.

To populate methods in the class diagram, you must compile the software architecture model. To
compile the model, navigate to Modeling > Update Model.

For more information, see “Class Diagram View of Software Architectures” on page 10-22.

10-19
10 Software Architectures

Code Generation

You can generate code to deploy the control system to the target hardware. Code generation requires
an Embedded Coder® license. Open the ThrottleControlComposition model and execute the
slbuild command, or press Ctrl+B to build the model and generate code.

slbuild('ThrottleControlComposition');

The generated code contains an entry-point function for each function of the components in the
software architecture. For more information on code generation for export-function models, see
“Generate Code for Export-Function Model”

10-20
Model Software Architecture of Throttle Position Control System

Copyright 2020-2021 The MathWorks, Inc.

See Also
systemcomposer.createModel | createArchitectureModel | createSimulinkBehavior |
increaseExecutionOrder | decreaseExecutionOrder

More About
• “Author Software Architectures” on page 10-2
• “Simulate and Deploy Software Architectures” on page 10-10
• “Class Diagram View of Software Architectures” on page 10-22

10-21
10 Software Architectures

Class Diagram View of Software Architectures


Use class diagrams to display a graphical representation of the structure of a software architecture
model. You can also use spotlight views to analyze component dependencies and hierarchy, and you
can use component hierarchy views to visualize the component hierarchy as a tree diagram. For more
information, see “Create Spotlight Views” on page 11-5 and “Display Component Hierarchy and
Architecture Hierarchy Using Views” on page 11-29.

A class diagram is a graphical representation of a static structural model that displays unique
architecture types of the software components optionally with software methods and properties.

Class diagrams capture one instance of each referenced model and show relationships between them.
A component diagram view can be optionally represented as a class diagram for a software
architecture model.

Software Architecture with Class Diagram View

This example uses a software architecture model with functions, stereotypes, and properties to
explore class diagrams in the Architecture Views Gallery. Open the model to follow the steps in this
tutorial.

Interact with Class Diagram View


1 Simulate the model to compile it and populate functions. On the toolstrip, click Run.
Alternatively, update the model to compile it by navigating to Modeling > Update Model.
2 To open the Architecture Views Gallery, navigate to Modeling > Architecture Views.
3 From the View Browser, select the View 1 view.
4 To open the class diagram view, click Diagram > Class Diagram.

10-22
Class Diagram View of Software Architectures

The class diagram consists of:

• A class box for each unique component type, including reference components.
• A class box as the root that corresponds to the root architecture of the top model.
• Composition connections between the types.

If there are multiple instances of the same type of component, for example, multiple components
that reference the same model across the model hierarchy, then the type of the component is still
represented as one unique box. The component will also relate to its parents and children with
multiplicity representations.
5 You can select Hide methods to simplify the output by removing software functions from the
diagram. Select Hide properties to hide information about stereotypes and property values
applied to the components.

Edit Function Properties Using Property Inspector

You can select functions in the class diagram view of a software architecture and edit properties of
the selected functions using the Property Inspector.

To edit function properties:

10-23
10 Software Architectures

1 Select a function in a root architecture, component architecture, or service interface.


2 Edit the function properties in the Property Inspector of the view. Properties can include the
function name, function stereotype, or, for service interfaces, the function prototype.
3 When you finish editing, you can see the updated function in the class diagram view.

When you modify the properties of a function in the class diagram view, your changes also get
propagated to the Functions Editor and the Interface Editor.

Client-Server Interfaces in Class Diagram View

Class diagrams display service (client-server) interfaces. The diagram shows the service interface
classes and available services.

In this example, a software architecture has two components that are connected with client and
server ports. The Interface Editor shows the interface assigned to the client and server ports.

model = systemcomposer.openModel('SoftwareArchitectureClientServer');
set_param('SoftwareArchitectureClientServer','SimulationCommand','Update');

10-24
Class Diagram View of Software Architectures

openViews(model)

To open the class diagram view, from the View Browser, select ServiceInterfaces.

This is the class diagram view of the software architecture.

• The icon on the upper right and the decoration bar of the class distinguishes the service interface
class.
• The service interface class contains function prototypes as services.
• The diagram displays an aggregation connection for the client port.
• The diagram displays a composition connection for the server port.

10-25
10 Software Architectures

See Also

More About
• “Author Software Architectures” on page 10-2
• “Simulate and Deploy Software Architectures” on page 10-10
• “Model Software Architecture of Throttle Position Control System” on page 10-16
• “Display Component Hierarchy and Architecture Hierarchy Using Views” on page 11-29
• “Service Interfaces Overview” on page 10-46

10-26
Author and Extend Functions for Software Architectures

Author and Extend Functions for Software Architectures


A function is an entry point that can be defined in a software component. For inline components, you
can author functions in the architecture level using the Functions Editor or by using the
addFunction function. You can then implement Simulink behaviors for your authored functions.

For reference components, the functions are automatically created from the referenced behavior
Simulink models. For information, see “Simulate and Deploy Software Architectures” on page 10-10.

In this topic, we explain the workflow to create functions in the architecture level and describe how
to:

• Author and visualize functions.


• Implement behaviors for the functions.
• Import and export functions.
• Add custom properties to functions using stereotypes.

Author and Visualize Functions Using Functions Editor


You can apply stereotypes to functions in software architectures, edit sample times, and specify the
function period using the Functions Editor.

The Functions Editor is visible only when you model software architectures. To open the Functions
Editor, in the toolstrip, navigate to Modeling > Functions Editor. The model automatically updates,
and the table displays the functions of components in your model.

This example shows a software architecture with two components and the Functions Editor with an
empty table.

10-27
10 Software Architectures

To author functions and sort them based on the order of execution:

1 Add a function. Select Component1 as the parent. Use the same steps to add a function for
Component2.

10-28
Author and Extend Functions for Software Architectures

2 Arrange the execution order of the functions by using the up and down arrows or clicking and
dragging functions to sort them.

3 You can change the name of these functions by modifying the name in the table. Change the
name of the first function to myFunction.

4 You can edit sample times of these functions by specifying their period in the table. Change the
period of the first function to 1.

10-29
10 Software Architectures

5 You can order functions automatically based on their data dependencies. This functionality is
available for functions from behavior models. To enable automatic sorting, select the Order
functions by dependency check box or enable OrderFunctionsByDependency on the
architecture model.
set_param('MySoftwareArchitecture','OrderFunctionsByDependency','on')

The default value for the parameter is off.

The Functions Editor visualizes the functions created at the architecture level and the functions
implemented in a Simulink model that is referenced by a component.

In this example, a third function is created in a Simulink behavior model, and the model is referenced
by a third component, Component3. The Software Component column of the table shows the
difference between functions created at the architecture level and functions created in a Simulink
behavior and referenced by a component.

10-30
Author and Extend Functions for Software Architectures

Author Functions Programmatically


You can also author functions for your components using the addFunction function.

Use the addFunction function to add a set of functions to the software architecture component,
architecture with specified names functionNames.

addFunction(architecture,functionNames)

For more information, see addFunction.

10-31
10 Software Architectures

Implement Behaviors for Functions in the Architecture Level

You can create functions in the architecture level, and then implement behaviors for your functions.

• To implement functions using the toolstrip:

1 Under the Modeling tab, select Component, and select Create Simulink Behavior.
2 Select the Type of the Simulink behavior as rate-based or export-function.

Alternatively, you can right-click a component and select Create Simulink Behavior.
• You can also use the createSimulinkBehavior function to implement functions
programmatically. The function creates a new rate-based or export-function behavior and links the
software component to the new model. You can create rate-based or export-function behaviors
only for software architectures.
createSimulinkBehavior(component,"mySoftwareModel",BehaviorType="RateBased")

Apply Stereotypes to Functions of Software Architectures


You can extend software architecture functions by adding stereotypes containing custom properties.
These steps describe how to add stereotypes to your functions and are very similar to the steps to add
stereotypes to other architectural elements. For more information, see “Apply Stereotypes to Extend
Model Elements” on page 5-13.

1 Define your function stereotypes using the Profile Editor.

10-32
Author and Extend Functions for Software Architectures

2 Use the Functions Editor to select functions in your software component, apply stereotypes, view
the stereotypes applied to your functions, and edit the stereotype property values.

In this example, you can specify the value for the FunctionValue property of the stereotype
called FunctionStereotype using the Property Inspector.

10-33
10 Software Architectures

Import and Export Functions of Software Architectures


You can import and export functions of your software architectures.

• Use the systemcomposer.exportModel function to output a functions field that contains a


table with information such as the name, execution order, parent component ID, period, and
stereotypes of a function.

This example shows how to export a software architecture model mySoftwareArchitecture.


The exportedSet output has the functions field that contains the table with function
information.
exportedSet = systemcomposer.exportModel('MySoftwareArchitecture')

exportedSet =

struct with fields:

components: [4×5 table]


ports: [6×4 table]
connections: [3×5 table]
portInterfaces: [0×9 table]
requirementLinks: [0×15 table]
domain: 'Software'
functions: [3×4 table]

10-34
Author and Extend Functions for Software Architectures

>> exportedSet.functions

ans =

3×4 table

Name ExecutionOrder CompID Period


_____________________ ______________ ______ ______

"myFunction" "1" "1" "1"


"Component2_Function" "2" "2" "-1"
"Component3_D1" "3" "3" "0.2"
• Use the systemcomposer.importModel function to import a model with functions where the
importStruct argument can have a functions field that contains function information.

See Also
Tools
Profile Editor | Functions Editor

Objects
systemcomposer.arch.Function

Functions
addFunction | decreaseExecutionOrder | increaseExecutionOrder |
systemcomposer.importModel | systemcomposer.exportModel

More About
• “Author Software Architectures” on page 10-2
• “Simulate and Deploy Software Architectures” on page 10-10
• “Model Software Architecture of Throttle Position Control System” on page 10-16
• “Display Component Hierarchy and Architecture Hierarchy Using Views” on page 11-29
• “Author Functions for Software Components of Adaptive Cruise Control” on page 10-39

10-35
10 Software Architectures

Merge Message Lines Using Adapter Block

This example shows how to use a Merge block to route messages between software components in a
software architecture. A Merge block is an Adapter block preconfigured to merge message and signal
lines.

Open the model.

systemcomposer.openModel('MergeMessagesfromSoftwareComponents');

In this model, message-based communication is constructed between three software components: two
send components, Component1 and Component2 create messages and send them to a receive
component, Component3.

A FIFO queue is used as a message buffer between the components.

Component1 is linked to the Simulink® behavior model swMergeSend1 that generates messages
with value 1 in every 0.1 sample time.

Component2 is linked to the Simulink behavior swMergeSend2 that generates messages with value 2
in every 0.3 sample time.

10-36
Merge Message Lines Using Adapter Block

Component3 is linked to the Simulink behavior swMergeReceive that receives messages and
converts them to signals. The In Bus Element port block is used to configure the queue outside the
component as a FIFO queue of capacity 100.

Simulate the model. Observe that the Scope block in swMergeReceive displays the values received
from both components.

See Also
Adapter | Send | Receive

More About
• “Author Software Architectures” on page 10-2
• “Simulate and Deploy Software Architectures” on page 10-10
• “Merge Message Lines for Architectures Using Adapter Block” on page 7-29
• “Merge Message Lines Using a Message Merge Block”

10-37
10 Software Architectures

• “Author Functions for Software Components of Adaptive Cruise Control” on page 10-39

10-38
Author Functions for Software Components of Adaptive Cruise Control

Author Functions for Software Components of Adaptive Cruise


Control

This example shows how to design an adaptive cruise control system in System Composer™:

• Capture the system architecture in terms of constituent software components and functions.
• Indicate which functions are critical for maintaining the desired speed of the vehicle using custom
properties.
• Implement the behavior of the functions using Simulink®.

Adaptive Cruise Control Architecture

An adaptive cruise control (ACC) system is a control system that modifies the speed of a vehicle in
response to conditions on the road. As in regular cruise control, the driver sets a desired speed for
the vehicle. Additionally, the adaptive cruise control system can slow the vehicle down if there is
another vehicle moving more slowly in the lane in front of it.

The ACC algorithm requires that the vehicle knows the curvature of the road, the relative distance,
and velocity of the lead vehicle immediately in front of it. For more information about the ACC
algorithm and the entire system, see “Adaptive Cruise Control with Sensor Fusion” (Automated
Driving Toolbox). The system software retrieves detections from a radar sensor and video from a
camera, which are fused by a sensor fusion component for more accurate detections. The detections
are provided to multi-object tracker to determine the relative distance and velocity of the lead
vehicle. These states and the longitudinal velocity of the vehicle are then provided to a controller
component to compute the acceleration to apply to the vehicle to maintain a safe distance.

Author Components and Interfaces

First, create the architecture of the adaptive cruise control software. To open a new software
architecture model, use this command.

systemcomposer.createModel('ACCSoftwareCompositionScratch', 'SoftwareArchitecture', true);

The system is composed of a SensorFusion component, a MultiObjectTracking component, a


Controller component, and a TrackerLogging component for monitoring.

10-39
10 Software Architectures

Author Component Functions

To specify the functions that define the behavior of each component, open the Functions Editor. To
open the Functions Editor, on the Modeling tab, in the Design section, click Functions Editor. To
create the functions to implement the behavior of each component, select a component and use the
add button. For more information about authoring functions using the Functions Editor, see “Author
and Extend Functions for Software Architectures” on page 10-27.

You can modify the built-in function properties such as the name, period, or execution order. The
name and period properties can be modified by editing the corresponding cells in the table. You can
specify the execution order of functions in the Functions Editor by dragging functions into the desired
order or by selecting a function and clicking the up and down buttons.

10-40
Author Functions for Software Components of Adaptive Cruise Control

Add Custom Properties to Functions

You can apply custom properties using System Composer profiles and stereotypes. Load the profile
ACCSoftwareProfile and import it into the composition. The profile contains three stereotypes.

• FunctionBase is a stereotype used as the base for all function stereotypes.


• CriticalFunction stereotype applies to functions that are critical in determining the output
acceleration.
• NonCriticalFunction stereotype applies to functions that are not critical in determining the
output acceleration.

10-41
10 Software Architectures

Add custom properties to a function by applying stereotypes from the loaded profile.

1 To open the Property Inspector, select Modeling > Design > Property Inspector.
2 In the Functions Editor, select fuse_vision_and_radar.
3 In the Property Inspector, select Stereotype > Add
ACCSoftwareProfile.CriticalFunction to apply the stereotype.

10-42
Author Functions for Software Components of Adaptive Cruise Control

This stereotype designates functions that are executed to determine the output acceleration. In the
ACC software architecture, all functions are critical to determining the acceleration except for the
functions defined in the TrackerLogging component.

Generate Code for Functions

Code for the adaptive cruise control system can be generated and deployed to the target hardware
using Embedded Coder®. To generate code, execute the slbuild command, or press Ctrl+B to
build the model.

slbuild('ACCSoftwareCompositionScratch');

10-43
10 Software Architectures

Since no component has a linked behavior, the generated code contains empty definitions for each
function in the software architecture.

Implement Behaviors for Functions

You can implement the behaviors for functions of a component in Simulink by creating a Simulink
behavior. Right-click the SensorFusion component and select Create Simulink Behavior, or
navigate to Modeling > Component > Create Simulink Behavior. To choose the type of the
Simulink behavior, for Type, select Model Reference: Export-Function or Model Reference:
Rate-Based. Click OK to create a SensorFusion export-function model linked to the
SensorFusion component.

For more information on using the export-function modeling style, see “Export-Function Models
Overview”.

10-44
Author Functions for Software Components of Adaptive Cruise Control

The new model contains one inport block with a function-call output port,
fuse_vision_and_radar, with a sample time of 0.1 seconds, as specified in the Functions Editor.
You can connect the output port to a function-call subsystem that models the behavior of that
function.

Copyright 2021 The MathWorks, Inc.

See Also
Tools
Profile Editor | Functions Editor

Objects
systemcomposer.arch.Function

Functions
addFunction | decreaseExecutionOrder | increaseExecutionOrder

More About
• “Author Software Architectures” on page 10-2
• “Author and Extend Functions for Software Architectures” on page 10-27
• “Simulate and Deploy Software Architectures” on page 10-10
• “Merge Message Lines for Architectures Using Adapter Block” on page 7-29
• “Merge Message Lines Using a Message Merge Block”

10-45
10 Software Architectures

Service Interfaces Overview


When your applications or software components need to communicate with each other through a
functional interface, use service-oriented communication where services are provided and requested
by different components depending on the target platform. You can use service-oriented architectures
to decide the implementation of a function in your component after deployment. A service-oriented
architecture allows you to think about your components as micro-services that enable powerful
capabilities such as over-the-air updates and cloud functionality. System Composer allows you to
model these scenarios using service interfaces.

You can model your service-oriented communication at the architecture level using software
architectures in System Composer. Starting at the architecture level allows you to design your service
interface and components independent of the implementation of their behavior. Ports and interfaces
in an architecture describe 'what' the system should do and implementation of behavior in linked
Simulink models describe 'how' the component should do it.

If you start from the architecture level, you can use these methods to define Simulink behavior for
your components:

• Use a preconfigured Simulink template.

System Composer can provide you with preconfigured Simulink template.


• Manually model your behavior in Simulink and attach the model to your software architecture
components. For more information, see “Model Client-Server Communication Using Function
Ports”.

This topic shows how to model service-oriented communication starting from a System Composer
software architecture and implementing component behavior with Simulink.

10-46
Service Interfaces Overview

Structure of Service-Oriented Architectures

A service-oriented architecture consists of these elements:

• A software component is a specialization of a component for software entities, including its


interfaces.

• A server is a component that defines and provides a function.


• A client is a component that sends a request to the server.
• A service interface defines the functional interface between client and server components. Each
service interface consists of one or more function elements.

• A service is a unit of functionality.


• A function element describes the attributes of a function in a client-server interface.

Clients and servers are often used to distribute functionality across a distributed system or to access
services offered by cloud APIs. Therefore, calling a service may require resources and you may want
to specify if the execution should be synchronous or asynchronous.

• Synchronous execution is when the client sends a request to the server, the function runs
immediately, and the function returns the output arguments to the client.
• Asynchronous execution is when the client sends a request to the server, the function executes
asynchronously based on the priority order, and the function returns the output arguments to the
client.

Modeling Service-Oriented Communication Using System Composer


In System Composer, to connect your client and server components, use client and server ports.

10-47
10 Software Architectures

Once you connect the client and server components, you can specify function elements by creating a
service interface. To create a service interface, open the Interface Editor, click the down arrow, and
select Service Interface.

You can create functions in your software architecture using the Interface Editor. For each function in
the service interface, add a function element. Specify if the function is asynchronous by selecting the
Asynchronous check box. To define the name and parameters of the function, edit the function
prototype. Below the function prototype are the parameters of the function represented as function
arguments. For each function argument, you can specify values in the Type, Dimensions, Units,
Complexity, and Asynchronous columns.

Once you define and select a service interface, you can assign the interface to client and server ports
in your architecture by right-clicking the port and selecting Apply selected interface.

10-48
Service Interfaces Overview

Implement Behavior of Functions Using Simulink

To implement behaviors for your functions, you can create a Simulink behavior model. To be able to
generate code for your components with a Simulink behavior, use a Simulink export-function model.
For more information about export-function models, see “Export-Function Models Overview”.

To create a Simulink behavior, right-click the component and select Create a Simulink behavior
and set the Type of the Simulink behavior to Model Reference: Export-Function.

The created model is a template export-function model that includes the service interface you created
in System Composer. In your software architecture, you see the export-function model as a model
reference in the component. The implementation of the behavior depends on the synchronicity of the
function execution.

The server model is where you define the function. To implement a function behavior, double-click the
Simulink Function block. Inside the Simulink Function block is a Trigger block, an ArgIn block, and
an ArgOut block. Add any necessary blocks to the function subsystem and connect elements to the
ArgIn block and the ArgOut block.

The client model is where you call the function. To implement the function call inside the Function-
Call Subsystem block, double-click the Function-Call Subsystem block. Add any necessary blocks to
the function call subsystem to represent an input and an output. For an asynchronous function call,
the output message is a message payload.

10-49
10 Software Architectures

For more information on implementing function behavior, see “Model Client-Server Communication
Using Function Ports”.

Simulate Your Client-Server Communication Using System Composer

You can simulate service-oriented communication by compiling and running your service-oriented
architecture model.

To run your architecture model, click the Run button or use the sim function. For example, if your
model is called myServiceModel, enter this command to run your model

sim('myServiceModel')

Once the model runs, you can analyze and visualize signals using the Simulation Data Inspector and
Sequence Viewer tools.

• To visualize the logged signals, go to the Simulation tab, and in the Review Results section,
select Simulation Data Inspector.
• To view the execution order of the functions calls, go to the Simulation tab, and in the Review
Results section, select Sequence Viewer.

You can modify the execution order of functions in the service interface in Functions Editor.

For more information, see “Model Service-Oriented Communication Between Sensors” on page 10-
52.

Test Your Service Interface Using Simulink Test

You can test your service interface by creating a test harness for models or components with client
and server ports.

A test harness is a model that isolates the component under test with inputs, outputs, and verification
blocks configured for testing scenarios. You can create a test harness for a model component or for a
full model. A test harness gives you a separate testing environment for a model or a model
component.

A Simulink Test license is required to create a test harness.

When you create a test harness, System Composer and Simulink Test autogenerate these models:

10-50
Service Interfaces Overview

• The mock architecture model contains a Reference Component referencing the component under
test.
• A test harness model containing a Model block referencing the mock architecture model and a
Test Sequence block for defining test scenarios.

Use the Simulink Test Manager with the test harness to create test files and test cases. For more
information, see “Test Harness and Model Relationship” (Simulink Test) and “Create or Import Test
Harnesses and Select Properties” (Simulink Test).

For an example, see “Model Service-Oriented Communication Between Sensors” on page 10-52.

Generate Code Using Embedded Coder

If you have an Embedded Coder license, you can generate code from a software architecture model
that includes a service interface by using the rtwbuild function.

Embedded Coder generates the service interface as an abstract class, which enables implementation
to be separate from the interface.

The generated code contains an entry-point for each function of the component. For more
information, see “Generate Code for Export-Function Model”.

See Also
Blocks
Function Element | Function Element Call | Simulink Function | Function Caller | Function-Call
Subsystem | Message Triggered Subsystem | Reference Component

Functions
addServiceInterface | setFunctionPrototype | getFunctionArgument | setAsynchronous

Related Examples
• “Simulate Asynchronous Services for Vehicle Headlight Management” on page 10-66
• “Define Port Interfaces Between Components” on page 3-2
• “Model Client-Server Communication Using Function Ports”
• “Model Service-Oriented Communication Between Sensors” on page 10-52
• “Software Component Modeling”
• “Author and Extend Functions for Software Architectures” on page 10-27

10-51
10 Software Architectures

Model Service-Oriented Communication Between Sensors

This example shows how to model service-oriented communication starting from a System
Composer™ software architecture and implementing component behavior with Simulink®. Modeling
service-oriented communication from the architectural level allows you to design your service
interface and components independent of the implementation of their functionality.

In this example, the model slexServiceInterfaceExample consists of a controller component,


Controller, and two sensor components, Sensor1 and Sensor2. You model the two sensor
components as two different instances of the same referenced model, scSensorModelRef. The
referenced model defines two services: reset, which resets the sensor from drifting over time, and
fetchData, which reads the latest sensor values. You specify a single service interface between the
controller and the two sensor instances, which allows the controller to call reset or fetchData for
a specific instance of the referenced sensor component.

Open the model.


model = systemcomposer.openModel('scServiceInterfaceExample.slx');

Both instances of the referenced sensor model output a sine wave with different amplitudes. You can
view and specify the amplitudes in the Model Data Editor of the top model. To access the Model Data
Editor, go to the Modeling tab, and in the Design section, select Model Data Editor.

10-52
Model Service-Oriented Communication Between Sensors

Component-to-Component Interaction Through Client and Server Ports

The controller component interacts with the sensor components using server ports and client ports.
The ball and socket icons represent server and client ports respectively.

Define Service Interface

You define the service interface sensorCmd through the Interface Editor. To access the Interface
Editor, go to the Modeling tab, and in the Design section, select Interface Editor. The service
interface sensorCmd is used across referenced models and stored in the data dictionary
slexServiceInterfaceExample.sldd.

The function prototype defines the function name and parameters. Below the function prototype are
the parameters of the function represented as function arguments. For each function argument, you
can specify a value in the Type, Dimensions, Units, and Complexity columns. Note that
sensorCmd contains two functions, reset and fetchData. The reset function has one function
argument specified as resetSignal. The fetchData function has one function argument specified
as data.

10-53
10 Software Architectures

Implement Behavior for Functions

The behaviors of the functions specified in the service interface are defined in referenced models. In
service-oriented architectures, you implement these function behavior models in export-function
models. For more information, see “Export-Function Models Overview”.

Server Component Model

The scSensorMdlRef model is an export-function model representing the behavior of the sensors. In
scSensorMdlRef, you define the two functions reset and fetchData in their respective Simulink
Function blocks. The reset function has a Boolean input argument, resetData. By default,
resetData is false, and thus the reset function does not reset the sensors until the controller sets
resetData to true.

Client Component Model

The scControllerMdlRef model is an export-based model representing the behavior of the


controller. In scControllerMdlRef, each sensor has a requestReset and requestFetchData
Function-Call Subsystem.

10-54
Model Service-Oriented Communication Between Sensors

For more information on the structure and functionality of the server and client models, see “Model
Client-Server Communication Using Function Ports”.

Schedule Functions and Simulate

To run the model, use the sim function.

sim('scServiceInterfaceExample');

To view the sequence of function calls throughout the simulation of the model, open the Sequence
Viewer.

Go to the Simulation tab, in the Review Results section, select Sequence Viewer.

10-55
10 Software Architectures

Test Service Interface Using Test Harness

You can test your service interface by creating a test harness for the components with client and
server ports.

Create Test Harness

1 Right-click the Sensor1 component. From the context menu, select Test Harness > Create for
'Sensor1'.
2 In the Create Test Harness dialog box, you can specify the inputs, outputs, and other options. By
default, the harness saves with the model file,
scServiceInterfaceSensorExample_Harness1.
3 Click OK to create the test harness.

At the center of the harness is a Model block referencing a mock architecture model. The vertical
subsystem contains signal specification and routing.

System Composer and Simulink® Test™ autogenerate a software architecture test model,
scServiceInterfaceSensorExample_MockArchitecture1, a Simulink behavior model

10-56
Model Service-Oriented Communication Between Sensors

scServiceInterfaceSensorExample_MockClients1, and the test harness model,


scServiceInterfaceSensorExample_Harness1.

To open the mock architecture model, double-click the


scServiceInterfaceExample_MockArchitecture1 block in the test harness model.

10-57
10 Software Architectures

The mock architecture contains a Reference Component referencing the component under test,
Sensor1. The component under test is connected to the MockClients component which references
a new, autogenerated Simulink behavior model, scServiceInterfaceExample_MockClients1.

Implement Behavior of Mock Components

Your component under test is the Sensor1 component which is the server providing services to the
Controller. The test harness isolates the Sensor1 component from the entire model by keeping
the component as-is in a reference component. Implementation of the mock client is necessary to
ensure the server component is behaving as expected.

Open the mock client model by double-clicking the MockClients1 component in the
scServiceInterfaceExample_MockArchitecture1 architecture model.

The controller calls the reset function and the fetchData function. To keep the test output of the
mock client component as expected, you must supply the test input and output to the mock client.

reset Function Caller

To implement the mock behavior of calling the reset function, you can add a Data Type Conversion
block connected to a Pulse Generator block to ensure the client is recieving a boolean value for
resetStatus.

10-58
Model Service-Oriented Communication Between Sensors

fetchData Function Caller

To implement the mock behavior of calling the fetchData function, you can add an Outport block to
log the output of the function call.

10-59
10 Software Architectures

Log Signals

To log the signals of the mock client and Sensor1 components, you can add Outport blocks.

Adding Outport blocks to the behavior models will propogate output signals to the harness model. In
the harness model, add three Outport blocks to log the signals of the mock client and Sensor1.

Run Test Harness

To run the test, you must add a step transition. Open the Test Sequence (Simulink Test) block in the
harness model, in the Transition column of the Run step, add true as the condition for transitioning
to the next step.

1 Click Run in the Simulation tab to simulate the harness.


2 Open the Simulation Data Inspector to observe logged output of the mock client and Sensor1
component.

10-60
Model Service-Oriented Communication Between Sensors

In this example, the component under test is Sensor1, so in the Simulation Data Inspector, you can
observe the signals from the sensor and mock client components to ensure they are as expected.

1 In the Inspect tab, select and deselect Data and data from callfetchData:1 signals to
observe if the signals match.
2 Similarly, select and deselect resetData @ Sensor1 and resetData from callreset:1
signals to observe if the signals match.

10-61
10 Software Architectures

If the signals match between the sensor and client component, your test is complete. For more
information on testing service interfaces, see “Test Your Service Interface Using Simulink Test” on
page 10-50.

Generate Code

To generate code for the model, which includes the service interface sensorCmd, use this command.

rtwbuild('scServiceInterfaceExample');

Simulink generates the service interface SensorCmd as an abstract class, which enables
implementation to be separate from the interface.

The generated code contains an entry-point for each function of the component. For more
information, see “Generate Code for Export-Function Model”.

10-62
Model Service-Oriented Communication Between Sensors

The generated code implements this abstract class for the referenced sensor model.

10-63
10 Software Architectures

You also use the generated abstract class to construct the class of the controller.

10-64
Model Service-Oriented Communication Between Sensors

The controller subsequently calls the service from the SensorCmd abstract class.

See Also
Function Element | Function Element Call | Simulink Function | Function Caller | Function-Call
Subsystem | addServiceInterface | setFunctionPrototype | getFunctionArgument

Related Examples
• “Define Port Interfaces Between Components” on page 3-2
• “Author and Extend Functions for Software Architectures” on page 10-27
• “Software Component Modeling”
• “Service Interfaces Overview” on page 10-46
• “Model Client-Server Communication Using Function Ports”
• “Simulate Asynchronous Services for Vehicle Headlight Management” on page 10-66

10-65
10 Software Architectures

Simulate Asynchronous Services for Vehicle Headlight


Management

This example shows how to use asynchronous services to simulate vehicle headlights in a System
Composer™ software architecture model.

Overview

In this example, the model HeadlightArch consists of a lighting manager component,


LightingManager, two headlight components, LeftHeadlight and RightHeadlight, and a
component for logging, Logging. The headlight components are modeled as two different instances
of the same referenced model, HeadLight.

The referenced model defines two Simulink® Functions:

• setMode, which takes in the lightMode variable and returns an output that indicates whether
the headlight is broken
• getMode, which returns the lightMode variable

A single service interface is specified between the lighting manager and the two headlight instances,
which allows the manager to call setMode or getMode for a specific instance of the referenced
headlight component.

Open the model.

model = systemcomposer.openModel("HeadlightArch");

Define Asynchronous Services Using Interface Editor

To view the Interface Editor, on the toolstrip, navigate to Modeling > Interface Editor. Notice that
the Asynchronous check box is selected for the function elements representing the functions
getMode and setMode.

10-66
Simulate Asynchronous Services for Vehicle Headlight Management

The block parameters for the Simulink behavior models are preconfigured to support asynchronous
simulation.

On the server model, the Trigger block parameter Execute function call asynchronously within
the Simulink Function blocks for setMode and getMode is selected. On the client model, the
Function Caller block parameter Execute function call asynchronously is selected.

Asynchronous Function Calls for Simulation of Vehicle Headlights

For asynchronous execution, when the client makes a request to the server, the server responds
according to the priority order defined in the Functions Editor instead of the order in which the
requests were received. To launch the Functions Editor tool, on the toolstrip, go to Modeling >
Functions Editor.

Use the Functions Editor tool to change the order of execution of the functions so that when these
functions are called at the same time, the higher priority function is executed first.

If a function from the list calls another function:

• If a lower priority function is already running, the higher priority function runs. After its
completion, the lower priority function continues to run.
• If a higher priority function is already running, the lower priority function runs after the higher
priority one.

10-67
10 Software Architectures

For asynchronous function calls, the Function Caller block has a message output port consistent with
the number of output arguments. This message output port connects to a Message Triggered
Subsystem block to process the messages. The LightingManager component references the
LightingManager Simulink model that consists of two asynchronous function calls. The
changelLightMode Function-Call Subsystem block uses the setMode function and determines how
each headlight should change its lighting mode. The checkLight Function-Call Subsystem block
uses the getMode function and checks whether each headlight is broken and returns its status.

10-68
Simulate Asynchronous Services for Vehicle Headlight Management

Simulate the model.

sim("HeadlightArch");

You can visualize the logged signals after simulation using the Simulation Data Inspector. On the
toolstrip, go to Simulation > Data Inspector.

10-69
10 Software Architectures

To view the execution order of the function calls, on the toolstrip, launch the Sequence Viewer by
navigating to Simulation > Sequence Viewer. Simulate the model again to view the logged
messages on the Sequence Viewer and the order in which messages are executed. Since the
setMode function is at a higher priority order on the Functions Editor, those server calls are
received first.

10-70
Simulate Asynchronous Services for Vehicle Headlight Management

You can change the priority order of the functions in the Functions Editor and view the result in the
Sequence Viewer.

See Also
Blocks
Function Element | Function Element Call | Simulink Function | Function Caller | Function-Call
Subsystem | Message Triggered Subsystem

Functions
addServiceInterface | setFunctionPrototype | getFunctionArgument | setAsynchronous

Related Examples
• “Define Port Interfaces Between Components” on page 3-2
• “Author and Extend Functions for Software Architectures” on page 10-27
• “Software Component Modeling”
• “Service Interfaces Overview” on page 10-46
• “Model Client-Server Communication Using Function Ports”
• “Model Service-Oriented Communication Between Sensors” on page 10-52

10-71
11

Create Custom Views


11 Create Custom Views

Create Custom Views Using Architecture Views Gallery


You can use custom views integrated with System Composer to filter large models to display a custom
subset of components. You can filter your views on criteria such as stereotypes, properties, and
requirement links.

These concepts are relevant for authoring custom views:

• A view shows a customizable subset of elements in a model. Views can be filtered based on
stereotypes or names of components, ports, and interfaces, along with the name, type, or units of
an interface element. Create views by adding elements manually. Views create a simplified way to
work with complex architectures by focusing on certain parts of the architectural design.

You can use different types of views to represent the system. Switch between a component
diagram, component hierarchy, or architecture hierarchy. For software architectures, you can
switch to a class diagram view. A viewpoint represents a stakeholder perspective that specifies the
contents of the view.
• An element group is a grouping of components in a view.

Use element groups to programmatically populate a view.


• A query is a specification that describes certain constraints or criteria to be satisfied by model
elements.

Use queries to search elements with constraint criteria and to filter views.
• A component diagram represents a view with components, ports, and connectors based on how
the model is structured.

Component diagrams allow you to programmatically or manually add and remove components
from the view.
• You can visualize a hierarchy diagram as a view with components, ports, reference types,
component stereotypes, and stereotype properties.

There are two types of hierarchy diagrams:

• Component hierarchy diagrams display components in tree form with parents above children.
In a component hierarchy view, each referenced model is represented as many times as it is
used.
• Architecture hierarchy diagrams display unique component architecture types and their
relationships using composition connections. In an architecture hierarchy view, each
referenced model is represented only once.
• A class diagram is a graphical representation of a static structural model that displays unique
architecture types of the software components optionally with software methods and properties.

Class diagrams capture one instance of each referenced model and show relationships between
them. A component diagram view can be optionally represented as a class diagram for a software
architecture model.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

11-2
Create Custom Views Using Architecture Views Gallery

Views are integrated with architecture models in System Composer. The table lists topics about using
views.

Topic Description
“Create Spotlight Views” on page 11-5 View components in the context of the entire
architecture.
“Create Architecture Views Interactively” on View structural and functional model hierarchies
page 11-9 interactively.
“Create Architecture Views Programmatically” on View structural and functional model hierarchies
page 11-23 programmatically.
“Display Component Hierarchy and Architecture Use hierarchy diagrams to view different aspects
Hierarchy Using Views” on page 11-29 of architecture models.

Create a view in the Architecture Views Gallery by clicking New > View.

See Also
Tools
Architecture Views Gallery | Interface Editor

Functions
openViews | createView | getView | deleteView | modifyQuery | runQuery | removeQuery |
addElement | removeElement | getQualifiedName | createSubGroup | getSubGroup |
deleteSubGroup | getQualifiedName | lookup

11-3
11 Create Custom Views

Objects
systemcomposer.view.View | systemcomposer.view.ElementGroup |
systemcomposer.query.Constraint | systemcomposer.interface.DataInterface |
systemcomposer.interface.DataElement

More About
• “Modeling System Architecture of Keyless Entry System” on page 11-33
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Use Interface Editor in Views” on page 11-49
• “Group Ports in Component Diagram Views” on page 11-52
• “Class Diagram View of Software Architectures” on page 10-22

11-4
Create Spotlight Views

Create Spotlight Views


A system being designed in System Composer for a real application is usually large and complex. It
typically consists of many complex functions working together to fulfill the system requirements. In
the process of designing and analyzing such architectures, you must understand existing components
and what needs to be added. A spotlight view is a simplified view of a model that captures the
upstream and downstream dependencies of a specific component. Use the model below to begin
creating spotlight views.

For a roadmap of the views topics, see “Create Custom Views Using Architecture Views Gallery” on
page 11-2.

Mobile Robot Architecture Model with Properties

This example shows a mobile robot architecture model with stereotypes applied to components and
properties defined.

11-5
11 Create Custom Views

Create Spotlight Views from Components


Create views dynamically using spotlight views.

1 Double-click the Sensors component, then select the DataProcessing component.


2 Select the DataProcessing component and navigate to Modeling > Architecture Views >
Spotlight. Alternatively, right-click the DataProcessing component and select Create
Spotlight from Component.

The spotlight view launches and shows all model elements to which the DataProcessing
component connects. The spotlight diagram is laid out automatically and cannot be edited.
However, it allows you to inspect just a single component and study its connectivity to other
components.

Note Spotlight views are transient. They are not saved with the model.

11-6
Create Spotlight Views

3 Shift the spotlight to another component. Select the Motion component. Click the ellipsis above

the component to open the action menu. To create a spotlight from the component, click the
button.

To view the architecture model at the level of a particular component, select the component and
click .

4
To return to the architecture model view, click the button.

You can make the hierarchy and connectivity of a component visible at all times during model
development by opening the spotlight view in a separate window. To show the spotlight view in a
dedicated window, in the component context menu, select Open in New Window, then create the
spotlight view. Spotlight views are dynamic and transient: any change in the composition refreshes
any open spotlight views, and spotlight views are not saved with the model.

See Also
Tools
Architecture Views Gallery | Interface Editor

11-7
11 Create Custom Views

Functions
openViews | createView | getView | deleteView | modifyQuery | runQuery | removeQuery |
addElement | removeElement | getQualifiedName | createSubGroup | getSubGroup |
deleteSubGroup | getQualifiedName | lookup

Objects
systemcomposer.view.View | systemcomposer.view.ElementGroup |
systemcomposer.query.Constraint | systemcomposer.interface.DataInterface |
systemcomposer.interface.DataElement

More About
• “Create Custom Views Using Architecture Views Gallery” on page 11-2
• “Modeling System Architecture of Keyless Entry System” on page 11-33
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Use Interface Editor in Views” on page 11-49
• “Group Ports in Component Diagram Views” on page 11-52
• “Class Diagram View of Software Architectures” on page 10-22

11-8
Create Architecture Views Interactively

Create Architecture Views Interactively

The structural hierarchy of a system typically differs from the hierarchy of the functional
requirements of a system. With views in System Composer, you can view a system based on different
hierarchies.

For a roadmap of the views topics, see “Create Custom Views Using Architecture Views Gallery” on
page 11-2.

A view shows a customizable subset of elements in a model. Views can be filtered based on
stereotypes or names of components, ports, and interfaces, along with the name, type, or units of an
interface element. Create views by adding elements manually. Views create a simplified way to work
with complex architectures by focusing on certain parts of the architectural design.

You can use different types of views to represent the system. Switch between a component diagram,
component hierarchy, or architecture hierarchy. For software architectures, you can switch to a class
diagram view. A viewpoint represents a stakeholder perspective that specifies the contents of the
view.

A viewpoint represents a stakeholder perspective that specifies the contents of the view. For example,
you can author a system using requirements. A view allows you to better understand what
components you need to satisfy your requirements while not necessarily focusing on the structure.

This example uses the architecture model for a keyless entry system to create component diagram
views.

A component diagram represents a view with components, ports, and connectors based on how the
model is structured.

Component diagrams allow you to programmatically or manually add and remove components from
the view.

For more information on the keyless entry architecture, see “Modeling System Architecture of
Keyless Entry System” on page 11-33.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Create Views with Component Filters and Port Filters


Create views with component filters to choose a collection of components to display in your view. Use
port filters to further simplify your view and show only relevant ports and connections.

Create View in Architecture Views Gallery

1 In the MATLAB Command Window, enter this command.

scKeylessEntrySystem

The architecture model opens in System Composer.


2 Navigate to Modeling > Architecture Views to open the Architecture Views Gallery.

11-9
11 Create Custom Views

3 Select New > View to create a new view.


4 In View Properties on the right pane, in the Name text box, enter a name for this view, for
example, Software Component Review. Choose a color and enter a description, if necessary.

Add Component Filters and Group Ports

1 In the View Configurations pane, on the Filter tab, click Add Component Filter to add new
form-based criterion to a component filter.
2 From the Select list, select Components. From the Where list, select Stereotype. Select isa.
In the text box, select AutoProfile.SoftwareComponent.

11-10
Create Architecture Views Interactively

3
Click Apply .

System Composer creates a view using the query in the Component Filter box. The view filter
selects all components with the AutoProfile.SoftwareComponent stereotype applied.

4 You can select Group Ports in the Architecture Views Gallery toolstrip to simplify complex
networks of connections and ports.

11-11
11 Create Custom Views

Each grouped set of ports connects to a common set of components. In this example, the view
does not group port AtoB because the port group containing components A and B belongs to a
different component set from the port group containing components A, B, and C.

11-12
Create Architecture Views Interactively

11-13
11 Create Custom Views

To revert to the original component diagram view, clear Group Ports. For more information, see
“Group Ports in Component Diagram Views” on page 11-52.
5 Select Add Component Filter. From the Select list, select Components. From the Where list,
select Name. Select ~contains. In the text box, enter "Door Lock". Select the Auto Apply
check box to apply future changes without selecting Apply.

6 An architecture view is created using the additional query in the Component Filter box. The
view is filtered to select all components not named "Door Lock".

11-14
Create Architecture Views Interactively

Add Port Filters

1 From the Add Port Filter list, select the option Hide Unconnected Ports.

2 An architecture view is created using the additional query in the Port Filter box. The view is
filtered to hide unconnected ports.

11-15
11 Create Custom Views

3
Delete the port filter. Pause on the constraint and select the Delete button.

Add Group By Criteria to Views


1 In the View Configurations pane, select Grouping.
2 To choose a property enumeration for grouping, click Add Group By.
3 From the list, select AutoProfile.BaseComponent.ReviewStatus.
4 Click Add Group By again.
5 From the list, select AutoProfile.SoftwareComponent.ImplementationLanguage.
6 Click Apply.

11-16
Create Architecture Views Interactively

Edit Views Interactively


With the Architecture Views Gallery tool, you can edit and rearrange your view layout interactively.

• Click and drag components anywhere inside or outside the views canvas. Resize components
inside and outside the views canvas. The views canvas expands to accommodate the moves.
• Move and resize a parent component with its children. Rearrange child components inside a
parent component. After moving a child component, the parent component expands to
accommodate the change.
• When a moved or resized component partially overlaps another component, the system is
highlighted to indicate an incorrect final state.
• Click and drag around a region to select multiple components and manipulate them together.
• Double-click a component on the Model Components browser to add the component to the
diagram. Right-click a component on the Model Components browser for additional options.
• Undo or redo interactive edits on the views canvas.

You can also use the Interface Editor tool from within the Architecture Views Gallery to add, edit, and
delete interface definitions and interface data dictionaries. For more information, see “Use Interface
Editor in Views” on page 11-49.

Follow these steps to add or delete elements from a view using the Model Components browser.

1 To add more components to the view, drag and drop components from Model Components.
Drag and drop the Lighting System component to the Software Component Review view.
Alternatively, click Add on the toolstrip. You can also press Ctrl+I to add component
instantiations to your view when you select them.

11-17
11 Create Custom Views

To delete components from the view, select your component. On the Architecture Views Gallery
toolstrip, from the Components menu, click Remove.
2 Observe that the Lighting System component has been added to the view.

You can add or remove components manually in views without deleting your initial filter because
the filter is augmented to reflect your manual edits to the view.

Add or Remove Requirements Links from Views


1 Navigate to Requirement > Requirements Manager. A Requirements Toolbox license is
required. The Requirement Links tab appears at the bottom of the Software Component
Review view.

11-18
Create Architecture Views Interactively

2 Select the Lighting Controller component and observe the linked requirement
Automatically turn off headlights.

3 Select the requirement Automatically turn off headlights to open the Requirements
Editor to view or modify requirement links.
4 In the Architecture Views Gallery, navigate to Requirement > Open Requirements Editor if
the Requirements Editor is not open already.
5 Select the Should unlock door requirement.
6 Return to the Architecture Views Gallery. In the Software Component Review view, select the
Lighting Controller component.
7 Navigate to Requirement > Link to selected requirement. The new requirement Should
unlock door is added.

11-19
11 Create Custom Views

8 To remove a requirement link, select and confirm deletion.

Add Custom Clauses to Component Filters and Port Filters


1 Select New > View to create a new view.
2 In View Properties on the right pane, in the Name box, enter a name for this view, for example,
Hardware Component View. Choose a Color and enter a Description, if necessary.
3 In the bottom pane on View Configurations, from the Filter tab, select from the list Add
Component Filter > Add Custom Component Filter to enter a constraint by which to filter. In
the box, enter contains(Property('Name'),'Dashboard').
4 In the bottom pane on View Configurations, from the Filter tab, select from the list Add Port
Filter > Add Custom Port Filter to enter a constraint by which to filter. In the box, enter
contains(Property('Name'),'sound').
5
Select Apply .

11-20
Create Architecture Views Interactively

The view is filtered using the constraints in the custom filters. For more information on
structuring constraints, see systemcomposer.query.Constraint.

See Also
Tools
Architecture Views Gallery | Interface Editor

Functions
openViews | createView | getView | deleteView | modifyQuery | runQuery | removeQuery |
addElement | removeElement | getQualifiedName | createSubGroup | getSubGroup |
deleteSubGroup | getQualifiedName | lookup

Objects
systemcomposer.view.View | systemcomposer.view.ElementGroup |
systemcomposer.query.Constraint | systemcomposer.interface.DataInterface |
systemcomposer.interface.DataElement

More About
• “Create Custom Views Using Architecture Views Gallery” on page 11-2
• “Modeling System Architecture of Keyless Entry System” on page 11-33
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46

11-21
11 Create Custom Views

• “Use Interface Editor in Views” on page 11-49


• “Group Ports in Component Diagram Views” on page 11-52
• “Class Diagram View of Software Architectures” on page 10-22

11-22
Create Architecture Views Programmatically

Create Architecture Views Programmatically


You can create an architecture view programmatically. This topic presents two examples of creating
architecture views programmatically using a keyless entry system architecture using element groups.

For a roadmap of the views topics, see “Create Custom Views Using Architecture Views Gallery” on
page 11-2.

An element group is a grouping of components in a view.

Use element groups to programmatically populate a view.

For more information on the keyless entry architecture, see “Modeling System Architecture of
Keyless Entry System” on page 11-33.

The third example is about how to use queries to find elements in a System Composer model.

A query is a specification that describes certain constraints or criteria to be satisfied by model


elements.

Use queries to search elements with constraint criteria and to filter views.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Create Architecture Views in System Composer with Keyless Entry


System

Use a keyless entry system architecture model to programmatically create views.

Import the namespace with queries.

import systemcomposer.query.*

Open the Simulink® project file for the keyless entry system.

openProject("scKeylessEntrySystem");

Load the example model into System Composer™.

model = systemcomposer.loadModel("KeylessEntryArchitecture");

Hardware Component Review Status View

Create a view that selects all hardware components in the architecture model and groups them using
the ReviewStatus property.

1. Construct a query to select all hardware components.

hwCompQuery = HasStereotype(IsStereotypeDerivedFrom("AutoProfile.HardwareComponent"));

2. Use the query to create a view.

11-23
11 Create Custom Views

model.createView("Hardware Component Review Status",...


Select=hwCompQuery,...
GroupBy={'AutoProfile.BaseComponent.ReviewStatus'},...
IncludeReferenceModels=true,...
Color="purple");

3. To open the Architecture Views Gallery the Modeling section, click Architecture Views.

model.openViews

FOB Locater System Supplier View

Create a view with components from the FOB Locater System and group them using existing and
new view components for the suppliers. In this example, you will use element groups, groupings of
components in a view, to programmatically populate a view.

1. Create a view architecture.

fobSupplierView = model.createView("FOB Locater System Supplier Breakdown",...


Color="lightblue");

11-24
Create Architecture Views Programmatically

2. Add a subgroup called Supplier D. Add the FOB Locater Module to the view element
subgroup.
supplierD = fobSupplierView.Root.createSubGroup("Supplier D");
supplierD.addElement("KeylessEntryArchitecture/FOB Locater System/FOB Locater Module");

3. Create a new subgroup for Supplier A.


supplierA = fobSupplierView.Root.createSubGroup("Supplier A");

4. Add each of the FOB Receivers to the view element subgroup.


FOBLocaterSystem = model.lookup("Path","KeylessEntryArchitecture/FOB Locater System");

Find all the components which contain the name Receiver.


receiverCompPaths = model.find(...
contains(Property("Name"),"Receiver"),...
FOBLocaterSystem.Architecture);

supplierA.addElement(receiverCompPaths)

Find Elements in Model Using Queries

Find components in a System Composer model using queries.

Import the namespace that contains all of the System Composer queries.
import systemcomposer.query.*

Open the model.


openProject("scKeylessEntrySystem");
model = systemcomposer.loadModel("KeylessEntryArchitecture");

11-25
11 Create Custom Views

Find all the software components in the system.

con1 = HasStereotype(Property("Name") == "SoftwareComponent");


[compPaths,compObjs] = model.find(con1)

compPaths = 5x1 cell


{'KeylessEntryArchitecture/Door Lock//Unlock System/Door Lock Controller' }
{'KeylessEntryArchitecture/Sound System/Sound Controller' }
{'KeylessEntryArchitecture/Lighting System/Lighting Controller' }
{'KeylessEntryArchitecture/FOB Locater System/FOB Locater Module' }
{'KeylessEntryArchitecture/Engine Control System/Keyless Start Controller'}

compObjs=1×5 Component array with properties:


IsAdapterComponent
Architecture
ReferenceName
Name
Parent
Ports
OwnedPorts
OwnedArchitecture
Parameters
Position
Model
SimulinkHandle
SimulinkModelHandle
UUID
ExternalUID

Include reference models in the search.

softwareComps = model.find(con1,IncludeReferenceModels=true)

softwareComps = 9x1 cell


{'KeylessEntryArchitecture/Door Lock//Unlock System/Door Lock Controller'
{'KeylessEntryArchitecture/Sound System/Sound Controller'
{'KeylessEntryArchitecture/Lighting System/Lighting Controller'
{'KeylessEntryArchitecture/FOB Locater System/FOB Locater Module'
{'KeylessEntryArchitecture/Engine Control System/Keyless Start Controller'
{'KeylessEntryArchitecture/Door Lock//Unlock System/Front Driver Door Lock Sensor/Detect Door
{'KeylessEntryArchitecture/Door Lock//Unlock System/Rear Driver Door Lock Sensor/Detect Door
{'KeylessEntryArchitecture/Door Lock//Unlock System/Rear Pass Door Lock Sensor/Detect Door Lo
{'KeylessEntryArchitecture/Door Lock//Unlock System/Front Pass Door Lock Sensor/Detect Door L

Find all the base components in the system.

con2 = HasStereotype(IsStereotypeDerivedFrom("AutoProfile.BaseComponent"));
baseComps = model.find(con2)

baseComps = 18x1 cell


{'KeylessEntryArchitecture/Door Lock//Unlock System/Door Lock Controller' }
{'KeylessEntryArchitecture/Sound System/Sound Controller' }
{'KeylessEntryArchitecture/Lighting System/Lighting Controller' }
{'KeylessEntryArchitecture/FOB Locater System/FOB Locater Module' }
{'KeylessEntryArchitecture/Engine Control System/Keyless Start Controller' }
{'KeylessEntryArchitecture/Door Lock//Unlock System/Front Driver Door Lock Sensor' }

11-26
Create Architecture Views Programmatically

{'KeylessEntryArchitecture/FOB Locater System/Front Receiver' }


{'KeylessEntryArchitecture/Engine Control System/Start//Stop Button' }
{'KeylessEntryArchitecture/FOB Locater System/Center Receiver' }
{'KeylessEntryArchitecture/Sound System/Dashboard Speaker' }
{'KeylessEntryArchitecture/Door Lock//Unlock System/Front Pass Door Lock Sensor' }
{'KeylessEntryArchitecture/Door Lock//Unlock System/Rear Pass Door Lock Sensor' }
{'KeylessEntryArchitecture/Door Lock//Unlock System/Rear Driver Door Lock Actuator' }
{'KeylessEntryArchitecture/Door Lock//Unlock System/Rear Pass Door Lock Actuator' }
{'KeylessEntryArchitecture/Door Lock//Unlock System/Front Pass Door Lock Actuator' }
{'KeylessEntryArchitecture/Door Lock//Unlock System/Front Driver Door Lock Actuator'}
{'KeylessEntryArchitecture/Door Lock//Unlock System/Rear Driver Door Lock Sensor' }
{'KeylessEntryArchitecture/FOB Locater System/Rear Receiver' }

Find all components using the interface KeyFOBPosition.

con3 = HasPort(HasInterface(Property("Name") == "KeyFOBPosition"));


con3_a = HasPort(Property("InterfaceName") == "KeyFOBPosition");
keyFOBPosComps = model.find(con3)

keyFOBPosComps = 9x1 cell


{'KeylessEntryArchitecture/Door Lock//Unlock System/Door Lock Controller' }
{'KeylessEntryArchitecture/Sound System/Sound Controller' }
{'KeylessEntryArchitecture/Lighting System/Lighting Controller' }
{'KeylessEntryArchitecture/FOB Locater System/FOB Locater Module' }
{'KeylessEntryArchitecture/Engine Control System/Keyless Start Controller'}
{'KeylessEntryArchitecture/Door Lock//Unlock System' }
{'KeylessEntryArchitecture/Engine Control System' }
{'KeylessEntryArchitecture/FOB Locater System' }
{'KeylessEntryArchitecture/Sound System' }

Find all components whose WCET is less than or equal to 5 ms.

con4 = PropertyValue("AutoProfile.SoftwareComponent.WCET") <= 5;


model.find(con4)

ans = 1x1 cell array


{'KeylessEntryArchitecture/Sound System/Sound Controller'}

You can specify units for automatic unit conversion.

con5 = PropertyValue("AutoProfile.SoftwareComponent.WCET") <= Value(5,'ms');


query1Comps = model.find(con5)

query1Comps = 3x1 cell


{'KeylessEntryArchitecture/FOB Locater System/FOB Locater Module'}
{'KeylessEntryArchitecture/Lighting System/Lighting Controller' }
{'KeylessEntryArchitecture/Sound System/Sound Controller' }

Find all components whose WCET is greater than 1 ms or that have a cost greater than 10 USD.

con6 = PropertyValue("AutoProfile.SoftwareComponent.WCET") > Value(1,'ms') | PropertyValue("AutoP


query2Comps = model.find(con6)

query2Comps = 2x1 cell


{'KeylessEntryArchitecture/Door Lock//Unlock System/Door Lock Controller' }

11-27
11 Create Custom Views

{'KeylessEntryArchitecture/Engine Control System/Keyless Start Controller'}

See Also
Tools
Architecture Views Gallery

Functions
openViews | createView | getView | deleteView | modifyQuery | runQuery | removeQuery |
addElement | removeElement | getQualifiedName | createSubGroup | getSubGroup |
deleteSubGroup | find | findElementsOfType | findElementsWithStereotype |
findElementsWithProperty | findElementsWithInterface | AnyComponent | Property |
PropertyValue | HasStereotype | IsStereotypeDerivedFrom | HasPort | HasConnector |
HasInterface | HasInterfaceElement | IsInRange | createView | getQualifiedName |
lookup

Objects
systemcomposer.view.View | systemcomposer.view.ElementGroup |
systemcomposer.query.Constraint

More About
• “Create Custom Views Using Architecture Views Gallery” on page 11-2
• “Modeling System Architecture of Keyless Entry System” on page 11-33
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Use Interface Editor in Views” on page 11-49
• “Group Ports in Component Diagram Views” on page 11-52
• “Class Diagram View of Software Architectures” on page 10-22

11-28
Display Component Hierarchy and Architecture Hierarchy Using Views

Display Component Hierarchy and Architecture Hierarchy


Using Views
This example shows how to use hierarchy views in the Architecture Views Gallery to use hierarchy
views to visualize hierarchical relationships.

For a roadmap of the views topics, see “Create Custom Views Using Architecture Views Gallery” on
page 11-2.

You can visualize a hierarchy diagram as a view with components, ports, reference types, component
stereotypes, and stereotype properties.

There are two types of hierarchy diagrams:

• Component hierarchy diagrams display components in tree form with parents above children. In a
component hierarchy view, each referenced model is represented as many times as it is used.
• Architecture hierarchy diagrams display unique component architecture types and their
relationships using composition connections. In an architecture hierarchy view, each referenced
model is represented only once.

Any component diagram view can be optionally represented as a hierarchy diagram. The hierarchy
view shows the same set of components visible in the component diagram view, and the components
are selected and filtered in the same way as in a component diagram view.

This example uses an architecture model representing data flow within a robotic system. Open this
model to follow the steps in the tutorial.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Robot Computer Systems Architecture

Use a robot computer system with controllers that simulate transmission of data to explore hierarchy
diagrams in the Architecture Views Gallery.

11-29
11 Create Custom Views

Switch Between Component Diagram View and Hierarchy Views


1 To open the Architecture Views Gallery, navigate to Modeling > Architecture Views.
2 From the View Browser, select the All Components view.
3 Observe the component diagram view that corresponds to the all the components in the
architecture model.

The component diagram represents a view with components, ports, and connectors based on how
the model is structured.
4 In the Diagram section of the toolstrip, click Component Hierarchy.

11-30
Display Component Hierarchy and Architecture Hierarchy Using Views

5 Observe the component hierarchy view that corresponds to the same set of components.

The component hierarchy diagram shows a single root, which is the view specification itself. The
root corresponds to the name of the view shown in the component diagram. The connections in
the component hierarchy diagram originate from the child components and end with a diamond
symbol at each parent component.
6 In the Diagram section of the toolstrip, click Architecture Hierarchy.

7 Observe the architecture hierarchy view that corresponds to the same set of components.

11-31
11 Create Custom Views

The architecture hierarchy diagram starts with the root architecture. The root corresponds to the
boundary of the system. A box in an architecture hierarchy diagram represents a referenced
model and appears only once even if it is referenced multiple times in the same model. For
example, ControllerSimulink, a referenced model that appears on three components, has
connections showing the multiplicity. The connectivity of the boxes represents the relationship
between ContollerSimulink and its parents.

See Also
Tools
Architecture Views Gallery | Interface Editor

Functions
openViews | createView | getView | deleteView | modifyQuery | runQuery | removeQuery |
addElement | removeElement | getQualifiedName | createSubGroup | getSubGroup |
deleteSubGroup | getQualifiedName | lookup

Objects
systemcomposer.view.View | systemcomposer.view.ElementGroup |
systemcomposer.query.Constraint | systemcomposer.interface.DataInterface |
systemcomposer.interface.DataElement

More About
• “Create Custom Views Using Architecture Views Gallery” on page 11-2
• “Modeling System Architecture of Keyless Entry System” on page 11-33
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Use Interface Editor in Views” on page 11-49
• “Group Ports in Component Diagram Views” on page 11-52
• “Class Diagram View of Software Architectures” on page 10-22

11-32
Modeling System Architecture of Keyless Entry System

Modeling System Architecture of Keyless Entry System

This example shows how to set up the architecture for a keyless entry system for a vehicle in System
Composer™. You also learn how to create different architecture views for different stakeholder
concerns. This example follows a model-based systems engineering (MBSE) workflow:

1 Define Stakeholder Requirements


2 Define Architecture Model
3 Define Stereotypes to Classify Components
4 Define Port Interfaces to Describe Data Flow
5 Create Views to Present to Stakeholders

openProject("scKeylessEntrySystem");

11-33
11 Create Custom Views

For more information about mask icons on components, see “Compose Architectures Visually” on
page 1-5.

Define Stakeholder Requirements

In MBSE design, functional requirements represent high-level stakeholder requirements based on


needs and concerns for the design to address. Run this command to open the Requirements Editor
(Requirements Toolbox) with the functional requirements. A Requirements Toolbox™ license is
required to inspect requirements in a System Composer architecture model.

slreq.load('FunctionalRequirements');

slreq.editor

These stakeholder requirements specify that the architecture model must include a door lock and
unlock system, a lighting control system, a sound system, and an engine control system. These
components should meet requirements after passing quality checks. For more information, see
“Manage Requirements” on page 2-9.

Define Architecture Model

The architecture of a keyless entry system includes sensors, a mechanical door lock system, a lighting
system, a sound system, and an engine control system. These components interact based on the
information passed through their ports by connections. Each top-level component can be decomposed
into its subcomponents to represent an architectural hierarchy.

Decompose the FOB Locator System

The FOB Locator System component includes the system the vehicle uses to receive a wireless
signal and isolate the location of the key to lock or unlock doors. This action is the first step in
implementing a keyless entry system.

11-34
Modeling System Architecture of Keyless Entry System

The referenced architecture FOB Receiver is reused to type the three receivers on the vehicle on
the front, center, and rear. Each receiver sends a signal, RxSignal, to the FOB Locator Module
component that determines the key location, keyLocation, and transmits the key location to all the
other systems represented by components.

Decompose the Door Lock and Unlock System

After the key location is identified, the automated door lock and unlock system activates. The door
lock and unlock system has both hardware and software components.

11-35
11 Create Custom Views

All four doors for the vehicle have sensors that detect whether the door is locked. The
DoorLockSensor referenced architecture types these components. According to the information
passed through the FOB, the Door Lock Controller component activates the actuators for the
four doors to optionally implement the door locks. The DoorLockActuator referenced architecture
types the actuators. The door lock status doorStatus is transmitted through the boundary from the
Door Lock Controller component.

Decompose the Sound System

The Sound System component controls emitting sounds to indicate key location, door status, and
engine status.

11-36
Modeling System Architecture of Keyless Entry System

The software for the Sound Controller component sends a command to the Dashboard Speaker
component to process and make the sounds.

Decompose the Engine Control System

The engine control system contains a system to control the brakes, transmission, and engine. The
keyless entry system activates a keyless start controller that starts or stops the vehicle.

11-37
11 Create Custom Views

The keyLocation signal from the FOB Locator System enters the Keyless Start Controller
component, which receives feedback from the Brake System, Transmission System, and Engine
System components. Next, a signal is sent to the Engine System to start or stop the vehicle
according to the buttonPressed signal from the Start/Stop Button component.

Decompose the Lighting System

The keyless entry system sends commands from a lighting controller to activate the headlights and
cabin lights.

11-38
Modeling System Architecture of Keyless Entry System

Engine status and key location information sent to the Lighting Controller component might
activate the different lights represented by the Headlights and Cabin Lights components.

Define Stereotypes to Classify Components

All components in the architecture have the appropriate stereotype applied. Use the Profile Editor
tool to define profiles, stereotypes, and properties to apply to components, ports, connectors, and
interfaces. Each of the component stereotypes inherits properties from the parent stereotype
BaseComponent. For each stereotyped component, you can define the Cost, ReviewStatus, or
Latency property values.

11-39
11 Create Custom Views

To stereotype components and ports, first apply the profile AutoProfile to the top model. Each of
the component stereotypes includes an icon that represents the usage of the stereotype and indicates
the component type. To apply stereotypes to all model elements in a batch process, use the Apply
Stereotypes tool. To launch the tool, on the Modeling tab in the toolstrip, click Apply Stereotypes.
To apply stereotypes one by one, use the Property Inspector. For more information, see “Apply
Stereotypes to Extend Model Elements” on page 5-13.

Define Port Interfaces to Describe Data Flow

You can use data interfaces and value types that you assign to ports to decompose the data transfer
through those ports along the connections between the ports. For example, the keyFOBPosition
interface describes the elements of information passing through the keyLocation ports to different
components of the architecture.

11-40
Modeling System Architecture of Keyless Entry System

A composite data interface such as keyFOBPosition that you decompose into data elements
radialDist and isInsideVehicle is an example of a design in the Interface Editor. You can also
decompose data interfaces by adding data elements typed by other data interfaces or typed by value
types like DoorStatus, EngineStatus, or FOBSignal. For more information, see “Assign Interfaces
to Ports” on page 3-11.

Create Views to Present to Stakeholders

You can create, view, and edit architecture views in the Architecture Views Gallery. To launch the
tool, on the Modeling tab in the toolstrip, click Architecture Views. Filtered views update

11-41
11 Create Custom Views

dynamically with changes to the model. Alternatively, you can use Spotlight Views, which are
transient views centered on specific components. For more information, see “Create Spotlight Views”
on page 11-5. The KeylessEntryArchitecture model has these views:

• Key FOB Position Dataflow — A view of the components in the model that make use of the
KeyFOBPosition interface.

• Door Lock System Supplier Breakdown — A view of the components in the door lock system
grouped by which supplier provides the given components.

• Sound System Supplier Breakdown — A view of the components in the sound system grouped by
which supplier provides the given components.

11-42
Modeling System Architecture of Keyless Entry System

• Software Component Review Status — A view of the components in the model with the
SoftwareComponent stereotype applied grouped by the value of the ReviewStatus property.

• Top Level Components — A view of the top level components on the architecture model with mask
icons.

11-43
11 Create Custom Views

See Also
Tools
Architecture Views Gallery | Interface Editor

Functions
openViews | createView | getView | deleteView | modifyQuery | runQuery | removeQuery |
addElement | removeElement | getQualifiedName | createSubGroup | getSubGroup |
deleteSubGroup | getQualifiedName | lookup

Objects
systemcomposer.view.View | systemcomposer.view.ElementGroup |
systemcomposer.query.Constraint | systemcomposer.interface.DataInterface |
systemcomposer.interface.DataElement

More About
• “Create Custom Views Using Architecture Views Gallery” on page 11-2
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Use Interface Editor in Views” on page 11-49

11-44
Modeling System Architecture of Keyless Entry System

• “Group Ports in Component Diagram Views” on page 11-52


• “Class Diagram View of Software Architectures” on page 10-22

11-45
11 Create Custom Views

Pivot Between Lifelines and Components in Views Gallery

This example shows how to use the pivot feature in the Architecture Views Gallery tool to transition
between diagrams with your chosen lifeline or component selected.

1. Open the traffic light example and then launch the Architecture Views Gallery.
model = systemcomposer.openModel("TLExample");

openViews(model)

2. Create a new view called All Components.


view = createView(model,"All Components");

3. Import the query namespace. Add a query to select all components from the model, then add the
query to the view.
import systemcomposer.query.*
view.modifyQuery(AnyComponent)

4. On the All Components component diagram view, select the switch component.

11-46
Pivot Between Lifelines and Components in Views Gallery

5. From the Architecture Views Gallery toolstrip, in the Views tab, select Pivot. Then, select the
PedestrianCross sequence diagram to pivot from the switch component to the switch lifeline
that represents the component.

You have navigated from the All Components component diagram view to the PedestrianCross
sequence diagram to interact with the same entity.

See Also
Tools
Architecture Views Gallery | Interface Editor

11-47
11 Create Custom Views

Functions
openViews | createView | getView | deleteView | modifyQuery | runQuery | removeQuery |
addElement | removeElement | getQualifiedName | createSubGroup | getSubGroup |
deleteSubGroup | getQualifiedName | lookup

Objects
systemcomposer.view.View | systemcomposer.view.ElementGroup |
systemcomposer.query.Constraint | systemcomposer.interface.DataInterface |
systemcomposer.interface.DataElement

More About
• “Create Custom Views Using Architecture Views Gallery” on page 11-2
• “Modeling System Architecture of Keyless Entry System” on page 11-33
• “Use Interface Editor in Views” on page 11-49
• “Group Ports in Component Diagram Views” on page 11-52
• “Class Diagram View of Software Architectures” on page 10-22

11-48
Use Interface Editor in Views

Use Interface Editor in Views

This example shows how to use the Interface Editor tool directly from the Architecture Views Gallery
to add and edit interfaces using the context of a subset of components from the top model.

Launch Interface Editor in Views

Launch the keyless entry system project.

openProject("scKeylessEntrySystem");

After launching the keyless entry system project, the KeylessEntryArchitecture architecture
model opens.

1 To launch the Architecture Views Gallery tool, on the System Composer™ toolstrip of the
KeylessEntryArchitecture architecture model, from the Modeling tab, click Architecture
Views.
2 In the View Browser, select the Top Level Components view.
3 To dock the Interface Editor tool below your view, on the Architecture Views Gallery
toolstrip, from the Design section, click Interface Editor.
4 To highlight ports, in the Interface Editor tool, expand Interfaces.sldd, right-click the
KeyFOBPosition interface and select Highlight port(s) using this interface. The
KeyFOBPosition interface is assigned to these ports.

11-49
11 Create Custom Views

Add and Edit Data Elements to Data Interfaces Using Interface Editor

To further describe the data interface KeyFOBPositon while considering a subset of components in
your architecture view, you can add descriptive data elements to your data interface.

1 On the Interface Editor, from your Top Level Components view, select the KeyFOBPosition
data interface.

11-50
Use Interface Editor in Views

2
Add two data elements by clicking the button twice. Name the first data element
radialDist to represent the distance the FOB is from the electronic keyless system. The
radialDist element should be of Type double, Dimensions 1, and Units m for meters. Name
the second data element isInsideVehicle to represent whether the FOB is inside or outside of
the vehicle. The isInsideVehicle element should be of Type boolean and Dimensions 1.

You can also edit interfaces or elements from the Interface Properties or Interface Element
Properties tab on the right of the Architecture Views Gallery.

See Also
Tools
Architecture Views Gallery | Interface Editor

Functions
openViews | createView | getView | deleteView | modifyQuery | runQuery | removeQuery |
addElement | removeElement | getQualifiedName | createSubGroup | getSubGroup |
deleteSubGroup | getQualifiedName | lookup

Objects
systemcomposer.view.View | systemcomposer.view.ElementGroup |
systemcomposer.query.Constraint | systemcomposer.interface.DataInterface |
systemcomposer.interface.DataElement

More About
• “Create Custom Views Using Architecture Views Gallery” on page 11-2
• “Modeling System Architecture of Keyless Entry System” on page 11-33
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Group Ports in Component Diagram Views” on page 11-52
• “Class Diagram View of Software Architectures” on page 10-22

11-51
11 Create Custom Views

Group Ports in Component Diagram Views

This example shows how to group ports in component diagram views in the Architecture Views
Gallery tool. Grouping ports simplifies view diagrams in System Composer™.

Open Architecture Model

Open an architecture model for which you have a complex, interconnected system. This example uses
the logical architecture of an electric vehicle.

Create Architecture View

Create a component diagram view in the Architecture Views Gallery. From the architecture model
menu, navigate to Modeling > Architecture Views. Then, click New > View. Drag only the top-
level components from your model into the view. Name your view.

11-52
Group Ports in Component Diagram Views

This view includes many ports and connections that make the diagram difficult to read.

Group Ports to Simplify View

To simplify your architecture view, click Group Ports. Ports are now grouped in your component
diagram view.

Click any grouped port to view its constituent ports in the Port Group Properties tab. For more
information on why you can group some ports and not others, see “Create Architecture Views
Interactively” on page 11-9.

11-53
11 Create Custom Views

You can also pause on a grouped connector to view detailed connection information on your view as
an overlay.

11-54
Group Ports in Component Diagram Views

This simplified component diagram view summarizes the key aspects of your system.

See Also
Tools
Architecture Views Gallery | Interface Editor

Functions
openViews | createView | getView | deleteView | modifyQuery | runQuery | removeQuery |
addElement | removeElement | getQualifiedName | createSubGroup | getSubGroup |
deleteSubGroup | getQualifiedName | lookup

Objects
systemcomposer.view.View | systemcomposer.view.ElementGroup |
systemcomposer.query.Constraint | systemcomposer.interface.DataInterface |
systemcomposer.interface.DataElement

More About
• “Create Custom Views Using Architecture Views Gallery” on page 11-2
• “Modeling System Architecture of Keyless Entry System” on page 11-33
• “Pivot Between Lifelines and Components in Views Gallery” on page 11-46
• “Use Interface Editor in Views” on page 11-49
• “Class Diagram View of Software Architectures” on page 10-22

11-55
12

Manage Architecture Models

• “Organize System Composer Files in Projects” on page 12-2


• “Compare Model Differences Using System Composer Comparison Tool” on page 12-5
• “Resolve Conflicts in Project Using System Composer Three-Way Merge” on page 12-10
• “Graphically Manage Shared Interfaces, Data Types, and Constants” on page 12-12
• “Programmatically Manage Shared Interfaces, Data Types, and Constants of Architecture Models”
on page 12-17
• “Resolve Conflicts in Projects Using System Composer Three-Way Merge Tool” on page 12-20
12 Manage Architecture Models

Organize System Composer Files in Projects


Use projects to organize your work, manage files and settings, and interact with source control.
Using System Composer generates multiple files, including but not limited to:

• Architecture models (.slx)


• Requirements Toolbox links (.slmx) and requirement sets (.slreqx)
• Allocation sets (.mldatx)
• Profiles (.xml)
• Interface data dictionaries (.sldd)
• Simulink Test files (.mldatx)
• MATLAB functions (.m) and live scripts (.mlx)
• Simulink behavior models (.slx)

To help organize these files, use projects.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Use Projects to Organize Files and Folders


Create a project from a folder with supporting files and folders.

For example, this folder structure represents typical steps in the process of model-based systems
engineering: models, profiles, interfaces, requirements, tools, tests, livescripts

The models folder can include architecture models, Simulink behavior models, and requirement
links. If architecture models and behavior models are constructed separately, you can split the
models folder into two folders, architectures and simulation, and decompose the folders
further to represent the different stages of architectural model-based design. The tools folder can
include functions and scripts for trade studies and analyses.

1 In MATLAB, navigate to the directory where your model files and artifacts are located.
2 Select New > Project > From Folder. Enter a name for your project.

3 The files in the folder you specify are added to the project, and the Project menu appears. To
generate your own project shortcuts, on the Project Shortcuts tab, click New Shortcut or
Organize Groups.

12-2
Organize System Composer Files in Projects

4 On the Project tab, in the Source Control section, click Use Source Control. In the Source
control Information dialog box, click Add Project to Source Control.

You can open the project again using the generated .prj file in your directory.

Any changes you make will be organized in the project. You can manage changes to files with multiple
contributors using source control. For more information on source control with projects, see “About
Source Control with Projects”.

To illustrate file dependencies across the project, use the Dependency Analyzer. To check and
upgrade the project, use the Run Checks option.

Export Models and Model Dependencies to Previous Version of System


Composer
To combine different model artifacts, you might need to export them to a previous version of System
Composer. Follow these steps to export the small unmanned aerial vehicle (UAV) model and its
dependencies to a previous version.

1 Launch the small UAV project by entering this command in the MATLAB Command Window.

scExampleSmallUAV
2 The model scExampleSmallUAVModel.slx launches in a separate window. Navigate to
Simulation > Save > Previous Version.
3 In the Export to previous version dialog box, choose an empty folder for the Save path. Then,
from the Version list, choose a previous version.

12-3
12 Manage Architecture Models

The model scExampleSmallUAVModel.slx is saved to a previous version, including the dependent


file, the UAVComponent.xml profile.

See Also
systemcomposer.exportToVersion

More About
• “What Are Projects?”
• “Modeling System Architecture of Small UAV” on page 1-37
• “Modeling System Architecture of Keyless Entry System” on page 11-33
• “Allocate Architectures in Tire Pressure Monitoring System” on page 8-14
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35

12-4
Compare Model Differences Using System Composer Comparison Tool

Compare Model Differences Using System Composer


Comparison Tool

This example shows how to use the System Composer Comparison Tool to compare two System
Composer™ architecture models with differences in architectural data. The models represent a
mobile robot hardware architecture and an edited version of the same model.

To open the System Composer Comparison Tool, enter this command.


visdiff("scMobileRobotHardwareArchitecture.slx","scMobileRobotHardwareArchitectureEdited.slx")

Rows in the comparison report are highlighted according to the type of difference:


Insertion — Added elements to the right side that did not exist on the left side

12-5
12 Manage Architecture Models


Deletion — Removed elements that did exist on the left side but not on the right side

Modification — Changes to existing elements that exist on both the left and right sides

Compare Structural Differences

The first section of the System Composer comparison report is called Architecture. The
differences in this section include changes to components, ports, and connectors. This section also
includes changes to component types, port types, and any owned interfaces added to ports. The
comparison report displays:

• A new physical port named Temperature Control added to the Power Supply Board
component and connected to the Battery Pack component.
• A new port named Wheel Stud connected from the Wheels component to the Mobile Robot
Case component.
• A new owned interface with elements Signal and Message owned by the Command output port.
• A port on the Target Machine component renamed from Commands to Command.
• The Controller component that is converted to a Stateflow® chart component.

12-6
Compare Model Differences Using System Composer Comparison Tool

To learn more about specific changes, you can select the row in the comparison report and view
additional information in the bottom pane. As you click on each row of the comparison report, the
corresponding open models on the right side are highlighted.

Compare Interface Dictionary Differences

The second section of the System Composer comparison report is called Interfaces. The
differences in this section include changes to interfaces on the model data dictionary. The comparison
report displays:

• Three new value type interfaces called RedPhase, GreenPhase, and BluePhase.
• A new Colors data interface with three data elements: R, G, and B.
• A new physical interface named ThermalMeasure with the physical element Heat.

12-7
12 Manage Architecture Models

When you click on the data element: R, G, or B, you can see that the element is typed by its value
type. You can also inspect the physical domain that types the physical element Heat.

Compare Views Differences

The third section of the System Composer comparison report is called Architecture Views. The
differences in this section added or deleted architecture views and shows whether the view mode has
changed between Component Diagram, Component Hierarchy, or Architecture Hierarchy.
The comparison report displays:

• The new BatteryPack view and the components that are displayed within it: Power Supply
Board, Battery Pack, and Charge Board.
• Changes to the existing views Life Expectancy and Mobile Robot due to renaming the
Battery component to Battery Pack.

When you click on each of the view names, the bottom pane will indicate if there are further
modifications to the views.

See Also
Functions
visdiff

Tools
System Composer Comparison Tool

12-8
Compare Model Differences Using System Composer Comparison Tool

See Also

More About
• “Compose Architectures Visually” on page 1-5
• “Define Port Interfaces Between Components” on page 3-2
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Create Custom Views Using Architecture Views Gallery” on page 11-2
• “Implement Component Behavior Using Simulink” on page 7-2
• “Organize System Composer Files in Projects” on page 12-2

12-9
12 Manage Architecture Models

Resolve Conflicts in Project Using System Composer Three-Way


Merge
Conflicts in System Composer models can occur when multiple users work simultaneously on the
same architecture and when it is not possible to keep both changes in the merged architecture. A
user must make a decision on which change they want to keep by resolving the conflict in the model
file. For example, a conflict occurs when two users change the value of a property in two different
branches of a project. Another example is when one user modifies the structure of the architecture by
deleting a component and another user in a different branch modifies the same component. A conflict
occurs in the model file and the user must make a manual change to fix the merge.

Architecture Model Changes and Conflicts


If a project is under source control, when you attempt to merge the changes of another user on the
main branch into your branch, the operation might result in a conflict.

To resolve the conflicts using the System Composer Three-Way Merge Tool tool, you examine your
local file (Mine), the conflicting revision (Theirs), and the common ancestor of these two files
(Base).

The Merge tool automatically merges non-conflicting difference before opening the Three-Way Merge
report. Follow these steps to review the automatic merge choices, apply your desired edits, and
decide how to resolve any remaining differences. After your resolve the conflicts, commit the resolved
model to source control.

Open System Composer Three-Way Merge


In the project Files view, look for conflicted files. The InsulinInfusionPumpSystem file shows a
red warning icon in the Git column, which indicates a conflict.

To see a detailed report of the conflicts, right-click the InsulinInfusionPumpSystem file and
select View Conflicts.

View Changes
The Three-Way Merge tool shows the changes to the two System Composer architectures that cause
this conflict.

• The Theirs, Base, and Mine trees show the differences between the conflicting revision, your
revision, and the base ancestor of these files.
• The Target tree shows the file into which you merge changes. The tool copies this temporary file
into the project when you choose to accept the merge result.
• The summary table in the bottom right corner shows that the merge tool automatically resolved
non-conflicting differences. The table also shows that you must resolve some remaining changes.

To resolve the remaining changes, follow these steps:

1 Examine a difference by clicking on a row in one of the trees. The Merge tool displays the change
for each model in an editor.

12-10
Resolve Conflicts in Project Using System Composer Three-Way Merge

2 On the Merge tab, in the Highlight section, choose the models to display by clicking Top Model
or Bottom Model.

Review Automatic Merges


The Merge tool automatically merges most non-conflicting differences before opening the Three-Way
Merge report.

Examine the first change at the top of the Theirs tree by clicking the

Resolve Conflicts
Two types of differences require you to take action.

• Conflict - The merge tool cannot automatically resolve these differences. You must choose which
design to keep in the target file. In the Target pane, in the conflict column, a warning icon
indicates these differences.
• Manual merge - Some differences require you to manually make a change in System Composer.
In the Target pane, in the conflict column, a pencil icon indicates these differences.

To resolve conflicts, follow these steps.

1 Use the Next button to navigate to the first conflict.


2 To resolve the line change difference in targetFile, in the System Composer canvas, change
the name of the line.

If you resolved all conflicts in the current view but the summary table title is Resolve remaining x
changes, disable the filters to view and resolve the remaining conflicts. On the Merge tab, in the
Filter section, turn the filters off.

Accept Changes
• After you resolve all filtered and unfiltered changes, click Accept & Close. The merge tool closes
the report and the models, accepts the merge result in targetFile, and marks the conflict as
resolved in the source control tool.
• Before you commit the resolved model file to source control, perform a final review by comparing
the merge changes against the current branch.

In the project Files view, right-click the model and select Compare > Compare to Ancestor.

See Also
visdiff | System Composer Comparison Tool

Related Examples
• “Compare Model Differences Using System Composer Comparison Tool” on page 12-5
• “Resolve Conflicts in Models Using Three-Way Merge”
• “Resolve Conflicts in Project Using Simulink Three-Way Merge”

12-11
12 Manage Architecture Models

Graphically Manage Shared Interfaces, Data Types, and


Constants

The Architectural Data section of a Simulink data dictionary enables interfaces, data types, and
constants to be authored, managed, and shared between components and compositions modeled in
Simulink. The Architectural Data section provides scalability for system-level and multicomponent
designs by containing these shared elements in a central location.

You can configure architectural data and apply your changes to a model using this basic workflow:

1 Create a data dictionary.


2 Design interface, data types, and constants with the Architectural Data Editor.
3 Link the data dictionary containing architectural data to a Simulink or architecture model.
4 Apply architectural data to a model in the Simulink environment.

Create Simulink Data Dictionary and Open Architectural Data Section


for Editing
To create a data dictionary from the System Composer architecture model toolstrip, on the Modeling
tab, open the Design gallery, and select Save to new dictionary from the Interfaces section.

12-12
Graphically Manage Shared Interfaces, Data Types, and Constants

Design Data Types, Interfaces, and Constants Using Architectural Data


Editor
Once you create your data dictionary, you can add and edit architectural data using the Architectural
Data Editor. This tool allows you to author elements shared outside of the context of a particular
component or composition and allow multiple team members to define and manage these elements.

Open Architectural Data Editor

To open the Architectural Data Editor from a System Composer architecture model that is already
linked to a data dictionary:


In the Interface Editor navigate to and select the icon with tooltip Manage interfaces, data
types and dictionary references in the Architectural Data Editor.

To open the editor from outside the context of a model, use one of these methods:

12-13
12 Manage Architecture Models

• In the MATLAB Current Folder browser, navigate to and double-click the .sldd file to open Model
Explorer. Expand the data dictionary file and select Architectural Data, then click Open
Architectural Data Editor from the Dialog pane.
• Use the show function on an Architectural Data object created using
Simulink.dictionary.archdata.create or Simulink.dictionary.archdata.open.
• Enter archdataeditor at the MATLAB command line.

Add and Configure Data Using Architectural Data Editor

With the Architectural Data Editor, you can create, configure, and manage architectural data.

• Create — On the toolstrip, in the Create section, add data type definitions, interfaces, and
constants. Data types, interfaces, and constants each have a dedicated tab for data management.
• Configure — In the right panel, use the Details pane to configure your data. The Details pane can
also display platform-specific properties.

For example, when you open a Simulink data dictionary linked to a model that is mapped to a
Native platform, the Details pane displays a Code Generation pane. You can then define the
Data scope and Header file. For more information on how to determine these settings, see
“Control File Placement of Custom Data Types” (Embedded Coder). To preserve dimensions of bus
objects that contain multidimensional bus elements, select the Preserve element dimensions
option.
• Manage — You can filter, sort, and search data on the Interfaces, Data Types, and Constants
tabs.

Link Data Dictionary to Model


To link an existing data dictionary from the System Composer architecture model toolstrip, on the
Modeling tab, open the Design gallery and select Save to new dictionary from the Interfaces
section.

12-14
Graphically Manage Shared Interfaces, Data Types, and Constants

For more information regarding linking dictionaries to System Composer models, see “Save, Attach,
and Delete Interfaces” on page 3-24.

Use Interface Editor to Apply Interfaces to Architecture Model


Alternatively, you can apply the interfaces to your model by using the Interface Editor and Property
Inspector. In the architecture model toolstrip, on the Modeling tab, open the Design gallery and
select Interface Editor. The editor opens as a pane in the current Simulink Editor window.

The primary focus of this model-centric editor is applying interfaces to ports. It displays the available
interfaces in the linked data dictionary. By using the Interfaces tab you can:

• Add data interfaces in the architecture model.


• Assign an interface to a selected port on the canvas by right-clicking on the interface.
• Trace between ports and interfaces.
• Focus on a particular interface by using the Port Interface View.
• View and configure a selected interface by using the Property Inspector.

You can also define profiles and stereotypes using either the Architectural Data Editor or the Profile
Editor. See “Define and Style Stereotypes in Profiles” on page 5-5 for more information regarding
related workflows.

See Also
Architectural Data Editor | Property Inspector | Simulink.dictionary.ArchitecturalData |
Simulink.dictionary.archdata.create | Simulink.dictionary.archdata.open

12-15
12 Manage Architecture Models

Related Examples
• “Programmatically Manage Shared Interfaces, Data Types, and Constants of Architecture
Models” on page 12-17
• “Build Architecture Models Programmatically” on page 1-29
• “Compose Architectures Visually” on page 1-5

12-16
Programmatically Manage Shared Interfaces, Data Types, and Constants of Architecture Models

Programmatically Manage Shared Interfaces, Data Types, and


Constants of Architecture Models
The Architectural Data section of a Simulink data dictionary enables interfaces, data types, and
constants to be authored, managed, and shared between components and compositions modeled in
Simulink. The Architectural Data section provides scalability for system-level and multicomponent
designs by containing these shared elements in a central location.

You can programmatically configure architectural data and apply your changes to your model using
this basic workflow:

1 Create or open a data dictionary.


2 Design interfaces, data types, and constants with the
Simulink.dictionary.ArchitecturalData programmatic interfaces.
3 Link the data dictionary containing architectural data to a Simulink or architecture model.
4 Apply architectural data to a model programmatically.

Create or Open Simulink Data Dictionary Programmatically


• To create a new data dictionary, use the Simulink.dictionary.archdata.create function.

dictName = "MyInterfaces.sldd";
archDataObj = Simulink.dictionary.archdata.create(dictName);
• To open an existing data dictionary use the Simulink.dictionary.archdata.open function.

archDataObj2 = Simulink.dictionary.archdata.open("OtherDictionary.sldd");

These functions return Architectural Data objects that you can edit using the
Simulink.dictionary.ArchitecturalData programmatic interfaces.

Design Data Types, Interfaces, and Constants Programmatically


1 To programmatically create, configure, and manage architectural data in your data dictionary,
use the programmatic interfaces for the Simulink.dictionary.ArchitecturalData object.

dictName = "myDataDictionary.sldd";
archDataObj = Simulink.dictionary.archdata.create(dictName);
2 Use type-specific functions to add alias types and enumerations to the data dictionary.

myAliasType1Obj = addAliasType(archDataObj,"aliasType",BaseType="single");
myAliasType1Obj.Name = "myAliasType1";
myAliasType1Obj.BaseType = "fixdt(1,32,16)";
myAliasType2Obj = addAliasType(archDataObj,"myAliasType2");
myAliasType2Obj.BaseType = myAliasType1Obj;

myEnumType1Obj = addEnumType(archDataObj,"myColor");
myEnumType1Obj.DefaultValue = "BLUE";
myEnumType1Obj.Description = "I am a Simulink Enumeration";
myEnumType1Obj.StorageType = "int16";
3 You can set the base type of the created alias type to be the created enumeration data type
myColor.

12-17
12 Manage Architecture Models

myAliasType3Obj = addAliasType(archDataObj,"myAliasType3");
myAliasType3Obj.BaseType = myEnumType1Obj;
4 Use the addNumericType function to add numeric types to the data dictionary.

myNumericType1Obj = addNumericType(archDataObj,"myNumericType1");
myNumericType1Obj.DataTypeMode = "Single";
5 Use the addValueType to add value types to the data dictionary. You can also set the data type
of the value types to be pre-existing data types or created enumeration data types.

myValueType1Obj = addValueType(archDataObj,"myValueType1");
myValueType1Obj.DataType = 'int32';
myValueType1Obj.Dimensions = '[2 3]';
myValueType1Obj.Description = "I am a Simulink ValueType";
6 Use the addStructType function to add struct types to the data dictionary.

myStructType1Obj = addStructType(archDataObj,"myStructType1");
structElement1 = myStructType1Obj.addElement("Element1");
structElement1.Type.DataType = 'single';
structElement1.Type.Dimensions = '3';
structElement2 = addElement(myStructType1Obj,"Element2");
structElement3 = addElement(myStructType1Obj,"Element3");
7 You can set the data type of a struct element by using the data type object or by using the name
of the data type, specified as a string scalar or character vector.

structElement2.Type = myValueType1Obj;
% or
structElement3.Type = "ValueType: myValueType1";
8 You can add constants using the addConstant function.

myConstantObj = addConstant(archDataObj, "myConst", Value=4);


9 You can add communication interfaces and their data elements using the functions of the
Simulink.dictionary.archdata.DataInterface object.

nvInterface1 = addDataInterface(archDataObj,"NV1");

dataElm1 = addElement(nvInterface1,"DE1");
dataElm1.Type = myValueType1Obj;
dataElm2 = addElement(nvInterface1,"DE3");
dataElm2.Type.DataType = 'single';
dataElm2.Type.Dimensions = '10';
dataElm2.Type.Minimum = '-5';

srInterface2 = addDataInterface(archDataObj,"SR1");

Link a Data Dictionary Programmatically


To link a dictionary to a model programmatically use the linkDictionary function.

1 Create or open a Simulink data dictionary. In this example you create a new data dictionary
MyInterfaces.sldd.

dictName = "MyInterfaces.sldd";
archDataObj = Simulink.dictionary.archdata.create(dictName);
2 Create a System Composer model and extract its architecture.

model = systemcomposer.createModel("myTopComposition_archdata");
archModel = Model.Architecture;

12-18
Programmatically Manage Shared Interfaces, Data Types, and Constants of Architecture Models

3 Add a physical interface and a physical element to the Architectural Data section of the data
dictionary.

physicalInterface = addPhysicalInterface(archDataObj,...
"PhysicalInterface");
physicalElement = addElement(physicalInterface,"ElectricalElement",...
Type="electrical.electrical");
4 Link the data dictionary to the model.

linkDictionary(model,dictName);

For more information regarding System Composer architecture models, see “Build Architecture
Models Programmatically”.

Apply Data Changes Programmatically


Once your data dictionary is linked to an architecture model, you can apply the changes to your
modeled application programmatically by using the Simulink.dictionary.ArchitecturalData
object.

Here, you can add components, ports, and connections to your architecture model. Set the interface
of the added component using the physical interface previously added to the data dictionary in “Link
a Data Dictionary Programmatically” on page 12-18.

1 Create or open a Simulink data dictionary. In this example you create a new data dictionary
MyInterfaces.sldd.

dictName = "MyInterfaces.sldd";
archDataObj = Simulink.dictionary.archdata.create(dictName);
2 Create a System Composer model and extract its architecture.

model = systemcomposer.createModel("myTopComposition_archdata");
archModel = Model.Architecture;
3 Add a component and a port to the architecture model. You can set the interface type using the
physical interface object created a previous section.

componentSensor = addComponent(ArchModel,"Sensor");
sensorPorts = addPort(componentSensor.Architecture,...
{'MotionData','SensorPower'},{'in','physical'});
sensorPorts(2).setInterface(physicalInterface)
4 You can also add a data interface and port.

srInterface2 = addDataInterface(archDataObj,'SR1');
pport = archModel.addPort("Sender", 'PPort');
setInterface(pport,srInterface2);

See Also
Simulink.dictionary.ArchitecturalData | Simulink.dictionary.archdata.create |
Simulink.dictionary.archdata.open

Related Examples
• “Graphically Manage Shared Interfaces, Data Types, and Constants” on page 12-12

12-19
12 Manage Architecture Models

Resolve Conflicts in Projects Using System Composer Three-


Way Merge Tool

This example shows how to use the System Composer Three-Way Merge Tool to investigate and
resolve conflicts in System Composer™ architecture models.

In this example, the RobotArchitectureProject is under Git™ source control with conflicting and
non-conflicting changes. The Three-Way Merge tool automatically merges non-conflicting changes
before you open the merge report. This example demonstrates how to:

• Review the automatic merge choices.


• Apply your merge choices to the target file.
• Decide how to resolve any remaining conflicts.

After you resolve the conflicts, you commit the resolved architecture to source control.

System Composer Architecture Changes and Conflicts

The RobotArchitectureProject is under Git source control. When you attempt to merge the
changes of a colleague on the main Git branch into your taskBranch, the operation results in
conflicts.

To resolve the conflicts using the Three-Way Merge tool, examine your local file (Mine), the
conflicting revision (Theirs), and the common ancestor of these two files (Base).

• Theirs - Your colleague updated the Motion component and updated the query used in the
Component View view.
• Mine - You updated the name of the Motion component, added a new property to the
simpleProfile.sysConnector stereotype, and updated the query in the Component View.

Open System Composer Three-Way Merge Tool

After opening the project, in the project Files view, look for conflicted files. Observe that the
RobotArchitecture file shows a red warning icon in the Git column, which indicates there is at
lease one conflict.

To see a detailed report of the conflict(s), right-click the RobotArchitecture file and select View
Conflicts.

12-20
Resolve Conflicts in Projects Using System Composer Three-Way Merge Tool

View Changes

The Three-Way Merge tool shows the changes to the two System Composer architectures that cause
this file conflict.


The Theirs , Base , and Mine trees show the differences between the conflicting
revision (Theirs ) , your revision (Mine ), and the base ancestor (Base ) of these files.

The Target tree shows the file into which you merge changes. The tool replaces your local file
when you click accept.
• The summary table in the bottom right corner shows that the merge tool automatically resolved
non-conflicting differences. The table also shows that you must resolve the remaining changes.

12-21
12 Manage Architecture Models

To resolve the remaining changes, follow these steps.

1 Examine a difference by clicking a row in one of the trees. The Merge tool displays the change
for each model in an editor, for example, the System Composer canvas, to the right of the Three-
Way Merge window.
2 On the Merge tab, in the Highlight section, choose the models to display by clicking Top Model
or Bottom Model.

12-22
Resolve Conflicts in Projects Using System Composer Three-Way Merge Tool

Resolve Conflicts

The Merge tool automatically merges non-conflicted differences before opening the Three-Way Merge
report. In this example, 26 differences were already merged.

The merge tool cannot automatically resolve the conflicted differences. You must choose which design
to keep in the target file in the Target tree.

To resolve conflicts, follow these steps.

1. Use the Next button to navigate to the first conflict.

Examine the first change at the top of the Theirs tree by clicking the Motion Component row. This
conflict is caused by the change of the component name. You can adjust the automatic choices using
the radio buttons in the Target tree. You can review and adjust all automatic merge choices.

2. To resolve the component name change difference in targetFile, in the Target tree, select the
Mine column for Architecture Property Name and Simulink Property Name.

3. On the toolstrip, click Next to review the next conflict. The Component View is conflicted because
you and your colleague changed the color and the query of the view.

• For the Color parameter of the Component View, you can resolve the issue by selecting the
Base change for Color to accept the default color for the view.
• For the Component Selection Query parameter of the Component View, you can resolve the
issue by selecting the Theirs change for Component Selection Query to accept the query
your colleague used in Component View.

4. On the toolstrip, use the Next button to navigate to the next conflict. The Motion Component is
conflicted in the Component View because you and your colleague changed the component name of
the Motion component and this change propagated to the view.

• To stay consistent with the change selected in step 2, select your change by selecting the Mine
change for Architecture Property Name and Simulink Property Name to keep
Motion Trajectory as the name of the component.

12-23
12 Manage Architecture Models

5. Check the summary table to verify you resolved all conflicts.

In this example, the summary table shows that you successfully resolved all conflicts.

If you resolved all conflicts in the current view but the summary table title indicates that you have
remaining changes, disable the filters to view and resolve the remaining conflicts. On the Merge tab,
in the Filter section, turn the filters off.

Accept Changes

1. After you resolve all filtered and unfiltered changes, click Accept & Close. The merge tool closes
the report and the models, accepts the merge result in targetFile, and marks the conflict as
resolved in the source control tool.

2. Before you commit the resolved model file to source control, perform a final review by comparing
the merge changes against the current branch.

In the project Files view, right-click the model and select Compare > Compare to Ancestor.

See Also
System Composer Three-Way Merge Tool | “Resolve Conflicts in Project Using Simulink Three-Way
Merge”

Related Examples
• “Resolve Conflicts in Models Using Three-Way Merge”
• “Resolve Conflicts”

12-24
13

Import and Export Architecture Models

• “Import and Export Architectures” on page 13-2


• “Import and Export Architecture Models” on page 13-5
• “Import System Composer Architecture Using ModelBuilder Class” on page 13-15
• “System Composer Report Generation for System Architectures” on page 13-21
• “System Composer Report Generation for Software Architectures” on page 13-26
13 Import and Export Architecture Models

Import and Export Architectures

In System Composer™, an architecture is fully defined by three sets of information:

• Component information
• Port information
• Connection information

You can import an architecture into System Composer when this information is defined in or
converted into MATLAB® tables.

In this example, the architecture information of a simple unmanned aerial vehicle (UAV) system is
defined in a Microsoft® Excel® spreadsheet and is used to create a System Composer architecture
model. It also links elements to the specified system level requirement. You can modify the files in this
example to import architectures defined in external tools, when the data includes the required
information. The example also shows how to export this architecture information from System
Composer architecture model to an Excel spreadsheet.

Architecture Definition Data

You can characterize the architecture as a network of components and import by defining
components, ports, connections, interfaces and requirement links in MATLAB tables. The
components table must include name, unique ID, and parent component ID for each component. The
spreadsheet can also include other relevant information required to construct the architecture
hierarchy for referenced model, and stereotype qualifier names. The ports table must include port
name, direction, component, and port ID information. Port interface information may also be required
to assign ports to components. The connections table includes information to connect ports. At a
minimum, this table must include the connection ID, source port ID, and destination port ID.

The systemcomposer.importModel(importModelName) function:

• Reads stereotype names from the components table and loads the profiles
• Creates components and attaches ports
• Creates connections using the connection map
• Sets interfaces on ports
• Links elements to specified requirements (requires a Requirements Toolbox™ license)
• Saves referenced models
• Saves the architecture model

Instantiate adapter class to read from Excel.

modelName = "simpleUAVArchitecture";

ImportModelFromExcel function reads the Excel file and creates the MATLAB tables.

importAdapter = ImportModelFromExcel("SmallUAVModel.xls","Components", ...


"Ports","Connections","PortInterfaces","RequirementLinks");
importAdapter.readTableFromExcel();

13-2
Import and Export Architectures

Import an Architecture

model = systemcomposer.importModel(modelName,importAdapter.Components, ...


importAdapter.Ports,importAdapter.Connections,importAdapter.Interfaces, ...
importAdapter.RequirementLinks);

Auto-arrange blocks in the generated model.

Simulink.BlockDiagram.arrangeSystem(modelName)

Export an Architecture

You can export an architecture to MATLAB tables and then convert the tables to an external file.

exportedSet = systemcomposer.exportModel(modelName);

The output of the function is a structure that contains the component table, port table, connection
table, the interface table, and the requirement links table. Save this structure to an Excel file.

SaveToExcel("ExportedUAVModel",exportedSet);

See Also
importModel | exportModel | updateLinksToReferenceRequirements

More About
• “Import and Export Architecture Models” on page 13-5
• “Compose Architectures Visually” on page 1-5
• “Decompose and Reuse Components” on page 1-19

13-3
13 Import and Export Architecture Models

• “Allocate and Trace Requirements from Design to Verification” on page 2-2


• “Import System Composer Architecture Using ModelBuilder Class” on page 13-15
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35

13-4
Import and Export Architecture Models

Import and Export Architecture Models


To build a System Composer model, you can import information about components, ports, and
connections in a predefined format using MATLAB table objects. You can extend these tables and add
information like applied stereotypes, property values, linked model references, variant components,
interfaces, requirement links, and parameters.

Similarly, you can export information about components, hierarchy of components, ports on
components, connections between components, linked model references, variants, stereotypes on
elements, interfaces, requirement links, and parameters.

Tip To learn more about how System Composer concepts apply to systems engineering design, see
“System Composer Concepts”.

Define Basic Architecture


The minimum required structure for a System Composer model consists of these sets of information:

• Components table
• Ports table
• Connections table

To import additional elements, you need to add columns to the tables and add specific values for
these elements.

Components Table

The information about components is passed as values in a MATLAB table against predefined column
names, where:

• Name is the component name.


• ID is a user-defined ID used to map child components and add ports to components.
• ParentID is the parent component ID.

For example, Component_1_1 and Component_1_2 are children of Component_1.

Name ID ParentID
root 0
Component_1 1 0
Component_1_1 2 1
Component_1_2 3 1
Component_2 4 0

Name = {'root';'Component_1';'Component_1_1';'Component_1_2';'Component_2'};
ID = {'0';'1';'2';'3';'4'};
ParentID = {'';'0';'1';'1';'0'};
components = table(Name,ID,ParentID)

components =

13-5
13 Import and Export Architecture Models

5×3 table

Name ID ParentID
_________________ _____ __________

{'root' } {'0'} {0×0 char}


{'Component_1' } {'1'} {'0' }
{'Component_1_1'} {'2'} {'1' }
{'Component_1_2'} {'3'} {'1' }
{'Component_2' } {'4'} {'0' }

Ports Table

The information about ports is passed as values in a MATLAB table against predefined column names,
where:

• Name is the port name.


• Direction can be one of Input, Output, or Physical.
• ID is a user-defined port ID used to map ports to port connections.
• CompID is the ID of the component to which the port is added. It is the component passed in the
components table.

Name Direction ID CompID


Port1 Output 1 1
Port2 Input 2 4
Port1_1 Output 3 2
Port1_2 Input 4 3

Name = {'Port1';'Port2';'Port1_1';'Port1_2'};
Direction = {'Output';'Input';'Output';'Input'};
ID = {'1';'2';'3';'4'};
CompID = {'1';'4';'2';'3'};
ports = table(Name,Direction,ID,CompID)

ports =

4×4 table

Name Direction ID CompID


___________ __________ _____ ______

{'Port1' } {'Output'} {'1'} {'1'}


{'Port2' } {'Input' } {'2'} {'4'}
{'Port1_1'} {'Output'} {'3'} {'2'}
{'Port1_2'} {'Input' } {'4'} {'3'}

Connections Table

The information about connections is passed as values in a MATLAB table against predefined column
names, where:

• Name is the connection name.


• ID is connection ID used to check that the connections are properly created during the import
process.

13-6
Import and Export Architecture Models

• Kind is the kind of connection specified by Data by default or Physical. The Kind column is
optional and will default to Data if undefined.
• SourcePortID is the ID of the source port.
• DestPortID is the ID of the destination port.
• PortIDs are a comma-separated list of port IDs for physical ports that support nondirectional
connections.

Name Kind ID SourcePortID DestPortID PortIDs


Conn1 Data 1 1 2
Conn2 Data 2 3 4

Name = {'Conn1';'Conn2'};
Kind = {'Data';'Data'};
ID = {'1'; '2'};
SourcePortID = {'1';'3'};
DestPortID = {'2';'4'};
PortIDs = {'';''};
connections = table(Name,Kind,ID,SourcePortID,DestPortID,PortIDs)

connections =

2×6 table

Name Kind ID SourcePortID DestPortID PortIDs


_________ ________ _____ ____________ __________ __________

{'Conn1'} {'Data'} {'1'} {'1'} {'2'} {0×0 char}


{'Conn2'} {'Data'} {'2'} {'3'} {'4'} {0×0 char}

Import Basic Architecture


Import the basic architecture from the tables created above into System Composer from the MATLAB
Command Window using the importModel function.
systemcomposer.importModel("importedModel",components,ports,connections);

The basic architecture model opens.

13-7
13 Import and Export Architecture Models

Tip The tables do not include information about the model's visual layout. You can arrange the
components manually or use Format > Layout > Auto Arrange.

Extend Basic Architecture Import


You can import other model elements into the basic structure tables.

Import Data Interfaces and Map Ports to Interfaces

To define the data interfaces, add interface names in the ports table to associate ports to
corresponding portInterfaces table. Create a table similar to components, ports, and
connections. Information like interface name, associated element name along with data type,
dimensions, units, complexity, minimum, and maximum values are passed to the importModel
function in a table format shown below.

Name ID ParentI DataTyp Dimension Units Comple Minimu Maximu


D e s xity m m
interface 1 DataInt
1 erface
elem1 2 1 interfa
ce2
interface 3 DataInt
2 erface
elem2 4 1 double 1 "" real "[]" "[]"

13-8
Import and Export Architecture Models

Name ID ParentI DataTyp Dimension Units Comple Minimu Maximu


D e s xity m m
elem3 5 1 valueTy 3 cm real 0 100
pe
valueType 6 int32 3 cm real 0 100
interface 7 Physica
3 lInterf
ace
elec 8 7 Connect
ion:
foundat
ion.ele
ctrical
.electr
ical
mech 9 7 Connect
ion:
foundat
ion.mec
hanical
.mechan
ical.ro
tationa
l

Data interfaces interface1 and interface2 are defined with data elements elem1 and elem2
under interface1. Data element elem2 is typed by interface2, inheriting its structure. For more
information, see “Nest Interfaces to Reuse Data” on page 3-9.

Note Owned interfaces cannot be nested. You cannot define an owned interface as the data type of
data elements. For more information, see “Define Owned Interfaces Local to Ports” on page 3-12.

This data interface interface1 includes a data element elem3, which is typed by a value type
valueType and inherits its properties. For more information, see “Create Value Types as Interfaces”
on page 3-8.

This physical interface interface3 includes physical elements elec and mech, which are typed
under their respective physical domains. For more information, see “Specify Physical Interfaces on
Ports” on page 7-24.

To map the added data interface to ports, add the column InterfaceID in the ports table and
specify the data interface to be linked. For example, interface1 is mapped to Port1 as shown
below.

Name Direction ID CompID InterfaceID


Port1 Output 1 1 interface1
Port2 Input 2 4 interface2

13-9
13 Import and Export Architecture Models

Name Direction ID CompID InterfaceID


Port1_1 Output 3 2 ""
Port1_2 Input 4 3 interface1

Import Variant Components, Stateflow Behaviors, or Reference Components

You can add variant components just like any other component in the components table, except you
specify the name of the active variant. Add choices as child components to the variant components.
Specify the variant choices as string values in the VariantControl column. You can enter
expressions in the VariantCondition column. For more information, see “Create Variants” on page
1-26.

Add a variant component VarComp using component type Variant with choices Choice1 and
Choice2. Set Choice2 as the active choice.

To add a referenced Simulink model, change the component type to Behavior and specify the
reference model name simulink_model.

To add a Stateflow chart behavior on a component, change the component type to


StateflowBehavior. If System Composer does not detect a license or installation of Stateflow, a
Composition component is imported instead.

Name ID ParentID Reference Componen ActiveChoi VariantCon VariantCon


ModelNam tType ce trol dition
e
root 0
Component C1 0 simulink_ Behavior
1 model
VarComp V2 0 Variant Choice2
Choice1 C6 V2 petrol
Choice2 C7 V2 diesel
Component C3 0 Stateflow
3 Behavior
Component C4 C1
1_1
Component C5 C1
1_2

Pass the modified components table along with the ports and connections tables to the
importModel function.

Apply Stereotypes and Set Property Values on Imported Model

To apply stereotypes on components, ports, and connections, add a StereotypeNames column to the
components table. To set the properties for the stereotypes, add a column with a name defined using
the profile name, stereotype name, and property name. For example, name the column
UAVComponent_OnboardElement_Mass for a UAVComponent profile, a OnBoardElement
stereotype, and a Mass property.

13-10
Import and Export Architecture Models

You set the property values in the format value{units}. Units and values are populated from the
default values defined in the loaded profile file. For more information, see “Define and Style
Stereotypes in Profiles” on page 5-5.

Name ID ParentID StereotypeNam UAVComponent UAVCompon


es _OnboardEleme ent_Onboard
nt_Mass Element_Po
wer
root 0
Component_1 1 0 UAVComponent.O 0.93{kg} 0.65{mW}
nboardElement
Component_1_1 2 1
Component_1_2 3 1 UAVComponent.O 0.93{kg} ""
nboardElement
Component_2 4 0

Assign Requirement Links on Imported Model

To assign requirement links to the model, add a requirementLinks table with these required
columns:

• Label is the name of the requirement.


• ID is the ID of the requirement.
• SourceID is the architectural element to which the requirement is attached.
• DestinationType is how requirements are saved.
• DestinationID is where the requirement is located.
• Type is the requirement type.

For more information, see “Manage Requirements” on page 2-9.

Label ID SourceID DestinationT DestinationID Type


ype
rset#1 1 components linktype_r C:\Temp Implement
:1 mi_slreq \rset.slreqx#1
rset#2 2 components linktype_r C:\Temp Implement
:0 mi_slreq \rset.slreqx#2
rset#3 3 ports:1 linktype_r C:\Temp Implement
mi_slreq \rset.slreqx#3
rset#4 4 ports:3 linktype_r C:\Temp Implement
mi_slreq \rset.slreqx#4

A Requirements Toolbox license is required to import requirement links into a System Composer
architecture model.

Specify Elements on Architecture Port

In the connections table, you can specify different kinds of signal interface elements as source
elements or destination elements. Connections can be formed from a root architecture port to a

13-11
13 Import and Export Architecture Models

component port, from a component port to a root architecture port, or between two root architecture
ports of the same architecture.

The nested interface element mobile.elem is the source element for the connection between an
architecture port and a component port. The nested element mobile.alt is the destination element
for the connection between an architecture port and a component port. The interface element
mobile and the nested element mobile.alt are source elements for the connection between two
architecture ports of the same architecture.

For more information, see “Specify Source Element or Destination Element for Ports” on page 3-15.

Name ID SourcePortI DestPortID SourceElement DestinationElem


D ent
RootToComp1 1 5 4 mobile.elem
RootToComp2 2 5 1 mobile.alt
Comp1ToRoot 3 2 6 interface
Comp2ToRoot 4 3 6 mobile.alt
RootToRoot 5 5 6 mobile,mobile.
alt

Import Parameters with Parameter Value Types

In the parameters table, you can specify parameters and their values. Parameters can exist on the
architectures of components and then be promoted to the root architecture of the model.

For parameters on Reference Component blocks, the parameters table shows the minimum set of
columns because the complete parameter value type is defined on the referenced model. The
minimum set of columns are:

13-12
Import and Export Architecture Models

• Name is the name of the parameter.


• ID is the ID of the parameter.
• Parent is the parent type (Component or Architecture) with a colon and then the parent ID.
• Value is the parameter value.

For more information, see “Author Parameters in System Composer Using Parameter Editor” on page
4-2.

Name ID Parent Value Units Type Compl Minimu Maxim Promot


exity m um edTo
Pressure 1 Compon 20 psi double real 0 100 Compon
ent:1 ent:0

Define Architecture Domain for Software Architectures

To specify that the architecture to be imported is a software architecture, specify the domain field of
the import structure as "Software". For more information, see “Import and Export Software
Architectures” on page 10-6.

Export Architecture
To export a model, pass the model name as an argument to the exportModel function. The function
returns a structure containing tables: components, ports, connections, portInterfaces,
requirementLinks, and parameters, and the field domain that is a character vector that
represents the type of architecture being exported. The value of domain is 'System' for
architecture models or 'Software' for software architecture models.

exportedSet = systemcomposer.exportModel(modelName)

You can export the set to MATLAB tables and then convert those tables to external file formats,
including Microsoft® Excel® or databases.

exportedSet =

struct with fields:

components: [3×4 table]


ports: [3×5 table]
connections: [1×4 table]
portInterfaces: [3×9 table]
requirementLinks: [4×15 table]
parameters: [6×9 table]
domain: 'System'

If you import requirements to the model using an external file, in order to export and reimport those
requirements, redirect reference requirement links within the model.

You can use the systemcomposer.updateLinksToReferenceRequirements function in System


Composer to make the requirement links point to imported referenced requirements instead of
external documents.

13-13
13 Import and Export Architecture Models

See Also
importModel | exportModel | systemcomposer.io.ModelBuilder |
systemcomposer.updateLinksToReferenceRequirements

More About
• “Compose Architectures Visually” on page 1-5
• “Decompose and Reuse Components” on page 1-19
• “Implement Component Behavior Using Simulink” on page 7-2
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Import and Export Architectures” on page 13-2
• “Import System Composer Architecture Using ModelBuilder Class” on page 13-15

13-14
Import System Composer Architecture Using ModelBuilder Class

Import System Composer Architecture Using ModelBuilder


Class

Import architecture specifications into System Composer™ using the


systemcomposer.io.ModelBuilder utility class. These architecture specifications can be defined
in an external source, such as an Excel® file.

In System Composer, an architecture is fully defined by four sets of information:

• Components and their position in the architecture hierarchy


• Ports and their mapping to components
• Connections among components through ports - In this example, we also import interface data
definitions from an external source.
• Interfaces in architecture models and their mapping to ports

This example uses the systemcomposer.io.ModelBuilder class to pass all of the above
architecture information and import a System Composer model.

In this example, architecture information of a small UAV system is defined in an Excel spreadsheet
and is used to create a System Composer architecture model.

External Source Files

• Architecture.xlsx — This Excel file contains hierarchical information of the architecture


model. This example maps the external source data to System Composer model elements. This
information maps in column names to System Composer model elements.

# Element :
Name of the element. Either can be component or port name.
# Parent :
Name of the parent element.
# Class :
Can be either component or port(Input/Output direction of the port).
# Domain :
Mapped as component property. Property "Manufacturer" defined in the
profile UAVComponent under Stereotype PartDescriptor maps to Domain values
in excel source file.
# Kind : Mapped as component property. Property "ModelName" defined in the
profile UAVComponent under Stereotype PartDescriptor maps to Kind values
in excel source file.
# InterfaceName : If class is of port type. InterfaceName maps to name of the interface
linked to port.
# ConnectedTo : In case of port type, it specifies the connection to
other port defined in format "ComponentName::PortName".

• DataDefinitions.xlsx — This Excel file contains interface data definitions of the model. This
example assumes this mapping between the data definitions in the Excel source file and interfaces
hierarchy in System Composer.

# Name : Name of the interface or element.


# Parent : Name of the parent interface Name(Applicable only for elements) .
# Datatype : Datatype of element. Can be another interface in format
Bus: InterfaceName
# Dimensions : Dimensions of the element.
# Units : Unit property of the element.
# Minimum : Minimum value of the element.
# Maximum : Maximum value of the element.

13-15
13 Import and Export Architecture Models

Step 1. Instantiate the ModelBuilder Class

You can instantiate the ModelBuilder class with a profile name.

[stat,fa] = fileattrib(pwd);
if ~fa.UserWrite
disp('This script must be run in a writable directory');
return;
end

Specify the name of the model to build.

modelName = 'scExampleModelBuilder';

Specify the name of the profile.

profile = 'UAVComponent';

Specify the name of the source file to read architecture information.

architectureFileName = 'Architecture.xlsx';

Instantiate the ModelBuilder.

builder = systemcomposer.io.ModelBuilder(profile);

Step 2. Build Interface Data Definitions

Reading the information in the external source file DataDefinitions.xlsx to build the interface
data model.

Create MATLAB® tables from the Excel source file.

opts = detectImportOptions('DataDefinitions.xlsx');
opts.DataRange = 'A2';

Force readtable to start reading from the second row.

definitionContents = readtable('DataDefinitions.xlsx',opts);

The systemcomposer.io.IdService class generates unique ID for a given key.

idService = systemcomposer.io.IdService();

for rowItr =1:numel(definitionContents(:,1))


parentInterface = definitionContents.Parent{rowItr};
if isempty(parentInterface)

In the case of interfaces, add the interface name to the model builder.

interfaceName = definitionContents.Name{rowItr};

Get the unique interface ID.

getID(container,key) generates or returns (if key is already present) same value for input key
within the container.

interfaceID = idService.getID('interfaces',interfaceName);

13-16
Import System Composer Architecture Using ModelBuilder Class

Use builder.addInterface to add the interface to the data dictionary.

builder.addInterface(interfaceName,interfaceID);
else

In the case of an element, read the element properties and add the element to the parent interface.

elementName = definitionContents.Name{rowItr};
interfaceID = idService.getID('interfaces',parentInterface);

The ElementID is unique within a interface. Append E at the start of an ID for uniformity. The
generated ID for an input element is unique within parent interface name as a container.

elemID = idService.getID(parentInterface,elementName,'E');

Set the data type, dimensions, units, minimum, and maximum properties of the element.

datatype = definitionContents.DataType{rowItr};
dimensions = string(definitionContents.Dimensions(rowItr));
units = definitionContents.Units(rowItr);

Make sure that input to builder utility function is always a string.

if ~ischar(units)
units = '';
end
minimum = definitionContents.Minimum{rowItr};
maximum = definitionContents.Maximum{rowItr};

Use builder.addElementInInterface to add an element with properties in the interface.

builder.addElementInInterface(elementName,elemID,interfaceID,datatype,dimensions,...
units,'real',maximum,minimum);
end
end

Step 3. Build Architecture Specifications

Architecture specifications are created by MATLAB tables from the Excel source file.

excelContents = readtable(architectureFileName);

Iterate over each row in the table.

for rowItr =1:numel(excelContents(:,1))

Read each row of the Excel file and columns.

class = excelContents.Class(rowItr);
Parent = excelContents.Parent(rowItr);
Name = excelContents.Element{rowItr};

Populate the contents of the table.

if strcmp(class,'component')
ID = idService.getID('comp',Name);

The Root ID is by default set as zero.

13-17
13 Import and Export Architecture Models

if strcmp(Parent,'scExampleSmallUAV')
parentID = "0";
else
parentID = idService.getID('comp',Parent);
end

Use builder.addComponent to add a component.

builder.addComponent(Name,ID,parentID);

Read the property values.

kind = excelContents.Kind{rowItr};
domain = excelContents.Domain{rowItr};

Use builder.setComponentProperty to set stereotype and property values.

builder.setComponentProperty(ID,'StereotypeName','UAVComponent.PartDescriptor',...
'ModelName',kind,'Manufacturer',domain);
else

In this example, concatenation of the port name and parent component name is used as key to
generate unique IDs for ports.

portID = idService.getID('port',strcat(Name,Parent));

For ports on root architecture, the compID is assumed as 0.

if strcmp(Parent,'scExampleSmallUAV')
compID = "0";
else
compID = idService.getID('comp',Parent);
end

Use builder.addPort to add a port.

builder.addPort(Name,class,portID,compID );

The InterfaceName specifies the name of the interface linked to the port.

interfaceName = excelContents.InterfaceName{rowItr};

Get the interface ID.

getID will return the same IDs already generated while adding interface in Step 2.

interfaceID = idService.getID('interfaces',interfaceName);

Use builder.addInterfaceToPort to map interface to port.

builder.addInterfaceToPort(interfaceID,portID);

Read the ConnectedTo information to build connections between components.

connectedTo = excelContents.ConnectedTo{rowItr};

ConnectedTo is in the format:

(DestinationComponentName::DestinationPortName)

13-18
Import System Composer Architecture Using ModelBuilder Class

For this example, consider the current port as source of the connection.
if ~isempty(connectedTo)
connID = idService.getID('connection',connectedTo);
splits = split(connectedTo,'::');

Get the port ID of the connected port.

In this example, port ID is generated by concatenating the port name and the parent component
name. If the port ID is already generated, the getID function returns the same ID for the input key.
connectedPortID = idService.getID('port',strcat(splits(2),splits(1)));

Populate the connection table.


sourcePortID = portID;
destPortID = connectedPortID;

Use builder.addConnection to add connections.


builder.addConnection(connectedTo,connID,sourcePortID,destPortID);
end
end
end

Step 3. Import Model from Populated Tables with builder.build Function


[model,importReport] = builder.build(modelName);

Clean up artifacts.
cleanUp

13-19
13 Import and Export Architecture Models

Copyright 2020 The MathWorks, Inc.

See Also
systemcomposer.io.ModelBuilder | importModel | exportModel

More About
• “Import and Export Architecture Models” on page 13-5
• “Compose Architectures Visually” on page 1-5
• “Import and Export Architectures” on page 13-2
• “Simulate Mobile Robot with System Composer Workflow” on page 5-35

13-20
System Composer Report Generation for System Architectures

System Composer Report Generation for System Architectures

This example shows the different parts of a report generation script for a System Composer™
architecture model and its artifacts.

Import the relevant namespaces.

import mlreportgen.report.*
import slreportgen.report.*
import slreportgen.finder.*
import mlreportgen.dom.*
import mlreportgen.utils.*
import systemcomposer.query.*
import systemcomposer.rptgen.finder.*

Initialize the report.

rpt = slreportgen.report.Report('OutputPath','SystemModel'+".pdf",...
'CompileModelBeforeReporting',false);

% for html: rpt = slreportgen.report.Report('Type','html-file',...


% 'OutputPath','SystemModel','CompileModelBeforeReporting',false);

Load the model and reference model.

systemcomposer.loadModel('mTest');
model = systemcomposer.loadModel("mTestModel");

Append the title page and the table of contents.

add(rpt,TitlePage("Title",sprintf('%s',model.Name)));
add(rpt,TableOfContents);

Introduction

Add sections and paragraphs to add textual information to the report.

Introduction = Chapter("Title","Introduction");
sec1_1 = Section('Title',"Purpose");
p1 = Paragraph(['This document provides a comprehensive architectural ...' ...
'overview of the system using a number of different architecture views...' ...
' to depict different aspects of the system. It is intended to capture...' ...
' and convey the significant architectural decisions which have been...' ...
' made for the system.']);
append(sec1_1, p1);

sec1_2 = Section("Scope");
p2 = Paragraph(['This System Architecture Description provides an architectural...' ...
' overview of the Mobile Robot System being designed and developed by the...' ...
' Acme Corporation. The document was generated directly from the Mobile...' ...
' Robot models implemented in MATLAB, Simulink and System Composer.']);
append(sec1_2, p2);
append(Introduction, sec1_1);
append(Introduction, sec1_2);

13-21
13 Import and Export Architecture Models

Architectural Elements

Create a new chapter to represent architectural elements.

ArchitecturalElements = Chapter("Architecture Description");

Use the Simulink® slreportgen.finder.SystemDiagramFinder (Simulink Report Generator)


finder to add a snapshot of the model to the report.

systemContext = Section(model.Name);
finder = SystemDiagramFinder(model.Name);
finder.SearchDepth = 0;
results = find(finder);
append(systemContext,results);

append(ArchitecturalElements,systemContext);

Use the systemcomposer.rptgen.finder.ComponentFinder finder to report on components in


the model.

cf = ComponentFinder(model.Name);
cf.Query = AnyComponent();
comp_finder = find(cf);

for comp = comp_finder


componentSection = Section("Title",comp.Name);

Create a list of components allocated from or to a particular component using the


systemcomposer.rptgen.finder.AllocationListFinder finder.

d = AllocationListFinder("AllocationSet.mldatx");
compObject = lookup(model,'UUID',comp.Object);
d.ComponentName = getfullname(compObject.SimulinkHandle);
result = find(d);
append(componentSection,comp);

Append the component information to the report.

append(systemContext,componentSection);

Append the allocation information to the report.

append(systemContext, result);
end

Allocation Sets

Create a chapter to report on the allocation sets associated with the model.

Find all allocation sets using the systemcomposer.rptgen.finder.AllocationSetFinder


finder.

allocation_finder = AllocationSetFinder("AllocationSet.mldatx");
AllocationChapter = Chapter("Allocations");
while hasNext(allocation_finder)
alloc = next(allocation_finder);
allocationName = Section(alloc.Name);
append(allocationName, alloc);

13-22
System Composer Report Generation for System Architectures

append(AllocationChapter, allocationName);
end

Architecture Views

Create a chapter to display information about the architecture views in the model.

Find all the views using the systemcomposer.rptgen.finder.ViewFinder finder.


ViewChapter = Chapter("Architecture Views");
view_finder = ViewFinder(model.Name);
while(hasNext(view_finder))
v = next(view_finder);
viewName = Section('Title',v.Name);
append(viewName, v);
append(ViewChapter, viewName);
end

Dependency Graph

Create a chapter to display the dependency graph image using the


systemcomposer.rptgen.report.DependencyGraph reporter.
Packaging = Chapter("Packaging");
packaging = Section('Title','Packaging');
graph = systemcomposer.rptgen.report.DependencyGraph("Source",[model.Name '.slx']);
append(packaging, graph);
append(Packaging, packaging);

Requirements Analysis

Report on all the requirement sets and requirement link sets associated with the model.
ReqChapter = Chapter("Requirements Analysis");

Requirement Sets

Collect the requirement sets using the


systemcomposer.rptgen.finder.RequirementSetFinder finder.
RequirementSetSection = Section("Requirement Sets");
reqFinder1 = RequirementSetFinder("TestRequirement.slreqx");
result = find(reqFinder1);
pp = Paragraph("This requirement set describes the system requirements for the" + ...
" mobile robot that are derived from the stakeholder needs to be documented.");
append(RequirementSetSection,pp);
append(RequirementSetSection,result.getReporter);

Requirement Link Sets

Collect the requirement link sets using the


systemcomposer.rptgen.finder.RequirementLinkFinder finder.
RequirementLinkSection = Section("Requirement Link Sets");
reqLinkFinder = RequirementLinkFinder("TestRequirement.slmx");
resultL = find(reqLinkFinder);
rptr = systemcomposer.rptgen.report.RequirementLink("Source",resultL);
append(RequirementLinkSection,rptr);

13-23
13 Import and Export Architecture Models

append(ReqChapter,RequirementSetSection);
append(ReqChapter,RequirementLinkSection);

Interfaces

Create a chapter to report on all the interfaces in the model.

Check if any dictionaries are linked within the model using the
systemcomposer.rptgen.finder.DictionaryFinder finder.
df = DictionaryFinder(model.Name);
dictionary = find(df);

No Dictionaries present in the Model

boolHasNoDictionary = isempty(dictionary)

boolHasNoDictionary = logical
1

Since boolHasNoDictionary is true, create a separate chapter for interfaces to report on all the
interfaces associated with the model using the
systemcomposer.rptgen.finder.InterfaceFinder finder.
if boolHasNoDictionary
InterfaceChapter = Chapter("Interfaces Appendix");
interfaceFinder = InterfaceFinder(model.Name);
interfaceFinder.SearchIn = "Model";
while hasNext(interfaceFinder)
intf = next(interfaceFinder);
interfaceName = Section(intf.InterfaceName);
append(interfaceName,intf);
append(InterfaceChapter,interfaceName);
end
end

Profiles

Create a chapter to report on all the profiles in the model.

Find all the profiles using the systemcomposer.rptgen.finder.ProfileFinder finder.


ProfileChapter = Chapter("Profiles Appendix");
pf = ProfileFinder("TestProfile.xml");
while hasNext(pf)
intf = next(pf);
profileName = Section(intf.Name);
append(profileName,intf);
append(ProfileChapter,profileName);
end

Stereotypes

Create a section to report on all the stereotypes in the profiles in the model.

Find all the stereotypes using the systemcomposer.rptgen.finder.StereotypeFinder finder.


StereotypeSection = Section("Stereotypes");
sf = StereotypeFinder("TestProfile.xml");

13-24
System Composer Report Generation for System Architectures

while hasNext(sf)
stf = next(sf);
stereotypeName = Section(stf.Name);
append(stereotypeName,stf);
append(StereotypeSection,stereotypeName);
end

append(ProfileChapter, StereotypeSection);

Final Report

Add all the chapters to the report in the desired order.

append(rpt,Introduction);
append(rpt,ArchitecturalElements);
append(rpt,ViewChapter);
append(rpt,Packaging);
append(rpt,AllocationChapter);
append(rpt,ReqChapter);
append(rpt,InterfaceChapter);
append(rpt,ProfileChapter);

rptview(rpt)

See Also
Classes
systemcomposer.rptgen.report.AllocationList |
systemcomposer.rptgen.report.AllocationSet |
systemcomposer.rptgen.report.Component | systemcomposer.rptgen.report.Connector
| systemcomposer.rptgen.report.DependencyGraph |
systemcomposer.rptgen.report.Function | systemcomposer.rptgen.report.Interface |
systemcomposer.rptgen.report.Profile |
systemcomposer.rptgen.report.RequirementLink |
systemcomposer.rptgen.report.RequirementSet |
systemcomposer.rptgen.report.SequenceDiagram |
systemcomposer.rptgen.report.Stereotype | systemcomposer.rptgen.report.View

More About
• “Compose Architectures Visually” on page 1-5
• “Create Custom Views Using Architecture Views Gallery” on page 11-2
• “Create and Manage Allocations Programmatically” on page 8-11
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Define Port Interfaces Between Components” on page 3-2
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “System Composer Report Generation for Software Architectures” on page 13-26

13-25
13 Import and Export Architecture Models

System Composer Report Generation for Software


Architectures

This example shows the different parts of a report generation script for a System Composer™
software architecture model and its artifacts.

Import the relevant namespaces.

import mlreportgen.report.*
import slreportgen.report.*
import slreportgen.finder.*
import mlreportgen.dom.*
import mlreportgen.utils.*
import systemcomposer.query.*
import systemcomposer.rptgen.finder.*

Initialize the report.

rpt = slreportgen.report.Report('OutputPath','SoftwareModel'+".pdf",...
'CompileModelBeforeReporting',false);

% for html: rpt = slreportgen.report.Report('Type','html-file','OutputPath',...


% 'SoftwareModel','CompileModelBeforeReporting',false);

Load the model and reference model.

systemcomposer.loadModel('mTest.slx');
model = systemcomposer.loadModel('SoftwareModel.slx');

Append the title page and the table of contents.

add(rpt,TitlePage("Title",sprintf('%s',model.Name)));
add(rpt,TableOfContents);

Introduction

Add sections and paragraphs to add textual information to the report.

Introduction = Chapter("Title","Introduction");
sec1_1 = Section('Title',"Purpose");
p1 = Paragraph(['This document provides a comprehensive architectural ...' ...
'overview of the system using a number of different architecture views...' ...
' to depict different aspects of the system. It is intended to capture...' ...
' and convey the significant architectural decisions which have been...' ...
' made for the system.']);
append(sec1_1,p1);

sec1_2 = Section("Scope");
p2 = Paragraph(['This System Architecture Description provides an architectural...' ...
' overview of the Mobile Robot System being designed and developed by the...' ...
' Acme Corporation. The document was generated directly from the Mobile...' ...
' Robot models implemented in MATLAB, Simulink and System Composer.']);
append(sec1_2, p2);
append(Introduction,sec1_1);
append(Introduction,sec1_2);

13-26
System Composer Report Generation for Software Architectures

Architectural Elements

Create a new chapter to represent architectural elements.

ArchitecturalElements = Chapter("Architecture Description");

Use the Simulink® slreportgen.finder.SystemDiagramFinder (Simulink Report Generator)


finder to add a snapshot of the model to the report.

systemContext = Section(model.Name);
finder = SystemDiagramFinder(model.Name);
finder.SearchDepth = 0;
results = find(finder);
append(systemContext,results);

append(ArchitecturalElements,systemContext);

Use the systemcomposer.rptgen.finder.ComponentFinder finder to report on components in


the model.

cf = ComponentFinder(model.Name);
cf.Query = AnyComponent();
comp_finder = find(cf);

for comp = comp_finder


componentSection = Section("Title",comp.Name);

Create a list of components allocated from or to a particular component using the


systemcomposer.rptgen.finder.AllocationListFinder finder.

d = AllocationListFinder("SWArchAllocationSet.mldatx");
compObject = lookup(model,'UUID',comp.Object);
d.ComponentName = getfullname(compObject.SimulinkHandle);
result = find(d);
append(componentSection,comp);

Append the component information to the report.

append(systemContext,componentSection);

Append the allocation information to the report.

append(systemContext,result);
end

Allocation Sets

Create a chapter to report on the allocation sets associated with the model.

Find all allocation sets using the systemcomposer.rptgen.finder.AllocationSetFinder


finder.

allocation_finder = AllocationSetFinder("SWArchAllocationSet.mldatx");
AllocationChapter = Chapter("Allocations");
while hasNext(allocation_finder)
alloc = next(allocation_finder);
allocationName = Section(alloc.Name);
append(allocationName,alloc);

13-27
13 Import and Export Architecture Models

append(AllocationChapter,allocationName);
end

Architecture Views

Create a chapter to display information about the architecture views in the model.

Find all the views using the systemcomposer.rptgen.finder.ViewFinder finder.

ViewChapter = Chapter("Architecture Views");


view_finder = ViewFinder(model.Name);
while(hasNext(view_finder))
v = next(view_finder);
viewName = Section('Title',v.Name);
append(viewName,v);
append(ViewChapter,viewName);
end

Dependency Graph

Create a chapter to display the dependency graph image using the


systemcomposer.rptgen.report.DependencyGraph reporter.

Packaging = Chapter("Packaging");
packaging = Section('Title', 'Packaging');
graph = systemcomposer.rptgen.report.DependencyGraph("Source",'SoftwareModel.slx');
append(packaging,graph);
append(Packaging,packaging);

Profiles

Create a chapter to report on all the profiles in the model.

Find all the profiles using the systemcomposer.rptgen.finder.ProfileFinder finder.

ProfileChapter = Chapter("Profiles Appendix");


pf = ProfileFinder('SWArchProfile.xml');
while hasNext(pf)
intf = next(pf);
profileName = Section(intf.Name);
append(profileName,intf);
append(ProfileChapter,profileName);
end

Stereotypes

Create a section to report on all the stereotypes in the profiles in the model.

Find all the stereotypes using the systemcomposer.rptgen.finder.StereotypeFinder finder.

StereotypeSection = Section("Stereotypes");
sf = StereotypeFinder('SWArchProfile.xml');
while hasNext(sf)
stf = next(sf);
stereotypeName = Section(stf.Name);
append(stereotypeName,stf);
append(StereotypeSection, stereotypeName);
end

13-28
System Composer Report Generation for Software Architectures

append(ProfileChapter,StereotypeSection);

Final Report

Add all the chapters to the report in the desired order.

append(rpt,Introduction);
append(rpt,ArchitecturalElements);
append(rpt,ViewChapter);
append(rpt,Packaging);
append(rpt,AllocationChapter);
append(rpt,ProfileChapter);

rptview(rpt);

Generate Report for AUTOSAR Software Architectures

You can generate a report for an AUTOSAR architecture model and its artifacts using the script in
this example. To load an AUTOSAR model, use autosar.arch.loadModel (AUTOSAR Blockset).
Check that the model, profile, requirements, and dictionary file names are updated in accordance
with your AUTOSAR model. For more information on AUTOSAR architectures, see “Software
Architecture Modeling” (AUTOSAR Blockset).

See Also
Classes
systemcomposer.rptgen.report.AllocationList |
systemcomposer.rptgen.report.AllocationSet |
systemcomposer.rptgen.report.Component | systemcomposer.rptgen.report.Connector
| systemcomposer.rptgen.report.DependencyGraph |
systemcomposer.rptgen.report.Function | systemcomposer.rptgen.report.Interface |
systemcomposer.rptgen.report.Profile |
systemcomposer.rptgen.report.RequirementLink |
systemcomposer.rptgen.report.RequirementSet |
systemcomposer.rptgen.report.SequenceDiagram |
systemcomposer.rptgen.report.Stereotype | systemcomposer.rptgen.report.View

More About
• “Compose Architectures Visually” on page 1-5
• “Create Custom Views Using Architecture Views Gallery” on page 11-2
• “Create and Manage Allocations Programmatically” on page 8-11
• “Allocate and Trace Requirements from Design to Verification” on page 2-2
• “Define Port Interfaces Between Components” on page 3-2
• “Extend System Composer Language Elements Using Profiles” on page 5-2
• “Describe System Behavior Using Sequence Diagrams” on page 6-2
• “System Composer Report Generation for System Architectures” on page 13-21

13-29

You might also like