• Nenhum resultado encontrado

Simulation of hybrid systems from natural language requirements

N/A
N/A
Protected

Academic year: 2021

Share "Simulation of hybrid systems from natural language requirements"

Copied!
94
0
0

Texto

(1)

Bruno Medeiros de Oliveira

SIMULATION OF HYBRID SYSTEMS FROM

NATURAL LANGUAGE REQUIREMENTS

M.Sc. Dissertation

Federal University of Pernambuco posgraduacao@cin.ufpe.br www.cin.ufpe.br/~posgraduacao

RECIFE 2016

(2)

Bruno Medeiros de Oliveira

SIMULATION OF HYBRID SYSTEMS FROM

NATURAL LANGUAGE REQUIREMENTS

M.Sc. Dissertation presented to the Center for Informatics of Federal University of Pernambuco in partial fulfillment of the requirements for the degree of Master of Science in Computer Science.

Advisor: Augusto Sampaio Co-Advisor: Gustavo Carvalho

RECIFE 2016

(3)

Catalogação na fonte

Bibliotecária Monick Raquel Silvestre da S. Portes, CRB4-1217

O48s Oliveira, Bruno Medeiros de

Simulation of hybrid systems from natural language requirements / Bruno Medeiros de Oliveira. – 2016.

93 f.: il., fig., tab.

Orientador: Augusto Sampaio.

Dissertação (Mestrado) – Universidade Federal de Pernambuco. CIn, Ciência da Computação, Recife, 2016.

Inclui referências e apêndices.

1. Engenharia de software. 2. Engenharia de requisitos. 3. Sistemas híbridos. I. Sampaio, Augusto (orientador). II. Título.

005.1 CDD (23. ed.) UFPE- MEI 2016-148

(4)

Bruno Medeiros de Oliveira

Simulation of Hybrid Systems from Natural Language Requirements

Dissertação de Mestrado apresentada ao Programa de Pós-Graduação em Ciência da Computação da Universi-dade Federal de Pernambuco, como requisito parcial para a obtenção do título de Mestre em Ciência da Computação

Aprovado em: 05/09/2016.

BANCA EXAMINADORA

———————————————————————– Prof. Dr. Juliano Manabu Iyoda

Centro de Informática/UFPE

———————————————————————– Prof. Dr. Eduardo Henrique da Silva Aranha

Departamento de Informática e Matemática Aplicada/UFRN

———————————————————————– Prof. Dr.Augusto Sampaio

(5)

I dedicate this thesis to my parents and professors who gave me the necessary support to get here.

(6)

Acknowledgements

I would like to thank Professor Augusto Sampaio, my advisor, for his guidance, and motivation and for providing the opportunity to work with him. He has been instrumental in bringing me to the field of Formal Methods and Testing and I am glad I got the chance to work with him.

I would like to thank Gustavo Carvalho for being on my thesis committee and providing invaluable advice and support in so many ways over past two years. Without his early coaching and enthusiasm none of this would have happened.

Finally, I would like to thank my parents who have been so close to me that I found them with me whenever I needed. It is their unconditional love that motivates me to set higher targets.

(7)

Far better is it to dare mighty things, to win glorious triumphs, even though checkered by failure... than to rank with those poor spirits who neither enjoy nor suffer much because they live in a gray twilight that knows not victory nor defeat.

(8)

Abstract

Despite technological advances in the industry of systems development, testing is still the most commonly used verification method to ensure reliability. Model-based testing (MBT) techniques are principally employed for the purpose of generating test cases from specification models. Contributing to this branch of research an MBT strategy for creating test cases from controlled natural language (CNL) requirements was created, called NATural Language Requirements to TEST Cases (NAT2TEST). The NAT2TEST strategy deals with data-flow reactive systems, a class of embedded systems whose the main feature is to have the inputs and outputs always available as signals. However, there is a demand from the industry to to apply the strategy in the context of hybrid systems. These systems are a fusion of continuous dynamical and discrete dynamical systems, that is, they combine dynamical characteristics from both continuous and discrete worlds. Hybrid systems have received much attention in the last years. The main contribution of this work is to extend the NAT2TEST strategy to deal with hybrid systems. Using the new proposed approach, it is possible to write the requirements of a hybrid system, whose semantics is characterised based on the case grammar theory. Then, a formal representation of the system is built considering a model of hybrid data-flow reactive systems. Finally, to analyse the system behaviour via simulation, a modelling environment for simulation of hybrid systems was used, called Acumen. Thereby, a specification model in Acumen is generated and simulated in this environment. The characteristics of the new approach are exemplified using two examples, one belonging to the electronic field, the DC-DC Boost Converter (BC), and the other belonging to the automotive domain, the Adaptive Cruise Control (ACC).

Keywords: Hybrid systems. Model-based testing. Controlled natural language. Case grammar.

(9)

Resumo

Apesar dos avanços tecnológicos na indústria de desenvolvimento de sistemas, testes ainda é o método de verificação mais comumente usado para garantir confiabilidade. Técnicas de testes baseadas em modelo (MBT) são empregadas principalmente com a finalidade de geração de casos de testes a patir de modelos da especificação do sistema. Contribuindo para este ramo de pesquisa, foi criada uma estratégia MBT para a criação de casos de teste a partir de uma linguagem natural controlada (CNL), chamada de NAT2TEST. A estratégia NAT2TEST lida com sistemas reativos de fluxo de dados (DFRS), uma classe de sistemas embarcados cuja principal característica é a de terem as entradas e saídas sempre disponíveis como sinais. No entanto, há uma demanda oriunda da indústria para a utilização da estratégia no contexto de sistemas híbridos. Estes sistemas são uma fusão entre comportamentos dinâmicos e discretos, isto é, que combinam características dinâmicas de ambos os mundos, contínuo e discreto. Os sistemas híbridos têm recebido muita atenção nos últimos anos. A principal contribuição deste trabalho é estender a estratégia NAT2TEST para lidar com sistemas híbridos. Utilizando a abordagem proposta, é possível escrever os requisitos de um sistema híbrido, cuja semântica é caracterizada através da teoria de gramática de casos. Em seguida, uma representação formal do sistema é construída considerando um modelo DFRS para sistemas híbridos. Finalmente, para analisar o comportamento do sistema, por meio de simulação, um ambiente de modelagem e simulação de sistemas híbridos foi usado, chamado Acumen. Com isso, a estratégia proposta gera um modelo da especificação em Acumen e esse modelo é simulado no ambiente. As características da nova abordagem foram exemplificadas usando dois exemplos, um pertencente ao o campo eletrônico, o DC-DC Boost Converter (BC), e a outra pertencente ao domínio automobilístico, o Adaptive Cruise Control (ACC).

Palavras-chave: Sistemas híbridos. Testes baseados em modelos. Requisitos. Linguagem

(10)

9 9 9

List of Figures

1.1 An overview of the model-based testing process . . . 16

1.2 Phases of the NAT2TEST strategy . . . 17

1.3 Phases of the hybrid NAT2TEST strategy . . . 18

2.1 Thermostat model – an example of a hybrid system . . . 26

2.2 Example of the behaviour of a thermostat . . . 27

2.3 Two-phase system . . . 27

2.4 A resistive circuit . . . 28

2.5 Flow control valve . . . 29

2.6 Boost converter . . . 32

2.7 Boost converter automata . . . 33

2.8 Graphical user interface of Acumen . . . 35

2.9 Order of evaluation . . . 38

3.1 Thematic roles from a requirement . . . 43

3.2 Syntax tree obtained for a requirement of a hybrid system . . . 45

3.3 User-defined functions . . . 47

3.4 Requirement frames obtained from a requirement of a hybrid system . . . 48

3.5 Variables defined from the DFRS of the running example . . . 48

3.6 Functions defined from the DFRS of the running example . . . 49

3.7 Running example simulation . . . 53

4.1 Requirement frame of REQ001 . . . 57

4.2 Requirement frame of REQ016 . . . 57

4.3 Screen of the Data-Flow Reactive System (DFRS) . . . 58

4.4 Simulation of the Acumen model obtained for the boost converter . . . 58

4.5 Simulation of the Acumen model obtained for the boost converter (2) . . . 59

4.6 Mechanisms of a vehicular speed control . . . 59

4.7 A state machine for an adaptive cruise control system . . . 60

4.8 Requirement and requirement frame of REQ010 . . . 62

4.9 Screen of the DFRS . . . 63

(11)

10 10 10

List of Tables

2.1 SysReq-CNL – a grammar for system requirements . . . 21

3.1 Part of the extended SysReq-CNL: – representing expressions . . . 41

3.2 Part of the extended SysReq-CNL: functions . . . 41

5.1 Tools analyzed . . . 69

(12)

List of Acronyms

ACT Action . . . 22

AGT Agent . . . 22

CF Case Frame . . . 22

CAC Condition Action . . . 22

CFV Condition From Value . . . 22

CMD Condition Modifier . . . 22

CNL Controlled Natural Language . . . 20

CPT Condition Patient. . . .22

CTV Condition To Value . . . 22

DFRS Data-Flow Reactive System . . . 15

s-DFRS Symbolic Data-Flow Reactive System . . . 23

e-DFRS Expanded Data-Flow Reactive System . . . 23

NAT2TEST NATural Language Requirements to TEST Cases . . . 15

h-NAT2TEST NATural Language Requirements to TEST Cases for hybrid systems . . . 17

h-DFRS Data-Flow Reactive System for hybrid systems . . . 39

PAT Patient . . . 23

SUT System Under Test. . . .15

TOV To Value . . . 22

TR Thematic Role . . . 22

RF Requirement Frame . . . 23

SysReq-CNL System Requirements Controlled Natural Language . . . 20

BNF Backus-Naur Form . . . 50

CPNs Colored Petri Nets . . . 44

XML Extensible Markup Language . . . 50

ACC Adaptive Cruise Control . . . 19

BC DC-DC Boost Converter . . . 19

MBT Model-Based Testing. . . .16

(13)

CSP Communicating Sequential Processes . . . 17

SCR Software Cost Reduction . . . 15

IMR Intermediate Model Representation . . . 15

QAS Qualitative Action Systems . . . 67

SDL Specification and Description Language . . . 67

CPSs Cyber-Physical Systems . . . 68

ODE Ordinary Differential Equations . . . 34

IMR Intermediate Model Representation . . . 15

(14)

13 13 13

Contents

1 Introduction 15

1.1 Research question and contributions . . . 17

1.2 Thesis structure . . . 19

2 Problem background 20 2.1 The NAT2TEST strategy . . . 20

2.1.1 Syntactic and semantic analysis . . . 20

2.1.2 Generation of data-flow reactive systems . . . 23

2.2 Hybrid systems . . . 25

2.2.1 Definition of hybrid systems . . . 25

2.2.2 Hybrid system representation . . . 30

2.2.3 DC-DC Boost Converter . . . 31

2.3 Simulation . . . 34

2.3.1 Acumen . . . 35

3 NAT2TEST for hybrid systems 39 3.1 The SysReq-CNL grammar for hybrid systems . . . 39

3.2 Semantic analysis of hybrid-system requirements . . . 42

3.3 Hybrid data-flow reactive systems . . . 43

3.4 Evolving the NAT2TEST tool . . . 44

3.5 Generating Acumen specifications . . . 50

3.5.1 From hybrid DFRSs to Acumen models . . . 50

3.5.2 Simulating the generated Acumen model . . . 53

4 Application of the h-NAT2TEST strategy 54 4.1 A DC-DC boost converter . . . 54

4.1.1 Writing the system requirements . . . 54

4.1.2 Inferring thematic roles . . . 56

4.1.3 Generating hybrid DFRSs and Acumen models . . . 56

4.2 Adaptive Cruise Control . . . 59

4.2.1 Writing the system requirements . . . 60

(15)

4.2.3 Generating hybrid DFRSs and Acumen models . . . 62 5 Conclusion 65 5.1 Related Work . . . 65 5.2 Future work . . . 70 References 72 Appendix 76

A SysReq-CNL for hybrid system requirements 77

B Acumen EBNF 79

C The DFRS representation in XML 81

C.1 The DFRS of the DC-DC Boost-Converter . . . 81 C.2 The DFRS of the adaptive cruise control . . . 86

D Acumen representation of DFRS models 91

D.1 The DFRS of the DC-DC Boost-Converter . . . 91 D.2 The DFRS of the adaptive cruise control . . . 92

(16)

15 15 15

1

Introduction

The competitiveness of the market together with the need for software reliability led to the creation of automatic techniques as alternatives to the traditional approach of manual testing, especially, because the most common verification method in the industry is still testing. In this context, model-based testing was devised (MODEL-BASED TESTING IN PRACTICE, 1999).

This strategy involves developing and using a specification model to generate tests. This model encodes the intended behaviour of an implementation, known as, System Under Test (SUT). Test generation can be especially effective for systems that are vulnerable to changes because it suffices to modify the specification model and then rapidly regenerate an updated test suite (MODEL-BASED TESTING FOR THE SECOND GENERATION OF INTEGRATED MODULAR AVIONICS, 2011). Examples of systems testing using MBT include avionics (MODEL-BASED TESTING FOR THE SECOND GENERATION OF INTEGRATED MODULAR AVIONICS, 2011), automotive (ZANDER-NOWICKA, 2008), control, medical, military, and manufacturing systems (MODEL BASED TESTING USING SOFTWARE ARCHITECTURE, 2010).

It is important to consider that the model can be written in several modelling languages and, thus, different techniques can be adopted to generate test cases. For instance, one might derive execution traces from the specification model, and then use these traces to gen-erate test cases for the SUT: a sequence of input and expected output actions (ZANDER; SCHIEFERDECKER; MOSTERMAN,2011). The NATural Language Requirements to TEST Cases (NAT2TEST) strategy, for example, take as input textual requirements and translates them into an internal representation model named Data-Flow Reactive System (DFRS). This model is translated to a target formalism, like, for example, Software Cost Reduction (SCR) ( AU-TOMATIC GENERATION OF TEST VECTORS FOR SCR-STYLE SPECIFICATIONS,1997), Intermediate Model Representation (IMR) (AUTOMATED TESTING WITH RT-TESTER - THEO-RETICAL ISSUES DRIVEN BY PRACTICAL NEEDS,2000), Petri nets (MURATA,1989) or the CSP process algebra (BROOKES; HOARE; ROSCOE,1984), in order to generate test cases CARVALHO(2016).

(17)

16

According toUTTING; PRETSCHNER; LEGEARD(2012), Model-Based Testing (MBT) can be described by the process shown in Figure 1.1. Using the system requirements or even the system specification documents the specification model is constructed. During the model creation, its level of abstraction is related to the purpose of testing, because sometimes this model is called the test model. Having a more abstract model of the real system implies that the model is potentially easier to check, modify and maintain than the SUT. This abstraction is useful when validating the model, otherwise, verifying the model would be so costly as to validate the SUT. However, it is desirable that the model is accurate enough to generate concrete test cases, with actions, input parameters and expected results, as well as other information required to run the generated tests. Due to the commonly large number of test cases that can be generated from a specification model, selection criteria are necessary to guide the generation process. A test script is an executable code responsible for performing a test case, abstracts the output of the SUT, and then produces the test verdict. Usually, the environment is capable of adapting the abstract test data to the concrete SUT interface.

Figure 1.1: An overview of the model-based testing process

Despite all the benefits that MBT provides, there are also some negative points for their adoption. Among them, these models are not always available at the beginning of the project, and there may be some resistance to create them due to unfamiliarity with the associated syntax and semantics. As an alternative to solve this problem,CARVALHO(2016) proposes a strategy called NAT2TEST that can use Natural Language Processing (NLP) techniques to obtain the required models from natural-language specifications.

NAT2TEST is an entirely automatic strategy for test case generation from natural language requirements. The approach focuses on reactive systems (CARVALHO,2016). The tests are generated from a Data-Flow Reactive System (DFRS): a class of embedded systems

(18)

1.1. RESEARCH QUESTION AND CONTRIBUTIONS 17

whose inputs and outputs are always available as signals. Figure 1.2, presented originally by CARVALHO(2016), shows the phases of this approach. The three initial phases are fixed: (1) syntactic analysis, (2) semantic analysis, and (3) DFRS generation; the other phases are related to the chosen formalism to generate test cases, for instance, SCR (HEITMEYER; BHARADWAJ, 2000), IMR (PELESKA; VOROBEV; LAPSCHIES; ZAHLTEN,2011), Communicating Sequential Processes (CSP) (CARVALHO,2016), among others.

Figure 1.2: Phases of the NAT2TEST strategy

However, the strategy does not support hybrid systems, which is a class of systems that are widely used by the industry and is gaining popularity in the scientific community. In reality, for several years great effort has been devoted to the study of testing hybrid systems in particular, within the context of MBTMODEL-BASED TESTING AND MONITORING FOR HYBRID EMBEDDED SYSTEMS(2004).

Without even realising it, hybrid systems cross our way several times a day: an automatic teller machine, a car’s anti-lock braking system, a video-recorder and a washing machine are examples thereof (HYBRID DYNAMICAL SYSTEMS,1989). In general, hybrid systems are those that consist of “a logical discrete-event decision-making controller system interacting with a continuous-time process” (SAVKIN; EVANS,1998). This kind of system has attracted considerable attention in recent years. Along with their importance the need for reliability also arises (LARSEN; STEFFEN; WEISE,1997).

1.1

Research question and contributions

Taking into account all the discussion presented so far, the central research question of this work is: how to extend the NAT2TEST strategy to deal with hybrid systems?

The proposed extension NATural Language Requirements to TEST Cases for hybrid systems (h-NAT2TEST) must be conservative, so that the NAT2TEST strategy shall still be

(19)

1.1. RESEARCH QUESTION AND CONTRIBUTIONS 18

employed for dealing with non-hybrid systems. As illustrated in Figure 1.3, the extension proposed here impacts all fixed stages of the original NAT2TEST strategy.

Our first concern is to extend the Controlled Natural Language to capture requirements of dynamic systems, particularly, differential equations. An extended version of DFRS is proposed as an internal formal model to represent such requirements.

Unlike the original NAT2TEST strategy, however, the main purpose here is to generate a target model with the purpose of simulation. To achieve this, a DFRS is translated to an AcumenTAHA; DURACZ; ZENG; ATKINSON et al.(2015) model and the environment presented inTAHA(2012) is used for performing simulation.

Figure 1.3: Phases of the hybrid NAT2TEST strategy

In summary, this work presents the following contributions:

 An extension of the Controlled Natural Language to allow expressing requirements

of dynamic systems;

 An extension of the DFRS model to allow the internal and formal representation of

such requirements;

 a systematic translation from requirements to the extended notion of DFRS;

 a translation from DFRS to Acumen;

 use of an Acumen environment to perform simulation; and

 two examples to illustrate the overall approach, from requirements definition to

simulation.

Test case generation for hybrid systems is out of the scope of this work; it is one of the suggested topics for future work.

(20)

1.2. THESIS STRUCTURE 19

1.2

Thesis structure

This thesis is organised as follow:

Chapter 2 Discusses foundation concepts that are used in this research. First, the original NAT2TEST strategy is briefly presented. Afterwards, a definition of hybrid systems is presented, along with how they are modelled. Finally, is shown a brief discussion of simulation and how Acumen project fits in this context.

Chapter 3 Explains how the NAT2TEST strategy was extended, showing the parts that have been affected and the resulting impact. In addition, a running example is presented to illustrate the contributions of this work. Finally, it presents the formalism (Acu-men) and the tool chosen to support the proposed extension and how models are simulated in this tool.

Chapter 4 Describes in details two case studies to illustrate the application of the h-NAT2TEST strategy. The first one is a DC-DC Boost Converter (BC), the running example, and the second is an Adaptive Cruise Control (ACC).

(21)

20 20 20

2

Problem background

This chapter introduces some of the main basic concepts that served as the foundation for this research. Particularly, the components of the original NAT2TEST strategy are presented, as well as how they are linked to generate test cases from natural language requirements. Soon after, it is introduced the concept of hybrid systems and how to represent them.

2.1

The NAT2TEST strategy

NAT2TEST is an entirely automatic strategy for test case generation from natural language requirements. This strategy aims at reactive systems, whose behaviour can be described through actions that should be taken when certain conditions are met. An important feature of the approach is the possibility of generating test cases for systems with discrete or continuous temporal properties (CARVALHO,2016).

The rest of this section is devoted to a brief description of the three first phases of the NAT2TEST strategy. These are the phases that are adapted when dealing with hybrid systems and, thus, this explanation is required to understand the extension proposed in this work. For more comprehensive explanation of the original NAT2TEST strategy, we refer toCARVALHO (2016).

2.1.1

Syntactic and semantic analysis

For an automatic processing of requirements and generation of test cases, the re-quirements must be written according to a specific grammar, namely the SysReq-CNL. The System Requirements Controlled Natural Language (SysReq-CNL) is a Controlled Natural Language (CNL) grammar that consists of a subset of the English language. It has been created in order to turn the writing of system specifications more standardized and reliable, facilitating the conversion to a formal notation. In addition, this grammar was designed to handle requirements of data-flow reactive systems. These systems are part of a class of embedded systems where inputs and outputs are always available as signals.

(22)

2.1. THE NAT2TEST STRATEGY 21

The lexicon entries are classified into lexical categories to simplify the grammar, for example, it uses determiners, nouns, adjectives and so on. The complete grammar expressed in the Extended Backus-Naur Form (EBNF) notation, is shown in the Table 2.1. An important feature to highlight is that the lexicon is domain dependent which means that the instantiation of the categories must be manually created considering the current system domain. Nevertheless, a small set of a lexicon is initialised by default.

The grammar start symbol is Requirement, which consists of a ConditionalClause and an ActionClause. Therefore, the requirements have the form of action statements guarded by conditions. A ConditionalClause begins with a conjunction, and then its structure is similar to a Conjunctive Normal Form (CNF) – conjunction of disjunctions. The conjunctions are delimited by a COMMA and the AND keyword, whereas the disjunctions are delimited by the OR keyword. The elementary condition (Condition) comprises a NounPhrase (one or more nouns eventually preceded by a determiner and adjectives) and a VerbPhraseCondition, which begins with a VerbCondition (the verb “to be” or any other in the present or past tense). A VerbCondition is followed by an optional NOT, which negates the meaning of the next term, an optional ComparativeTerm and a VerbComplement.

An ActionClause begins with a NounPhrase followed by a VerbPhraseAction, which is rewritten as SHALL followed by at least one VerbAction and one VerbComplement. If more than one VerbAction and VerbComplement is used, then it is necessary to add a COLON after the SHALL keyword and use the COMMA to delimit the elements. A VerbComplement is an optional VariableState (a NounPhrase, an adjective, an adverb or a number) followed by zero or more PrepositionalPhrase, which consists of a preposition and a VariableState.

Although imposing writing structure, this grammar is general enough to allow the user to write sentences in several application domains. A simple example of how a requirement may be written, in SysReq-CNL, is shown below.

 When the input1 becomes greater than or equal to 10, the System shall assign valid

to the output1.

The natural way of describing the system behaviour, imposed by the SysReq-CNL, facil-itates the usability because the user does not need in-depth learning of a particular technology to describe a system entirely.

Table 2.1: SysReq-CNL – a grammar for system requirements

Requirement → ConditionalClause COMMA ActionClause PERIOD; ConditionalClause → CONJ AndCondition;

AndCondition → AndCondition COMMA AND OrCondition | OrCondition;

OrCondition → OrCondition OR Condition | Condition; Condition → NounPhrase VerbPhraseCondition;

(23)

2.1. THE NAT2TEST STRATEGY 22

ActionClause → NounPhrase VerbPhraseAction; VerbPhraseAction → SHALL (VerbAction VerbComplement

| COLON VerbAction VerbComplement (COMMA VerbAction VerbComplement)+); VerbAction → VBASE;

VerbPhraseCondition → VerbCondition NOT? ComparativeTerm? VerbComplement;

VerbCondition → VTOBE_PRE3 | VPRE3RD | VTOBE_PRE | VTOBE_PAST3; ComparativeTerm → (COMP (OR NOT? COMP)?);

VerbComplement → VariableState? PrepositionalPhrase*; VariableState → (NounPhrase|ADV | ADJ | NUMBER); PrepositionalPhrase → PREP VariableState;

NounPhrase → DETER? ADJ* Noun+;

Noun → NSING | NPLUR;

For the semantic analysis, a syntax tree is required, which is generated for each valid requirement during the syntactic analysis. The NAT2TEST strategy uses Thematic Role (TR) to give meaning for each sentence: each word or group of words has its role and functionality. In its notation, the TRs associated with a particular verb are grouped in a struct called Case Frame (CF).

Since the requirements are interpreted as actions that take place under certain condi-tions, the TRs and the CFs can also be classified into condition or action types. There are nine TRs grouped by type, which are:

TR’s associated with conditions:

 Condition Patient (CPT): the entity related to each condition;

 Condition Action (CAC): the action that concerns each condition;

 Condition Modifier (CMD): a modifier related to the condition.

 Condition From Value (CFV): the CPT previous value;

 Condition To Value (CTV): the value satisfying the condition;

TRs associated with actions:

 Agent (AGT): entity who executes the action;

 Action (ACT): the action to be executed if the conditions are met;

(24)

2.1. THE NAT2TEST STRATEGY 23

 Patient (PAT): entity who is affected by the action

A requirement can generate several CFs: one for each verb. They are grouped in a structure called Requirement Frame (RF), in other words, a requirement gains full meaning through the interpretation of a RF.

For example, the thematic roles for the requirement described above are assigned as follows: TR’s associated with conditions:

 Condition Patient (CPT): the input1;

 Condition Action (CAC): becomes;

 Condition Modifier (CMD): greater than or equal to;

 Condition From Value (CFV): -;

 Condition To Value (CTV): 10.

TRs associated with actions:

 Agent (AGT): the System;

 Action (ACT): assign;

 To Value (TOV): valid;

 Patient (PAT): the output1.

2.1.2

Generation of data-flow reactive systems

After creating all the case frames, the strategy has an informal, but structured, meaning of each system requirement, and the frames are used as input to the third phase. In this step, a formal representation of the system behavior is built: DFRS. This formal representation is a symbolic, timed and state-rich automata-based notation for representing natural-language requirements.

A DFRS has two different representations: a Symbolic Data-Flow Reactive System (s-DFRS) and an Expanded Data-Flow Reactive System (e-DFRS) one. The s-DFRS is a more abstract representation that avoids representing possible infinite sets, thus avoiding the state explosion problem. The e-DFRS representation is dynamically built from the symbolic model, and is used to check properties such as reachability, determinism, and completeness (CARVALHO; CAVALCANTI; SAMPAIO,2016). In the present work we use s-DFRS to represent the requirements of hybrid systems.

The DFRS is intended to model an embedded system. To help to model temporal conditionals the DFRS can have timers in its definition. The Symbolic Data-Flow Reactive

(25)

2.1. THE NAT2TEST STRATEGY 24

System (s-DFRS) is formalised as a 6-tuple: (I, O, T, gcvar, s0, F). Inputs (I) and outputs (O) are system variables, timers (T) are a special kind of variable whose values are non-negative numbers representing a discrete or a dense (continuous) time. The system global clock (gcvar) has the same type as the timers. The initial state is s0, and F is a set of functions.

The construction of the s-DFRS follows some steps, primarily, from the RFs it is inferred the system variables (inputs, outputs, and timers), as well as the functionsF. Afterwards, these two pieces of information are compiled to instantiate the model. The definition and construction of the e-DFRS will not be discussed, given that it is not used in the NAT2TEST extension proposed in this work.

For example, the DFRS for the only requirement described above is formed by “the input1” in the set of input, “the output1” in the set of output, the set of Timers is empty, it has a global clock, also an initial state with initial values of the variables, and a function with the “input1 >= 10” representing a conditional, and “the output := valid” as statement of the conditional.

After deriving DFRS models from the RFs, in the original NAT2TEST strategy, an intermediate formal notation is considered to generate test cases. For instance, an s-DFRS model can be encoded as CSP processes, and then test cases are generated via refinement checkingCARVALHO(2016). These phases are not further described since they are specific to the original approach, and, in the context of hybrid systems, our focus is on simulation, rather than on test case generation, as already emphasised.

(26)

2.2. HYBRID SYSTEMS 25

2.2

Hybrid systems

Hybrid systems are an integral part of modern society. Numerous applications are all around us: rockets; autonomous auto-mobile systems; medical monitoring; process control systems; automatic pilot avionics, among others. Actually, hybrid systems is a generic term used to describe networks of interacting digital and analogue devices. Cyber-physical systems, control systems and embedded systems are, for example, relevant fields that share the concepts of hybrid systems (BRANICKY,2005).

2.2.1

Definition of hybrid systems

It is a challenge to establish a unique definition for hybrid systems, since their investiga-tion occurs on such a large variety of study areas, which have many concepts in common, even though the overall area of hybrid systems has not been fully consolidated (BRANICKY,2005). There are different perspectives of studying hybrid systems, e.g., the computing industry considers the context of a digital system interacting with an analogue environment (also known as embedded systems), where the key points are the analysis and verification of systems with discrete and dynamics events (SCHAFT,2000).

Analysing physical systems, it was found that systems can usually operate in different modes, and changing from one mode to another sometimes can be described as an instanta-neous discrete transition. From this context, the perspective of the modelling and simulation emerged. Another perspective involves control systems, where hierarchical systems have a discrete decision layer and a continuous implementation layer, e.g. supervisory control and multi-agent control (SCHAFT,2000).

Therefore, in general, we can say that hybrid systems are a combination of discrete and continuous events. These events coexist, interact and change in response to dynamics as described by differential or difference equations in time (NICOLLIN; OLIVERO; SIFAKIS; YOVINE,1993). These functions responsible for describing the behaviour of the variables are called activities (LARSEN; STEFFEN; WEISE,1997).

One way to define the behaviour of hybrid systems is via the set of all possible tra-jectories of the continuous and discrete variables associated with the system. In this context, a hybrid systems is represented as a hybrid automaton model (FAHRENBERG; LARSEN; LEGAY,2013).

To illustrate a hybrid system, we consider the thermostat described in (LUNZE; LAMNABHI-LAGARRIGUE,2009). A thermostat is a device to regulate the temperature in a room. The heating system is supposed to work at its maximum power or completely turned off. This is a system that operates in two modes, "on" or "off". In each operation mode, the evolution of the temperatureT can be expressed by a different differential equation. Figure 2.1, presented in (LUNZE; LAMNABHI-LAGARRIGUE,2009), shows the modes and the differential equations of

(27)

2.2. HYBRID SYSTEMS 26

Figure 2.1: Thermostat model – an example of a hybrid system

the system.

Each mode corresponds to a node of a directed graph, while the edges indicate the possible discrete state transitions. The hybrid system in this example consists of two discrete states, q∈ {on, off }, and a continuous state T, where T represents the temperature (real number). Regarding the behaviour of the system, we can say that the system has two distinct continuous behaviours that establish the evolution of the temperatureT. One when in mode "on", ruled by the dynamicsT˙(t) = fon(T (t)), which describe temperature lowering, and another

when in the mode "off", governed by the dynamics T˙(t) = fo f f(T (t)), which governs the

temperature increase.

The continuous stateT and different conditions onT are responsible for changes of the discrete state q, since they may trigger discrete transitions. In Figure 2.1 it is possible to see that if the discrete state q is "on", andT is greater than or equal toTmax, the discrete transition from "on" to "off" becomes enabled. Differently, in state "off", the discrete transition is enabled ifT is less than or equal toTmin. In addition, each discrete state also has an invariant, and the process may only stay within a state as long as it does not violate the invariant and when the transition is enabled it is executed instantaneously, without time-consuming (LARSEN; STEFFEN; WEISE,1997).

The thermostat behaviour is shown graphically in Figure 2.2. It is possible to see that the temperature does not suffer from discontinuities while the state q changes discontinuously. Based on this example, we note that hybrid systems are two-phase systems as depicted in Figure 2.3, reproduced fromLARSEN; STEFFEN; WEISE(1997). A continuous phase, where arbitrary continuous variables, including the clocks, evolve with time, and a discrete phase, in which one or more operations happen simultaneously with their corresponding state changes, but where no time passes. Thus, for each discrete state, it is necessary to define the behaviour of the continuous variables and, as discussed above, the most commonly used way is through differential equations as usual in physics. In what follows, we show how equations can be used as a basis for describing the system behaviour, in particular, of hybrid systems.

(28)

2.2. HYBRID SYSTEMS 27 t T f on(T (t)) fo f f(T (t)) t Q on o f f

Figure 2.2: Example of the behaviour of a thermostat

(29)

2.2. HYBRID SYSTEMS 28

through a set of input variables u and output variables y. In a continuous time system the timet is represented byt∈ R, whereas in a discrete time system the timetis represented by t ∈ Z. Regularly, the symbolk is used instead oft to denote discrete time indices. A typical system that uses discrete-time is the computer, whereas physical systems use continuous time (HUBBARD; WEST,1993).

A system can be classified as static or dynamic. The system is static if its output depends only on its present input. In others words, there is a function f(u,t)to determine the output at any timet,t∈ T using only the inputulike in equation 2.1.

y(t) = f (u(t),t) 2.1

Figure 2.4, originally presented in (CHEN,2013), shows an example of static systems, which is a resistive circuit excited by an input voltage u(t). Let the output be the voltage across the resistanceR3, according to the circuit theory, the output can be simply determined by the present input.

On the other hand, a dynamic system requires information on previously received input to determine the system output. i.e. to determiney(t)one needs to know u(τ),τ ∈ (−∞, t]. Figure 2.5, originally presented (Y.LI,2012), shows an example of a dynamic time invariant system: the flow control valve. The fluid pressurePis constant. Ais orifice area andρ is fluid density. However, the flow rate history is a function of the forceF(t)acting on the valve. It is necessary to know the time history of the forcing functionF(t)in order to determine the flow rate at any time. The positionx(t)of the valve is governed by the following differential equation (Y.LI,2012):

¨

x= F(t) − b ˙x− kx 2.2

Wherekis the spring constant andbis the damping factor. For a circular pipe of radiusR, the flow rate is then given by the following equation (Y.LI,2012):

(30)

2.2. HYBRID SYSTEMS 29

Figure 2.5: Flow control valve

Q= x 2 R2A s 2P(t) ρ     2.3

This type of representation, shown in equations 2.2 and 2.3, is commonly used for system description in research areas such as electrical and mechanical engineering. This is called state-space representation (KHALI,2002;SKOGESTAD; POSTLETHWAITE,2005). In representation,x˙means the first derivative with respect to time,x¨means the second derivative with respect to time, and so on.

Three essential elements are the basis of the state-space representation: a vectorxof state variables, a vectoruof input variables, and a vectoryof output variables. All of them are explicit functions of time, and this means that their values depend on the time at which they are evaluated. In general, the values ofx,uandyas a function of time are expressed asx(t),u(t),

andy(t), respectively. The temporal domain of the state-space representation is continuous or

discrete, and the relationship amongxanduis usually governed by differential or difference equations, respectively. For instance, in the following scheme:

˙ x(t) = f (x(t), u(t),t) x(k + 1) = f (x(k), u(k), k)     2.4

wheret∈ Randk∈ Z. Using the equation 2.1 as a basis algebraic relation amongyand the state and input variables, incrementally, it is possible to give an initial conditionx(0). Thus, to define a function of the inputs,u(t), is required, then, all functionsxthat are solutions to Equation 2.4 denote the possible system behaviours.

(31)

2.2. HYBRID SYSTEMS 30

2.2.2

Hybrid system representation

Once the key concepts to understand a representation of a hybrid system has been described, now we present how a hybrid system can be represented as a hybrid automaton model. ALUR; COURCOUBETIS; HALBWACHS; HENZINGER; HO; NICOLLIN; OLIVERO; SIFAKIS; YOVINE(1995) define a the hybrid automaton model as a finite automaton equipped with a set of continuous variables. Formally, it is a seven-tupleHA= hX , Q, ψ, Inv, A, Ev, Asi, where:

 X is a finite set of real-valued variables{xi}. It is denoted byx, which is a vector

of variables. The values of all variables at a given moment define a state of the variables. The set of all possible states is denoted byV.

 Qis a finite set of vertices called locations.

 ψ is a function that assigns to each location l ∈ Q a function ψl describing the

evolution of variables in time.

ψl(x, f ) → ˙x( f ) = f (x, f ).     2.5

 Inv is a function that assigns to each location l ∈ Qa predicate Invl, called the

invariant ofl.

 Ais a finite set of transitions. Each transitiona= (l, l0)joins a source locationl∈ Q

to a target locationl0∈ Q.

 Ev is a function that assigns to each transitiona= (l, l0), a predicate Eva called

guard. The transitiona= (l, l0)may be fired if the guardEvais satisfied.

 As is a function that assigns to each transition a= (l, l0) a relation Asa called

assignment. It is used to model the discrete changing of the values of variables.

Asa→ x = g(x). 2.6

A state of a hybrid automaton is represented by the pair(l, x), wherel∈ Qandx∈ V. In each position (vertice) of the automaton, the values of the variables change continuously with time according to the associated evolution function (an element ofψ). Each transition (edge) of the automaton is guarded by a condition, and its execution changes the values of the variables according to the associated assignment. Each location is also labelled with a condition, called invariant, which must hold while the system remains in the vertice.

The fully automatic analysis of hybrid systems described as hybrid automata is not feasible due to the complexity inherent to these systems. Therefore, subclasses of hybrid automata are studied. We can highlight the following subclasses described in (LARSEN; STEFFEN; WEISE,1997):

(32)

2.2. HYBRID SYSTEMS 31

Timed automata are the special case of hybrid systems where all activities have a growing

and constant behaviour, invariants and pre-conditions are comparisons of clocks (and clock differences), and post-conditions are restricted to clocks reset.

Drifting-clock timed automata are a similar subclass of timed automata, where all activities

may vary the behaviour within a given interval.

Linear hybrid systems is a subclass which can be analysed effectively and automatically by

techniques shown in (ALUR; COURCOUBETIS; HENZINGER; HO,1993), unlike the nonlinear. In these systems, invariants, guards and activities may only depend linearly on time. It is precisely this hybrid system subclass that this work considers.

2.2.3

DC-DC Boost Converter

To exemplify the use of the proposed strategy, we consider here a DC-DC Boost Converter (BC) as a running example. This example is the same one presented in (AERTS; MOUSAVI; RENIERS,2015). This example is used in Chapter 3 to emphasize the changes with respect to the original NAT2TEST strategy, and is developed in full in Section 4.1.

The BC is a power converter that rises voltage while stepping down current, from its input to its output. This type of device is old in the electrical field but widely used in modern equipment. For example, the engines used in driving electric vehicles require much higher voltages, than could be provided via a single battery. Even if it were possible to use a single battery, its weight and size make its use impractical. The solution is to use fewer batteries and to boost, using a boost converter, the available DC voltage to the appropriate voltage.

The Figure 2.6, originally presented in (AERTS; MOUSAVI; RENIERS,2015),illustrates a example physical of the BC and its basic circuit. A generic BC is composed of:

An inductor (L) is a passive electrical device that stores energy in the form of magnetic field,

usually combining the effect of various loops of electric current;

A capacitor (C) is a passive two-terminal electrical component that stores electrical charges

in an electric field, accumulating an internal imbalance of electric charge;

A switch (S) is a physical mechanism that rapidly switches a device on and off.

A diode (D) is a component that allows an electric current to pass in one direction ( it has low

resistance in one direction) while blocking current in the opposite direction (it has high resistance in the other direction).

A resistive load (R) is the output.

Closing the (S) generates a short circuit from the right side of L to the negative input. Consequently, a current flows between the positive and negative supply terminals through L,

(33)

2.2. HYBRID SYSTEMS 32

which stores energy in its magnetic field. Initially, there is no current running in the right side of the circuit because of the combination of D, C and the resistive load represent a much higher impedance than the path straight through the (S).

Opening the (S) causes a sudden drop in current and produce an electromotive force (emf) in the opposite polarity to the voltage across L (VL) during the open period. The resulting current through D loads up C toVIN + VL minus the forward voltage loss across D, and also

supplies the load.

After the first start, the switch is closed, consequentely, the output of the circuit is isolated from the input, despite the load continues to be fulfilled withVIN + VL from the charge

on C. C is recharged each time the switch is open, so maintaining an almost steady output voltage across the load.

Summarising, the boost of the DC voltage is a consequence the combined physical properties of the inductor L and capacitor C, which are controlled by the switch S and diode D. This process transforms the input voltage E to an increased output voltage that is applied to the resistive load R. Note that the control elements of the boost converter transform the otherwise continuous system into a hybrid system. Finally, the system is made input dependent by tuning the resistive load R which results an internal stabilizing behaviour of the boost converter. In Figure 2.7, originally presented (AERTS; MOUSAVI; RENIERS,2015), this system is modelled as a hybrid automaton.

Figure 2.6: Boost converter

The four discrete states of the system are solely dependent on the position of the switch S and the mode of the diode D (conducting/blocking). In addition, the physical properties of the system are modelled by the electric charge q of the capacitor and the magnetic fluxΦof the inductor.

(34)

2.2. HYBRID SYSTEMS 33

(35)

2.3. SIMULATION 34

2.3

Simulation

Advances in technology continually lead to the construction of systems with higher complexity; therefore any change in these systems is made more complicated. A simulation is an approach to understanding and to evaluate the behaviour of these systems. More formally, simulation is “the process of designing a model of a real system and conducting experiments with this model for the purpose either of understanding the behaviour of the system of or evaluating various strategies (within limits imposed by a criterion or a set of criteria) for the operation of the system” (SHANNON,1975).

Simulation has several advantages, for example, it is used to compress a time frame, a simulation running on a computer describes more quickly the effects of a change in a real word circumstances. It used in engineering design to verify the effects of changes on the product without producing a physical prototype. It is especially valuable for testing conditions that might be difficult to reproduce with simple prototypes, mainly in the early phase of the design process when the system may not be available. Also, it can increase the quality of the systems, potentially decreasing the number of errors found later in the design process (FRAMEWORK FOR SIMULATION OF HYBRID SYSTEMS: INTEROPERATION OF DISCRETE EVENT AND CONTINUOUS SIMULATORS USING HLA/RTI,2011).

Moving our focus to hybrid systems, they have participation in several areas, including in safety-critical areas, and consequently, there is the need to analyse the behaviour of these systems. A common approach used here is the numeric simulation of such systems. The simulation of pure continuous systems (ROBERTS; SEDRA; SEDRA; SMITH,1992) and pure discrete systems is thereby well understood (CASSANDRAS; LAFORTUNE,2009). There exist several numeric simulation methods for systems of Ordinary Differential Equations (ODE). However, the combination of discrete and continuous dynamics leads to challenging problems for simulation (MIXED-SIGNAL SIMULATION CHALLENGES AND SOLUTIONS,2008).

In this context, the idea of building a simulation and verification environment to fill several gaps in this research area, led to Acumen. The main goal of the Acumen project was developing a semantic foundation that unified the formalism Functional Reactive Programming, which has been used successfully in a wide range of domains, including robotics and computer animation, with real numbers detailed treatment. A peculiarity that enhances the use of Acumen for hybrid systems is its continuous language. The use of this feature allows the use of real-valued variables, derivatives with respect to time, partial derivatives, tuples, families of equations (finite quantifiers), vectors, matrices and recursive functions during the construction of models (TAHA et al.,2015).

Other features which have been taken into account in the construction of Acumen is the accessibility (open-source) and the usability. Acumen is used in this work and a brief introduction is given in the next section, according toTAHA(2012).

(36)

2.3. SIMULATION 35

2.3.1

Acumen

Acumen is an experimental environment for modelling and simulation of hybrid systems. It is built upon a textual modelling language that has the same name. Hereafter, we highlight the main features of the environment and the language. Using the Acumen GUI, shown in Figure 2.8, the user can load, edit and save textual models in the Acumen language; also the user can easily simulate models pressing a single button. Similarly, the user can view a plot, a table or a 3D visualization of the system variables over time.

Figure 2.8: Graphical user interface of Acumen

A complete model in Acumen is composed of a set of model declarations, which may appear in any order. A valid model must contain at least a model declaration called Main. This main statement should have exactly one parameter, and by convention, this parameter is called simulator. The model declaration starts with a name for the model and, right after, a list of formal parameters between brackets, followed by an equal sign (=). After the name and the parameters, the statement may contain a section initially, besides an always section. Model statements may appear in any order. For example, a typical model has the form presented below. In this case, we are modelling a bouncing ball, whose initial position is 0 (x,y), considering a given mass and size.

(37)

2.3. SIMULATION 36 1 model B a l l ( mass , s i z e ) = 2 i n i t i a l l y 3 x _ p o s i t i o n = 0 , 4 y _ p o s i t i o n = 0 5 always 6 / / t h e r e s t o f t h e body o f t h e d e c l a r a t i o n o f t h e B a l l model 7 model Main ( s i m u l a t o r ) =

8 / / body o f t h e d e c l a r a t i o n o f t h e model Main

Initially sections are responsible for the declaration of the variables that are used throughout the model , besides defining their initial values. Always sections contain a sequence of statements, usually made up of assignments and/or conditional assignments. It is important to understand that all these statements are executed at the same time. Thus, the order in which they are introduced does not matter.

In a model statement, it is allowed to instantiate objects declared in another model, via the reserved word create. The instantiation is permitted in both initially and always sections. When in the initially section, it is called a static instance, whereas in the always section, it is called a dynamic instance. It is shown below how instances differ: the difference between static instances and dynamic ones is that the static ones can be accessible during all the running of the program, while the dynamics ones cannot be referenced because they do not have a bound with a variable. For example, in the code below,bis a static instance, whereas the ball created later is a dynamic one.

1 model Main ( s i m u l a t o r ) = 2 i n i t i a l l y 3 b = c r e a t e B a l l ( 5 , 14) / / S t a t i c i n s t a n c e 4 always 5 / / . . . 6 c r e a t e B a l l ( 1 0 , 42) / / Dynamic i n s t a n c e 7 / / . . .

Expressions in Acumen can be built with variables, literals, embedded functions, vector generators, and summations.

A variable has a name followed by zero or more apostrophes (’). Such apostrophes indicate that this variable is the derivative with respect to time of the variable without apostrophe. For example,x,x0, x00, andx000 represent the variablex, its first, second and third derivative, respectively. Acumen defines five types of statements, namely: continuous assignments, condi-tional (or guarded) statements, discrete assignments, iteration, and sequences of statements. In a continuous assignment the left-hand side must be a variable or a derivative of a variable, its right side can be any expression, and the assignment operator is (=). The example below shows a continuous assignment where two derivatives, from the running example, are being updated. gc0 is the global clock derivative and it is assigned 1.0 to indicate a steady growth time.q0is a variable derivative and it is assigned the corresponding equation of its behaviour.

(38)

2.3. SIMULATION 37

1 q ’ = ( (−q ) / ( ( r ) * c ) )

2 gc ’ = 1 . 0

Any continuous statements on the same object are evaluated simultaneously after all discrete assignments have been made, provided no change occurs in program state.

Similarly to the continuous assignments, in discrete assignments the left-hand side must be a variable or a derivative of a variable, the right-hand side may be any expression, and the assignment operator is (+ =). However, discrete assignments are instantaneous. It is used to indicate that there is a discontinuous shift in a particular variable during simulation.

In order for the simulation to behave in an appropriate manner, any discrete assignment in the model definition must occur within a conditional statement. An if-statement is executed only if certain conditions are valid. The following code illustrates how if-statements are written:

1 i f ( x >0) then

2 x ’ ’ = −9.8

3 e l s e

4 x ’ = 0

A match-statement is another type of a conditional statement. It can be seen as a generalisation of an if-statement, or as the switch-statement in imperative programming languages. It allows one to execute specific statements according to different conditions. These conditions are based on the value of a particular expression that is being evaluated. The following example illustrates this statement:

1 match myCommand w i t h 2 [ " F a l l " −> 3 x ’ ’ = −9.8 4 | " Freeze " −> 5 x ’ = 0 6 | " Reset " −> 7 x = 0 8 ]

A for-statement allows the execution of an iteration, either for a particular number of times or for each element in a collection. For example:

1 f o r e a c h i i n 1:10 do x =2*y

2 f o r e a c h c i n c h i l d r e n do c . x + = 15

Sequential statements are delimited by a comma (,). For example, the code bellow shows a continuous statement followed by an if-statement using a discrete assignment in its body:

1 gc ’ = 1 . 0 ,

2 i f s i n (1000000* gc ) >= 0 then

3 s += 1

4 e l s e

(39)

2.3. SIMULATION 38

Initially, the simulation of an Acumen model has only one Main object. Due to the dynamic creation of objects, a tree of objects is created, where the Main object is always the root of the tree, and the children are the objects dynamically created.

Each simulation step involves the visit of all tree objects, starting from theMain. Two kinds of steps are performed, as shown in Figure 2.9, originally presented in (TAHA,2012). During the discrete step, discrete statements and structural actions (create) are processed. Once all the discrete statements available are collected, the instructions are performed in parallel. For each object, the processing begins with the execution of its the structural actions, and then structural actions of all its children are executed. While there are active actions that change the state, the execution continues making discrete steps. Contrarily, it makes a continuous step. During a continuous step, all continuous assignments and integrations are performed.

(40)

39 39 39

3

NAT2TEST for hybrid systems

In this chapter, we explain how the SysReq-CNL, proposed inCARVALHO(2016), is extended to enable writing requirements for hybrid systems. All changes are defined to keep the expressiveness and overall structure already provided, besides keeping all the requirements written in the old SysReq-CNL still valid in the new version. We then show how the extended SysReq-CNL is translated into a Data-Flow Reactive System for hybrid systems (h-DFRS), which is itself translated into Acumen for the purpose of simulation.

3.1

The SysReq-CNL grammar for hybrid systems

As described in Section 2.2, to express requirements of hybrid systems it is necessary to use mathematical expressions, variables, functions and derivatives. Some of these features are not supported by the previous version of the SysReq-CNL, as can be seen in Section 2.1. As previously mentioned, the extensions to the SysReq-CNL that support these features are conservative. For a better understanding, each extension is explained in isolation, using a running example (the DC-DC boost converter). For compatibility with the used parser and to facilitate the processing and analysis of the requirements, the grammar has been benefited of techniques to avoid ambiguity (SCOTT,2005).

Hereafter, only parts of the modified grammar are shown. The whole grammar can be found in the Appendix C. In the new version of SysReq-CNL, the most crucial change was the inclusion of expressions, so that it is now possible to write expressions (see Example 3.1) in conditions instead of writing single comparisons with constant values. In this example, although Sandqare being compared with constant values, they could have been compared with other variables and expressions as well. The inclusion of expressions in the grammar permits the construction of logical comparisons, such as those used in the transition guards in Figure 2.7. For instance, one way to represent the guard of transition from mode 1 to mode 2 is as follows.

S== 1 && q >= 0 3.1

(41)

3.1. THE SYSREQ-CNL GRAMMAR FOR HYBRID SYSTEMS 40

requirements. Furthermore, the inclusion of expressions permits the use of variables or values in arithmetic expressions, making it possible to describe the behaviour of the variableqin mode 1 as follows:

(Phi/L) − (1/R ∗C) ∗ q 3.2

Considering these characteristics, it is possible to write the requirements of the boost converter related to transitions between modes. For example, the requirement representing the transition from mode 1 to mode 2 can be written as follows:

 When the system mode is 1, and S == 1 && q >= 0, the DC-DC boost control system

shall assign 2 to the system mode.

In what follows, one can see how the original SysReq-CNL was evolved to consider expressions. Now, a VariableState can be written as an Expression, whereas it considered noun phrases, adverbs, adjectives, and numbers, previously. The grammar roles ensure the precedence of operators, thus an Expression generates a list of AndExpression separated by the OR operator. An AndExpression generates a list of NotExpression separated by the AND operator. A NotExpression generates ComparativeExpression or a token LOGICALNOT follow by a NotExpression. A ComparativeExpression generates a list of ArithmeticExpression separated by the ComparativeOperator operator. A ComparativeOperator could be a greater than (GT ), less than (LT ), greater than or equal to (GE ), less than or equal to (LE ), equals (EQ), or not equals (NE ). An ArithmeticExpression generates a list of Term separated by the AdditiveOperator operators. An AdditiveOperator can be a token PLUS or MINUS. A Term generates a list of Factor separated by the MultiplicativeOperator operators. A MultiplicativeOp-erator could be a token MULT, or SLASH, or MOD. A Factor is a PrimaryExpression, and it may be preceded by a PrefixOperator. A PrefixOperator has the same roles as an AdditiveOperator. A PrimaryExpression is the core of the grammar; it can generate values, variables, anothers expression between bracket and call functions. The grammar defined four default functions, namely, SIN, COS, EXP, LOG and SQRT.

VariableState → Expression;

Expression → AndExpression (OR AndExpression)*; AndExpression → NotExpression (AND NotExpression)*;

NotExpression → LOGICALNOT NotExpression | ComparativeExpression; ComparativeExpression → ArithmeticExpression

(ComparativeOperator ArithmeticExpression)*; ComparativeOperator → GT | LT | GE | LE | EQ | NE ;

ArithmeticExpression → Term (AdditiveOperator Term)*;

(42)

3.1. THE SYSREQ-CNL GRAMMAR FOR HYBRID SYSTEMS 41

Factor → PrefixOperator? PrimaryExpression; PrefixOperator → AdditiveOperator;

AdditiveOperator → PLUS | MINUS;

MultiplicativeOperator → MULT | SLASH | MOD;

PrimaryExpression → FunctionID LP ArgumentList? RP

| TRUE | FALSE | NUMBER | NounPhrase | LP Expression RP;

FunctionID → SIN | COS | EXP | LOG | SQRT | Noun; ArgumentList → VariableState (COMMA VariableState)*;

Table 3.1: Part of the extended SysReq-CNL: – representing expressions

Besides expressions, now it is also possible to declare functions, with or without parameters. After declaring a function, it can be referred to (called) within a requirement. As it can be seen in Table 3.2.

The function declaration begins with an identifier, then a list of the parameters between parentheses and finally the function body. The body of a function can be just a simple expression, or a ternary expression, or can even be defined using pattern matching. These last two are constructs inserted to enhance the flexibility and the expressiveness of the grammar.

The ternary conditional operator is a way to make a simple conditional test, analogously to an if-else structure. This structure is written as follows: test? expression1 : expression2,

where test is any boolean expression, expression1 is an expression evaluated if test is true, whereas expression2 is evaluated otherwise.

The last construct allows the definition of expressions for pattern matching. This form is widely used in the writing of mathematical equations. The structure is as follows, (test

DO expression1)+. Where test is any boolean expression and expression1 is an expression

evaluated if test is true. Using this form, it is possible to define functions by pattern matching. Since our grammar allows expressions rather than being confined to literals, a peculiarity was added to simplify the writing. For example, the original grammar, a conditionala> b is true is a valid conditional, in the proposed one this conditional remains valid and the conditional a> bis also valid.

Table 3.2: Part of the extended SysReq-CNL: functions

Sentence → Requirement |FunctionDeclaration;

FunctionDeclaration → Noun LP ParameterList? RP EQUALSSIGN FunctionBody; ParameterList → Noun (COMMA Noun)*;

FunctionBody → TernaryExpression | PatternMatching | Expression;

TernaryExpression → Expression IN TernaryDefinition COLON TernaryDefinition; TernaryDefinition → Expression | TernaryExpession;

(43)

3.2. SEMANTIC ANALYSIS OF HYBRID-SYSTEM REQUIREMENTS 42

Returning to the running example, the behaviour ofqin mode 1 can be described as the following function:

q_mode1(Phi, L, R,C, q) = (Phi/L) − (1/R ∗C) ∗ q 3.3

As shown in Section 2.2, in hybrid systems, the behaviour of a variable can involve the computation of derivatives. Therefore, the new version of the SysReq-CNL also allows such a characteristic. For such improvement, the new verb action set was incorporated into the dictionary, and the word derivative was defined as a reserved word, in order to denote when the derivative of a variable is being considered. In our research, the second, the third and the others derivatives were not necessary for the description of a hybrid system, but they can easily be incorporated by adding new reserved words. Now, it is possible to write a requirement to describe the behaviour of variables using function calls and derivatives. For example, the requirement for the continuous behaviour ofqandPhiin themode1can be written as follows:

 When the system mode is 1, the DC-DC boost control system shall:

set q_mode1(Phi,L,R,C,q) to the q derivative, set Phi_mode1(C,q,E) to the Phi derivative.

Now, during the syntactic analysis phase of the NAT2TEST strategy, a syntax tree is generated for each grammatically correct requirement, considering the new grammar structure. Syntax trees are also generated for the user-defined functions. To enable the parsing of these new elements, the SysReq-CNL (component of the NAT2TEST tool that parses requirements) was extended.

About the perspective of implementation, the new grammar has introduced into the parser, and the new tokens were included. In the GUI, it was necessary to create a new area responsible for creating and manipulating functions.

3.2

Semantic analysis of hybrid-system requirements

This phase consists of relating syntactic structures of grammar elements with semantic roles according to the theory of Case Grammar (FILLMORE,1968). The relation of the meaning of each thematic role to a group of words is obtained by analysing the syntax tree generated for each valid requirement according to the new System Requirements Controlled Natural Language (SysReq-CNL) grammar.

The thematic roles considered here are the same shown in Section 2.1. However, now, the words related to each role can comprise expressions and function calls. Therefore, some inference rules considered by the RF-Generator (the NAT2TEST component that relates words to thematic roles) were updated accordingly.

A peculiarity in semantic processing is when the user decides to use one expression as a condition, for example, to writea> b instead ofa> b is true, the thematic role patient

(44)

3.3. HYBRID DATA-FLOW REACTIVE SYSTEMS 43

receives the expression as the value, and the same occurs with toValue. This interpretation does not affect the Data-Flow Reactive System (DFRS) generation (CARVALHO; CAVALCANTI; SAMPAIO,2016).

For generating the thematic roles it is necessary to analyse an entire requirement. With this in mind, an analysis of the requirement introduced in the previous section is pre-sented. Figure 3.1 shows the Requirement Frames corresponding to the semantic analysis. This requirement presents one conditional, “the system mode is 1”, where, thesystemmode receives the role of Patient (PAT) and 1 receives the role of Condition To Value (CTV). This requirement also contains two actions, both being executed bytheDC− DCboostcontrolsystem which plays the role of Agent (AGT). As there are two actions, there is also two Patient (PAT), namely,theqderivativeandthePhiderivative. And each patient receives a value, in this case, q_mode1(Phi,L,R,C,q) and Phi_mode1(C,q,E), respectively.

Meanwhile, looking on the side of development the keywords had a special treatment, the constants were changed by expressions, and consequently, the definition of expressions and types was needed.

Figure 3.1: Thematic roles from a requirement

3.3

Hybrid data-flow reactive systems

In the NATural Language Requirements to TEST Cases for hybrid systems (h-NAT2TEST), the DFRS definition, given in Section 2.1, was modified to incorporate user-defined functions. Function declarations were incorporated. As a result, the s-DFRS is now formalised as a 7-tuple: (I, O, T, gcvar, s0, F, FD). Inputs (I) and outputs (O) are system variables, timers (T)

are a special kind of variable whose values are non-negative numbers representing a discrete or a dense (continuous) time. The system global clock (gcvar) has the same type as the timers. The initial state is s0, F is a set of functions describing the system behaviour and FD are user-defined functions, which can be referred to (called) by definitions inF.

In the same way, changes on the generation of DFRS models from requirement frames were performed. In the previous version, only constants were considered and, thus, the type inference was trivial. Now, with the improvements described in this chapter, the DFRS can

Referências

Documentos relacionados

Cage density significantly influenced FCR per dozen eggs, with the density of 10 birds per cage presenting the poorest FCR due to their highest feed intake, whereas the other

A partir do momento em que um investimento pode ser analisado como uma opção e não apenas como uma obrigação, os parâmetros analíticos se alargam permitindo que haja uma

Nesta modalidade estão enquadradas as nascentes, que, de acordo com a Portaria, devem ser analisadas mensalmente por meio dos parâmetros cor, turbidez, pH, coliformes totais

Com isso, concluímos que, se a sentença contém o verbo esser (ser), ela pode exibir um clítico neutro quando o Spec do IP não está ocupado por um sujeito; e se a sentença não tem

7) segurança política: são apontados tanto os direitos humanos dos cidadãos num Estado, como os elementos que impedem a sua efetivação: a repressão política por parte

Dessa forma, limitaria a habilidade das firmas para ajustes no alinhamento com o ambiente a partir de variações nas suas características centrais (HANNAN; FREEMAN, 1984, p. Por

Because the variation of these traits along environmental gradients here, zones can be caused by both species turnover and intraspecific trait variability, it is necessary

Por outro lado, ele salienta que “o SQ+ tem como diferencial dar maior liberdade ao arquiteto tratar com o cliente, já que existem questões que são mais