Professional Documents
Culture Documents
EXCET
Table of Gontents
Verification and Validation of Simulink@ Models
r ilril]t ilil ] ]il ]t¡il ]ilt ilil ll] ilil llll llll
slw417V1
@ 2017 by The MathnØorks, Inc. Verification and Validation of Simulink@ Modeis TOC - 1
Table of Contents
This Training Coutse Notebook, along with other Training Course Examples
and Exercises, shall at all times temain the intellecmal propetty of The
MathWorks, Inc. The Math\X/orks, Inc. reserves all rights in these materials.
No part of these materials may be photocopied, reproduced in any form, or
distributed without prior wdtten consent from The MathW'orks,.Inc.
@ 2017 by The Math\ü/orks, Inc. Verification and Validation of Simulinrk@ Models TOC - 2
Table of Contents
Table of Contents
L. Introduction
4. AnalyzingTest Results
6. FormallyVedS'ingModels
7. Conclusion
Appendices
A 2U.7 by The Math\X/otks, Inc. Vedfication and Validation of Simufink@ Models TOC - 3
Table of Contents
Introduction
MathìØorks@ at a Glance . . . . . . 1-2
nØotldwide Off,ces 1-3
Math\Works@ Product Overview 1,-4
Diverse ljsers 1-5
Computer Setup 1-6
Course LearntngOutcomes. . . . 1. -7
Course Outline 1-8
@ 2017 by The MathWorks, Inc. Vedfication and Validation of Simulink@ Models TOC - 4
Table of Contents
Summaty.... .2-72
@ 201,7 by The Math\X/orks, Inc. Vedfi.cation and Validation of Simulink@ Models TOC - 5
Table of Contents
@ 2017 by The Math\üØorks, Inc. Vedfication and Validation of Simulink@ Models TOC - 7
Table of Contents
VrewrngTestResults . . . . . . . .5-12
Collecting Model Covetage . .
ReportingTest Results. . . . . . .5 - 1,4
@ 2017 by The Math\Works, Inc. Verification and Validation of Simulink@ Models TOC - 8
Table of Contents
Conclusion
Math\X/orks@ Product Overview '7 '.)
TestYour Knowledge
@ 201,7 by The Math\X/orks, Inc. Verification and Validation of Simulirrk@ Models TOC - 9
Table of Contents
Appendices
Automating Verifi cation A ctivifies A
Inttoduction to Model Coverage. . B
Exetcises C
@ 2017 by The Math!Øorks, Inc. Verification and Validation of Simulink@ Models TOC - 11
lntroduction
lntroduction
Verification and Validation of Simulink@ Models
I
¿
@ 2017 by The MathWorks, Inc. Verification and Validation of Simulink@ Models 7-7
lntroduction
MathWorks@ at a Glance
Mathlü/orks@ is the leading developer and suppliet of technical computing
software in the world. Founded tn 1984, it now employs ovet 3,000 people
worldwide with approximately 45o/o engaged in ptoduct development. The
company is privately held and has been ptofitable eveîy ye r since its inception.
Jack Litt1e and Cleve Moler, the founders of Mathrù(/orks, tecognized the need
among engineers and scientists for more powedul and ptoductive computation
environments beyond those provided by languages such as Fortran and C.
In response to that need, they combined their expertise in mathematics,
engineering, and computer science to develop M,{TLAB@, a high-petformance
technical computing environment. MATIAB combines comprehensive math
and graphrcs functions with a powerfrrl high-level language. In addition to
MATIAB, Maths7orks now develops and matkets Simulink@, a product for
simulating linear and nonlineat dynamic systems. Math\X/otks also develops
and markets an extensive family of add-on products to meet the application-
specific needs of scientists, engineets, and educators.
The guiding pdnciple at MathWorks is "Do the Right Thing." This means
doing what is best for our staff membets, customers, business pârtners, and Math\ülotks
communities for the long term, and believing that "right' answers exist. It
meafls measuring our success not merely in financial terms, but also by how
consistently we âct according to this princrple. Our mission and cote values
statements express what "doing the right thing" meâns in out day-to-day work.
MathlØorks also has a social mission: 'qWe will be active membets of out
communities, promote social responsibilit¡ and encorxage environmental
awareness." MathWotks people actively patticipate tn rcalning the social
mission.
Worldwide Offices
Math\X/otks customers are over 1,000,000 of the world's technical leaders, in
over 175 countries on all seven continents (includingAntarcttca). These people
work at the wodd's most innovative technology companies, government
research labs, financial institutions, and ât more than 3,500 universities. They
reþ on Math\X/orks because MATIAB and Simulink have become the standard
throughout science and industry.
@ 201,7 by The MathrX/orks, Inc. Verification and Validation of Simulink@ Models 1,-3
lntroduction
A 2017 by The MathWorks, Inc. Verification and Validation of Simulink@ Models 1.-4
lntroduction
Diverse l]sers
In the last few years, Math\X/orks tools have been used to:
' Veri$r the legality of currencyby scanningimages of the notes andidentifying . Teach computer progrâmming to undergraduates by developing a test and
the small fibers that they contain measurement laboratory that poses authentic engineering problems to the
students
. Improve the quality of next-generation network audio products by simulating
sþals transmitted over network . Create images ofunexplored underwater archeology and geology sites by
^
m,apping plankton density relative to wâter masses
. Enable temperâte crops to be grown ir dty coastal regions by designing a
gteenhouse that converts seawâteÍ into fresh water . Translate the distorted human voice in high-pressure environments by
lowedng the frequency and pitch of the sound made by the larynx
. Improve race car performance by designing a system for the automad.c
testing of suspension systems
@ 2017 by The MathrX/otks, Inc. Verification and Yaltdatton of Simulink@ Models 1-5
lntroduction
Computer Setup
To get ready for class, you need to install the examples and exercises from yout
course CD. Follow these steps:
Foilow the prompts in the installer t}rough the installation process. A shortcut
will be created on your desktop to start MATLAB for this class.
*lect CÐnrpÞüênt$
lulrich cornponents sfr*uld b* ànstalled?
In the installet, you have these options:
$elect tfie conrpcne*ts y*u v¡a¡l ts iïstatri; cl*ar the co,mpoÊsnts yç* dç not v¡ant t* . Choose a class toot directoty fot your course files.
ingcll. Çlick f'lerË e¡he* yc* vrc ready to contie*e.
. Choose the coutses for which you need to install the files. (Exampies and
ücurse Rslease 20lqRijps
exetcises for all of our courses are otL the CD.)
*11*Ê : MÅTl-48 f r¡üdäffi Ë$tô¡Ë 15.: l\'tB
) uUe-x, ffÅ f LåB Fundannentals for Åutû$ûtive Åpp¡ic8tíûns 4.6 M8 . Create a shortcut on the desktop to start MATLAB for this class. (This
ij *t-æ-ol fitÀTt"ÀÐ Funder*entðls frr åesû$.fãcÈ Alpl¡cü(islrs t*.9 M8
shortcut runs a s t a rt up . m file when starting MATI-AB that is customized
:-
j ¡+t-ee-s: trgATtÅF# for Llf€ sËientists 7.â M8
,
",
¡*t-C¡nt: CornrÌìunicätrüu STstsms üestçn qdith þlåTtÅB€: t.? M8 for the installed course files.)
,: j ¡¡¡-Ett*t g-'IATLA& t* t v¡ith lilÅTLAF tcd*r 14"5 M8
| ; ntlX: Tfttsrfacing A{¡\Tr,{Ë wilh C Cade *.ð M8
j''
-ì
n*r*: p4,4ït-4å
fcr lir¡anciaì ApÞlicntir$s s"? 1|{g
A 2017 by The Mathrü/orks, Inc. Verification and Validation of Simulink@ Models 1-6
lntroduction
@ 201,7 by The Math\ü/orks, Inc. Verification and Validation of Simulink@ Models 1-7
lntroduction
Course Outline
. Introducdon
. Verifi.cation and Validation in Model-Based Desþ
. Developing Test Cases
. Analy ztngTest Results
Appendices
@ 2017 by The Math!Øotks, Inc. Verifi.cation and Validation of Simulink@ Models 1-8
Verification and Validation in Model-Based Design
@ 201.7 by The Math\ùØotks, Inc. Vedfication and Validation of Simulink@ Models 2-1
Verification and Validation in Model-Based Design
Outline
. Continuous test and vedfication
. Ty¡les of verification
. Electronic throttle conftol project
. MÄII-AB@
. Simulink@
. Simulink Verification and Validation'" (for requirements linking)
@ 2017 by The Math\X/orks, Inc. Verification and Validation of Simulink@ Models )',
Verification and Validation in Model-Based Design
@ 2017 by The MathlüØorks, Inc. Vedfication and Validation of Simulink@ Models 2-3
Verification and Validation in Model-Based Design
Certification authority or
quality assurance
@ 2017 by The MatlilX/orks, Inc. Verification and Validation of Simulink@ Models 2-4
Verification and Validation in Model-Based Design
Types of Verification
There are two main types of verification tools avaiTable in Simulink. Test cases ate usuah created manually with the intent of validating system
requìrements. They do not guaran;tee fr;llinformation about the desþ errors
. Simulation-based testing - This apptoach consists of repeatedly simulating in a system. There may be hidden errors in a model that could be revealed with
a model under various scenalios, o! lesl cases, and analyzíngthe model outputs additional test câses.
for each test câse.
Formalvedfication removes the need fot manual desþ of test cases. Howevet,
formal verification tools typically
Test cases Results Because of these limitations, formal methods ate also îot gurúanteed to find
all desþ errors.
. Formal vetification - l]ses formal methods to veri4¡ the design of a Note Formal vedfication can be used to complement simulation-based testing.
Simutink model. Formal methods are mathematcalanalysis techniques that
c Ír produce tesults without test câses.
^vtomati."lly
-'ð
_ä;-t!;ü;;;r:; i .;.i l-l;;t- 'E
-:
. :
pñú7¿/9b&"r :"j
ir.iia c7üi hpd>þ¿€.1ì6ûF AffiVfL@g ì
bpd > bs Id T Þ¿&Þ Lffi¡c
l.r
+>
No test Mathematical
CASCS analysis of system
Simulation-B as ed Testing
When testing a Simulink model, thete ate some broad steps that you will
typicaliy follow.
. Ptepare the model - Pdor to running âny tests, you should set up your
model so that you can run those tests. This might mean settìng solver opdons,
model inputs, or simulation logging options.
@
. Load test case - Define input sþal data and set paratrreteÍ values as
desired. Data must be formatted to be acceptable to the model. The soutce
of this data could be in a vanety of places, such as a spreadsheet or vrithin
the model file itself.
. Run test - A test could involve a single simulation, or more elaborate tasks
such as srñ,'eep or alineat analysis of the model.
^pzrametet
. Process tesults - A common anaiysis task is visualizing the simulation data.
However, more complex tasks, such as coveïage analysis ot detetmining
whether test results meet some desited cttteria, are also cornmon.
. Produce report - It is often important to document tests and their results.
Reports give information on whether the desþ was implemented cottecdy
and satisfies all its corresponding tequirements.
@ 201.7 by The Mathìü/orks, Inc. Verification and Validation of Simulink@ Models 2-6
Verification and Validation in Model-Based Design
Formal Vedfication
Simulink Desþ Velifi.er'" allows you to verify Simutink models using formal
methods. SØhen using this tool, there are some bròad steps that you will
typicatly follow.
. Ptepate the model - Prior to verification, you must ensure th¿t the model
implementation is compatible with the tool.
. Set options
speci$r which
- Because formal verification is an automatic process, you must
verification t¿sks to petform, which tesults to extrâct, arid how
to report them.
W Manual
@ 2017 by The MathWotks, Inc. Verification and Validation of Simulink@ Models a'7
Verification and Validation in Model-Based Design
Course Example:
Electronic Throttle Control
The throttle of an engine is responsible for conftolling the amount of ztt that The diagram below shows the system components as they are architected
is allowed into the engine. This is done by opening and closing the throttle in Simulink. In this course, you will petfotm verif,cation and validation on
plate, thus allowing more or less air into the engine. comlionents within the completed model.
In an Electronic Throttle Control (ETC) system, the traditional mechanical The course Sinulink@ ModelManagemenl andArchilecTare discusses how to desþ
linkage between the pedal and throttle plate is replaced with electronic sensors and manage such a model in a collaborative project environment.
and actrators, and the control logic is impiemented in softwate. This allows
the desþer the freedom to modify the control strategy being implemented S:
Pedal
:::::
sensof 11ngme ' Throttle hodY J
I Ì14
Input PVA4
scaling conversion
Pedal
Output
PI control
scaling
@ 2017 by The MathrüØorks, Inc. Verification and Validation of Simulink@ Models 2-8
Verification and Validation in Model-Based Design
the files within the fi.le system. The throttle control system in this course is
otgantzed as shown below.
;.,
rJÐen Ële model, inspect lts lt.
)) efc
. data -Data files that ate needed by the models
. documents - System desþ documents, such as requirements and test You can also desþate a folder as a Sìmulink prEecT, which provides additional
plan documents features for collaborative development.
. l-ibraries - Simulink libtaty files The course fi.les are alrcady otgznized in a Simulink project. You can open the
. models - Simulink model files Simulink project interface by navigating to the ch2 folder and double-clicking
the ElectronicThrottleControl . prj file.
. work - Folder fot temporary, derived files or othet automattcally genetated
files
ElectronicThrottleControl . pr j
Simulink
project
I I
r. Ï Derived files in
,lf
. . Éf
,
t;
!¡
t¡ ,' i¡
tÈ
Àt
'**__j) Ë[
*-*-"""_ü; 'ç-t. [¡"
working foider
/
,-'; rJI. adcUti-Ls. -)rù:
controller. sIx
m ¡
busData.mat ffi'.,',
urt_ ^+-lt_t r m^^r^
^l a cò t_.1 -
,,1^
^4.-
s-Lx rü:
:
s controLlerData .m
t:t;!
t;"3-7
throttleData throttfeReqs . doc
l!-itFi
i piCtrl . sJ-x
{:ïl . mat
ffi' Sl
flj
pwmCnv. slx
You can link requirements infotmation to components in your Simulink ,Þ) controLLer
models, or to lines of MATLAB code.
View ut_Scali'ng :and
Simuünk Verification and Validation supports linking to mâny different tlpes Ou p lrInçnv'
of requirements documents, including
. Text
There are severalways to view the requirements linked to a model ot subsystem.
. HTML For example,
. Microsoft@ \X/ord . Select Anatysis ) Requirements Traceability ) Highlight Model.
. Microsoft@ Excel@ Click the highlighted blocks and view the corresponding information in the
Requitements Details window.
. Adobe@ PDF
. Right-click block or model canvas and select Requirements Traceability
a
. IBM@ Rational@ DOORS@ database
from the context menu. Click the requirements, if any, that appear in the
following menu.
For a complete list of supported file qT)es, see the documentation.
Requrreme¡ts Tr¿<sbi¡i{y l. 'scêied datì fruet þe to Tu¡¡ af dàtà.
Li.eàr A.âÀìl5is l. -OJtpu't'¿:rge fo" eàch $g¡al ñusl be rc4¿f ¿ed."
N
Document Types' )
nsign Verifier
Li¡h lû Sele{lisn ¡r i!4,A11Àg
Li¡k lo Seleclion ¡tr fJa¡d
?vlodeì Àdïisâr Lìnfr tÐ Sefect;on ¡n !¡c€l
The linking is performed by the Requitements Management Intetface (RMI).
Prior to using the RMI, you should execute the command
. Navþate to â system that contains a System Requirements block fiom the
Simulink Verification and \älidation block library. This block will display the
requirements that ate linked to the model or subsystem it is in.
to configure the RMI for use with MATI-AB.
System Requirements
1" "Ðuty cycle n:ust be proporlional to controller output, when in a valid range."
2. "PWM torque should act ilr pasltive sense wi:en cantrolêer output ts positive or ter*."
3 "PWM torque should act in negative sense when csntroller ûu{ptit is tregative."
4. "Duty cycTe rnuså be in range from t to t ^"
@ 2017 by The Math\üØorks, Inc. Verification and Validation of Simulink@ Models 2-10
Verification and Validation in Model-Based Design
Test Plans
Details on tests that need to be run on a system are typicaþ contained in a
document, or test plan. For a Simulink model, a test plan can prowide details
on several arifacts, including
You can use Simulink Verification and Validation to link components in a Futthermore, you canlevenge MATLAB functionality to read extern¿l data
Simulink model ditectly to requirements inside a test plan document. files, such as Microsoft Excel spreadsheets, and use them âs test cases for
Simulink models. This ptocess is covered in alater chapter.
Pl Controller
Testdescription-Mãintainthepedal scafed-angÌe_scaledquantityasapos¡tive
v¿lue for a period of tjme wh¡le the output saturãtes änd the integral state would have a chance
towindups¡gnif¡cantly. Afterthattime,changelhepedat sÇateC-ang1e_scaied Í{
quantily to a negat¡ve value to ensure that the controller output is respons¡ve.
3" tinne pedal_scaled angle scaled
J ')
lnputs 5 L
pedal_scaled - 5 when simulat¡on t¡me is less than I seconds, then 0 when s¡mulat¡on
t¡me is greater than or equal to 3 seconds
3
J ] 2
ângle scaled - 2throughoutthesimuJation
t ?
Expected outputs 5 ü 2
contrçller_ori-lprrl -Outputshouldsaturateatsomepointw¡th¡nfirstSseconds" Then,
at I seconds, output should decrease, without any delay, foìlowed by a continual period of 6
reduction- Pl Teç* å FI T*.çl 2
@ 201,7 by The MathlüØorks, Inc. Vedfication and Validation of Simulink@ Models 2- 1.1,
Verification and Validation in Model-Based Design
Summaty
. Continuous test and vedfication
. Tlpes of verification
. Elecúonic throttle control project
@ 2017 by The Mathlü/otks, Inc. Verification and Vaüdation of Simutink@ Models 2-72
Developing Test Cases
@ 2017 by The Math\X/orks, Inc. Verification and Validation of Simulink@ Models 3-1,
Developing Test Cases
Outline
. Defining test câses
. Genetating test harnesses
. Creating and importing test inputs
. Incorporating logic in tests
. rvl,t*ILAB@
. Simulink@
. Simulink TesC" (fot test hatnesses and Test Sequence blocks)
. Simulink Verification and Validation'" (for requirements linking)
. State the options ava:/rable fot defining and storing test cases fot Simulink
models.
. Genetate and manage test hatnesses.
. Create test inputs manuall¡ from extetnal files, and using logic-based rules'
. Run â test câse and inspect the results.
@ 201,7 by The Math\ü/orks, Inc. Vedfi.cation and Validation of Simulink@ Models J-J
Developing Test Cases
To test a Simulink model, you will need to take infotmation from a test plan Open the the ch
and convett it into data that is usable by Simulink. Test cases can consist of Review the t e file in the do
@ 2017 by The Math\ü/orks, Inc. Verification and Validation of Simulink@ Models 3-4
Developing Test Cases
Test l{arnesses
A. test harness tlpically consists of five parts. . Component under test (CUT) - Ar isoiated component or reference of
the model being tested.
. Input signals - Soutce blocks that define individual sþals, such as the
. Selection blocks - Blocks that take the output srgnal data and seiect the
Sþal Buildet block.
sþals of interest. These often include Bus Selector or Selector blocks.
. Convetsion blocks - Blocks that convert the raw srgnâl data of the input
sþals to the formatthe model under test requires. For instance, if the model ' Analysis blocks - Sink blocks that allow you to visualize the data, or perform
requires a bus sþal input, then a Bus Creator block might be used. other analysis tasks.
mï
f t
, .;...:......t.!
+
naøom
T^-l
Number
Component f'-' ' ;
å
LU
Sine Wave
Þ undef test ? Chêck
Statb Range
@ 2017 by The Math\'X/orks, Inc. Verification and Validation of Simulink@ Models 3-5
Developing Test Cases
You can use Simulink Test to automaticalJy cteate a test harness fot a model. Open fte Pv\lni:Cn model and ,cfe¿te â te.st Larness with def¿a1t seff]ltgs.
To do this, ::.:r,,,
The contain an Inpoit blookap,'t eþourÉe aod an
1. Select Anatysis ) Test Flarness ) Create for Model. âs
2. In the dialog that opens, specifr the options prior to cteating the test
hatness. These options include Note By default, test harnesses are saved in the same file as the component
. Information - Hatness nâme and descrþtion undet test. To cÍeate test harnesses in separate files, you carL enable the Save
test harnesses externally option. With this opd.on, an XML file will be created
. Sttucture - Source and sink blocks to add to the harness in the crrrent folder. This file contains metadata which links the component
. Configuration - Options for simulating and synchronizing the test under test to its external test harnesses.
hatness and component undet test
3. Select OK.
l0l { cúv
Abs Saturat¡cñ
Sasic Preperties
1
¡1oìor inpd5
mrÍq,in pL¡ts
llarner pwmfnv_llarness I
-1
Sources and Sinks
Reveße ÐlR Switch
i,ier:á: u2 >* Thr€5ilål¿
lnþ,-,-,-,-,üi't Ctr4pÕnÊ.nt nnd*.r Teßt Inresh¡l{ C
ç¡ :, C¡rnel p\vrrrf4jv
1 c{$1rûl¡er_o¡JÞnt
cûnlmlÉr_0ìJtpul ildûr hputs
cûntrû[þr_ûutpüt rnoiÐr_inputs
@ 201,7 by The Math\ù7otks, Inc. Vedfication and Validation of Simulink@ Models 3-6
Developing Test Cases
Once the test harness is open, you cân modify it by selecting Analysis ) Test
Flarness ) Propeties. You can also click the harness badge on the lower
p*,mCnv_l-iarness pivmfinu left of the model.
r4erqç availa,ble.
üì€ t€st harness.
þþ
Ted f-larnesç {nterface
Petspectives ¡{f þ
tr test harness nanre nnd
control VariableStepDiscrete
Opening test harnesses for a model From the test hatness, you can go to the Analysis ) Test Flatness menu
and then select
A 201,7 by The MathWorks, Inc. Verification and Validation of Simutink@ Models .t- I
Developing Test Cases
,,1. ,
Param There are m^ny wâys to define sþal data. Some options willbe discussed on
the next page.
To pass data into root-level Inpott biocks, you must specify a vanable name
in the Simulation ) Model Configutation Parametets ) Datalrnport/
Export ) Input option.
¡i-:nnitia| state:
.
Optin*izaticn
n --H-.
@ 2017 by The Mathlù(/orks, Inc. Verification and Validation of Simulink@ Models 3-8
Developing Test Cases
,o;.1,"Ì*
.,-\ q
'/ ,{ui-cd¡R-
. Timeseries - object that inherently
-A.n
contains data over time. This could be created
using MATI-AB code or logged from previous tl I
The atay fotmat is the easiest to use. However, it can only be used if
simulations Ë fnWWÈ . Allinputs aterezland of double dataspe.
' All inputs share the same time values, since ali columns of the ârray must
have the same number of elements.
. There are rLo structured inputs, i.e., bus input sþals.
. Structure- Structute vanable with a time field
and a signals fie1d, which represents the data. Note The Root Inport Mapping tool can help you to interactively map
wotkspace data (or data from external files) to the input ports in a model To
open this tool, click the Connect Input button.
\\ rr
u
: 11.)1.
LLf ¿) f
@ 201,7 by The Math\ü7orks, Inc. Verification and Validation of Simulink@ Models 3-9
Developing Test Cases
Shift+click to I
add new point 0 t.2 t.1 û.8
Tr*e {seÐ)
lndex: 1
It is commofl to load test case data from external data sources, such as dat*.
spreadsheets or text files. The two main u/ays to do this are
tããe to trrnporl
4 80 L
ests.xås
PI Teçt L
5 100 7 * :- il pedai-scaìed
6 I W angìe-scaìed
,1
ff Test L 2 0 ? 46 o
PI TÊst {$ .l4 Yl lest I Tme {sec}
r-4 pedal-scaåed
: ü ançle-scaled ilame: sedsl scaled
@ 2017 by The Math\üØotks, Inc. Verification and Validation of Simulink@ Models 3-1,1
Developing Test Cases
alternative way to develop test cases is by using logic. This ptovides a more
-A.n Open the p:i UT r-L â û€:!¡¡
natwral ianguage to define tequirements-based tests. To do this, you can use a bk¡ck.I-eave
Test Sequence block ftom the Simulink Test block ltbtary.
Test Sequence blocks can be configured to have any number of inputs and
Test Sequence blocks enable you to graphically author test cases using a talnlar
ouq)uts. Therefore, you cân use these blocks to perform
list of sreps. Transiriozs between steps can be defined using comparisons or
temporal logic. . Open-loop tests (ouçuts only), which generate a predefined sequence of
steps governed by logic
Both the test actions and transitions are written using MATLAB syntax. In
addition, you can use test-specific syntax that pnmartly deals with temporal ' Closed-loop tests (inputs and outputs), which use information about the
logic and vedfîcation þass/fail) activities. test ouq)uts to modi!' the inputs
. Test assessments (inputs only), which use logic to analyze test outputs and
determine the test results. This will be covered in the next chapter.
A 20fl by The MathrüØorks, Inc. Ved{ication and Validation of Simulink@ Models 3-1,2
Developing Test Cases
$t*pilnwn
aÊdScaled.pedalsc*Íed = -1 ;
@ 201,7 by The MathrüØorks, Inc. Verification and Validation of Simuliflk@ Models 3-13
Developing Test Cases
:,..:: .
You can use the Data Symbols section on the left of the Test Sequence Editor Ädd Kp to the *iË:t blocK.'
to add, delete, or edit datain the Test Sequence blocks.
The types of data avalTzble arc To create data,placeyour crúsor over the coresponding section (for example,
Pararneter) and select Add data.
. Input -Data comes from a Simulink sþal.
. Output -Data is output to a Simulink sþal. Once you have defined the data, you cân place your cursor over it and select
Edit or Delete.
. Local -Data is local to the chzrtar-:d persistent between time steps. Can be
modified during simulation. Note You can also view all the data tn a Test Sequence block in the Model
. Constant - Similar to local data, but remains constant during simulation. Explorer by clicking the Model Exploret (ffi ) button.
äy*trbolx
ûymb*ls $tep
Input
Standhy
1. controller_o*tput aäd.**caled.pedal_s*aled = ü;
tu$mt
a2d_*saled.angl*_s*nl*d * t;
tutput t e?rl r¡*l¿¡*
L ir;, aËd-scaled ñ Testty*le
Lnçal
:
ßonçtant
tonetant
Farameter
Fararnet*r
A 201.7 by The Math\ü/orks, Inc. Vedfi.cation and Validation of Simuünk@ Models 3-1,4
Developing Test Cases
An advantaee of creating logic-based tests is that the test input can be made the test
robust to changes in the desþ. Fot example, if the controller gains or sample sþals.
time are modified, the time at which transitions occur will change accordingly.
re$ults.
To verify the behaviot of the Test Sequence block, you can view
the animation in the Test Sequence Editor while the simulation is
running.
Simulation Animation
controls speed
Ðata used by
* ;$t*pUp
3^
t, Å;
$tepUp: >,r i.1 r. í{i:j
a2d_scafed
pedalscaÌed: 0
angle_scaled: 0
\\nit
A 201,7 by The Math\ü/orks, Inc. Verification and Validation of Simulink@ Models 3-15
Developing Test Cases
Summaty
. Defining test cases
. Generating test harnesses
. Creating and importing test inputs
. Incorporating logic in tests
@ 2017 by The MathWotks, Inc. Verification and Validation of Sirnulink@ Models 3-1,6
Developing Test Cases
@ 2017 by The MathrüØorks, Inc. Verification and Validation of Simulink@ Models 3-17
Developing Test Cases
Answers
1.7
2.8
3.F
4.8
)
@ 2017 by The MathWotks, Inc. Verification and Validation of Simulink@ Models 3-18
Analyzing Test Results
Outline
. Performing tequirements-based assessments
. Loggog, inspecting, and comparing test results
. Collecting model coverage
. MÄTI,AB@
. Simulink@
. Simulink Test'" (fot test hatnesses and Test Sequence blocks)
. Simuliflk Verification and Validation'" (for tequirements linking and modei
covetage)
*-¡\
Raxn fest
\Ì @
@ 2017 by The MathrX/orks, Inc. Verification and Validation of Simulink@ Models 4-2
Analyzing Test Results
@ 201.7 by The MathWotks, Inc. Verification and \älidation of Simulink@ Models 4-3
Analyzing Test Results
Results Anaþsis
Anzlyztng simulation test results typically involves inspecting simulation
outputs, with the goal being to better undetstand the system behavior.
Is that the
coffect fesult?
Stç R6ponse
a.E
!'1-
:A-..--
+ 7l +
2.5
t o
@ 201,7 by The Math\ü/orks, Inc. Verification and Validation of Simulink@ Models 4-4
Analyzing Test Results
An"ly.is Approaches
Regarding Simulink model datz, fhere are two modes of anaþsis that arc
colnmofl.
You may find that oîe àppr.o ch is better suited for a particular task than the
Run-time analysis othet
4.9
5.2
4.r
@ 2017 by The Math\X/orks, Inc. Verification and Validation of Simulink@ Models 4-5
Analyzing Test Results
¡ <&qr ¡ <drd¡æ>
a.ø0Ð0w
Ðúty Scðpe
Inpr
u
wwtï]î:Tîîtfiï
ronl 0 [ê r-outpll m oto r_inpuls
<d¡rectbn>
hputs
@ 2017 by The Math\X/orks, Inc. Verifi.cation and Validation of Simulink@ Models 4-6
Analyzing Test Results
Some Simulink libraries that contain usefi.rl blocks for this include
duty sþal is between 0 and 1.
. Signal Routing - Contains blocks that you cân use to select the desired
sþals for analysis.
¡L ...
. Logic and Bit Opetations - Contains relational and iogical operators that
are usefr.rl as part of the analysis.
_Ë
Check
. Sinks - Contains display blocks that you cân use to visualize simulation data Static Range
This libtary also contai.ns the -A.ssertion block, which can stop the Cornpare
Tö Cons{ant1
simulation based on a logical input sþal. This allows you to create your
own run-time âssessmert logic and combine it with an Assertion block.
dlrect j-on sþal is either -1 or 1
If
yout test harness contains a Sþal Builder block, you cafl enable and disable
asserdons in Model Verification blocks for individual sþal groups. To do this,
An er¡:or occu::red while lunning the simulation and the
show the verifi.cation settings of the block and use the Verification block
simulati on was terminated
settings section.
Caused by:
Errcr evaluatínc ri-.-^,ri..,.a..,. cailback uf Checks SRanoeI
Note You can only toggle assertions for Model Verification blocks from a
Ìrlock (mask) 'pl,rnír.-,rJ;"uir*..r-ì.5.i1.í:.nl;.qlk... f--i-r.c:.-Li.c:..-å.::ì-ï-1e_Ç.'
Sig"ul Builder block if the Enable assertion option is disabled in that block. Duty outsi-de a-Ll.or..¡abì e range.
l.{)Íflr'i::'lÊr"' :i:rl, tl li. i i ì.ltrylfjtT $ i}iì\ iìi,.)i
@ 2017 by The Math\X/orks, Inc. Verification and Validation of Simulink@ Models 4-7
Analyzing Têst Results
For example, suppose v/e'$/ant to use logic to stop the simuiation if any of the The fust two conditions carr be tested using the assert function. If the
following conditions are violated. conditions are false, the simulation will stop and ptoduce an eÍror message.
You can customize the error message in the second ârgument of the function.
. The value of the integral state must be less tban 1,.
. The value of the integral stâte must be greater than -1.. Generate Analyze
. After the input sþal changes to -1, the integrator state must take no more test inDuts. test results.
than one time step to unsâturate.
Since the controller also has a ptoportional btanch with gain Kp, the test /
conditions must account for this offset. Since the test inputs use a conttollet
input value of either 1. or -1, the conditions cân be tested as follows. aÊd sca&
. The controller outputmustbe less than (1-Kp) one tìme step (Ts) after
the pedal_scal-ed sþal steps down from 1 to -1.
les Sequsce lAsssent)
Note There is also a fourth condition that tests windup when the
pedal_scaled sþal steps up ftom -1 to 1. Howevet, this condition will
be þored to simplift the course example.
Step
Assæssm*rnf
@ 2017 by The Math\ü7orks, Inc. Verification and Validation of Simutink@ Models 4-8
Analyzing Test Results
. Needs to be checked aftet a certain time - In this case, one time step
after the conttoller input steps down.
The second substep has no when condition, and Qfenl ln a*sert{controller_output >- -{1 + Kp}, 'L*w*r Add suh-step
a2d_scaled.pedal_scaled = 1, Erase last step content
executes when no other when conditions âre ttue.
Wlndup Add iränsi'tion
This substep performs no actions. Wait
'l*f*gr*t*r ørindup detected at
Rêquîrerrrênts kaceability r
É = %f^',t);
Note The Windup substep uses the verify
key'word. This is similar to assert, except the $tepÞown Else Br€äk while exeÐuting stêp
@ 2017 by The Math\ùØorks, Inc. Verification and Validation of Simulink@ Models 4-9
Analyzing Test Results
tbe
.:
ñ6i"r
Srtj
frT
I t:t @ffi'&#iv ¡rã-
a -¿
Jl" Ì:.: ,?,-
e:-.- 1""'t ':",/
the most flexible way of loggrog data, and supports all sþal data types. npul$ ä te
sarne data type?
Saturatíon
N1åx: 1 Seve to workspace ar file
+ l-4in: -"1
You can log a sþalby right-clicking Laçgi*g a*d accessibiiity 1 lrlTÍrne: tsut
+ 7
the sþal, selecting Properties, and !i:! I -!-
Test ìnputs ure the FlStates: xcr¡t
,,----i
yiû-ü
then enabling the Log signal data snÊ?e dêlå SËìe?
JI¡IY.'' IÞ
Logging name
option. A loggtng badge ( ,,:') vrill ;'i;.iûutput: yout
r next to the sþai to indicate it i i ts¡nãI crãrèé. n*l
^ppe
is being logged.
Signei logging: loçsaut
In addition, you can use the following blocks from the Simulink ) Sinks
Iibrary to ouq)ut simulation data.
l{srrnal
@ 201,7 by The Math\ü/orks, Inc. Verification and Validation of Simulink@ Models 4-1,1
Analyzing Test Results
Accessing LoggedData
The format of data saved to the workspace cart diffet depending on what is
being saved and the format option you choose.
. Array - All data stored in a single matrix (no support for different data
types)
. Structure/Structure with time - Each ouq)ut stored within
different elements of a structure (no support for bus data tlpes)
. Dataset - Default loggrog format for outputs, states, and logged sþals.
Data sets contain variables that can be accessed using the getElement
function.
Sþal loggrg in Dataset format. For output and state logged
data is always
A summary of how to access data from the logged formats is shown in the data, you can choose the output format using the Format option under
table below. Simulation ) Model Configuration Parametets ) Data Impot/Expott.
(alJ, data)
t sig. Values . Time;
v sig.Values.Data;
@ 201,7 by The MathV/orks, Inc. Verification and Validation of Simulink@ Models 4-1.2
Analyzing Test Results
Irnport ?X
ir4$¡1 il.Ѐ sÈ¡ìsç CårÉ i¡,'r llÌ4 ¡#è Rlkrp¿¿:e ¡¡ ¿ â.ûI-llÞ
E2 æ¡ed:p4 dãi:s4¿fèd
- lrgÈôJi
]-1.:
r:d_9ffi iùd a¡{le*çièl¿d
cü¡Tcl¡sr_3lF l
t€dg,-¡ r e leC
t))a/J"-i,ait\1iit
ffi Cã5131
¡larpf
ÐèssiÞtúÍ
nl
HBlel
íiiii¡UlÊÞ iilide : ¡ôr4ìj
St¡,1¡,,,*
glnr ¡i*È I
@ 201.7 by The MathrùØorks, Inc. Vedfrcation and Validation of Simulink@ Models 4-13
Analyzing Test Results
olrtf)utlíÍ'' 'i
Since there arc only three sþals in each run, you can remove all grouping by fufls. ì,
: Ëêg:i¡fÞ uçiãuits
¡.5
Ë'll:i_..ì.?Ísi¡
B Û¿I.i NÅöe
i
9i6iiFalh ri.'!1 ';"- ,,¿:- .r,5ù!
t
@ 20L7 by The Math\ùØotks, Inc. Verification and Validation of Simuünk@ Models 4-14
Analyzing Test Results
You can specify the Abs To[ (absolute tolerance), : ú.rtàa *iefticA ¡ Ëcrùêll*r_rü$qi ll$D 'l: F¡Ct'_ÎañEõil Ll rrcnlrõlìÈr_âulF0t lRrn 2: ,ñÞ$rl€d_úilè: +: Tp'êr?rt:e
I ûærÞrae : IúlÊrãlce
from the compadson results by clicking the Create
Report button. :n
U¡¡re iar¡Ìr*ììBi-ri¡riir:r
-rìriiÌ si
: rr, i, lí I l: r r
È.Í9¿ìûlÉ talerarcÞ
TùleriÈæ û l]3ì
Ìð,èËnr€ .l
T:iìrê
@ 2017 by The Math\ü/orks, Inc. Verification and Validation of Simulink@ Models 4-1,5
Analyzing Test Results
@ 201,7 by The Math\ùØorks, Inc. Vedfi.cation and Validation of Simulink@ Models 4-1.6
Analyzing Test Results lï
Viewing Model Coverage +
r Try
By default, model coverage results will appear in the Covetage Results Explorer coverâge the V ñ<1 rnes s hâffiess.
. .: :: :::
after simulation. You can control whether to show this tool using the Show
Results Explorer option under Coverage ) Results.
There are thtee other ways you can view coverage results. CsveraEe ûãta
, &i prvmCnv
¡;lodel versirn 1.185
. Model coloring # setliñgs
¡ :.-' Lurren( Lumutãç{ve Dðrä Author ]rlvitus
Coverage results are displayed on the block diagram itself, and you can Runl : st¡rted execulion 06-lul-2O16 13:10:20
interactively obtain more details about each block by selecting the block. ' i;ì¡ Ðeta *ep{rsit0ry Fle name: pwr*Cnv_Hamess_cvdata
Descript¡on
select Highlight model with coverage results from the Coverage Results summary
Deds¡on Exea$iÐn
1. 5 88o/c 1û0Yc
. HTML report l. n'Iodel "pwmCnv"
Produces an HTML document that summarizes the
coverage tesults. Ifetrls CoveÌågr {fLis obje(f) Cover?ge (iuc. dÊ-(eeil{i¡rf s)
Ci ùlolÐàtic Coupleriq,' 1 5
G€n€rate repûrt
Decision ¡I)iì S8',¡ (flE) decisioù sü¡colrès
Hi,:hlicht módel with cÕvêråÕÈ rÊsults
To enable the HTML report, go to Covetage ) Results Ere¿uliot NA lú0oo (6r6J Ðlrecti\r'
Produces a Model Coverage Web view, which allows you Deùision (Di) 7590 (3r4i deciriç¡ì outco$es
'10094 (ir'l) lul
Eaec$1iùt objectile oritÉöües duty
to view and share coverage results in a Web btowser. This
:,(isions Abs Saturation
requires a Simulink Report Genetator'" license. ìrput > lower liuír 509¿
Missing u<ûtiiy< t
@ 201.7 by The Mathrù7orks, Inc. Verification and Validation of Simulink@ Models 4-77
Analyzing Test Results
. Disable automatic report genetation and model Select; äi Show Results ExpÌorer
the HTML report, \X/eb view, or model highlighting Hardware Impleme... Autosave data file name:
Model Referencing '$ModelName$*cvdata
obtrusive. lWhen you âre ready to generâte repott ot
^ Simulation Target
highlight the model with covetage results, you can do it r Code Generation Output directory:
from the Coverage Results Exploret slcov_outpuV$Model Name$
Híffi nhy/Cønp¡ãitï
fiom individual tuns or from cumulative data. :
'¡tod€l
Ilsisiofi ExæutÍø
Ðata Rep$silory :
@ 201.7 by The MathWorks, Inc. Verificati.on and Validation of Simulink@ Models 4-1.8
Analyzing Test Results
Summaty
. Pedorming tequirements-based assessments
@ 2017 by The Math\X/orks, Inc. Verification and Validation of Simulink@ Models 4-1,9
Analyzing Test Results
3. (Select alJ.thatapplÐ SØhich of the foliowing can be used for post simulation
analysis of a model?
@ 2017 by The Mathrü/orks, Inc. Verification and Validation of Simulink@ Models 4-21
Analyzing Test Results
Answers
1. A,D
3. B,C,E
4.F
@ 2017 by The Mathlü/otks, Inc. Verifi.cati.on and Validation of Simulink@ Models 4-22
Building Test Suites
ir
@ 201,7 by The Math$Øorks, Inc. Vedfi.cation and Validation of Simulink@ Models 5-1
Building Test Suites
Outline
. Creating test fi.les
. Confi.guring simulation, baseline, and equivalerìce tests
. Viewing and documenting test results
. MATLAB@
. Embedded Coder@ (for software-in-the-loop verifi.cation)
. Simulink@
. Simulink Test'" (for test hatnesses, Test Sequence blocks, and test managet)
. Simulink Verification and Validation'" (for requirements linking ¿nd model
covetage)
@ 2017 by The Math\X/otks, Inc. Verification and Validation of Simulink@ Models 5-2
Building Test Suites
@ 2017 by The MathrX/orks, Inc. Verification and Validation of Simulink@ Models 5-3
Building Test Suites )
' )
Organizing Tests Tr,,f',. '": ,,.,
)
,::, .
:':::::' i
During the lifetime of a Simulink project, you may \Ã/ant to run tests on the the protect m^ foldet )
models at vatious dmes to ensure the tests are s :ll successful. )
)
To do this effectively, model tests should be desþed with the following goals
In this chaptet, you will learn how to orgatize and automate tests graphically )
in mind.
using the test managet in Simulink Test.
)
. Otganization - Tests should be grouped by functionality. This means that )
You can also build test ftameworks by running each test fiom u¡ithin its own
changes in desþs or requiremefl.ts can be easily mapped to a known set of
MATLAB function. This is discussed in -Appendix 4.. )
tests that may need to be rerun or modified.
)
. Repeatability - Tests should not leave a lasting effect on the model (ot
)
anything else, including the base workspace) unless it is explicitly intended.
)
. Self-containment - Tests, or groups of tests, should load all required
)
dependencies and perform any post ptocessing necessary.
)
)
)
-&l
ür¿il Models
)
ru )
A 201,7 by The Math\üØorks, Inc. Vedfication and Validation of Simulink@ Models 5-4
Building Test Suites
To open the test manager, select Analysis ) Test Manager fiom the Simulink O¡en the bl¿nk test file, $ave it in the
menu or enter sltestmgr in the MATLAB CommandWindow. 'tolder âse t
From the toolstrip, select New ) Test File.
In the Test Browser pâne, you cân right-click any test case or test suite. The
context menu that appears enables you to perform the following actions on
Note that the Test Browser pane displays the following elements.
the selected item.
. Test file - A . mldatx file, which can contain test suites and test cases.
. ,A.dd, rename, delete, cop¡ and paste
. Test suite - Used to group functionally related tests. You can place test
. Temporarily enable ot disable
suites inside other test suites to create multiple levels of hierarchy.
. Test case - . Run individuai test câses or test suites
individual simulation-based test, which can be configured
-A.n as
shown on the next pâge. tÉ919
dt . mldatx Re:rlb er:d ¡.tì{åt'-r ffi san eage Ìì I i,'-j !,¿ewlÈstcðs€ 't l
,i
' i: . Ne( lerlsl¡1e I 9: .i,.: . :, f, : J- ì .i. -
+
E¡Þand Ål
ll)
r ìì û il|' i:ì i:irì :: i :'r-l
CFllãpsè All
'$,
::
Test case i- Clt Ctn+X
req test i*
r' tna0,eð
I ijl.Ìr¡i..,itla ::Iìl!l I rlù¡ lìIj
ll* n '¡ai
ß *€¡erÈ
Test case
Requirements \Z I Edrl les'ltaEs
t sui
A 201.7 by The N{ath\X/orks, Inc. Verification and Validation of Simulink@ Models 5-5
Building Test Suites )
)
Structure of a Test Case )
All test cases in Simulink Test contain the following infotmation. )
)
. Tags )
. Description )
Documentadon
)
. Requirements links
)
)
. System under test
)
. Callbacks Note In many situations, you cafl equivalently configure test cases using
)
callbacks or overrides. Fot example, you can use both approaches to modi$r
MJ\*TLAB commands the value of avanable pdor to simulating a model. )
to run before or after )
the test Overddes for each test câse are cleated after the test case is finished running.
)
In other words, overrides do not influence the behavior of other tests because
Test defìnition . Overrides they cannot make permanent modifications to the MATLAB environment. )
Patameters, inputs, )
outputs, settings Callbacks are more flexible than overddes because you can rufl any Qpe of
)
¡uJ\-TLAB command as a callback. Because of this, callbacks areableto modify
. Iterations variables in the MATL,{B base workspace or even make changes to models (if
)
different overrides )
Therefote, callbacks can affect the rcpeatabiJity of tests but overddes cânnot.
)
@ 2017 by The Math\ü/otks, Inc. Vedfication and Validation of Simulink@ Models 5-6
Building Test Suites
Types of Tests
You can cteate three different tt?es of tests using the test managet
Input Output
. Baseline test
Simulates a model and compares the results against a predetermined
+ +>
baseline set of data froma MÄI-file or Microsoft@ Excel@ spteadsheet.
Recommended for 4,*
i.l,
. Comparing simulation to a set of expected ouq)uts. Expected ouþut
File
. Performing tegtession tests.
Baseline test
. Equivalence test
Runs two simulations and compares their ouq)uts. Recommended for
. Comparing results from the same model under different test conditions.
Input :';;, Output
. Comparing results from two different models.
+ 9-l
L
Both baseline and equivalence tests petform srgnâl compatisons to be within
some specified absolute and relative toletance. This can be individually Input Output
configwed for each sþal. + +
Equivalence test
)
ÊÈsr¡ììs E{ld ÅÊifurÞ å urndçpiëst )1 ftt Start Page iì )
li ËnùblÉd )
Windup Test
)
r i'"'1 Fr,Sl"1 ù*nversrcn sj:sj.' ¡ : l':r,ri'ii+: t i': r:i¡:;l ::r-
* Èrl l:ÕÎiF.llÂr ar-..,.r--il^- -i:".r1
I
Y Si:..r it-t,Liiii1¡ :*
)
ÅdS v )
Linh Edilo¡
w:ì"JìI:l l.itii.: Ii:i iËiì:
Li;'rk ta Selection in f"IATLA*
@ 2017 by The Math\ùØorks, Inc. Verification and Validation of Simulink@ Models 5-8
Building Test Suites
check box next to the Kp and Kí parameters, and click OK. : : Indudå þäsåliftÊ dal¿ in lest Fës811
./ þedùl_rcated
* 'iid{i...
I
*.4dd - L: Herresn L I," ìr':i"-
CanùeI
@ 201,7 by The MatliWorks, Inc. Vedfication and Validation of Simulink@ Models 5-9
Building Test Suites )
)
Creating Test Iterations Ifv
)
)
Ifyou wânt to run multiple tests of the same tl1)e on a particular component, to the baseline ,tèst..:.... '':,bôth
s,ueh that ,14.
::r':,
,
I
you can cîe te iterations of a test case instead of building multiple separâte test te :
)
câses. )
The piCtrl_Harness test harness has two Sþai Builder groups. To )
\7ith iterations, you can reuse the same test definition under different test
creatÞ iterations of the baseline test such that both groups âre executed, take
settìngs. Test settings include )
the followrng steps.
)
. Assessment cdteria - Includes baseline or equivalence crttena, depending
1. In the Table Iterations section, use the Add button to creâte two itetations. )
on the type of test
2. For each iteration, change the entty in the Signal Builder Group column )
. Parameters - Usefü for patameter sweeps ot robustness testing as shown below. )
. Inputs - Includes external inputs passed through input ports, as well as
!1 i:: .: ,!t a.i
)
Sþal Buildet groups -
)
. Configuration sets - Can tun the same test with different configuratìon * iqllL.F- :l I-il qil'..,),¡:'
)
parâmeters, fot example, solver settings. : ;:.iri.l. iì. li.iì:ì.i ;il::-' ¡ !i:,Sr,.Ê:ii :;ilì'
)
Pl TËri Ì .;È:èi.iiii:"ifi¡r,i.
To create iterations, you can expand the Iterations section of a test case and Þl Tèsl l :i*i;,ìii rr,',';.t, .. 1ì.,tilr..l; .'fl:':r." .'i;t ,'.t
)
Fl T.æ1 i
use either the Table Iterations or Scrþted Iterations options. Table iterations )
Pì Test 2
are graphical, and. therefore easier to create, whereas sctþted iterations ate
more flexible but require you to write MATLAB code. E@ )
)
Test case :' Note You can also use the Auto Genetate button to quickly gefletateiterations
)
F
w
i__
CUT using combinations of avaúable test settìngs.
:.*.-.....]
To verify that you have cortectly created itetations for a test case, you can c]ick
the Show Iterations button. This will open â dialog with details about all the
,!
-* settings for each iteration.
irJ
@ 2017 by The MathlùØorks, Inc. Verification and Validation of Simulink@ Models 5-10
Building Test Suites
The final test willbe an equivalence test. This test will check whether generating
code from the pwmCnv model causes âny unexpected differences in results. and
To test this, you will run the model tn software-in+he-loop (SIL) mode.
3. This test does not use â test harness, so tfre model inputs need to ! rii |,i ì.i i.,:: i.:i.. ¡ S :ìi ¡,,: tì i. Ì", tì ¡ Fi t aj I iì
be overridden. Go to the Inputs section and map the inputs to the :5iïïHlå{iùn lr4sdË: lh'lûdËj $ettin$s
tests \pwmTestData. mat file as shown below lfi4ûd€l
gÊtlinEsl
I
: : gtärt T¡me:
fl¡0nral
-ltii:i i:ì å,cælerãtflr
1rÕF f rne
i lnclrúe sylemel rinpuLs/s¡gnãl bu¡idff ¿lala ¡n test resuli RåÞid AÈÈelÈÎãißr
S.ûfrlfårernlhe-LooF tSlLÌ
ãtop simulËlìDn atlãs1 iìn,È FÐÌñt r ln¡tiat Siate: lh
Prûcessotrrfi lhê-Lôùp IPILV
'þ.sdd 5. Expand the Equivalence Criteria section. click Capture to simulate the
i i Siçnal Éqild€re{cçÞ l1l.ql,(: l:i1 !:: ff1::t:
model and populate the list of sþals to compare.Lezve the tolerances at
File 1Þ¡Jnìïâst*âi,1. mfii n their default values of zero. This means that the test cân pass only if the
Ådd íiÉrsliûn€ tè flrn thís înFüt
v LriFUf lr'lÅFPl"lG
sþais are identical in both simulations.
lllapping lt"{*c'a ¡"4æp l¡ìpul5
-n-.:. Ll'1..:::i.,
- fi'lÁ.FPllt {ì S tETfJS
.Sr/rce¡; sfùT',l in å.?pèd r¡pr¡s. v-:
,lri.:
¡niì :!::: , I i fi r,t*r*inp6Is.duf,t I U Uil:f B
1 pvmün'røûnlrûllúr_autFilt s&ntÐller_ûl¡lp|'r,t ; ßrrtrri*¡nputs {ÍirÈr'liBn ù il Ìlila,,n 0
r Aû\rANtEn '*
C.afice¡
@ Lì+l¡L¡
@ 2017 by The Mathrü/orks, Inc. Verification and Validation of Simulink@ Models 5-11
Building Test Suites
Tr,y,
:
Once you have created all the tests, you can run them by selecting the test frle Rgn the Ðc all the
and clicking the Run button in the toolstrip of the test mânâger.
The Results and Artifacts pane leverages the Simulation Data Inspector,
which was discussed in the previous chapter.
This means that the test màrraget has access to many capabilities of the
Simulation Data Inspector, including data cursors, view customizat)ons, and
n€5ulÌs ånd Å*:lä.:t5 exporting results to a MÄTL-A.B figure window.
v; Éliïestr
- ;'-i P!',,T',4 C.,lnrÊrci']n
- ;*': P¡ üsntrüllÈr
*
iä.i \'1,ìndLlf"ì iBSt Rê3ulb: 2tiììJ-.-1,'lãtr24 T¡ 3r:ãfi H I cffiÞêrisff
6i Pxrarnxlxr TunehiliÞ,' Tesl rf¡j:{ntrù1,Èr_ruÞil1i8éâelireJ a[cünt{lle._sutpr*lacnp¿rels,]'r-tr8leråüce
:c
Once the tests have finished tunning, you will see tesults available in 19
the Results and Artifacts pâne of the test mânâget. The icons in the ¡1
Status column indicate the pass/fail stâtus of the test results.
- i&¡ !'ëüly åtãlËnìents s
fÈÈt , trMÈÊ {Âssssnl
Note The tests may initially take a long time to ruri because Simulink ¡ & Sìn OllpLll tFií.ld ffiell
8gÌç
has to genetate code from the pwmCnv model to run the simulation in - i:r Par*meler Tsnät¡ilit_v- Isi
SIL mode. -Assuming you do not modify the model, subsequent runs * g 3ìf¡ereoçe T -Djerançe
,.ii ccntraÍler_ruttrjt
r n $im ûllpíi ipic¡1 : ñnmrå¡;
i ú itBralìwÈ ;:
,J
éèr,nr. 1¡11-'-¡.r-:q l_ ì
¿s 1!
@ 201,7 by The Math\ù7otks, Inc. Verification and Validation of Simulink@ Models 5-1.2
Building Test Suites
You can directly enabie coverage collection in the test manâger by expanding
the Coverage Settings menu and using the options as shown below.
The test m^î^ger aggregates covefâge for all, test suites and test cases, so you The aggregated coverage will appear in the test results. For each component,
should configure the coverage options at the test file level. Then, you cân use you can click the icon in the Report column to open i.ts coverage report.
the Coverage To Collect options to locally disable coverage collection for any
test suites or test cases you v/ânt to exclude.
TÊsi grtì.rser
l:riìì.:t:rlt:irt I'iliirìàiàiìrv
âesillh and,q$iiå.!s etcTçata &t *ot",t Prg" r :L¡r
... I r:..i ::a.i::ì :lr :i:ìì : :: l:11 li rì.r: i::r:ì
* RÈsdts: 3{11-ñ1ar25 1?:55:43
: r:ji_'j :::t -
'.:iltj!iríri.r::'i.:
I Recsti ççær?iJÊ lff slslen ü'ìiJë legl
|: "1i::íirlr"r::
Coverage Report for pwmcnv
li!ir: irì:i ü
I fiecis;i* r : CÊndi-iirìrÌ
Tnble of Contents
rJ,lËiü iocRup,:ìþìè
@ 2017 by The Math\X/otks, Inc. Verification and Validation of Simulink@ Models 5-1,3
Building Test Suites
Once you are rcady to share your test results, you cân select the results and passed
click the Report button in the Tests tab of the toolstdp.
Note \7ith a Simulink Repott Generatot" license, you can use the
fÈ9i ärùs€Èr Res$fàs:
Customization section in the options to customize the generated report.
rî ,Íì i,1iìi:ç!
You can also use the Expott button to save test results to a .mldatx file.
f..ri{nn€ Any results you have saved in this format can be later loaded back into the test
m^n^ger using the Import button.
. Hlpedinks J
to requirements
,
ì li
Sìnrillati*n mètÂdãtð
llû'rsr¡ì$è rpililt g
ü SimulãtÉ the PÌ mntrÐXler mÕdel !,,/ith pararrÉtÊr overr¡de\ and ÈúffFåre ìt tð expertèd oLÈtpdls.
@ 201.7 by The Math\ü/orks, Inc. Verification and Validation of Simulink@ Models 5-14
Building Test Suites
I{ote that there may be a delay prior to the first , : glart ïiste.
ifcl8úÈi 5e'ttjnqsl
Þlß{mal
execution of a modei in accelentor mode because the
code has to be built. Also, you canfl.ot collect coverage 5-J9p
'rne:
tesults when running a model in accelerator mode. S.Bür!ârÈ-inl[e-LÉaF iSlL]
¡nìtial gtåte:
Frûcåsåqr-in-thÈ-Lüfl p tF¡Llì
. Fast restart simulation
Allows you to simulate a model multiple times without
recompiling. SØhen fast restart is enabied, you cân
v iTÊR.{Tl*i'.lS''
change inputs and tunable pârameters. However, you
cannot make structural changes to the modei as this ; I.jri; lã. i ïË ËÅli r- ii :l
would require the model to recompile. ¡ ¡i:::i:Ë- iËü'i 'r --
Fâst restart simulation can be configured for tests ¿ 1i:rr i¡:t ,,.Jl *J :inr:rl ,;/ri i,'r.:lí : il f tf.;iiiìtr
with iterations, since changing inputs, pafâmetefs, or
Ruñ iìã.F1 itëråt¡ons in iësl re.sl*rt
assessment cnteria tlpically has no effect on the model.
. Parallel simulation
/ f
" simulations in parallel using
You can run individual
th. P¿d4c"-p"tirs T""lb""'". This is useful when
performing many simulations, such as pàtaÍneter
sweeps. To simulate models in parallel, enable the
Parallel option in the Tests tab of the test m^fl^get.
Summaty
. Creating test files
. Configuring simulation, baseline, and equivalence tests
. Viewing and documenting test results
@ 2017 by The Mathrü/orks, Inc. Vedfication and Validation of Simulink@ Models 5-1,6
Building Test Suites
A. Simulation
B. Baseline
C. Equivalence
2. \Øhich tipe of test would be suitable for a model that produces ân error
when a sþal exceeds a certain limit?
A. Simulation
B. Baseline
C. Equivalence
3. (Select allthat apply) w4rich of the following test case elements can modify
models and workspacevaríabIes, thus affecting test repeatability?
A. Input/ouþut overides
B. Callbacks
C. Parz¡meter overrides
D. Configuration settings overddes
a. G /Ð, Requirements links in tesr files are srored in the test file itself.
@ 2017 by The MathnØorks, Inc. Vedfication and Validation of Simulink@ Models 5-17
Building Test Suites
Answers
1.8
2.4
3.8
4.F
@ 201,7 by The MathIØorks, Inc. Verification and Validation of Simutiflk@ Models 6-1
Formal ly Verifying Models
Outline
. Using Simulink@ Desþ Vedfi.er"
. Automatically genetating tests
. Proving model properties
. Detecting desþ erÍors
. MATLAB@
. Simulink
. Simulink Desþ Verifier (fot formal model verification)
. Simulink Vedfication and Validation'" (for coverage analysis)
@ 2017 by The MathW'orks, Inc. Verification and Validation of Simulink@ Models 6-2
Formally Verifying Models
@ 2017 by The Math!Øorks, Inc. Verification and Validation of Simulink@ Models 6-3
Formally Verifying Models
Fot instance, if the test cases you have defined do not provide full coverage
fot your modef then you may flot have explored your model's functionality
completely. This could either mean that more tests âre needed or that the
model contains some ufl.necessary elements.
In addition, the existing test ca.ses mây not be sufficient to identify all defects
and unexpected behaviors in the desþ.
@ 201,7 by The MathnØotks, Inc. Vedfication and Validation of Simulink@ Models 6-4
Formally Verifying Models
1. Prepare model
Cetain blocks or modeling constructs are not supported for use urith
Simulink Design Verifier. For inst¿nce, compatible models must use a
fixed-step solver, and contain no aþebraic loops or unsupported blocks.
2. Set obiectives
Set Simulink DesþVerifi.er options, such as coverâge goals or block
replacement options (for blocks thatarc not supported). You can also add
@ Manual
Automatic
@ 201.7 by The MathlØorks, fnc. Verification and Validation of Simulink@ Models 6-5
Formally Verifying Models
d
Lcu¡er fi¡,nit: b c
Outl
tn1
Sat¡.iration Bias
Gaìn
lvtå),, f uu Lawer LÌrnit; t
l"lpper Linril; 3*
@ 201,7 by The Math\)7orks, Inc. Verification and Validation of Simulink@ Models 6-6
Formally Verifying Models
To see if a model is compatible with Simulink Desþ Verifier, you can select ,¡€p,e the SimulifT< projeat lrr &b
Analysis ) Design Vedfier à Check Compatibility ) Model from rhe
Simulink menu. t ri>l-I
:rjii
If the model is not compatible, then you will ger a message stating the thern
incompatibility.
Incompatible
@ 2017 by The Math\X/orks, Inc. Verification and Validation of Simulink@ Modeis 6-7
Formally Verifying Models
2. Genetate tests 1
m otor_inputs
m(*orlnputs
1
@ 201,7 by The Math\X/otks, Inc. Verification and Validation of Simulink@ Models 6-8
Formally Verifying Models
1. Configure the existing test harness (piCtrJ-_Harness) to collect 4. Configure the piCtrI model to þore the covetage ptovided by the
coverâge from the piCtrl referenced model and open the Coverage existing test cases.
Results Explorer after simulation.
To do this, go to the Design Verifier ) Test Generation pane in the
2. Run all the test câses in the test harness using the Sþal Builder block.
Model Configuration Parameters dialog. Enable the Ignore obiectives
satisfied in existing coverage data option and browse to the fi,le you
)l¡ x gÀi *H tïî ¡ r']|
t_:J
previously saved.
a Desiçn Verifier
ßun alå and roduce
tsl*ck Replacements
ffiffi:mi: ìs
ParameterE
góLd
lferificati$n block se,ttings: Þesign Enûr Detecii0n J: Ignore objectives satisfied in exist'ng ccuerage data:
Pr0Þert'/ Provinû
Þa<¡ rlk CoveraEe data fiNe: tests\piCtrlCov.cr,.t
3. From the Coverage Results Explorer, save the cumulative data to a fiTe
Report
*bjective filter
named piCtrlCov. cvt in the tests folder of the project.
: .ftlpiCtrt 5. Finalt¡select Analysis ) Design Verifier ) Generate Tests ) Model
W s*ttinEs from the Simuünk menu to generâte tests.
¡
,: FI T*st L Save curnuîatíve ccverage data Note You can also generate
:t ^-- tests for missing coverage directly from the Test
PI {eS[ ¿
. f-i nñfä R*positcry
X Ëxc[¡de ntl fnnm rumulative data Manager by selecting Add Tests fot Missing Coverage from test results.
- Å¡.i ¡.] ï i: i::À.1 f U {ì íi\,iï 1ì Àii: f. ll ijlj i ì iS
¡
. ..." ::: .: :alrË:L' i;:.ì i.
Note that instead of manually saving the coverage file, you can also use the lLbt
picv¡ I 3 75s;è m, 1[tü%re
@ 2017 by The MathWorks, Inc. Verification and Validation of Simulink@ Models 6-9
Formally Verifying Models
Objectives that
tl*e
In addition to the coverage objectives infered from the blocks within your € _5.
model, you can add blocks specifically fot the pu4)ose of adding test objectives.
The two blocks you can use for this are in the Simulink Design Verifier )
Objectives and Constraints Jibrary. to
il, t\
lÞ
+
+
+ Proportiûnat Gain v outpul
åìe
'äf,Nis
s,?æå dåie X.pe'¿
l-5 5j
@ 201,7 by The Math\)Øorks, Inc. Vedfication and Validation of Simulink@ Models 6- 1,0
Formally Verifying Models
l*,"T1 ¡_{ lt sr
Ê Simul¡nk Ðesiçñ Veriier lngpector
f- duty
*ffi
direction
ffi ._,
'l
:,, & ?m
Proof
Saturatfon ##* pwmCnv/ Proof Objective
Objective: {0. rl \¡Åf-fe
Ü < dutY ": ^{
ÐlR Switch
2. Provepropenies
0r
You can attempt to prove the objectives by seiecting Analysis ) Design
Vedfier ) Ptove Propeties ) Model fiom the Srmulink menu.
Ädive Gwp:
" $iJ.dl-#
c0ctro¡tst_DrJfFùl
If objectives are proved, then you will get a messâge sâlng so. If some
al1 [ü r] t5
are disproved, then you are able to generâte test cases showing how the
proof objectives could be invalidated. )ffiþ 1.5
Counterexample
,
0 s,.{i0? ri.0û4 0.00$ Ð.0û8 o.rt
::
!7hen adding test or proof objective blocks to your model, you can place to &e aad tåea pteate proof
all of the logic fot calculating the sþals of interest tn a aerifcation subslsTem.
This allows you to ensure that the logic you add to your model for desþ
verification is not included in any code you generate fot the model.
It is common to add logical blocks and temporal operators to help you System Requirements
calculate sþal values you wânt to vedfii. Some libraries of interest include
"l . "*uty cycle rnust he proportional tn ccntnçlfer autput, when in a valid rangê.'o
. Simulink à Logic & Bit Operations 2. 'PWM åorque shau[d a*t in posit[ve sense wf:en ccntrofler output is p*si[ive orzei-o."
. Simulink ) Model Verification 3" 'PWf\4 tnrque shcuåd act i* negatirre sense when cantrofler output Ís negative."
'L
il L_
*T**-
lnierval Test
\# .:Ï -i<u<l ,{==> I
duty B
pwm_4
pwm_1
tÈ 4t lmolies
duty
lul
Relational
direction Abs
Operator
controller_output controller_output
<0
Verif ication Subsyslem
,4==> B A==> B
a B
p¡m_2 --4
pwm_3
==f lmpliesl lrnpIesZ
iF.iê
2
direction
@ 201,7 by The Math\X/orks, Inc. Verification and Validation of Simulink@ Models 6-1.2
Formally Verifying Models
Run-time errors
You can review the results by generating example test cases, creating a report,
or coloring the model. If you highlight the model, the blocks that were tested
are colored either
[itto *umma¡y=]ç
' Green- Overflow or division-by-zeto errors are notpossible. controllerlCC_Logicj Logical ûperator Dead
Logic: input pcrt 1 T &üTãVf L#ffË#
. Red - Test cases were found that demonstrate overflow or Logic: input port 1 F ÅCTfWf $-*Sfü
logic
division-by - zero errors. Logic: input port 2 T nËÅff LûËIt
Logic: input port 2 F &{trf\dE :LüSft
. Otange -Result for block is undetermined. This can happen
if the analysis tìmes out, or as a result of automatic stubbing
þlock replacement). cc_outpl.ds <on_ofÞ
ÜR
pedal_scêled
à3 a2d_smled_cc
L*çical
a2d_scaled_cc
C*r*p*r* ûp*rêtor
T0 ßorlstänt iì:lii r:, : :.
i ,
:::: :ìr,i:: i
a2d_scaled <¿ngþ_sælêd>
A 201.7 by The Math\X/orks, Inc. Verification and Validation of Simulink@ Models 6-13
Formally Verifying Models
. Test Generation Advisot Fot more information, refer to the documentation under Simulink Design
Performs a highJevel analysis of a model to help identify analyzable Verifier ) Complexity Management ) Block Replacement.
components. This includes suppotted components, time-consuming
components, or components that are unteachable due to dead logic.
1-D T{u}
) Use Test Generation Advisor to IdentiS' Analyzable Components. Math 1-Ð Lookup
Function Iabte
&ftd! ¡èr cüweìi æ
. Model Slicet
l* ¡: c¿'lrre.
À Allows you to visualize functional dependencies in large or complex
models. You can also use Model Slicer to creàte simplified standalone
Sarcøe,z .,# *¡e*¡':
models fiom larget models.
Summary
. IJsing Simulink Desþ Vedfi.er
. Automatica)ly generzting tests
. Proving model properties
. Detecting desþ errors
@ 201,7 by The MathnØorks, Inc. Verification and Validation of Simulink@ Models 6-15
Formally Verifying Models
@ 2017 by The MathW'orks, Inc. Verification and Validation of Simulhk@ Models 6-1,6
Formally Verifying Models
3. (Select all that applÐ Simuünk Desþ Verifier carl. a:utoma¡ti."1ly detect
potential
A. Integer overflows
B. Floating-point overflows
C. Divisions by zero
D. Deviations from modeling standards
4. Consider a, Proof Objective block with the proof value set to [0, 5 ]
To be provefl valid, the block input must
A. Oniy be able to atøin the values of 0 and 5.
B. Always stay within the range between 0 and 5.
C. Always zttain a value of 0 or 5 at some point in every simulation.
D. Be capable of attaining ali values between 0 and 5.
@ 2017 by The Math\X/orks, fnc. Verification and Validation of Simutink@ Models 6-1,7
Formally Verifying Models
Answers
1.D
2. A,C,D
3. A,C
4.8
Conclusi0n
Verification and Validation of Simulink@ Models
A user-friendl¡ intuitive syntax favoring brevity and simplicity without A complete environment for modeling, simulating, and implementing dynamic
compromising intelligibiJity and embedded systems
The highest quality numedcal aþorithms, based on close historical ties with Desþ and test Tinezt, nonlineat, discrete-time, condnuous-time, hybrid,
the numerical analysis research community and multirate systems
Powerfrrl, easy-to -us e graphic s and visualiz ation capabilitie s Applications in controls, DSP, communications, and systems engineedng
A highJevel language, making it possible to cafty out computations in a line ot Open architecture allows integration of models from other environments
two that would require hundreds of lines of code in languages such as Fortran
orC
ÐF':tg*f-tNlcAt
. Products & services home . View and report bugs ' Create Math\7orks account
. Training schedule . Documentation ' Manage your account
. Downloads . Obtain product updates
@ 201.7 by The Math$Torks, fnc. Verification and Validation of Simulink@ Models t-3
Conclusion
The page that appears will contain information about the products you o\Ã/n âs
well as anavigatton bar on the left side with a number of links. To enter a new
support request, select "Cteate New Request" ftom the "My Support" section
of the navigation bar.
Then, select "Technical Support" from the Iist of request types and choose
a specific category of technical support request fiom the list that appeârs.
Now you c^î enter the information describing yout request and submit it to
technical support.
After the request has been satisfied, the system archives your entire
correspondence history for review at any time.
Further Training
Math\Øorks Training Services can help you use our products to succeed in ..:,
your work. Our training courses ate deveioped around the core responsibilities
a
of engineers, scientists, and educators. Our trainers focus on your goals and
how to use Mathrü/orks tools to achieve them. a Teltng
Public instructor-led courses are offered in North -A.medca, Europe, and Asia.
In addition, rlralay of our distributors offer training at other international sites.
So, whether you are in NØinnipeg or rùØien, you can find hands-on training near
you.
Math\X/orks also offers custom training courses, which can be taught at your
own facility. our engineers can incorporate company- or industry-specific
examples into a curriculum of your choosrng.
Course Evaluation
Thank you for attending Math\7orks training! If needed, zn alternate method of starting the evaluation is through the
following IJRL:
Please take a moment to fill out abtief couÍse evaluation.
http ; / /www. mathworks . com/services/trainin g / eval
Tlpe the following at the MÄTI-AB command line:
Note Please enter the email address that you used to register for this course.
FrÊf'err*d
, :-I-91""t qlç: :
2. Hou did you learn ðbout th¡5 course?
Eqail ug*el ioT çlå.qs fâU,istration: Ll [,t¿thlTDrks t+Êb site
O m¡thu,iorks traini¡g c¿t¡loq
Franç {11 tuar'lmouth {e.g. eollÉ¿gue, mènê!srlsupervisùr, etc )
crf
'lis t
--¡ f¡¡thworkç e-r¡¿il
Deutsch Plèåse rÈ-iyFè your email *ddr*çs: 'll,J sales representali're
Españo I
{i HarLre oiqest
It alia n o Ù other; ple¿se speclfl
I Crntinue t0 oaoe 2 0f 4
baúfi l
Ifyou have any further questions following the training, please contâct your
mstfuctor.
Appendix A:
Automati ng Verification Activities
Verification and Validation of Simulink@ Models
@ 201,7 by The Math\ùØorks, Inc. Verification and Validation of Simulink@ Models A-1
Appendix A: Automating Verification Activities
Outline
. Authoring tests in lvlr\*TI-AB@
. Building harnes ses progtarmmalically
. Automating test file creation and execution
. Collecting, reporting, and extending model coverage
. Scripting fotmal verification tasks
@ 2017 by The Math$Øorks, Inc. Verification and Validation of Simulink@ Models A-2
Appendix A: Automating Verification Activities
You can write tvtt*TI-AB@ code to progrâmmarcaþ test models using the inùe. appA'foldet add $o to
same wotkflow discussed throughout the coutse. tests \ IILd
:::
L.Ld.TJ
'êdí t
test
Ð Ptocess results
Finally, retrieve the simuiation data using the get function on the simout
variable. For example, the following command returns the logged sþals in
the model.
Load test case
First, define the input data and parameters to be used by the model. You can
use MÄTI-AB to cteate variables in the base workspace prior to simulating the Once you have accessed the numerical data from the above vanable, you can
model. For example, useMATLAB to analyze it. Some cornmon analysis tasks include
' Saving - Save logged data, or any other datain the workspace, to various file
fotmats, including M-{f-files, text files, and spreadsheets.
. Yistabzation Use functions such as pJ-ot or stairs to visualize data
-
Run test vectors or timesedes variables.
. Range checking - Lise functions such as min and max to veriS' the range
Then, use the s im function to simulate the model from rvr,t*TLAB. \X4ren
using this function, you can store all of the simulation outputs (time, out¡ruts,
of a sþal.
logged sþals, etc.) into a single vanable. . Equivalence - Load previously saved data ftom files and then compare the
previous results to the current simulation outputs.
Any additional arguments to the s im function allow you to temporadþ
. Displays - Use functions such as disp, warning, and error to display
overide certain model parameters. The example below shows how you can
simulate a model whose input is defined tn øvartable named inp. your test results to users.
@ 2017 by The Math\ü/orks, Inc. Verification and Validation of Simulink@ Models ,t-3
Appendix A: Automating Verification Activities
çry.:..., ,
t:
-A disadvantage of using scripts is that they may have a lasting effect on the Go to the te sts of
base wotkspace. The best way to create tepeatable tests in Simulink is to run
each test from within its own funcTion.MÄTLAB functions have their own
fanction workspaces, so separate functions cannot interfete with one anothet.
>>, êdii.t Þ:.
To simulate a model from within a MÄTI-AB function, you must .. :
end
@ 201,7 by The MathWorks, Inc. Verification and Validation of Simulink@ Models A-4
Appendix A: Automating Verification Activities
'i,,
There are several v¡ays to speed up test scrþts and functions, including
. Acceleratot mode
You can run simulations in acceletator mode instead of normal mode. )) edi teçt$a.j-teÀceel
Simulink will generate code for the model and use the compiled version of
your model for the simulation.
set_param('modeJ' ,
' SimulationMode' r'accelerator' ); Parallel sirad*tioas (in úe, pä ra¡, t êl- fbider) -.
!
+^^+1.
LCÞ L-L, )) e. :
t^^+4.
LEò LZ ¡
cf ose system ('model-') ; . Parallel simulations
You can run individual simulations in parallel using the Parallel Computing
Note that there may be a delay prior to the frst execution of a model in Toolbox'". This is useful when doing many simulad.ons, such as p^tameter
acceleratot mode because the code has to be built. Also, you cannot collect sweeps. To simulate models in parallel, you can place the simulations within
coverage results when running a model in accelentor mode. a parf or loop.
. Fast restart simulation
Allows you to simulate a model multiple times without recompiling. ì7hen parfor i : 1:3
fast restart is enabled, you can change inputs and tunable parameters. switch i
L-4.ì C
However, you cannot make sftuctural changes to the model as this would L
@ 2017 by The Math\ùØorks, Inc. Verification and Validation of Simulink@ Models A-5
Appendix A: Automating Verification Activities
Once you have perfotmed the comparison, you cân wdte M,{|LAB code Simulation Expected
to extract and analyze the results. You can find an example of this in the
piTestSDI
-*1 results outputs 4fi,
scrþt.
f,
Alternativel¡ you can open the Simulation Data Inspector from the
command line once you have performed multiple comparisons. -411 the
runs and comparisons you have created will be displayed so that you cân simulink. sdi. createRun simulink. sdí. createRun
manually view the results.
ffi
Comparison results object
The syntax below shows how to create a test harness from the pwmCnv model
and then simulate it. The test harness has a Sþal Builder source block and
Outpott sink block.
Anothet common task related to test harnesses is to modify Sþal Builder
tName' blocks at the command line. To do this, you can
r' harnessName' ,
'Source' , 'Signal Builder' ,
1. Seatch the test harness for any existing Sþal Builder blocks.
'Sink'r'Outport');
blockNames find_system(harnessName
'MaskType' , 'Sigbuilder bfock' );
:
block blockNames{1};
pwmCnv 2. rJse thesignal-builder function to modi4r the block. This includes
adding, deleting, or modiS'ing groups and sþals. You can also change the
contrcller_ouþüt motor_inpub
t_
contrcller_ouÞut mot3._inputs
mo{or_¡nputs
active sþal group in the block prior to simulating the test harness.
Hamess lnputs
@ 2017 by The MathWorks, Inc. Verification and Validation of Simulink@ Models A-7
Appendix A: Automating Verification Activities
Simulink Test also ptovides a command-line intedace for working with test .Go. to th¿ ä\ q
m uIanK'l' eet subfoldet of &" .ffrolect.
files in the test manager. Some common commands are described below. :
L.
Creating test files
Jt,
#&. sltest . testmanager . TestFile
"l
@ 201,7 by The Math\X/orks, Inc. Verificati.on and Validation of Simulink@ Models A-8
Appendix A: Automating Verification Activities
You can m^îage model coverage settings and results using wr,I*TLAB code. Go to the lests\covera ¿.f ê sãb foltler bfi üe pfryE"t.,l
The typical command-line coverage workflow is as follows:
ü egvÍes rl :::
4. Perform your anaþsis using the coverage results vadable. Some examples
2. Define coverâge options using the test specificattonvanable. For example, include
to enable coverâge settings for all referenced models, use the syntax . Saving and loading coverage results to . cvt files using cvsave and
cvload.
. Viewing coverage results by generating an HTML report (cvhtml) or
To enable decision and condition coverâge, you cân use by highlighting the model (cvmodelview).
. Extracting information about a parttcular qpe of coverage. Some
example functions include de c i s i o n i n f o, c o nd i t i o n i n f o, and
mcdcinfo.
3. Execute the test case using thecvs im function and referring to the test
specification vadable. Coverage results from the simulation are stored in a
coverage results vatízlsle, which is passed from cvs im as the first ouþut. Create and modifii
CVteSt
test specification
Note The cvsim function allows the same property name - property
value pair arguments as the s im function. For example, the foliowing
-
syntax will simulate a model for 10 seconds and collect coverage.
ç
Simulate and return
CVS 1M
model coverage
t ffi
Process results
CVSAVC
cvhtmf
cvmodelview
decisioninfo
conditioninfo
@ 2017 by The Math\X/orks, Inc. Verification and Validation of Simulink@ Models ¡,-9
Appendix A: Automating Verification Activities
Simulink@ Desþ Verifi.er'" can help you to find test cases that fill covetage G'o to rhe tçet
gaps that might be left by manual testing. The process for doing this is
t
1. Define test objectives.
2. Test model and collect coverâge.
3. Use collected coverage as a starting point to automatic test generation. You can combine covefage results objects from multiple tests by adding them
together.
One way you can use preexisting coverage information as a starting point for
automatic test genetation is by using the command-line interface.
You can use the s ldvgencov function to generate coverage for a model. If you v/âflt to sâve a test harness with the generated tests, you can specify that
in an options structlrre (used as the second input argument).
To start with preexisting coverage, you can pâss a coverage results vanable
from cvsim as the fourth input to sldvgencov.
You can also obtain the coverage data of the tests genefâted by s ldvgencov
as shown below. You can then use the covetage results of the newly created
Note \ü/hen you close a model, the coverage results object becomes invalid, so test when you gerlerate a coverage report.
you must use it befote closing the model.
::::
}# edi,t
¡:;
ii
1,. Create a desþ verification options vanable. To do this, you can use the >> edj ::
4. IJse the sldvrun function to perform the analysis given the options
2. Configure the desþ verification task using the Mode property of the specif,ed.
desþ verification options vanable.
'PropertyProving' ,'
' DesignErrorDetection' ; To open the report at alater time, you cân use the Report property in
'TestGeneration' ; the f il-enames ouq)ut. Note that you can also set your own ouq)ut file
locad.on in s ldvoptions.
Note The default mode is TestGeneration. This is equivalent to
using sldvgencov as shou¡n on the previous page.
@ 2017 by The MathWorks, fnc. Verification and Validation of Simulink@ Models A-11
Appendix A: Automating Verification Activities
Summaty
. Authoring tests in MÄTI-AB
. Building harnesses progrâmmatically
. Automating test file creation and execution
. Collecting, repotting, and extending model coverage
. Scripting formal vedfication tasks
Appendix B:
lntroduction to Model Coverage
Verification and Validation of Simulink@ Models
3
I
.
@ 2017 by The Math\X/orks, Inc. Verification and Validation of Simulink@ Models B-1
Appendix B: lntroduction to Model Coverage
Outline
. Model coverage
. Model elements that receive coverâge
. Types of covetage
Model Coverage
Model coverage is used to determine whether cert¿in elements of models
have been firlly tested. This helps you determine whether your test câses âre
sufficient to vedfy a model.
. Simulink blocks
. States and tansitions in Stateflow@ charts
. M.{|LAB@ code inside MATI-AB Function blocks
. C/C++ code in S-functions
Ðecisions
iulCl.:f! å,! uÍìÌ 5üo/ò
false t0ll10l
il¿.i..erftkiu
j:i1,1ìJ1.0;
Statefl.ow C/C++
charts Condifioas S-functions
Ðeserþtion: Tr¡re False
5û 5i
@ 201.7 by The Math\){/orks, Inc. Vedfication and Validation of Simulink@ Models B-4
Appendix B: lntroduction to Model Coverage
Execution Coverage
Execution coverage is the most basic covetage metdc. Ä test case achieves fifl
coverage if every nonvirtual block in the model executes at least once during
the simulation.
rWhen coverage analysis for a model is enabled, execution coverage results are
always displayed.
Is every block
executed during
simulation?
Step
Inl tutl
Gain
Ernbbd Subsystern
@ 2017 by The MathìØorks, Inc. Vedfication and Validation of Simulink@ Models B-5
Appendix B: lntroduction to Model Coverage
\:.t t:
Decision Coverage (DC) Try
Decision coverage (DC) examines items thât represent decision points in a the
model, such as a Switch block or Stateflow@ stâtes. For each item, decision
coverage determines the percentage of the total number of simulation paths
through the item that the simulation traversed. n
^ctvalfy
T and F?
I
Path taken?
X
T if ().{ & Y)
AND
Z Z = L;
LogÍcaf Switch
Operator else
z -1 f
I
Path taken? end
A 201,7 by The Mathrü(/orks, Inc. Verification and V¿lidation of Simulink@ Models B-6
Appendix B: lntroduction to Model Coverage
Condition coverage anaþsis reports on each block in the model whether the
test câse fi;lly covered the block.
X
T if (x&Y)
AND
Z Z = L;
Logicat
Switch
2
ûperator else
z -1 f
1
T and F? end
@ 2017 by The Math!Øotks, Inc. Verification and Validation of Simulink@ Models B-7
Appendix B: Introduction to Model Coverage
Z
(x&Y)to (x&v)to
In the example on the right, the table shows that Logical Swii¿h
be T and F? be T and F?
Operator
three test câses are sufficient to achieve MCDC I
Y
covefage.
-t
. TT þoth inputs are true)
. FT (input 1 is false, tnput2 is true)
. TF (input 1 is true, tnput2 is false)
Input l required to be true if
if (x&Y)
TT
Note that the TT test case is sufficient to ensure that output is to be true z L;
both inputs arc affectjng the output to be true, since
Input l required to be false if
if either one changed, the output would change.
ouq)ut is to be false
FT else
Additionaliy, the FF test case is not useful at z -1
achieving any MCDC coverage, since in that case Input 2 required to be ttue if TT
f
output is to be true
either input could change and the ouq)ut would not
change.
end
Input 2 requited to be false if
ouþut is to be false
TF
@ 201.7 by The Math\Øorks, Inc. Verification and Validation of Simulink@ Models B-8
Appendix B: lntroduction to Model Coverage
.: .., .
Reiational boundaty coverage checks fot possibie outcomes thztate considered Open the followiog nrãdel, simelâteit,anéanq.þeu.;$letelationalb'oundary
to be near the edge of an equivalence test (::, ), (:, etc.). cover¿ge. Then, reduce the relative toleranee to 0 ¡,001- end comp.are the
tesults.
The table below summarizes the different outcomes for. an equality operadon
(::) depending on the data types of the inputs. The floating-point outcomes
are süghtly different depending on the type of relational operator being tested.
SineWave
LSB represents the least significant bit (or precision) of the fixed-point data Swilch 1
true. z.
Relational
-1 Operator
tol is computed based on absolute and relative tolerances, which can be intS
Floating-point Integer
relation relation
@ 201,7 by The Math\X/orks, Inc. Vedfication and Validation of Simulink@ Models B-9
Appendix B: lntroduction to Model Coverage
Note Thete is also a sþal size coverage, which reports the minimum and
maximum dimensions fot variable-size sþals.
a
Signal Rnnges
ConsTant
-1
b u2
e
1
ûut1
. . . Srryitch -1 1
Constantl
Lookup . . . f,snstnnt x1
Table {n-D}
u1 bre*kp*ints - [-t, -l
, ¡! hrêrkr1^ìnrq - l-)
. " , ümrstar¿tl -1 -r
-1
Sine Wave
.".$i¡r*\Vavr -0.996165 û.999793
Âmplîtude:
Sias: ü
1
.".$t*p t1
Lookup tabte (LUT) coverâge examines blocks, such as the 1-D Lookup Table simulate it, and analyze &e table co.rief?ge,
block, that output the result of looking up one or more inputs in a table of in tþle $enerated report. :: :
Lookup table coverage records the frequency that table lookups use at each
interpolation interval. A test case achieves full coverage if it executes each
intetpolation and extrapolation intemal at least once. For each LLT biock in
the model, the coverage report displays a colored map of the lookup table
indicating where each interpolation was performed.
Constant
lll]Ì1ilM
cond l d
(l!a*
Step
2-D I{u} Interpolation TO
liø¿ s. Switch u1
interval r- 10
u2
,Ø 1
Outl
11 -20
b
Constantl
Lookup
u¡ Jf
Table (n-D)
r4ñilun¡i5 - L-¿. - L U. I Ël
ilzl-30
Sine Wave
ul hreækpoínis - L-2. -1 , *, 1 21
Exact values ffi :t - 4s
Ân:plitude:
8îas: û
1
K >+o
Cyclomatic Complexity
Cyclomatic complexity is a measute of the structural complexity of a model.
It apptoximates the McCabe complexity meâsure for code generated ftom the
model. In genetal, the McCabe complexity meâsuÍe is slþhtly highet because
of erot checks that the model coverage anaþsis does not consider.
Model coverâge uses the following formula to compute the cyclomatic
complexity of an object (such as a block, chart, or state):
N
c ->(o"
1
-l)
In this formula, N is the number of decision points that the object represents
and oris the number of outcomes for the nù decision point. The tool adds 1
to the complexity number computed by this formula fot atomic subsystems
and Stateflov¡ charts.
@ 2017 by The Mathrü/orks, Inc. Verification and Validation of Simuünk@ Models B - 1,2
Appendix B: lntroduction to Model Coverage
Summaty
. Model coverage
. Model elements that receive coveÍâge
. T¡>es of coverage
@ 201,7 by The MathÏØorks, Inc. Vedfication and Validation of Simulink@ Models B-13
Appendix C: Exercises
Appendix C: Exercises
Verification and Validation of Simulink@ Models
@ 201,7 by The MathWotks, fnc. Verification and Validation of Simulink@ Models c-1
Appendix C: Exercises
Exercises
,4.11exetcise and solution files ate found in the ex subfoldet of the
C: \class\coursef iles\slvv folder created by the course installet.
@ 201,7 by The MathnØorks, Inc. Verification and Validation of Simulink@ Models c-2
Appendix C: Exercises
L. Generate â test harness from the cruise control model, using a Sþal 3. Crcate requirement links between the sþal grol]psin Sþal Builder block
Builder source block and a Scope sink block. Modify the test harness so and the spreadsheet. To do this, select Gtoup ) Verification Settings
both output sþals are displayed on one Scope block. from the Sþal Builder block menu. Then, right-click the Requirements
section on the dght and select Open Link Editor.
2. Load test câses from the cc_test_vectors. xls spreadsheet. To do
this, double-click the Sþal Builder block and select File ) Import from 4. For both test cases, simulate the test harness and visualize the resuits using
File. the Scope blocks.
<ædai_eq!iv_scaled>
AND
Cmdan! Logìcå¡
OÞe¡aid1
@ 201,7 by The MathWorks, fnc. Verification and Validation of Simulink@ Models c-3
Appendix C: Exercises
lfl Ê1e
Te*2
tI Vc!¡fidion bìod(
-1
o ve.ifiÉiio¡ b,o.16 file
1
-i.:
0.5
o
2
pedãl-."sffiled
0
-2
1
o ffi
!e,ed{ile lc inpoi
cc_rcdeLsln
lhe data fi,e to in¡a^ to $gnal 8ui¡dEi.
'cc_tèst_vêdcrt*s r¿¡s read
titeb Ìnpo* of viorishæìir .¡
âème{s):
tesll
¿üi rl.j--t,te'iì lii Test2
ffi
cc_14t_vBalort.Iis
B¿r,eis)ì
ped¿l_eaurv-råled
¡edê¡_{^led
ðng:e.saa:ed
lnputs
a0glê sæld
:1-t ¡:ee¿:-eq¡ìv-scaìed
tsasic Froperties
ii-i peia:-scaleo
i/] ¡Ìql¿-sc¿ted
Narn*: fc HETness
@ 2017 by The MathÏØotks, Inc. Verification and Validation of Simulink@ Models c-4
Appendix C: Exercises
In this exercise, you will create MATIAB scripts that define test cases for the
cc_scaf ar_inp and cc_bus_inp models. Details of the two test cases
ate shown below.
No No Yes Yes
0
I
I
10 0
I
I
^t
u I lu u
^t
| _LU
+ + --t- true
4
I
I
4 false I
I
true true 3 2 -2 -1
u
^I
I ru 0
I
I
5
I
I
10 u
^t
i ru 0
I
I
10
--+- + + --+- + fal se
4 4 fal se
I
I true I
I true -l^
Jtz -2
I
I -1
2. Cteate two MÄTLAB scrþts where each script defines one of the test cases Hint Fot bus input sþals, you can create â structure of time series
shown above for the cc_scalar_inp model. variables as shown below.
3. Test both scripts to make sure they work. For each test case, simulate the
model and view the results in the srgnal viewers.
pedal_equiv_scafed
rå 5:*dæå*se).äìe$ :.: 5:e$al*s,*.ä.å*,S. i......i data
! : l$;101 ; t - ls¡10]; 2
CC_Disabte
ri anç:å**s*;rl"**. er a*çtåæ*x*rale{å
t : :[s;1û] ; r : tG;1_ûl;
Conslant
u : [-2;-L3; 1l : [-2;-1]; 4
inpll = tineseríes{u,t} in¡r4 : tineseries du.rÈ),'
"' pedalscaled
data
* {l*-Såse}¡le t f { îlaqåhtê
4
CC Ðåsab1e = fa1se; CC-Ðîsablle : true; angle_scaled
ti -t.it:i .t:
@ 2017 by The Math\X/otks, Inc. Vedfication and Validation of Simulink@ Models c-6
Appendix C: Exercises
In this exercise, you will cteate a test harness for a room temperâture controller.
This controller implements the following des:
To test the control algorithm, take the following steps.
. If the room temperâture is greater than dT degrees above the seçoint, then
enable the cooler (heat_input heatingModel.
1. Open the model Crezte ¿ test harness for the
-1). Temperature Control subsystem using the following options.
. If the room temperature is less than dT degrees below the setpoint, then
enable the heater (heat_input 1).
' IJse a Test Sequence source block and no sepârâte assessment block.
. Modify the Test Sequence block such that it is in an open-loop
. Else, do nothing (heat_input 0). configuration, i.e., it has no inputs.
' Ensure that users cânnot modify the component under test inside the
test harness.
T_e*
2. Impiement the following test case in the Test Sequence block
TffipèÊ!æ
.IntrtaLz,e the test so that both desired temperature (T_des) and room
Ereretlêmgeøt!æ temperature (T) have a value of 6 0.
70 hsil€ Tea@tre
. r\ftet one second, transition to a step named CoolDown, which sets
Dæired
H HddhÂd
T_des to 56.
'Âfter three mote seconds, transition to a step named HeatUp. This
should have two substeps. The first substep should execute only once
and instantaneously changes T_de s to 6 0. The second substep should
condnuouslyincrement T_des by 1.
. Once T_des exceeds a p^r.^metet Tmax, transition back to the
J
CoolDown step.
ii,
sþals. Try modiftrng the values of dT and Tmax in the base workspace
and compare results.
@ 201,7 by The MathìØotks, Inc. Verification and Validation of Simulink@ Models c-7
Appendix C: Exercises
Ì -L ':.
>i i:
T-des
Ff
rl h€aT inpu¡
I rrri' l: i il i
Cannot edit
subsystem
inside test
1
harness. ììi
heaL¡nput
a'ì
Cfftrol I Enable compo*ent editinE in harness nnadel
T_des = 56;
Rampl-leat
T des = T_des + 1.
@ 2017 by The Math\)7orks, Inc. Vedfication and Validation of Simutink@ Models c-8
Appendix C: Exercises
':¡¡ l
.l=i a,t - ,.;,4
Reference: Chapter 4 CI@the Sírnulækprojeø tn the ex\etc folder.
Topics: Sþal l"ggog and comparison ,L]'
">> etc
In this will use the Simulation Data Inspector to inspect sþals
exercise, you
and compare runs in a throttle control system model.
4. Open the Simulation Data Inspector and petform the tasks belov¡.
1. Open the Simulink project in the ex\etc folder. Then, open the etc . Plot the angle_integer sþals in the same figure. Which of the
model. runs reaches the angle saturation upper limit?
2. Configure the model to 1og the bus sþals at the input and output of the . Find the differences in the controller ouq)ut sþals (duty_scaf ed
Controller Model block. and di rect ion_s caled) betweefl. runs.
3. Record the simulation ouq)ut and simulate the model with the following 5. (Optional) Try inspecting and comparing logged sþals and runs. lJse the
controller p arameters : Create Report option to automaticaþ generate reports fiom your results.
cc_orfp$ts
Log sþals
Cru,sêContaûl
coFrkoÌþr
dúl_a¡aþg dtu'ty_aãbg
Sqnãl 1 pedal ìúlts
L p€dal_vdts da_i¡pr.¡t ängle_mfts
a2d*or{pl-{
a2d_outprrt dire¿tkh_ãna@
arEle_vÕlts
Pedallrçut
B . Fodúf Eûl pÐlsed
Contrdlêr DigitêJ2,4¡alsg Throttle
AnalogaDis¡[al
'ì - Fe{i¿i} lùlfy iXdtr¡",¿rùJ] i Sr if.w ;¡ ç: I iiiì riiii# íÀi B ¡r ii-.,f ärÞj f H¿rd'**r"€ - ph¡sir:rzls,1:l;ari
FÍiKYiÊ-d ii.lÌrld¡r;ïè i s]í|,'yåre jnierl*öÈ]
@ 2017 by The MathWorks, Inc. Verification and Validation of Simuünk@ Models c-9
Appendix C: Exercises
Bù¡ iiË?lûil.ä3d*ü!1Fìlì-ÍrËflal-i[lÉ9qt
- l?ür ¡: êtû
Ëûs Ð,êãl¡.:1.r:d-ûrirul.þûdê¡_ìËleücr
Bçs ¿rËë,1ür:'i.d'Ëuþüh.wL õrt ¡
BuÈ útÈ¿loÍl c ! 1f
t919çliÉr.l.dkf¡:sæ,é¡
v Ruñ f: Bir:
-
U Simul*Èir:r-r ünt.o i*spertr*r
åìJ: Ê1È?tôi-Ì
tioif o Jier :.direal;ot_ìcäf çd
ii
5¡
t
¡ñð ñcom$içx*re Ê-llgçinq,". ] t 1i)
]
dä¡1 l-åelp,."
t
In this
T 3T¿¿r*tolxT
T 2Tasr-tol*T
. Stop the simulation with erÍor if the analysis cntern are violated.
^fl
3. Simulate the test harness with tolerance values of 5% (tol : 0 . 0 5)
and 10% (tol 0. 1-) and compâre the results.
T ext
If the tests fail, can you find a value of the dT p^rarr.eter such that the
T_ext heatingVeriiStart
requirements are met? From Workçace T ext
1
T des T Temperafure
T
70
T des
A 201,7 by The MathWorks, Inc. Verification and Validation of Simutink@ Modeis c-1.1
Appendix C: Exercises
The scope output on the right shows the analysis results for a L00/o relative
toletance.
The test passes with a 1.0o/o rcIaave tolerance but fails with a 5o/o relaÛve Tæst
tolerance unless you reduce the value of dT to about 1 . 5 or lower. ,Þ
Relative
Tolænce Upper Lmf
T_ext +..........._
.¡n ffitrËJ ìíi. iit
T_er{ heat¡ngvsìfSoln ì elt'r¡.'i:l'.3i irr e 1.-il il'i: i :. :l r .. .t'.'. 1...ì¡ r-ìll
Frw Wo*spaæ T_ql Su!Êract
T sg
I des f TempeËfute
Check
Ðymmic Range
70
T_des
¡¿
Assessment
Tmax=T*des+retTol.ï
assert{T {= Trnax.'[v{*xirnçra T*nrperæt*r* Fx*ææded') ;
*r 'l*nip*ri:i,;r*
Ut!F€r.Lìiliit
Lr:,,,1.Èa Lim¡l
Tmin=T_des-relTol-X i:i 'i
assertff >= Tmin, 'Minim¡¡m T*rnpær*ture Hx*e*d*d');
7A 2
UpperLinil
fmax
Teg Sequsce
@ 201,7 by The Math\Øorks, Inc. Verification and Validation of Simulink@ Models C - 1'2
Appendix C: Exercises
Reference: Chzpter 4
Topics: Test harnesses, Model coverage ':,1::
heaÈi c
In thisexetcise, you will collect coverage information from an existing test
harness for a room temperâture controller model.
H
T
l_des
¡-t 1
T hea{_input
-t
TeS Sequence
Fu1l coverage?
@ 201,7 by The Math\)7orks, Inc. Verification and Validation of Simulink@ Models c-1,3
Appendix C: Exercises
this: F
2
åivitch
. The desired temperatrúe T_de s is never below Rate
0fi
In this exetcise, you will create a test file that leverages eústing test cases for a
cruise control model. To do this, take the foliowing steps.
3. Cteate another test suite that runs the cc Harness test harness in the
1. Open the test m^n^ger and create a new test file.
cc modef soln model.
. Configure the test case to run the Testl Sþal Builder group in the test
2. Create â test suite that runs the cc scalar soln model using two
harness.
different sirnulation test cases.
. The írtst test should execute the testl_scalar_inp scrþt prior to ' Make sure the test is a baseline test, whose ouq)uts are compared to a
baseline stored in the ccExpectedOutputs . mat file. This file can
simluating the model.
be found in the ex\cc_test_suite folder.
. The second test should execute the test2 scalar inp scrþtprior
' Use an absolute tolerance of 0 . 0 01 and telative toletance of 0 . 01
to simulating the model.
(70h) for all sþals except the on_of f sþal. Since this is a Boolean
. The cc_scal-ar_sol-n model is not configured to produce any (logical) sþal, setits tolerances to zero.
output data. For. both tests, override the model settings such that ouq)ut
4. Run the test file and explore the results. Generate â report, ensuring to
data is produced.
include results and plots from all tests þassed and failed).
Test
te st 1_s calar_inp
ccExpectedOutput s . mat
@ 2017 by The Math'ü7orks, Inc. Verification and Validation of Simulink@ Models c-15
Appendix C: Exercises
rìiIì,:
The baseline test fails because the cc_outputs. on_of f sþal becomes
lr{rdâli f,i-sìålär*s*lü tïue at a different time than in the expected results. This affects the value of
the a2d_scaled_cc. pedal_scaled sþal, which is why that baseline
Y lir::-"
w iii.r ii:'1..
i, ::;.i',f.]
comparison fails as well.
n
it:- s:autFu¡Ê sr_ùl
ç r r:, i: $¡i1! ì:þi L n¡ÍrÊ¡aè lf TslårarcÐ
i: a2d.sealed_m.pedal_sca..
, g SiÀuf"Or"l"utZ
: Så\'€ b3s*ìifte date in :sst rs*¡llt
;1,Í.ì -'Í... Å -1
5 3 4 ? !
''.,''., 4 4!;al
tr_üutpill$.ú11_sfi ü ü .Jlt?;
Ådd.." lf ,CsptürÈ..
@ 2017 by The Math$Øorks, Inc. Verification and Validation of Simulink@ Models C - 1tr
Appendix C: Exercises
1. Open the Simulink project in the ex\etc folder. Then, open the etc 5. Run the test case and atalyze the results.
model. . View the a2d_output.pedal_integer and duty_scaled
2. Configxe the model to log the bus sþals at the input and ouq)ut of the sþals for all iteradons on two separâte subplots.
Controller Model block. . View the aggregated covetage results and find the blocks with missing
3. Create a test file consisting of a simulation test which runs the etc model covefâge.
using the following pârâmeter sets: 6. (Optional) Generate â report ftom the test results.
cc ouþr.rts
Log signals
Crui,sêContrù¡
coñtrûller
dr.ùl_anaf¡E du¡l_anãbg
Sltnãl 1 pèdaLvúlts
----¡
p€dat_vdts da_nput dZLinpul angk-r¡ofis
Pedal lnpuf
Contrdler D¡g,taizArlalog Tlrrottie
tl .. l"oda! pÕl preDsûd Affilog2tlgital
'1
- FÊ{:!å} iìrIT Fri*,r{."{l {Ërfl!r.¿r*} isüf1yri$* i i'r.* r d,",/ âi* in ierlâ cÊJ {f-ià¡d'¡r*íe.. ph,isir¿ìi s{silÈr¡i
{11*rdaar+ i sritur'ar€ ii':?årfär:e}
@ 201,7 by The MathrJØorks, Inc. Verification and Validation of Simulink@ Models c-1.7
Appendix C: Exercises
Select the bus sþa1s at the input and output of the Controller Model block - $l ri$i[1Í i.ii!i--1!i"l iÍ]l i
¿nd select the Log Selected Signals option as shown below.
Itl¡:del nrlñry
t i.¡ri:il l- ir$lìilifL
) a i f ,i: rì l.4ll i,:lti rli: l-* ì lri ti'* t-': I ËÉÊ ì I ãf
-, iParamsierset2
J i.l5 bax* vr'orltgFa;e ütl¡lßñlrc: :Ët
1#,tl
*.q** - ff R*fre*h ìil E:spsÍt ffi' ú*t*t-"
- 1,ù*iã ìrËlATìir !ì
T i#i l:l;:iíÌ +
I rnË¿rF-.-ãî Íiìïå1È..
fu Confiqr¡ne Lcqqinq.". 1
J:lt*rübûn Farsmètãr Ssl i lisiåsiii
",r'.;irrr
Jitt*rsti*nt Prr,rnelilr Ssl 3 .:l rti". ij
"':'ftç
Jìneråti¡nr Faran*lsrSxt 3 iÍsib;iii; #ï¡ìt'
At the test fi.le level, go to the Coverage Settings section and enable the
options shown below.
w.å2i_sritiu:.Êëú¿l,i¡ìsger * ¿3ii_îsÞ!tinðie_inþçer
L¡2C_alit'!r.¿r!lÊ*i¡tÈger îi .à:,ì_rüEul êf qiÈ_iîtegËr
- ç*'ì
elÈPa¡a¡nSv¡seF" *Ì*F*r*nrSr,ve*p - Ræults; 2Ëîâ'\1ar44 BfD6:&0
¡ I ã :.
,:.irì:'ü!;.:r-ri' i',.: !
' .ìf:tì..ì. !., .'
riùìr_s¿åled i .dutr_stsiêd s.drt/-x3:èd t.c!it_sa's'J
3
¡ I è Ê
@ 2017 by The Math\)üorks, Inc. Verification and Validation of Simulink@ Models c-1,9
Appendix C: Exercises
: l. ,,::::1"::'
:t, ,,
Reference: Chapter 5
,SPtn &e Simulink ¡rtoject
Topics: Test files, Equivalence tests
Hint The models are not configured to ouq)ut data to the base
The default datatype for these blocks is f ixdt (L, L6, 10 ) , which is a
wotkspace. Before running the tests, make sure you enable data logging
for the a2d_output bus sþal in both models.
sþed 16-bit data value with 10 fractional bits. Tty increasing the numbet
of fracional bits to f ixdt (L,76,12) and compâre the results.
a2d_ortput
C¿nr¡ert
a2d_output
angle-votls
<pedaf saþd>
Analog2Digital
il"lsrdwer* 1 s*ftvç* r* intrerfac* j
Tyæ CcElvers¡en1
@ 2017 by The Math\ü7orks, Inc. Verification and Validation of Simulink@ Models c-21
Appendix C: Exercises
Create a simulation test and use the following models in the Simulation 1 aod Gã toùe tesès subfàldäc öf
Simulation 2 sections. ,. :i,
,
After enabling 1"ggog fot the a2d_output sþals in both models, you cân
Rerll¡ tr
i-r' a2d-ù!ì Þul Þed;ìlinìeg€r i:
capture these sþals in the Equivalence Criteria section as shown below. ,S: ú*_elput ãrgle-iñtÊgø :1 ¡ i¡
1.0 fracttonal
/' :: *ì"'t:
' ":ri;'1-
J â2d_0rrlput.p+rlal_i *teç*r : UJ'/ð
bits - Fail
/ å.:l_Õúlpijt..an.!lle_¡nlËgs r
ilF ÐsÞlr¡e..
ffisurla¡e r fiÇæparison r
* ?_ir{ete. iB*sel
The diagrams to the right show the equivalence crìteria results fot 10 fncttonal 9: C_È uiF u:.¿nÐl ine i
, ìi c?rìEq6,15s]n
Note that the increased precision makes the equivalence test pass. r i ll Fi^Ëd rË Fle€tinù-Pcinì CùnìÞ¡lèr
¡ tl ÊÈuìYåleñ.è -¡*t
¿ À tqu "¡ ente *les¡ rcsull
i:' a2c_aÈtpul pe¡àLintêgÊ¡
9:
ii ê3d-oulrut elgle-intÊger
I aife.g¡sÊ i r=ü'eraeae
' [i
Srñ ifrÌtpüt 1 têit ] nomal,l
) Ei SinÐslËul 2 lel._v2 : nomul)
1,2 ftacttonal
a;
bits - Pass
rTrX
a:
In this exercise, you will collect model coverage from an existing group of tests.
Then, you will automatically generate tests with Simulink Desþ Vetj.fi.er'" to
ptovide any missing covetage
3. Simulate the test harness with both sþal groups in the Sþal Buildet block
1. Open the cc_testgen model andnavtgate to the cc_Harness test and collect cumulative coverage. Ensure the coverage information is saved
harness. to a file.
2. Configxe the test harness to collect coverage information, such that 4. From the cc_testgen model, use Simulink Desþ Verifier to generate
tests that filIin the missing coverage. How do the generated tests differ if
. Decision, condition, and MCDC coverage are collected.
you do not use the generated covetage file?
. Coverage information is collected for the cc testgen referenced
model only.
cc oLûpds-pda,_@un_sc¿þd
cc_oillpúls_on_of
t_
lnpub
AND
p€dalscabd
Test
Logícal azd_scaled_cc
Switch a2d_scaled_cc
Ope€td CASCS
Coverage cc_d¡sble
NOT i:¡ilerìe
Âiñ^^!
-fu
1
r lr¡Jssirf¡
'ra -: ñ
file Operatø1
<pedalscâbd>
<dgle-scâled> f
SêtrEtiú
-5 <-_ u .:= 5
@ 2017 by The MathnØorks, Inc. Verification and V¿lidation of Simulink@ Models c-23
Appendix C: Exercises
First, configure the coverage settings in the cc_Harness test harness. s'o
Þ Other n¡etrics
t
¿
à Two test
0
-5 objectives
-'1û
Simulate all test cases in the harness and save the cumulative coverage to a fi,le. I
ftq
To do this, you cân use either the Coverage Resuits Explorer or the automatically t
0 û.üû5 û.s1 ü.ü15 U,U¿
generated coverâge file based on settings in the Covetage ) Results section Tirne {s*c}
of the Model Configuration Parameters dialog.
Finally, set up the cc_testgen model so its generated tests extend the
t ¿c"-euïpr.äiÊ. ped.ai-eq *rv
-1
coverage data you just collected. "2
1
û.s
0
0 ñ n.1 û,t: t.$3 0.t4 t.ü5
Time lsec)
Try
In this exercise, you will use Simulink Desþ \rerifier to test the ciuise contiol
system using formalvenficai-lon instead of test cases.
3. Place the newly added blocks in aYenltcation Subsystem block.
1. Open the cc_prove model. Check that it is compatible with Simulink
Desþ Verifier and make any necessary modifications if it is not. HintMake the inputs to this block the cc_outputs and
a2d_scaled_cc sþals, and extract sþals using Bus Selector blocks.
2. lJsing Proof Objective blocks, prove the following properties about the
model. 4. Ptove the model propeties. If any of the objectives are falsif,ed, view the
counterexâmple using a teport or test harness. Can you add any assumptions
Objective 1:
to the model to change the results?
Thepedal_scaf ed sþalin the
a2d_scaled_cc bus is always
between -5 and 5.
Obiective: Obiective:
Objective 2:
If on_of f is true and on_off : true pedal_scaled always
CC_Disable is false, this implies between -5 and
and 5
that the pedal_scaled sþal in
the a2d_scaled_cc bus is equal
CC Disable : false
to the peda l_equiv_s ca l- ed
srgnal in the cc_outputs bus.
implies
AND
pedaì sæld
Logica¡ a2d scabd cc
a2d sâlêd cc
NOT
Opsâtor
j T
angþ scaled
Saiuration
@ 2017 by The Math\)Øorks, fnc. Verification and Validation of Simulink@ Models c -25
Appendix C: Exercises
,t
CC Disable NOT
As the counterexâmple below shows, this can occur when the
AND
Constant LogÌcal on_of f srgnal is üue (i.e., cruise control is enabled), and the
Logical
0perator'1
Operator pedal_equiv_scaled sþal is outside the objective rânge.
A
A:> B (lomnterexnmple
<on_ofÞ tt
cc_oulputs lmplies
Time û
Lq Ã,!
Step I
L e *:
cc_outputs.pedal_equiv_scaled -6
<pedal scaled>
a2d scaled cc Relãt¡onal Operator cc_CIurputs.on_off 1
¡ND tvvl
pedaÌ_scaled
tìlr.;¿ir
t¡$æl Switch a2d_eald_cc
cc Сsble NOl Operator <pedalequiv-scabd>
cc_oulputs <on_off>
In this exercise, you will use Simulink Desþ Verifier to detect vadous desþ
errors in a model.
Modi$ the Minimum and Maximum pârâmeters in the input ports such
that integer overflows and division by zerc are not possible.
1
Hint The minimum and maximum values for uint B data arc 0 and ln1
f,s6âûi.! jinÌite: 4\
2 5 5, respectively.
Constânt Subtract
4. Detect dead logic in the model ?*sÇn limits.
tf-] tq{1
Modift the Saturation blocks in the model to remove any deadlogic you X
may find.
2
ln2
3Ê5çfl !im:ts: Add
f Divide
double
Data Type
-{
Saturatío¡1
1
Outl
Saturation
îü 2t5t nesi?n lirîìits: les¡gn:im¡tsi Conversion l-ztt..z*tl
li¡ l))J
I
2
Unit Delay
A 201,7 by The MathìØorks, fnc. Verification and Validation of Simulink@ Models c-27
Appendix C: Exercises
The model contains integet ovetflow and division by zero defects. The reasons
for these defects are
. If the fust input is less than 1,5, there is negative integer overflow.
Changing the minimum value of the second input to 1 means that the lower
. If the second input is greater thzn 1.28, adding the ouçut of the Unit Delay limit of the Saturation blockwill nevet be reached. This will thetefore
block (which can be as large as 127) may lezd to positive integer overflow. cre te dead logic in the model.
. If the ouq)ut of the S at u r at í on block is exactly 0, there will be a division In addition, the Saturationl- block also contains dead logic because the
by zero. value of a uint B sþal can never be negative.
uint8 uinlS
+ 1 t
u¡ntg
tnl ln1 u¡n18
lesíqfi limilå: 15 tes¡g* i¡rl1rÍs:
f
uin8 uintg
2 +
f 6 X
!
ü¡,{de
double
f 1
Outl
2
ln2 f
X
g
D¡vide
dÐuble
Outl
Saturatiôrì Ðata ïypÊ Satural¡øì1 lJesql;fm;ts Add Sãturâtìùn
nËs¡ç-rì linÌils: çonveßion
¡U:1tr.I Conversion DËsiçn ltllits: tft .',aa
rn )qql
l 1
uìnt8 z uìn6 z
Un¡t Delay Unil Delay
255, You can resolve this by changing the lower limit of the Saturation block
You can resolve this by constaining the first input to be between 1,5 and
and by constraining the second input to be between 7 and 1.28.
to 1, and by changing the lowet limit of the Saturationl block to 0.