scieee AI-readable full text Open interactive document viewer

Simulation of hybrid systems regulated by newtonian mechanics

Correia, Ricardo da Silva

Abstract

The evolution of software products that interact with the physical world has led to a greater need to simulate their behavior in order to verify their effectiveness and safety in different scenarios. This dissertation project aims to enhance a simulation tool for hybrid programs called Lince, more specifically to provide more powerful simulation capabilities to hybrid programs regulated by Newtonian mechanics. These include the addition of new language constructs (such as the division operator and the trigonometric functions), the implementation of non-linear expressions, grammar relaxation and organization, improved error detection, and the mitigation of existing tool-related issues. Throughout this dissertation, it is discussed how the implementation of these improvements benefits the simulation of hybrid programs and are explained the key methods adopted for their conception. Finally, this new version of Lince is put to the test by handling case studies related to autonomous driving (for example, adaptive cruise control and a missile targeting a moving object) and other types of systems as well, such as purely physical systems and the so-called on-off systems. The results obtained in the treatment of these case studies attest to the enhanced capabilities of this tool and the contribution of this dissertation to the scientific community, demonstrating its relevance in simulating integrated systems in everyday life.

Full text

University of Minho School of Engineering Ricardo da Silva Correia Simulation of Hybrid Systems Regulated by Newtonian Mechanics october 2023 University of Minho School of Engineering Ricardo da Silva Correia Simulation of Hybrid Systems Regulated by Newtonian Mechanics Masters Dissertation Master’s in Physical Engineering Area of physics of information Dissertation supervised by Renato Neves José Proença october 2023 Copyright and Terms of Use for Third Party Work This dissertation reports on academic work that can be used by third parties as long as the internationally accepted standards and good practices are respected concerning copyright and related rights. This work can thereafter be used under the terms established in the license below. Readers needing authorization conditions not provided for in the indicated licensing should contact the author through the RepositóriUM of the University of Minho. License granted to users of this work: CC BY https://creativecommons.org/licenses/by/4.0/ i Acknowledgements I couldn’t help but express my deep gratitude to all the people who made this research project possible. The journey that comes to an end here was enriched by their support and dedication, so I must mention those whose contributions were essential to my growth. Firstly, I would like to thank the University of Minho for providing the opportunity to carry out this project, allowing me to effectively apply the knowledge I have acquired throughout my academic journey. In this regard, I wish to express my sincere appreciation to my academic supervisors, Renato Neves and José Proença, for their guidance and support throughout this journey, steering this project to success. On this path, I cannot fail to mention my friends, girlfriend and fellow travelers who were always available to help and motivate me during my academic journey. To my parents and sister, for believing in me and their unwavering support at every stage of my life. To everyone, my heartfelt thanks. This work was partially supported by National Funds through FCT - Fundação para a Ciência e a Tecnologia, I.P. (Portuguese Foundation for Science and Technology) within the project IBEX, with reference PTDC/CCI-COM/4280/2021. ii Statement of Integrity I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. University of Minho, Braga, october 2023 Ricardo da Silva Correia iii Assinado por: Ricardo da Silva Correia Num. de Identificação: 30367215 Data: 2023.10.30 01:00:03+00'00' Abstract The evolution of software products that interact with the physical world has led to a greater need to simulate their behavior in order to verify their effectiveness and safety in different scenarios. This dissertation project aims to enhance a simulation tool for hybrid programs called Lince, more specifically to provide more powerful simulation capabilities to hybrid programs regulated by Newtonian mechanics. These include the addition of new language constructs (such as the division operator and the trigonometric functions), the implementation of non-linear expressions, grammar relaxation and organization, improved error detection, and the mitigation of existing tool-related issues. Throughout this dissertation, it is discussed how the implementation of these improvements benefits the simulation of hybrid programs and are explained the key methods adopted for their conception. Finally, this new version of Lince is put to the test by handling case studies related to autonomous driving (for example, adaptive cruise control and a missile targeting a moving object) and other types of systems as well, such as purely physical systems and the so-called on-off systems. The results obtained in the treatment of these case studies attest to the enhanced capabilities of this tool and the contribution of this dissertation to the scientific community, demonstrating its relevance in simulating integrated systems in everyday life. Keywords Lince, hybrid programming, autonomous driving, SageMath. iv Resumo A evolução de produtos de software que interagem com o mundo físico levou a uma maior necessidade de simular o seu comportamento como forma de verificar a sua eficácia e segurança em diferentes cenários. Este projeto de dissertação tem como objetivo melhorar uma ferramenta de simulação para programas híbridos denominada Lince, mais especificamente para fornecer capacidades de simulação mais poderosas a programas híbridos regulados pela mecânica Newtoniana. Estas incluem a adição de novas construções linguísticas (como o operador de divisão e as funções trignométricas), a implementação de expressões não-lineares, relaxamento e organização da gramática, melhoria da deteção de erros e a mitigação de problemas existentes associados à ferramenta. Ao longo desta dissertação, é discutida a forma como a implementação dessas melhorias beneficia a simulação de programas híbridos e são explicados os principais métodos adotados para a sua conceção. Finalmente, esta nova versão do Lince é testada através do tratamento de casos de estudo relacionados com a condução autónoma (por exemplo, o adaptative cruise control e um míssil que visa um objeto em movimento) e também outros tipos de sistemas, como sistemas puramente físicos e os chamados sistemas on-off . Os resultados obtidos no tratamento destes casos de estudo aferem para as capacidades melhoradas desta ferramenta e o contributo desta dissertação para a comunidade científica, demonstrando a sua relevância na simulação de sistemas integrados no quotidiano. Palavras-chave Lince, programação híbrida, condução autónoma, SageMath v Contents I Introductory material 1 1 Introduction 2 1.1 Motivation and context ................................ 2 1.2 Contributions ..................................... 3 1.3 Document structure .................................. 4 2 State of the Art 6 2.1 Hybrid systems and cyber-physical systems ...................... 6 2.2 Modelling cyber-physical systems: tools ........................ 8 2.3 Lince in detail ..................................... 9 2.3.1 Example 1: A simple displacement ...................... 10 2.3.2 Example 2: Cruise control .......................... 11 2.3.3 Example 3: Unsupported example ...................... 12 2.3.4 Strengths and limitations ........................... 13 2.4 Scala overview .................................... 15 2.4.1 What is the Scala language? ......................... 15 2.4.2 Scala’s most important instructions and features ............... 16 2.4.3 Abstract data types in Scala ......................... 16 2.4.4 Parsing ................................... 17 II Core of the Dissertation 21 3 Lince and Newtonian Systems 22 4 Extending Lince’s Language 28 vi 93 Position of the projectile in the “x” and “y” coordinates .................115 94 Representative image of a RLC series electrical circuit [CC06]. .............116 95 Variation of voltage across the capacitor for critically damped regime (green), for underdamed regime (orange), and for overdamped regime (grey). ..............118 96 Schematic representation of the hydraulic system to be simulated. ...........120 97 Evolution of water level in the tank (red) and faucet state (green). ............121 98 Graphical representation of the numerical derivative (purple) and numerical integral (green) of the function x2 (red) ............................124 99 Graphical representation of the function x2 (pink), the function 2x (purple) and the function (1/3)x3 (orange) .................................124 xiii List of Tables 1 Arithmetric operators supported by Lince ....................... 25 2 Mathematical functions supported by Lince ...................... 26 3 Mathematical constants supported by Lince ...................... 26 4 Arihtemetic operators .................................154 5 Relational operators ..................................155 6 Logic operators ....................................155 7 Bitwise operators ...................................155 8 Assignment operators .................................156 xiv Acronyms CPS Cyber-Physical System CPSs Cyber-Physical Systems AEB Automatic Emergency Bracking ACC Adaptative Cruise Control DDL Differential Dynamic Logic CTL Computation Tree Logic JVM Java Virtual Machine xv xvi Part I Introductory material 1 Chapter 1 Introduction 1.1 Motivation and context Hybrid programs orchestrate classical computation with physical processes, for example movement and velocity, in order to achieve certain goals. In modern programming practice there is a growing trend of combining programs with physical processes, even though this combination is often implicit. The reason behind this trend is the need to deliver software products that can closely interact with the physical world, typically involving aspects such as velocity, movement, energy, and time. Numerous examples of such systems exist, spanning from small medical devices like pacemakers and infusion pumps to more complex systems like surgical robots, autonomous vehicles, and large-scale electric grids that serve entire districts [Nev18]. Figure 1: Pacemaker device [Hea22] . Figure 2: Autonomous vehicle [Aut]. The rapid proliferation of hybrid programs in the recent decades has led to a flurry of research on languages, semantics and tools for their design and analysis [GNP20a,GST09,Pla10,SH11]; but while great progress has been made in this area, several important challenges remain largely open. A case in point concerns the simulation of hybrid programs centred on the tool Lince [GNP20a]: it lacks certain language constructs that are important for modelling important classes of hybrid programs, particularly 2 those governed by Newtonian mechanics, such as autonomous vehicles. The latter are important because a myriad of autonomous systems are currently under development and being able to simulate them before implementation is useful to ensure that they will behave as intended. 1.2 Contributions The first objective of this dissertation was to enhance the tool Lince in order to improve the simulation of hybrid programs, in particular to make it better suited to those programs that interact with physical processes governed by Newtonian mechanics. The improvements and contributions made in this regard consist of: •Addition of new language constructs: this includes arithmetic operators such as division and remainder and mathematical functions such as exponentiation, power, square root, and trigonometric functions. This expansion enables a more rigorous simulation of hybrid programs that, for example, depend on calculating intersection points between two trajectories (which often involves the use of division and square roots). •Extension of the Lince programming language to support non-linear expressions: the ability to use non-linear expressions, along with the new constructs, enables not only the simulation of a wider range of hybrid programs, but also provides an increased user comfort in their design. •Detection and implementation of potential improvements: these improvements consist, for example, in avoiding what we call ‘block assignments’, which require assignments to be made atomically rather than in blocks, and the relaxation of conditional expressions. •Enhancement of semantic error detection: this enhancement involves the development of semantic error detection strategies, such as mathematical indeterminacies, and the detection of non-supported mathematical operations. This contribution will facilitate the user’s debugging process. •Mitigation of existing limitations in Lince: this improvement consists of mitigating some of the limitations of the tool, such as the inability to handle large symbolic expressions. The second objective of this dissertation was to explore case studies using Lince’s improved version. In this regard, we put special emphasis on case-studies revolving around autonomous driving, due to their recent proliferation in the automotive industry. Specifically, we explored Automatic Emergency Bracking 3 (AEB) systems, Adaptative Cruise Control (ACC) and a system capable of missile targeting a moving object. Other important systems, such as classical physics systems and on-off systems, were also thoroughly studied. In sum this dissertation develops a “next-generation” simulation tool with applications in diverse areas, offering a wide range of possibilities for precise and comprehensive simulations of hybrid programs. 1.3 Document structure This dissertation consists of 6 chapters that address different aspects of the project. Below is a summary of each chapter: •Chapter 1: Introduction In this initial chapter the context that motivated this dissertation project is presented and the main contributions made are highlighted. The chapter also provides an overview of the document’s structure. •Chapter 2: State of the Art The second chapter addresses the concepts of a hybrid system and of a cyber-physical system. Additionally, examples of tools capable of modelling and simulating hybrid programs will be presented, with a special focus on the tool Lince. The strengths and weaknesses of the tool will be analysed, and a brief overview of the Scala language, used in the implementation of Lince, will be provided, with emphasis on parsing. •Chapter 3: Lince and Newtonian Systems The third chapter covers the types of differential equations required to model hybrid programs regulated by Newtonian mechanics. The main obstacles limiting the design in Lince of a wide range of hybrid programs governed by Newtonian mechanics will be identified. Moreover the implemented solutions to overcome these obstacles will be presented, enabling a more comprehensive and accurate simulation. •Chapter 4: Improvements to Lince In this chapter each of the implemented solutions will be detailed, presenting the limitations of the previous version, the adopted method to overcome them, and the results obtained from the changes made. 4 •Chapter 5: Autonomous Driving and Beyond The fifth chapter discusses the importance of autonomous driving and its limitations. The utility of Lince’s improved version in the simulation of systems associated to autonomous driving will be highlighted, as well as Lince’s ability to simulate classical physical systems, on-off systems, and to perform numerical calculations. •Chapter 6: Conclusion and Future Work In the final chapter, possible future work and conclusions are drawn from this dissertation and discussed. Additionally, an Appendix is also provided with relevant functions for the improvement of the tool, the full version of the hybrid programs explored in the case studies, the grammars of Lince’s old and new versions, and further exploration of some topics addressed in the aforementioned overview of the language Scala. 5 Chapter 2 State of the Art 2.1 Hybrid systems and cyber-physical systems As explained in [BG11], the term “Cyber-Physical System (CPS)” refers to next-generation digital devices that closely interact with physical processes, such as velocity, time, and movement. Such a discretecontinuous interaction gives rise to new, interesting ways of managing the physical world through computation, communication and control. It is therefore a key piece in future technological developments. On the other hand, the term “hybrid system” is used almost as a synonym to that of a CPS but such is not the case. Whilst the latter usually refers to an actual technological piece (or composite) of software (or hardware), the former is typically reserved to the mathematical model used to study the behaviour of aCPS, the external environment, and their interaction. Interestingly, as a modelling framework, hybrid systems go much beyond cyber-physical ones, as they avoid some restrictions concerning computability. For example, one can model impact-based physical systems, such as a bouncing ball (which can bounce infinitely many times in finite time) [HLLDS09]. As referred in [Mat21], Cyber-Physical Systems (CPSs) are used in various areas, some of which are: •Manufacturing - They are useful in optimising manufacturing processes, reducing costs, labour and production times; •Healthcare and Medical Devices -CPSs allow to monitor and manage the state and physical condition of patients, both remotely and in real-time. They also allow to monitor older people through intelligent sensors which e.g. in case of a fall send out an alert; •Agriculture -CPSs facilitate a more efficient use of water and pesticides. Also, these systems can accurately collect and analyse the state of the soil, climate, etc., to improve agricultural management; 6 interval. In both cases the front vehicle maintains a constant speed. When this program is given as input to Lince, the following parsing error message is returned: Er ro r : When par si ng G§15 // maximum time i n the plot§0§p :=0; v :=0; p l :=50; v l :=10; np:=0; nv :=0; aux :=0; while true do{ np:=p+v +2.5; nv:=v+5; aux:=pow (( nv−10) ,2)+4∗(np−(p l +10)) ; i f (np<p l +10)/\( aux<0) then p’=v , v ’=5 , pl ’=10 f o r 1 ; e l s e p’=v , v’=−2,pl ’=10 f or 1; } − hprog .common. ParserException : [ 3 . 1 ] f a i l u r e : end of input expected while true do{ ^ Figure 7: Error message returned by Lince This happens because the instruction “pow((nv-10),2)” (responsible for exponentiation) does not exist in Lince’s language. A few other limitations are mentioned in the following section. 2.3.4 Strengths and limitations Like any tool, Lince offers a number of advantages, some of which are [GNP19,GNP20a,GNP20b]: •Simple program constructs – A very simple, clear language with program constructs familiar to all programmers. Contrarily to e.g. Simulink, the language is text-based which facilitates the development of complex systems whilst in Simulink its visual design may become quite cumbersome; •Well-defined semantics – Contrarily to most tools, Lince’s language has a clear, well-defined semantics which allows for a more rigorous verification of safety-critical systems; •Simulations capabilities — Contrarily to Keymaera X, Lince has simulation capabilities which facilitates the analysis of complex systems. In fact in the former tool, theorem proving is a highly specialised task and resource-demanding. Simulation, on the other hand, is a relatively easy task to perform which can already reveal many possible bugs in the system under development. Lince has also several restrictions that hinder its use in more complex hybrid programming. In detail: •Only linear expressions – Assignments only support simple linear expressions which greatly restricts the specification of discrete actions. This restriction also applies to the specification of a 13 continuous dynamic’s duration, in the expressions of the differential equations and in the relational expressions; •Rigid syntax – For example the relational expressions of conditional instructions can only contain a variable on the left of the relational operator and a linear expression on the right, making it impossible, for example, to have “x+1<=y+2”. Furthermore, linear expressions are associated with a very restricted syntax, so that it is not possible to use, for example, “2*(x/2)”, but if you write “2*(x*0.5)”, there is no problem (the reader is advised to consult the Lince’s grammar of the old version from the non-terminal symbol linP to the end in Appendix B.1); •Few supported arithmetic operators and no supported mathematical functions/constants – The only supported operators were addition, subtraction, negation, and multiplication; •Unintuitive atomic assignments – The semantic analyser updates the values of the variables at the end of each assignment block and not at each assignment necessarily. For example, if the variable “x” is assigned with the value 1and “y” with the value 0, and within a “if-then-else” is introduced the statement “x:=10; y:=x+10;”, the result of the variable assignment “x” will be 10, while the variable “y” will be assigned a value of 11, which is different from the expected value of 20. This is because variable values are not updated after each assignment, but at the end of the assignment block, and so “x” had not yet been updated when the assignment “y:=x+10;” was performed. The previous situation also caused the initial assignments not to support the use of variables on the right-hand side, even if they had been previously assigned. This situation occurred because variables are recognised/stored at the end of the assignment block, and whenever the variables on the right hand side of the initial assignments were encountered, they had not yet been recognised/stored. As a result, Lince would return an error message indicating the presence of this variables, which might not have been expected by the user. •Incomplete parser of replies from SageMath– SageMath does not always find a (simple) solution, sometimes it produces replies that Lince’s parser cannot handle; •Error messages – In general, the error messages produced by Lince are too vague and not useful for the user; •SageMath limitations– The way in which Lince is implemented and/or the existence of SageMath limitations entails the existence of programs that cannot properly yield a symbolic plot; 14 The scope of this dissertation is essentially to try to overcome the previous restrictions in order to allow the creation of a simulator of hybrid programs that is better adapted to dealing with programs that interact with physical processes regulated by Newtonian mechanics. 2.4 Scala overview To develop the Lince, its creators used the programming language Scala. In the following subsections, the key concepts of Scala will be explained, especially those that were crucial not only to develop Lince but also to modify and add new functionalities to the tool in this dissertation. 2.4.1 What is the Scala language? As described in [tut], Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant and safe way, smoothly integrating the features of objectoriented and functional languages. This language presents certain characteristics that make it different from most conventional programming languages, such as Python, some of which were mentioned in the previous reference and will be mentioned here [tut, Overview]: •Scala is object-oriented - Scala is an object-oriented language, where the types and behaviour of objects are defined by classes; •Scala is functional - In a functional language a function is a value, and since in Scala a value is an object, then a function is an object; •Scala is statically typed - Unlike other languages, in Scala it is not obligatory to assign the data type in the vast majority of cases – the compiler infers the type based on the data assigned; •Scala can execute Java Code - Scala can be compiled into Java Byte Code which is run by the Java Virtual Machine (JVM). Futhermore Scala can import existing Java libraries; •Scala can compile to JavaScript - Scala can also be compiled into JavaScript using the Scala.js plug-in [ALRF+22]. The compiled JavaScript file can be included in an HTML file and be executed in any modern internet browser. 15 2.4.2 Scala’s most important instructions and features Let us now discuss some of the most relevant Scala instructions and features in the context of this dissertation. As typical features of most programming languages, Scala allows: • To declare mutable and immutable variables (see Appendix B.3); • To use data types “Int”, “Float”, etc (see Appendix B.3); • To use common operators such as “+”, “<”, “>”, etc (see Appendix B.4); • To perform “While”, “Do-While” and “For”loops, as well as the conditional structure “ifelse” and the declaration of functions (see Appendix B.5); • To work with strings and arrays (see Appendix B.6). In addition to these “standard” features, Scala is an object-oriented language, where the types and behavior of objects are defined by classes, and a class can inherit from another class (see Appendix B.7). 2.4.3 Abstract data types in Scala We will now focus on some concepts involving abstract datatypes in Scala. Due to the the nature of this dissertation we will only give a very brief overview. The curious reader is invited to consult Appendix B.7 to gain a better understanding of some concepts discussed in this section. In Scala there are four types of classes that are important to deal with in the scope of our project, these being abstract,trait,case and sealed classes. Based on the code excerpt from Fig. 8from the “Syntax.scala” file (one of the files responsible for making the Lince parser ), we can see that it uses at least three of the classes we intend to deal with. The class “LoopGuard” (corresponding to the loop guards) is of abstract type and of sealed type. In the context of this project, abstract type means that this class doesn’t need to have its body defined and can never be instantiated [Gee19a], whereas sealed type means that this class can only have heirs in that file and as a consequence Scala’s type system is able to give warnings when finding uncovered cases in case analysis [oS22]. 16 sealed abstract cla s s LoopGuard case c lass Counter ( i : Int ) extends LoopGuard case c lass Guard( c : Cond) extends LoopGuard Figure 8: “ LoopGuard ” sealed abstract class The classes “Counter” (which corresponds to guards consisting only of integers) and “Guard” (which corresponds to guards consisting of Boolean conditions) are all inherited from the “LoopGuard” class and are of the case type. In the context of this project, the case type means that classes don’t need the “new” keyword to be instantiated, and more importantly, it allows for pattern matching [Gee19c]. Pattern matching happens for example in this code excerpt from Fig. 9from the “Utils.scala” file (which contains auxiliary functions used in the implementation of Lince). def getVars ( guard : LoopGuard) : Set [ String ] =guard match { case Counter(_) => Set () case Guard( c ) => getVars(c) } Figure 9: Function “ getVars ” It takes the argument “guard” (which is of type “LoopGuard”) and returns the set of variables present in it, checking first whether the argument is a “Counter” case class (a “Counter” is associated with an integer, so an empty set is returned) or a “Guard” case class (a “Guard” is associated with a condition, so the “getVars” function is used to return the set of variables present in it), this verification method is only possible because these two classes are of case type. As for the trait type, this is also used in the development of the Lince language, and this type is a variation of the abstract type with support for multiple inheritance (class that inherits from more than one class) [oS23]. 2.4.4 Parsing Following Gabriele Tomassetti [Str22], parsing is defined as: “The analysis of an input to arrange the data according to the rule of a grammar”. In other words, a parser is used for encoding input data into a structured data type ( i.e. based on a grammar). Programming languages are a good example of this, as programs are written in a file and understood by humans, and need to be converted into a data structure to be understood by computers and thus analysed and executed. 17 A very important component in parsing is regular expressions , which according to Gabriele Tomassetti [Str22] are defined as: “A sequence of characters that can be defined by a pattern”. Regular expressions are widely used in lexers, becoming a very powerful tool, because a pattern of characters can identify a set of characters/words in which we are interested. For more detailed information about regular expressions , see the reference [Doc22]. Looking at the structure of the parser . It generally consists of a lexer , which is responsible for converting the input text into a set of tokens , and the parser itself, which takes the set of tokens and performs their syntactic analysis (basically, checks whether they respect the grammar established in the parser ), returning an organised data structure that will later be processed by the semantic analyser to check for semantic errors and process the results [Str22]. Apart from this way of parsing, where one separates the lexer from the parser , there are situations where that is not so easy and so the parser ends up doing both at the same time, keeping a grammar identical to what it would be if it had the lexer separated [Str22]. In addition to everything seen in the previous sections, many approaches and libraries to implement parsers exist in Scala. A common approach, followed e.g. by ANTLR [Ter13], is to describe the grammar of the input language in a dedicated language and to generate code automatically that converts text into intermediate data structures. An alternative approach, followed by Lince and used in this project, is to use so-called parsing combinators . These are popular in functional programming languages, where parsers are built with the help of combinators that, given a sequence of parsers , produce a new parser . This will be further explain below. This approach facilitates the compilation of Scala to both Java and to JavaScript, since it does not rely on code generators. Pedro Palma Ramos [Ram16] describes in detail how to use the parser combinators to create a lexer and a parser to make a workflow. This reference is recommended to be read so that the reader can gain a better understanding on how to create a separate lexer and parser using parser combinators . However, the parsing done in this project was made differently from the parsing described in reference [Ram16], due to the fact that the lexer is created not separately but together with the parser , among other changes. We thus choose to describe how this concrete parsing works and let the reader investigate how other parsing methods can be performed in Scala. Initially, a file called “Syntax.scala” was created, which contains a set of classes that will serve as the parser’s output. The main sealed abstract class is called “Syntax” and is associated to a program. From it four inheritance case classes were created: “Atomic” (associated to assignments and differential equations), “Seq” (associated to the composition of programs), “ITE” (associated to the conditional structure 18 “if-then-else”) and “While” (associated to the cyclic structures “while” and “repeat”). These case classes take arguments, for example the “While” case class takes three arguments. The first is of type “Syntax” (program before the “while” loop), the second is of type “LoopGuard” (corresponds to the “while” loop guard and its implementation was shown in Fig. 8) and the third is of type “Syntax” (corresponds to the program in the body of the “while” loop). To elaborate the data types that are present in the arguments of the previous classes, it was necessary to create certain case classes and sealed abstract classes, and even after elaborating them, it may or may not be necessary to create classes that define the data types of the arguments of these new classes. Next, the file “Parser.scala” was created. It contains the instructions for performing the parsing operations. This file begins by creating an object with the same name as the file, which inherits from “RegexParsers” to allow the use of regular expressions . Next, a function called “parse” is created, which receives as argument a string representing the input text, and performs the parsing of that string using the “parseAll” instruction (present in the library of parser combinators ). This instruction only needs to receive two arguments, one is the input text, and the other is the variable “progP”. The variable “progP” uses the parser combinators to verify whether the input text complies with the grammar intended for the Lince language and to return the corresponding parsing. This variable can be found right at the beginning of the grammar diagram in Appendix B.1, and one can see that it can only be the variable designated by “seqP”. The “seqP” variable checks if the input text complies with the grammar of a “while” loop, a “repeat” loop, an atomic instruction3, an “if-then-else” condition and a “wait” command (via the “basicProg” variable), or any combination of these and return the corresponding parsing. To do this, this variable either returns only the “basicProg” variable, or uses recursion and returns the “basicProg” variable followed by “seqP” itself. The “basicProg” variable, as mentioned earlier, is associated with one of the aforementioned instructions and therefore requires the use of other variables, such as “whileGuard” (is responsible for parsing the guards of the “while” loops) and “linP” (is responsible for parsing the linear expressions). By creating and associating the variables in this file, the grammar of Lince was developed (the complete grammar of the old version of Lince can be found in Appendix B.1). To describe how these variables perform parsing of the produced text, based on the parser combinators provided by Scala, it was decided to extract the “whileGuard” and “durP” variables from the “Parser.scala” file. The Fig. 10 contains the code excerpt that implements these two variables. The “whileGuard” variable, as mentioned earlier, is responsible for parsing the guards of the “while” 3An atomic instruction consists of the most elementary instruction supported by Lince, which is a list of assignments and a list of differential equations with or without duration. 19 lazy val whileGuard : Parser [ LoopGuard ] ={ condP ^^ Guard | intPP ^^ Counter } lazy val durP : Parser [ Dur] = ”until” ~ opt ( untilArgs ) ~ condP ^^ { case _ ~ None ~ cond => Until (cond , None , None) case _ ~ Some( args ) ~ cond => Until (cond ,Some( args ._1) , args ._2) } | ” for ” ~> linP ^^ For Figure 10: Variable “ whileGuard ” and variable “ durP ” loops, while the “durP” variable is responsible for parsing the durations (see the grammar in Appendix B.1 to understand where these variables fit in) . Regarding the “whileGuard” variable, it has the possibility of receiving the “condP” variable (responsible for returning the parsing of conditions) or the “intPP” variable (responsible for returning the parsing of integers), this possibility of choice of more than one input parsing is due to the use of the “|” combinator (the combinators covered here come from the parser combinators library). If it receives the “condP” variable then the “Guard” case class will have to be returned, however if it receives the “intPP” variable it will have to return the “Counter” case class (these two case classes were covered in the Section 2.4.3). The combinator responsible for modifying the value returned by a parser is the “^^” combinator. As for the variable “durP”, it is only important to mention the other combinators that are used in its implementation, covering all the combinators used in parsing development, namely: the ‘~” combinator, which serves to compose parsers sequentially; the “~>” combinator, which only considers the parsing that this combinator points to; the “opt(...)” combinator, which checks whether the parsing procedure in its argument was successful or not, returning “Some(...)” (together with the corresponding result) if it was and “None” if it wasn’t. The parser combinators library also provides the ability to create basic parsers for keywords (such as the “until” instruction on the variable “durP”) and for regular expressions. After obtaining the result of parsing the input text, the semantic analyzer will take this result and check for semantic errors, calculate the values assigned to variables and determine the solutions of differential equations (using SageMath), among other things. 20 Part II Core of the Dissertation 21 Chapter 3 Lince and Newtonian Systems In the simulation of hybrid programs regulated by Newtonian mechanics, particularly in the field of kinematics, it is of utmost importance to understand the differential equations used to simulate the temporal evolution of the variables involved. These equations establish fundamental relationships between the positions, velocities, and accelerations of moving bodies, enabling us to predict and describe their behavior over time. As referred in [Pla18a], the basic system of differential equations for 1D motion is as follows: x′=v, v′=a(3.1) These differential equations tell that the rate of change of position (x) is velocity (v), and the rate of change of velocity (v) is acceleration (a). Given the initial conditions of the body, i.e. initial position and initial velocity, we obtain solutions to the differential equations (3.1) which characterize the motion of the body in 1D. An example in which the aforementioned system of differential equations is used is the simulation of programs that aim to manage a train’s motion. Since trains move exclusively on a track, it is often sufficient to describe its motion in 1D. The system of differential equations can be reformulated to describe the motion of a body in 2D and 3D. Based on reference [Pla18b], the system of differential equations for 2D motion is represented as follows: x′=v, y′=u, v′=ω∗u, u′=−ω∗v(3.2) The body is located at position (x,y) and moves in the direction (v,u), which means that the body moves along the x-axis with a velocity vand along the y-axis with a velocity u. The direction of the body can vary, curving to the right (if ωis greater than zero), curving to the left (if ωis less than zero), or moving in a straight line with a constant velocity (if ωis equal to zero). The value of ωrepresents the angular velocity of the body, and thus, a larger value of ωleads to faster and tighter curves. Additionally, the body can be accelerated with a constant acceleration in each of its axes. This can be achieved by modifying the previous system of equations so that the derivative of vand the derivative of w are both equal to a real number. 22 4.1.1 Updated data structures To update the data structures returned by the parser, we need to modify the “Syntax.scala” file. This file, as mentioned in Section 2.4.4, is essentially made up of a set of classes of the case type that will serve as output from the parser, to be later processed by the interpreter (which performs semantic operations, iterating with SageMath and the Inspector, as mentioned in Section 2.3). As such, it was necessary: • To implement data structures referring to non-linear expressions; • Change the data structures of assignments, relational expressions, durations and differential equations in order to admit non-linear equations; • Ensure that pre-processing functions do not group a sequence of assignments into a single atomic instruction. To implement the data structures referring to non-linear expressions it was necessary to alter the abstract class for linear expressions, changing its name to “Notlin” and adding inherited classes for the remaining arithmetic operators, mathematical functions and mathematical constants planned to add. The code excerpts in Fig. 11 represent the data structure of linear expressions (left), and the implementation of the data structure of non-linear expressions (right). There are now a case class (which in other words are the data structures that will be returned by the parser) directed to a variable (“Var”), a real number (“Value”), addition of two non-linear expressions (“Add”), multiplication of two non-linear expressions (“Mult”), division of two non-linear expressions (“Div”), remainder of two non-linear expressions (“Res”) and a case class “Func” directed to the mathematical functions and mathematical constants that we intend to add (see Table 2and Table 3of the Chapter 3). To enable the data structures associated with assignments, relational expressions, durations and differential equations to support non-linear expressions rather than linear ones, the data type of the arguments associated with linear expressions within these case classes has been converted to the corresponding data type for non-linear expressions. In the case of assignments, their data structure has been modified as illustrated in the code excerpt in Fig. 12 (on the left is the data structure of the assignments of the old version, on the right is the data structure of the assignments of the new version). 29 // Original data structure sealed abstract c las s Lin { def +(other : Lin ) : Lin =Add( this , other ) } case c lass Var(v : String ) extends Lin { def :=( l : Lin ) : Assign =Assign ( this , l ) def ^=( l : Lin ) : DiffEq =DiffEq ( this , l ) def >(l : Lin ) : Cond =GT( this , l ) def <(l : Lin ) : Cond =LT( this , l ) def >=( l : Lin ) : Cond =GE( this , l ) def <=( l : Lin ) : Cond =LE( this , l ) def ===( l : Lin ) : Cond =EQ( this , l ) } case c lass Value (v : Double) extends Lin { def *( l : Lin ) : Lin =Mult( this , l ) } case c lass Add( l1 : Lin , l2 : Lin ) extends Lin case c lass Mult (v : Value , l : Lin ) extends Lin // Updated data structure sealed abstract cl a s s NotLin { def +(other : NotLin) : NotLin =Add( this , other ) } case c lass Var(v : String ) extends NotLin { def :=( l : NotLin) : Assign =Assign ( this , l ) def ^=( l : NotLin) : DiffEq =DiffEq(this , l ) def >(l : NotLin) : Cond =GT( this , l ) def <(l : NotLin) : Cond =LT( this , l ) def >=( l : NotLin) : Cond =GE( this , l ) def <=( l : NotLin) : Cond =LE( this , l ) def ===( l : NotLin) :Cond =EQ( this , l ) } case c lass Value (v : Double) extends NotLin { def *( l : NotLin) : NotLin =Mult( this , l ) } case c lass Add( l1 : NotLin , l2 : NotLin ) extends NotLin case c lass Mult( l1 : NotLin , l2 : NotLin) extends NotLin case c lass Div( l1 : NotLin , l2 : NotLin) extends NotLin case c lass Res( l1 : NotLin , l2 : NotLin) extends NotLin case c lass Func( s : String , arg : List [ NotLin ] ) extends NotLin Figure 11: Data structure of linear and non-linear expressions // Original data structure case c l ass Assign (v : Var , e : Lin ) // Updated data structure case c l ass Assign (v : Var , e : NotLin ) Figure 12: Data structure of assignments in both versions of Lince For relational expressions, their data structure has been changed as illustrated in the code excerpt in Fig. 13 (on the left is the data structure of the relational expressions of the old version, on the right is the data structure of the relational expressions of the new version). (Note: The data types of the arguments in each case class of the relational expressions were both 30 // Original data structure case c l ass EQ( l1 : Var , l2 : Lin ) extends Cond case c l ass GT( l1 : Var , l2 : Lin ) extends Cond case c l ass LT( l1 : Var , l2 : Lin ) extends Cond case c l ass GE( l1 : Var , l2 : Lin ) extends Cond case c l ass LE( l1 : Var , l2 : Lin ) extends Cond // Updated data structure case c l ass EQ( l1 : NotLin , l2 : NotLin) extends Cond case c l ass GT( l1 : NotLin , l2 : NotLin) extends Cond case c l ass LT( l1 : NotLin , l2 : NotLin) extends Cond case c l ass GE( l1 : NotLin , l2 : NotLin) extends Cond case c l ass LE( l1 : NotLin , l2 : NotLin ) extends Cond Figure 13: Data structure of the relational expressions in both versions of Lince converted to type “NotLin” (previously “l1” was of type “Var” and “l2” was of type “Lin”) so that the relational expressions would allow relating two non-linear expressions instead of relating a variable to a linear expression, thus giving greater power and flexibility in the writing of relational expressions.) As for durations and differential equations, the code excerpts in Fig. 14 represent the data structures of durantions and differential equations of the old version (left) and the data structures of durations and differential equations of the new version (right). // Original data structure // D i f f e r e n t i a l equation case c l ass DiffEq (v : Var , e : Lin ) // Duration sealed abstract cl a ss Dur case c l ass For ( e : Lin ) extends Dur case c l ass Until ( c :Cond, eps : Option [ Double ] , jump : Option [ Double ] ) extends Dur case object Forever extends Dur // Updated data structure // D i f f e r e n t i a l equation case c l ass DiffEq (v : Var , e : NotLin ) // Duration sealed abstract cl a ss Dur case c l ass For ( e : NotLin ) extends Dur case c l ass Until ( c :Cond, eps : Option [ Double ] , jump : Option [ Double ]) extends Dur case object Forever extends Dur Figure 14: Data structures of the differential equations and duration in both versions of Lince Finally, to ensure that the pre-processing functions did not combine sequences of assignments into a single atomic instruction1, it was necessary to eliminate the third case from the method “∼” within the “Atomic” case class, as shown in the code excerpt in Fig. 15. The third case in the method referenced in Fig. 15 was triggered when the method was applied between an atomic instruction containing only 1An atomic instruction consists of the most elementary instruction supported by Lince, which is a list of assignments and a list of differential equations with or without duration. 31 case c lass Atomic( as : List [ Assign ] , de : DiffEqs ) extends Syntax { override def ~(p : Syntax ) : Syntax =( de . dur , p) match { case (_, Seq (p , q) ) => Seq( t hi s ~p , q) case (_, While ( pre , d , doP) ) => While( t hi s ~pre , d , doP) /** case ( For( Value (0) ) , Atomic( as2 , de ) )=>Atomic( as++as2 , de ) */ case (_,_) => Seq( this , p) } } Figure 15: Data structure of an atomic instruction and its corresponding method in the new version of Lince assignments (resulting in a zero duration for the differential equations) and another atomic instruction. Since the continuous component of the first atomic instruction did not exist or did not evolve in time, then it was only necessary to take into account the discrete component, which was the assignments, and join them with the discrete component of the second atomic to form a single atomic instruction. However, the interpreter was designed to update the value of the variables at the end of each atomic instruction, and if that atomic has a list/block of assignments associated with it, unexpected results can happen, as in the example referred to in Section 2.3.4 in the topic “Unintuitive atomic assignments”. As such, it was necessary to remove this case so that the grouping of assignments would no longer happen, ensuring that atomic instructions are associated with only one assignment and that variable assignments are performed sequentially/atomically. 4.1.2 Updated parser After creating a data structure for the non-linear expressions, compatibilizing the remaining data structures to handle these expressions and avoiding grouping assignments into an atomic instruction, it was necessary to modify the file “Parser.scala”. This file is responsible for parsing, according to a certain grammar, the hybrid program developed in the Lince tool. The changes made in this file were intended to modify the grammar and the output coming from the parser, so that the hybrid programs: • Start with at least one atomic instruction to ensure that the initial assignments are made at the beginning of the program; • Recognise non-linear expressions; • Associate durations, assignments and differential equations with non-linear expressions; 32 • Have a more relaxed grammar of relational expressions, being able to relate a non-linear expression to another non-linear expression. In order for the language grammar to require the initial assignments to be made at the beginning of the hybrid program, the changes illustrated in Fig. 16 have been implemented (on the left is the implementation of the old version and on the right is the implementation of the new version). lazy val progP : Parser [ Syntax ] = seqP ^^ { stx => Utils . isClosed ( stx ) match { case Left (msg) => throw new ParserException(msg) case Right (_) => stx } } lazy val seqP : Parser [ Syntax ] = basicProg ~ opt ( seqP ) ^^ { case p1 ~ Some(p2) => p1 ~ p2 case p ~ None => p } lazy val progP : Parser [ Syntax ] = declr ^^ { stx => Utils . isClosed ( stx ) match { case Left (msg) => throw new ParserException(msg) case Right (_) => stx } } lazy val declr : Parser [ Syntax ] = atomP ~ opt ( seqP ) ^^ { case a ~ Some(n) => a ~ n case a ~ None => a } lazy val seqP : Parser [ Syntax ] = basicProg ~ opt ( seqP ) ^^ { case p1 ~ Some(p2) => p1 ~ p2 case p ~ None => p } Figure 16: Change made in the parser to require the hybrid program to begin with an atomic instruction The “progP” variable is meant to hold the parsing result (coming from the variable “seqP” in the old version and the variable “declr” in the new version), evaluate if there are certain semantic errors (by the “Utils.isClosed” function) and if the parsing contains one of these semantic errors, return it, if not, return the parsing result (we will deal with the detection of these semantic errors in the Section 4.5.1 and the Section 4.5.2). As for the variable “seqP”, it expects to receive the parsing of one instruction (it may come from a “while” loop, a “repeat” loop, a “skip” instruction, a “wait” instruction, an “if-then- else” or an atomic instruction) coming from the variable “basicProg”, or the composition of the parsings of more than one instruction. However, the variable “declr” was implemented in the new version and it was interspersed between the variable “progP” and the variable “seqP”. This variable expects to receive the parsing of an atomic instruction (assignment and/or differential equations) or the composition of the parsing of an atomic instruction with the result of the variable “seqP”, thus guaranteeing a grammar that requires at least one atomic instruction before starting other instructions. 33 To exemplify, consider the following hybrid program in Lince: x:= 1; y:= 10; i f (x<=y) then {x:=x+1;} el s e {x:=x+10;} If we run the previous hybrid program on each of the Lince versions and extract the output of the parser for each of them, we get the results shown in Fig. 17. Seq (Atomic( List ( Assign (Var(x) , Value ( 1. 0) ) , Assign (Var(y) , Value (1 0.0) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) , ITE(LE(Var(x) ,Var(y) ) , Atomic( List ( Assign (Var(x) , Add(Var(x) , Value ( 1 . 0) ) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) , Atomic( List ( Assign (Var(x) , Add(Var(x) , Value (10.0) ) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) ) ) Seq ( Seq (Atomic ( Li st ( Assign (Var(_x) , Value ( 1. 0 ) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) , Atomic( List ( Assign (Var(_y) , Value (10.0) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) ) , ITE(LE(Var(_x) ,Var(_y) ) , Atomic( List ( Assign (Var(_x) , Add(Var(_x) , Value ( 1.0) ) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) , Atomic( List ( Assign (Var(_x) , Add(Var(_x) , Value (10.0) ) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) ) ) Figure 17: Parser output from the old version (left) and the new version (right) We can verify in Fig. 17 that the parser output in both versions only differs in the fact that the new version returns an atomic instructon for each assignment (so that the updating of the variables would not be done in a block, as seen in Section 4.1.1) and that the name of the variables is preceded by the character “_” (the reason of the use of this character will be explain in the Section 4.2). Nevertheless, changing the previous example in order to remove the initial assignments (but without compromising the objective of the program): i f true then {x:=1+1;} el s e {x:=1+10;} The results shown in Fig. 18 are obtained for each of the Lince versions. We can verify in Fig. 18 that the new version returns an error message because, as already mentioned, it requires that the program always start with an atomic instruction2(whereas the old version does not), and this guarantee offers the following advantages: 2The atomic instruction required by Lince’s grammar at the beginning of the hybrid program can be an assignment and/or one or more differential equations. However, the interpreter will verify if the variables present in the differential equations have been assigned at the beginning of the program, and will return an error message if the program starts with one or more differential equations because their variables have not been previously assigned. 34 ITE(BVal( true ) , Atomic( List ( Assign (Var(x) , Add(Value (1.0) , Value (1.0) ) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) , Atomic( List ( Assign (Var(x) , Add(Value (1.0) , Value (10.0) ) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) ) Error : When parsing G§15 // maximum time in the p lot § 0§i f true then {x:=1+1;} e l s e {x:=1+10;} − hprog .common. ParserException : [ 1 . 4 ] f a i l u r e : ’ ’ ’ expected but ’ t ’ found i f true then {x:=1+1;} Figure 18: Parser output from the old version (left) and error message returned by the new version (right) • Makes hybrid programs more grammatically structured; • Allows the interpreter to more easily determine which assignments correspond to the initial assignments. Next, the grammar had to be modified to recognize non-linear expressions. To do so, it was necessary to change the variables responsible for recognizing linear expressions (variable “linP” and its complementary variables), so that they would recognize non-linear expressions (variable “notlinP” and its complementary variables). (Note: Due to the dimension of the codes elaborated for both variables, it was decided not to show them in the sequence of the previous paragraph. As such, to see the grammar associated with non-linear expressions you can consult Appendix A.1.) The grammar of non-linear expressions was designed to admit additions, subtractions, divisions, multiplications and remainders of two expressions, in addition to allowing the negation of an expression. On the other hand, these expressions can contain pi numbers, Euler numbers, real numbers, variables, non-linear expressions between parentheses and mathematical functions such as exponentiation, power, greater, lesser, square root, logarithm, base-10 logarithm and trignometric functions. In addition to the large number of operations that can be performed on non-linear expressions, the grammar of these expressions was designed to be as relaxed as possible, avoiding the writing limitations that existed in the grammar of linear expressions in the old version. With the grammar of non-linear expressions already elaborated, it was necessary to make the expressions of assignments, durations and differential equations associated to non-linear expressions. In each case, it was enough to change the variable that returned the result of the parser of the linear expressions, that is the variable “linP”, to the variable that returned the result of the parser of the non-linear expressions, that is the variable “notLinP”. Finally, it was enough to relax the grammar of the relational expressions, making them relate two 35 non-linear expressions instead of one variable and one linear expression. To do that, the variable “bopP” (responsible for recognizing and returning the parser of booleans and relational expressions) had to be changed as illustrated in the code excerpt in Fig. 19 (on the left is the variable “bopP” in the old version and on the right the variable “bopP” in the new version). lazy val bopP: Parser [Cond] = i d e n t i f i e r ~ opt ( bcontP ) ^? ( { case ” true ” ~ None => BVal( true) case ” f a l s e ” ~ None => BVal( f a l s e ) case e ~ Some( co ) => co (Var( e ) ) }: PartialFunction [ String ~ Option [ Var=>Cond ] , Cond ] , { case e ~ _ => s”Not a condition : $e” }) lazy val bcontP : Parser [ Var => Cond] = ”<=”~> linP ^^ ( e2 => ( e1 : Var) => e1 <=e2 ) | ”>=”~> linP ^^ ( e2 => ( e1 : Var) => e1 >=e2 ) | ”<” ~> linP ^^ ( e2 => ( e1 : Var) => e1 < e2 ) | ”>” ~> linP ^^ ( e2 => ( e1 : Var) => e1 > e2 ) | ”==”~> linP ^^ ( e2 => ( e1 : Var) => e1 === e2 ) | ” !=”~> linP ^^ ( e2 => ( e1 : Var) => Not( e1 === e2 ) ) lazy val bopP: Parser [Cond] = ” true ” ^^ { case _=> BVal( true) } | ” f a l s e ” ^^ { case _=> BVal( f a l s e ) } | notlinP ~ ”<=”~ notlinP ^^ { case l1 ~ _ ~ l2 => LE( l1 , l2 ) } | notlinP ~ ”>=”~ notlinP ^^ { case l1 ~ _ ~ l2 => GE( l1 , l2 ) } | notlinP ~ ”<” ~ notlinP ^^ { case l1 ~ _ ~ l2 => LT( l1 , l2 ) } | notlinP ~ ”>” ~ notlinP ^^ { case l1 ~ _ ~ l2 => GT( l1 , l2 ) } | notlinP ~ ”==”~ notlinP ^^ { case l1 ~ _ ~ l2 => EQ( l1 , l2 ) } | notlinP ~ ” !=”~ notlinP ^^ { case l1 ~ _ ~ l2 => Not(EQ( l1 , l2 ) ) } Figure 19: Change made in the parser to make it support relational expressions that relate two non-linear expressions (Note: The syntax schema of the new version of Lince can be found in Appendix B.2 and the syntax schema of the old version can be found in Appendix B.1) The following examples show the ability of the new version’s grammar to deal with hybrid programs containing non-linear expressions. If we have the following hybrid program: y:= 1; x:= 1; x:= sqrt (2^2+3^2)*x*y ; x’=sin ( pi () /2) for exp (2) ; 36 The output of the parser in the new version of Lince is shown in Fig. 20. Seq ( Seq (Seq (Atomic ( List ( Assign (Var(_y) , Value ( 1. 0) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) , Atomic ( Li st ( Assign (Var(_x) , Value ( 1. 0) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) ) , Atomic( List ( Assign (Var(_x) , Mult(Func( sqrt , List (Add(Func(pow, List (Value ( 2 . 0) , Value ( 2 .0) ) ) , Func(pow, List ( Value (3.0) , Value (2.0) ) ) ) ) ) , Mult(Var(_x) ,Var(_y) ) ) ) ) , DiffEqs ( List () , For(Value (0.0) ) ) ) ) , Atomic( List () , DiffEqs ( List ( DiffEq (Var(_x) ,Func( sin , List ( Div(Func(PI , List () ) , Value (2.0) ) ) ) ) ) , For(Func(exp , List ( Value (2.0) ) ) ) ) ) ) Figure 20: Parser output from the new version of Lince for the previous hybrid program It can be seen that the grammar is now able to recognize non-linear expressions (with the possibility of using the operations of the Table 1, the Table 2and the Table 3of the Chapter 3) both in assignments, differential equations, and durations. If we have the following hybrid program: x:= 1; y:= 0; i f (( x^2+sin (x) )<(y^2+cos (y) ) ) then x:= 10; el s e x:= -10; The output of the parser in the new version of Lince is shown in Fig. 21. Seq ( Seq (Atomic ( Li st ( Assign (Var(_x) , Value ( 1. 0 ) ) ) , DiffEqs ( List () , For(Value ( 0 . 0) ) ) ) , Atomic ( Li st ( Assign (Var(_y) , Value ( 0. 0) ) ) , DiffEqs ( List () , For(Value ( 0 . 0) ) ) ) ) , ITE(LT(Add(Func(pow, List (Var(_x) , Value ( 2.0) ) ) ,Func( sin , List (Var(_x) ) ) ) , Add(Func(pow, List (Var(_y) , Value (2.0) ) ) ,Func( cos , List (Var(_y) ) ) ) ) , Atomic( List ( Assign (Var(_x) , Value (10.0) ) ) , DiffEqs ( List () , For(Value ( 0 . 0) ) ) ) , Atomic ( Li st ( Assign (Var(_x) , Value ( -10 .0) ) ) , DiffEqs ( List () , For(Value ( 0 . 0) ) ) ) ) ) Figure 21: Parser output from the new version of Lince for the previous hybrid program It can be seen that the grammar has also started to recognize relational expressions over non-linear expressions, as intended. 37 4.2 Adaptation of the interpreter for the treatment of nonlinear expressions Having improved the grammar with the ability to recognise non-linear expressions, the next step was to alter the interpreter so that it would be able to handle non-linear expressions. As mentioned in Section 2.3, the interpreter is responsible for performing semantic operations. Some of the tasks performed by the interpreter include: • Simplify symbolically an expression (using Sage); • Calculate the approximate value of an expression; • Find the solution of a system of differential equations (using Sage); • Calculate symbolically the value of the variables at any given point in time (using Sage); • Calculate approximately the value of the variables at any given point in time; • Detection of semantic errors. The interpreter is implemented throughout several files. The main files that constitute the interpreter are: •Eval.scala - mainly responsible for: –Determining the numerical value of non-linear expressions from the parser of the hybrid program and the parser of SageMath; –Determining the respective boolean of the conditions boolean; –Converting the data type coming from the parser to the data type that is associated with the parsing of the SageMath response; –Updating expressions with the respective initial values. •Distance.scala - mainly responsible for: –Finding the closest point that satisfies a given condition; •Traj.scala - responsible for: 38 differential equations allows users to streamline the process by simply adjusting the assignments of these constants, resulting in automatic updating of the terms within the differential equations. To exemplify, based on the previous program, the ease that the use of constant variables brought when it comes to changing parameters in the differential equations, it was decided to pass the damped harmonic motion to the overdamping regime: m:= 1; // mass of the object k:= 2.32; // Spring constant b:= 3 . 5 ; // Damping constant x:= 2; // I n i t i a l position v:= 0; // I n i t i a l veloc ity x’=v , v’=-x*k/mv*b/m for 20; // D i f f e r e n t i a l equations The symbolic plot resulting from the previous hybrid program is depicted in Fig. 27. Figure 27: Symbolic plot of the damped harmonic motion in the overdamping regime. For the regime to become overdamping, it is necessary that b/(2m)>√k/m, which implies that b > 2m√k/m⇔b > 3.046, so if the damping constant has a value of 3.5, the regime becomes overdamping. Due to all this, it was enough just to change the variable “b” to the value 3.5. 4.3.2 Implementation of constant variables To enable the use of constant variables without them contributing to non-linearity, it was necessary to go to the file “Traj.scala”, and change the functions “runAtomicWithTime” (responsible for calculating the value of a given atomic instruction at a given time) and “runAtomicWithBounds” (responsible for calculating the value of a given atomic instruction for a given number of cycles or a given time limit). These changes were implemented at the beginning of each of the preceding functions. The process began by saving a list of dynamic variables from the differential equations of the atomic instruction received as arguments. Next, the symbolic expressions of each variable in the program were updated based on the assignments found in the atomic instruction. In the next step, the data type of each variable in the program 45 (symbolic data type) was converted to the “NotLin” data type (associated with the non-linear equations in the “Syntax.scala” file). After converting the data type of each variable in the program to the “NotLin” data type, the next phase involved examining each of the differential equations presented in the atomic instruction. This involved replacing constant variables with their corresponding expressions to ensure that the differential equations only contained dynamic variables. Finally, we conducted a thorough examination of the differential equations to identify potential problems. First, we checked for the presence of “max” or “min” instructions/mathematical functions with dynamic variables in their arguments. This step was crucial because SageMath sometimes exhibits inconsistencies in the symbolic computation of these instructions, leading to incorrect results. In cases where such instructions were found, the system generated an error message indicating the problematic differential equation. Next, we verified whether the differential equations exhibited any non-linear characteristics. If any of the equations exhibited, or were suspected of exhibiting, non-linearity, the system generated an error message identifying the specific differential equation in question. Ultimately, if neither of these verifications detected any problems with the differential equations received, the system proceeded to perform the operations on the differential equations and assignments in the provided atomic instruction argument of the “Traj.scala” functions, where these modifications were implemented. The code instructions responsible for executing the procedure described are shown in Fig. 28. Afterwards, each of the functions that were developed so that constant variables could be used without contributing to the non-linearity of the differential equations will be looked into in more detail. As previously mentioned, the dynamic variables within the differential equations of the atomic instruction, which are passed as arguments in each of the functions where the code excerpt of the Fig. 28 was implemented, have been extracted. To achieve this, the function “extractVarsDifEqs has been implemented in the “Utils.scala” file, and you can consult its implementation in Fig. 29. The function “extractVarsDifEqs” takes an atomic instruction and returns a list of the names of the dynamic variables3contained in it. To do so, the variable “listVars” was created, which will 3The main characteristic that distinguishes dynamic variables from constant variables is that dynamic variables vary over the execution time of their differential equation. However, it is agreed that variables are dynamic if the expression of their differential equation (after numerical simplifications) contains variables, or if the numerical result of the equation is non-zero. The reason for agreeing that the presence of variables in the expression of the differential equation would indicate dynamic behaviour was to avoid the need to use complex algorithms, such as symbolic simplification algorithms. These complex algorithms would bring a greater efficiency in obtaining variables with dynamic behavior, however the case studies for which Lince is intended, contain differential equations of low complexity and easy identification as to their evolutionary behavior over time. As such, the criteria established for the detection of dynamic variables have 46 // Extraction the dynamic variables from the d i f f . eq . var extractVDE=Utils . extractVarsDifEqs ( at ) //Updating the simbolic expressions of each variable var updateValuate=x ++ Utils . toValuation ( at . as , x) //Convertion the type simbolic to ”NotLin” var newNotLin : ValuationNotLin=updateValuate . view . mapValues( e=>Eval . syExpr2notlin ( e ) ) . toMap //Change the constant variab les of the d i f f e r e n t i a l equations var newListDiffEq=( at . de . eqs ) .map( e=>Eval . updateDiffEq (e , newNotLin , extractVDE ) ) . toList //Creation of the updated Atomic var updateAtomic : Atomic=Atomic( at . as , DiffEqs ( newListDiffEq , at . de . dur) ) // Verif icatio n of ’max ’ and ’min ’ instru ctio ns with dynamic var ia bles in t he ir arguments , //as well as the presence of non - l inear expressions in the d i f f e r e n t i a l equations . var linVerify=Utils . verifyLinearityEqsDiff (updateAtomic) var min_max_check=Utils . verify_min_max(updateAtomic) i f (min_max_check.nonEmpty) return throw new ParserException((s” It i s not poss ib le to apply the max or min instruc ti on s to expressions with dynamic variable s in d i f f e r e n t i a l equations : ${Show. apply (min_max_check. get )}” ) ) el s e i f ( linVerify . nonEmpty) return throw new ParserException(s”There i s one d i f f e r e n t i a l equation that i s not l i nea r or the semantic analyser suspects that i t i s non - l ine ar ( try s implifyin g the differential equation ) : ${Show. apply ( l in Ve ri fy . get )}” ) el s e { //The code present in the e l se condition corresponds to symbolic/numerical calcu latio n of the Atomic } Figure 28: Code extract responsible for enabling the use of constant variables in differential equations def extractVarsDifEqs ( prog : Atomic) : List [ String ] ={ var listVars : List [ String ]=List () for (eqDiff <- prog . de . eqs ){ i f (extractTotalVarsLinearExp(eqDiff .e)==0) { i f ( calc_doubles ( eqDiff . e ) !=0) listVars=listVars ++ List (( eqDiff . v) . v) }el s e listVars=listVars ++ List (( eqDiff . v) . v) } return listVars } Figure 29: Function “ extractVarsDifEqs ” accumulate the names of the dynamic variables in a list. Then, a “for” cycle was created that will scan each differential equation in the atomic instruction and determine, through conditional instructions, if proven to be adequate for the case studies already covered and seem to be effective for the whole range of case studies that can be treated. 47 the expression of the differential equation contains variables after numerical simplifications (through the “extractTotalVarsLinearExp” function that will be discussed in more detail in Section 4.5.5). If it has variables in the expression after numerical simplifications, the derived variable (the which is on the left side of the “=” sign of the differential equation) is saved in the “listVars” list (it is considered that the presence of variables in the expressions made the derived variable dynamic), otherwise it was checked whether the result of the equation was different from 0 (through the function “calc_doubles” which will also be discussed with more detail in Section 4.5.5). If the result of the equation was different from 0, the derived variable was dynamic and it was saved in the list “listVars”, if it was 0 then the variable was constant and not stored in this list. For example, if the differential equations present in the atomic instruction were “x’=p*x,p’=1- 1,y’=x∧0 for 1”, the variables contained in the list returned by the previous function would be “x” and “y”, because the expression of the differential equation of “x” contained variables and the expression of the differential equation of “y”, after applying numerical simplifications (x∧0=1), has a numerical result different from 0. However, the expression of the differential equation of “p”, which contained no variables and the numerical result was 0, meeting the criteria for being a constant variable. Next it was necessary to update the symbolic expressions of the program variables based on the assignments present in the atomic instruction. For that, it was used the function “toValuation”, which had already been implemented in the file “Utils.scala”. The next step was to pass the values of the program’s variables from the symbolic data type to the “NotLin” data type. This was possible by going into the “CommonTypes.scala” file (file where we find data types that are used in the other files) and adding a new data type called “ValuationNotLin”, as depicted in Fig. 30. type ValuationNotLin=Map[ String , NotLin ] Figure 30: Data type “ ValuationNotLin ” Unlike the “Valuation” data type (data type returned by the “toValuation” function), which maps variables to data structures of symbolic type, the “ValuationNotLin” data type maps variables to data structures of type “NotLin”. Having created the “ValuationNotLin” data type, it was necessary to create a function that converted symbolic data type to “NotLin” data type. So in the file “Eval.scala” the function “syExpr2notlin” was created. This function is shown in the code extract in Fig. 31 and receives an argument of symbolic type (more specifically of type “SyExpr”) and returns the conversion of this argument to the respective 48 case class “NotLin”. def syExpr2notlin ( l : SyExpr) : NotLin=lmatch { case SVal(v) => Value (v) case SFun( s , l i s t )=> Func( s , l i s t .map(( l : SyExpr) => syExpr2notlin( l ))) case SDiv (e1 , e2 ) => Div(syExpr2notlin(e1) ,syExpr2notlin(e2)) case SRes(e1 , e2 ) => Res(syExpr2notlin(e1) ,syExpr2notlin(e2)) case SMult( e1 , e2 )=> Mult(syExpr2notlin(e1) ,syExpr2notlin(e2)) case SPow( e1 , e2 ) => Func( ”pow” ,List(syExpr2notlin(e1) ,syExpr2notlin(e2))) case SAdd( e1 , e2 ) => Add(syExpr2notlin(e1) ,syExpr2notlin(e2)) case SSub( e1 , e2 ) => Add( syExpr2notlin ( e1 ) ,Mult( Value ( -1) , syExpr2notlin ( e2 ) ) ) } Figure 31: Function “ syExpr2notlin ” Having created the “ValuationNotLin” data type and the “syExpr2notlin” function, it was enough to go to the result of updating the symbolic expressions of the variables from the code of the Fig. 28 (variable “updateValuate”) and execute the code of the Fig. 32. var newNotLin : ValuationNotLin=updateValuate . view . mapValues( e=>Eval . syExpr2notlin ( e ) ) . toMap Figure 32: Line of code responsible for converting the data type of the program’s variables to the type “ NotLin ” What the line of code of the Fig. 32 did was store in the “newNotLin” variable (now of type “ValuationNotLin”) the result of the “updateValuate” variable, but now, instead of the variables being associated with a symbolic data structure, they are now associated with a “NotLin” data structure due to the use of the “syExpr2notlin” function. The next step was to create a list of differential equations where constant variables were replaced by their respective expressions (of the type “NotLin”). For this, the functions of the Fig. 33 was created in the file “Eval.scala”. The “updateDiffEq” function receives a differential equation, the association between the variables and their expression and the list of dynamic variables from the set of differential equations, returning the differential equation with the constant variables of the expression replaced by the respective expressions. However, to replace the constant variables in the expression of the differential equation, it was necessary to create the function “updateNotLin”, which receives the association between variables and their expression, the expression of the differential equation and the list of dynamic variables from the set of differential equations. This function uses recursion to go through the expression of the differential equation 49 def updateDiffEq ( d if fe q : DiffEq , v : ValuationNotLin , vars : List [ String ] ) : DiffEq ={ var newNotLin=updateNotlin (v , di f feq . e , vars ) var newdiffeq=DiffEq ( d if feq . v , newNotLin) return newdiffeq } def updateNotlin ( s tate : ValuationNotLin , not lin : NotLin , vars : List [ String ] ) : NotLin =notlin match { case Var(v) => {i f ( vars . contains (v) ) {Var(v)} el s e { st ate (v)}} case Value (v) => Value (v) case Add( l1 , l2 ) => Add( updateNotlin ( state , l1 , vars ) , updateNotlin ( state , l2 , vars ) ) case Mult( l1 , l2 ) => Mult( updateNotlin ( state , l1 , vars ) , updateNotlin ( state , l2 , vars ) ) case Div( l1 , l2 ) => Div( updateNotlin ( state , l1 , vars ) , updateNotlin ( state , l2 , vars ) ) case Res( l1 , l2 ) => Res( updateNotlin ( state , l1 , vars ) , updateNotlin ( state , l2 , vars ) ) case Func( s , l i s t ) => Func( s , l i s t .map( l=>updateNotlin ( state , l , vars ) ) . toList )} Figure 33: Function “ updateDiffEq ” and function “ updateNotLin ” and find the variables present in it, replacing the variable by its expression (using the association received in the argument) if it was not present in the list of dynamic variables. Having these two functions implemented, it was enough to elaborate the lines of code of the Fig. 34 to create a set of differential equations equal to those present in the atomic instruction received as an argument, only with the constant variables replaced by the respective non-linear expression. var newListDiffEq=( at . de . eqs ) .map( e=>Eval . updateDiffEq (e , newNotLin , extractVDE ) ) . toList var updateAtomic : Atomic=Atomic( at . as , DiffEqs ( newListDiffEq , at . de . dur) ) Figure 34: Lines of code responsible for replacing the constant variables in the differential equations with their respective expressions The final step involved verifying dynamic variables within the “max” and “min” mathematical function arguments within the differential equations, as well as checking the linearity of these equations. Detailed information about the strategies and functions developed for these tasks can be found in Section 4.5.4 andSection 4.5.5, respectively. The lines of code responsible for checking the presence of dynamic variables in the “max” and “min” instructions, as well as verifying if the differential equations exhibit non-linear behavior, is illustrated in Fig. 35. To illustrate how the treatment of constant variables works, let’s consider the following hybrid program: x:= 1; y:=2/3; x’=y*x , y’=0for 1; 50 var linVerify=Utils . verifyLinearityEqsDiff (updateAtomic) var min_max_check=Utils . verify_min_max(updateAtomic) i f (min_max_check.nonEmpty) return throw new ParserException((s” It i s not poss ib le to apply the max or min instruc t ions to expressions with dynamic variables in d i f f e r e n t i a l equations : ${Show. apply (min_max_check. get )}” ) ) el s e i f ( linVerify . nonEmpty) return throw new ParserException(s”There i s one d i f f e r e n t i a l equation that i s not l ine ar or the semantic analyser suspects that i t i s non - l ine ar ( try simplifying the d i f f e r e n t i a l equation ) : ${Show . apply ( l in Ve rify . get )}”) el s e { //The code present in the e l se condition corresponds to symbolic/numerical calcu latio n of the Atomic } Figure 35: Lines of code responsible for checking the presence of dynamic variables in the “max” and “min” instructions, as well as verifying if the differential equations exhibit non-linear behavior This program is parsed and then sent to the interpreter. The interpreter performs the necessary semantic operations until it reaches the processing stage of the atomic instruction containing the differential equation from the previous hybrid program. To perform this processing, it uses the function “runAtomicWithBounds” and applies the treatment of constant variables discussed in this section, with each step schematised in Fig. 36. Figure 36: Schematic example of the treatment of constant variables As depicted in the schematic of the Fig. 36, it was necessary to: • Extract the list of dynamic variables based on the differential equations (which in this case only “x” is dynamic); • Update the association between the variables and their symbolic expression and convert the symbolic expression to an expression of type “NotLin”; 51 • Change the differential equations so that the constant variables were replaced by their respective expression; • Check for the presence of “max” and “min” instructions with dynamic variables in their arguments in the differential equations (as there was no such instructions in this example, “None” was returned); • Checked if the differential equations are linear or nonlinear (in this example they were linear, so “None” was returned). In this way, all conditions were provided so that the previous set of differential equations could be evaluated, even using a constant variable. 4.4 Implementation of the numerical plot Based on reference [GNP], Lince’s semantics were designed to handle symbolic representations (or symbolic expressions) in the solutions of differential equations (obtained through SageMath), allowing for more precise solutions compared to numerically obtained ones. These symbolic representations are also present in conditional expressions, allowing the use of SageMath to perform symbolic manipulations to verify whether conditions are True or False, thereby achieving more accurate results compared to conventional conditional expression evaluation functions. The following hybrid program illustrates the usefulness of using symbolic representations: x:= 1; x’=-x for 10; x’=xfor 10; i f x==1 then x:= 2; el s e x:= 0; This program first assigns the variable xas 1 and continuously evolves this variable according to the differential equation x’=-x for 10 seconds, and then according to the differential equation x’=x for the same period. Finally, it checks whether xis equal to its initial value, returning 2 if True and 0 if False. The symbolic plot resulting from the execution of the previous hybrid program in the Lince tool is depicted in Fig. 37. A brief analysis of the plot of the Fig. 37 shows that the variable xevolves according to a negative exponential function until 10 seconds, and then evolves according to a positive exponential function for the next 10 seconds, ending exactly where it started. 52 Figure 37: Symbolic plot resulting from the hybrid program: x:=1; x’=-x for 10; x’= x for 10; if x==1 then x:=2; else x:=0; The variable ends exactly where it started due to the use of symbolic representations and SageMath in the solutions of the differential equations and conditional expressions. For better understanding, you can click on the “all jumps” button at the top right of the plot to show the value of the variable xat each iteration of the hybrid program. Clicking on the value of xat t=0 (initial iteration), you will see that at that moment, xis associated with the expression e−tand the numerical value 1 resulting from substituting the time twith 0 in that expression. This expression represents the solution of the first differential equation based on the initial conditions and comes from the symbolic representation of the solution of this differential equation from SageMath. Additionally, the samples between time 0 and 10 come from this expression. Clicking on the value of xat t=10 (second iteration), you will see that at that moment in time, xis associated with another expression, namely e−10 ∗et, and the corresponding numerical value 45.39993× 10−6resulting from substituting the time twith 0 in that expression (since at t=10 the variable xevolves according to another differential equation, the initial value corresponds to the symbolic expression of x at t=10 from the previous differential equation expression). In the same way as the expression from the previous iteration, this expression represents the solution to the second differential equation. It allows the generation of samples within the time interval of 10 to 20 units. It is important to note that these samples are obtained by replacing the variable twith values between 0 and 10, since this corresponds to the evaluation of a new differential equation over a period of 10 seconds. Finally, when clicking at t=20 (third iteration), you will observe that the result of the conditional expression x==1 is True, as SageMath is able to relate the symbolic expression e−10 ∗e10 to the symbolic expression 1, returning True as expected. With the use of symbolic solutions of differential equations, all the samples extracted from these expressions to construct the plot will be more precise than any numerical method for solving differential equations. This is because numerical methods return numerical values that are subject to rounding and propagation errors [SEN14]. 53 In addition to the increased precision in obtaining samples for constructing the plot, the use of conditional expressions involving symbolic expressions with SageMath allows for symbolic manipulations to identify the resulting boolean value. In the previous example, SageMath will manipulate the expression e−10 ∗e10, and since the exponentials cancel each other out, it returns 1 and the result will be True. If you were to try running the condition e−10 ∗e10 == 1 in a language like Scala, for instance, the result would be False due to approximation errors, which could critically affect the hybrid program. Although the previous method implies higher precision in the results of hybrid programs, it is also susceptible to an error that can affect a wide range of hybrid programs governed by Newtonian mechanics, particularly when using the differential Eq. (3.2) and Eq. (3.3). The error arises from the inability to condense/simplify the symbolic expressions of the solutions of the differential equations returned by SageMath, causing the solution to grow larger with each iteration until SageMath can no longer handle it, resulting in an error. This error can be encountered in the simulation of the following hybrid program: x:= 0; y:= 0; vx:= 1; vy:= 1; w:= 0; while true do { w:= 0; x’=vx , y’=vy , vx’=w*vy , vy’=-w*vx for 1; w:= 1; x’=vx , y’=vy , vx’=w*vy , vy’=-w*vx for 1; w:= -1; x’=vx , y’=vy , vx’=w*vy , vy’=-w*vx for 1; } This hybrid program begins with assignment of the initial position (x,y) and initial velocity (vx,vy) of a body, as well as the assigment of the variable wwhich determines whether the body moves forward or turns. Them, a loop is executed that iteratively runs three differential equations of motion (see Eq. (3.2)) for 1 second each. The first differential equation is evaluated for w:=0, causing the body to move forward at a constant velocity, the second equation is for w:=1, causing it to turn right, and the third equation is for w:=-1, which will make the body turn left. Running the previous program resulted in the error message shown in Fig. 38. The error message of the Fig. 38 indicates that Sage was unable to handle this expression, which occurred at t=19. Reducing the maximum simulation time to 3 seconds, the expressions for xas a function of tare the following: 54 def assignmentsVerify ( prog : Syntax ) : Set [ String ] =prog match { case Seq (p , q) => { var res=extractAssignments(p) ++ extractAssignments(q) var indice=re s . indexOf ( Assign (Var(”Stop case ” ) , Value ( -1) ) ) var as=res i f ( indice>=0) { as=as . take ( indice ) } var declVar=as .map(_. v . v) . toList var aux=0 var aux2=1 var zz : Set [ String ]=Set () for ( i <- as ){ var z=getVars ( i . e ) for ( j <- 0 unt i l (aux) by 1){ z -=declVar ( j ) } zz=zz++z aux=aux+1 } return zz } case Atomic ( as ,_)=>{ var declVar=as .map(_. v . v) . toList var aux=0 var aux2=1 var zz : Set [ String ]=Set () for ( i <- as ){ var z=getVars ( i . e ) for ( j <- 0 unt i l (aux) by 1){ z -=declVar ( j ) } zz=zz++z aux=aux+1 } return zz } case While ( pre , c , p) => assignmentsVerify ( pre ) case _=> Set () } Figure 41: Function “assignmentsVerify” are not associated with initial assignments. As such, in case the output is a cyclic instruction, the recursivity of the “assignmentsVerify” function is applied in the program that precedes it and the list of variables 61 on the right hand side of the initial assignments that were not previously assigned from the program that precedes it, is extracted. In case the output is a conditional instruction it returns an empty list. Having created the two previous functions, it was necessary to modify the “isClosed” function (function invoked by the “Parser.scala” file to check if the program contains unassigned variables on the right hand side of the initial assignments and in the rest of the program) so that it would be able to detect the existence of unassigned variables on the right hand side of the initial assignments and return the respective error. The function “isClosed” is shown in the Fig. 42. def isClosed ( prog : Syntax ) : Either [ String , Unit ] ={ val asVerify=assignmentsVerify ( prog ) i f ( asVerify . nonEmpty) Left ( s ” I n i t i a l assignments have variables on the right hand side that were not assigned : ${ asVerify . mkString ( ” ,”)}” ) el s e Right ( ( ) ) } Figure 42: Function “ isClosed ” This function takes as argument a variable of type “Syntax” (i.e. the result of parsing the hybrid program) and returns a statement of type Either, which can be a Right(()) if there are no errors, or aLeft(s“...”) if there are errors. To check if there are variables on the right hand side of the initial assignments that were not previously assigned, this function use the function “assignmentsVerify” to return a list with these variables, then checking if this list is an empty list or not and if it is an empty list just return Right(()), but if it is a non-empty list, a Left(s“...”) is returned (containing an error message indicating the variables to the right of the initial assignments that were not previously assigned in the program). (Note: The “isClosed” function mentioned above is not the final version of the “isClosed” function, in the Section 4.5.2 a future version will introduce instructions to check for variables in the rest of the program that were not assigned in the initial assignments.) To demonstrate how the detection of unassigned variables on the right hand side of the initial assignments works in the Lince tool, an example will be presented where the hybrid program presents this type of semantic error in its conception. Having the following hybrid program: x:=1+y ; y:=2+z ; z:= 3; 62 z’=2for 1; And if this program is run on Lince, the error message depicted in Fig. 43 appears. Error : When parsing G§150 // maximum time in the plot§0§ x:=1+y ; y:=2+z ; z :=3; z’=2 for 1; − hprog . common. ParserException : I n i t i a l assignments have v a r i a b l e s on the r i g h t hand s i de tha t were not as sign ed : _y , _z Figure 43: Error message returned by Lince It can be noted, as intended, that an error was returned indicating that the variables on the right hand side of the initial assignments “y” and “z” were not assigned previously, because in the expression of the assignment of the variable “x” (“x=1+y”) the variable “y” was used which had not been assigned previously, and the same happened in the expression of the assignmente of the variable “y” (“y=2+z”) because the variable “z” had not been assigned before either. However, if the previous hybrid program is changed so that the variables on the right hand side of the initial assignments are assigned before: z:= 3; y:=2+z ; x:=1+y ; z’=2for 1; And if that program is run in Lince, the symbolic plot of the Fig. 44 is obtained. Figure 44: Symbolic plot resulting from the hybrid program: z:=3; y:=2+z; x:=1+y; z’=2 for 1; The appearance of the symbolic plot, relative to variables as a function of time of the previous hybrid program, shows that the changes made previously allow the new version of Lince to use variables in the right side of the initial assignments, provided that they have been assigned before being used in the 63 expressions of the initial assignments. On the other hand, the old version could not support any kind of these variables, returning the following error if the previous hybrid program was running: Error : When parsing G§15 // maximum time in the plot§0§ z :=3; y:=2+z ; x:=1+y ; z’=2 f o r 1; − hprog .common. ParserException : I n i t i a l assignments have v a r i a b l e s on the r i g h t hand s i de that were not a ss igne d : z , y Figure 45: Error message returned by old version of Lince 4.5.2 Detection of variables that were not assigned at the beginning of the program Regarding the verification of variables that were not assigned at the beginning of the program, we found that the old version of Lince already had functions designed for this purpose. However, the verification of initially assigned and used variables exhibited some inconsistencies. The old version did not require programs to start with initial assignments, so in cases where a program started with a “if-then-else” statement, the initial assignments were considered to be placed inside the “then” branch of the “ifthen-else” construct. This particular feature, which allows initial assignments to be placed exclusively within one of the program branches associated with the conditional statement, was considered inconsistent and inappropriate. However, in the new version of Lince, the initial assignments are obligatory and always take place at the beginning of the program (see Section 4.1.2). Consequently, the function “getFstDeclVars”, responsible for determining the set of initially variables, has been modified to consider only the initial set of assignments. This change allows it to extract initially variables from the program in a consistent and efficient manner. The function “getFstDeclVars” in the new version of Lince is shown in Fig. 46. If the program is a sequence of instructions, the function of Fig. 46 starts by extracting the assignments that precede the appearance of a cyclical or conditional structure, then it only extracts the assignments that precede the appearance of the first set of differential equations (corresponding to the initial assignments, as seen in Section 4.5.1) and returns the set of variable names corresponding to those assignments. If the program were an atomic instruction, it would just return the set of the variable name of the assignment associated with it. For the case of the program being a cyclic structure, it was enough to use recursion to extract the set of variables corresponding to the initial assignments in the previous program, and finally, if 64 def getFstDeclVars ( prog : Syntax ) : Set [ String ] =prog match { case Seq (p , q) => { var res=extractAssignments ( Seq (p , q) ) var indice=re s . indexOf ( Assign (Var(”Stop case ” ) , Value ( -1) ) ) var as=res i f ( indice>=0) { as=as . take ( indice ) } var asSet=as .map(_. v . v) . toSet return asSet } case Atomic(a , _) => a .map(_. v . v) . toSet case While ( pre , _, _) => getFstDeclVars(pre) case _=> Set () } Figure 46: Function “ getFstDeclVars ” it is another type of statement (like a conditional statement) it was enough to return an empty set. Besides the previous function, responsible for returning the set of variable names initially assigned in the program, it was necessary to alter the function “getUsedVars”, responsible for returning the set of variable names used in the program. This function is represented in the code excerpt shown in Fig. 47. def getUsedVars ( eqs : Lis t [ DiffEq ] ) : Set [ String ] = eqs . flatMap ( eq => getVars ( eq . e )+eq . v . v) . toSet //New def getUsedVars ( prog : Syntax ) : Set [ String ] =prog match { case Atomic ( as , de ) => as . toSet . flatMap (( a : Assign )=>getVars (a . e )+a . v . v) ++ getUsedVars(de) case Seq (p , q) => getUsedVars(p) ++ getUsedVars(q) case ITE( ifP , thenP , elseP ) => getVars ( ifP ) ++ getUsedVars (thenP) ++ getUsedVars ( elseP ) case While ( pre , d , doP) => getUsedVars ( pre ) ++ getVars (d) ++ getUsedVars (doP) } def getUsedVars ( eqs : DiffEqs ) : Set [ String ] = getUsedVars ( eqs . eqs ) ++ getUsedVars ( eqs . dur) def getUsedVars ( dur : Dur) : Set [ String ] =dur match { case Until ( c ,_,_) =>getVars(c) case For( nl ) => getVars ( nl ) //New case _=> Set () } Figure 47: Function “ getUsedVars ” 65 The fuction “getUsedVars” has been modified only for the case where it is applied to a list of differential equations, as it now also returns the variables present on the left side of each differential equation (which was not taken into account in the old version), and also for the case where it is applied to a duration, as it did not handle the case where the duration is a “for ...”. Finally, the detection of variables that were not assigned at the beginning of the program and the return of the corresponding error, similar to the detection of the unassigned variables on the right hand side of the initial assignments, are handled by the “isClosed” function. With the introduction of this detection, we have reached the final version of the “isClosed” function, and its representation can be found in Fig. 48. def isClosed ( prog : Syntax ) : Either [ String , Unit ] ={ val declVar=getFstDeclVars ( prog ) val usedVars =getUsedVars ( prog ) val asVerify=assignmentsVerify ( prog ) i f ( asVerify . nonEmpty) Left ( s ” I n i t i a l assignments have variables on the right hand side that were not assigned : ${ asVerify . mkString ( ” ,”)}” ) el s e i f ( ! usedVars . f o r a l l ( declVar ) ) Left ( s ” Variable ( s ) not assigned : $ {(( usedVars - - declVar ) ) . mkString ( ” ,” )}” ) el s e Right ( ( ) ) } Figure 48: Function “ isClosed ” The function “getFstDeclVars” starts by storing the set of variables that were initially assigned in the program in the variable “declVar” and the function “getUsedvars” stores the set of variables used in the program in the variable “usedVars”. After adding this variables and checked if there were any variables on the right hand side of the initial assignments not previously assigned, it was verified if there were not any variables used that had not been assigned in the beginning of the program and if it was false, a “Left(s“...”)” was returned with the error message identifying which variables are. To demonstrate how the detection of variables that were not assigned at the beginning of the program works in the Lince tool, an example will be presented where the hybrid program presents this type of semantic error in its conception. Given the following hybrid program: p:= 0; v:= 2; while true do { i f v<=x then p’=v , v’=kf or w; el s e p’=v , v’=-k for w; 66 } The output results in the error message shown in Fig. 49. Er ro r : When p ar si ng G§15 // maximum time i n the plot§0§ // C ru is e c o nt r o l p:=0; v :=2; while true do { i f v<=x then p’=v , v’=k for w; e l s e p’=v , v’=−k f or w; } − hprog .common. ParserException : Variab le ( s ) not assigned : _x , _w, _k Figure 49: Error message returned by Lince It can be seen that the hybrid program only assigned the variable “p” and “v” in the beginning of the program, but used the variable “x” in the “if-then-else” condition, the variable “k” in the expression of the equation differential in order to “v” and the variable “w” in the duration expression. Since the variables “x”, “k” and “w” were not assigned at the beginning of the program, then the semantic analyzer is expected to detect this error and return an error message regarding it, as it happened. 4.5.3 Better errors when using mathematical functions and mathematical constants In the old version, there were only the arithmetic operators +,−and ∗, and whenever you used an operation that was not supported, a parsing error was returned, just like the error message in Fig. 50 resulting from running the following hybrid program: v:= sqrt (25) ; v’=1for 1; Error : When parsing G§150 v´=1 f o r 1; − hprog .common. ParserException : [ 1 . 8 ] f a i l u r e : ’; ’ expected but ’( ’ found v:= sqrt (25) ; ^ Figure 50: Error message returned by Lince In the previous case, the parser error does not indicate which operation is not supported, giving relatively vague information to the user, who in more complex programs may have difficulty debugging. 67 As for the detection of mathematical indeterminacies, its implementation was not useful, since there were no indeterminacies for the three arithmetic operations supported by the old version. In the new version, to parse the mathematical functions (see Table 2) and mathematical constants supported by Lince (see Table 3), the instructions in Fig. 51 have been implemented in the variable “notlinOthers” of the file “Parser.scala”. identifier ~ ” (”~” ) ” ^^ { case s ~ _ ~ _ => Func( s , Lis t ( ) ) } | identifier ~ opt(”(” ~> argsFunction <~ ”)”) ^^ { case s ~ Some( arguments ) => Func( s , arguments ) case s ~ _ => Var( ”_” + s ) } Figure 51: Instructions of variable “ notlinOthers ” responsible for recognizing mathematical functions and mathematical constants The “notlinOthers” variable is responsible for receiving the parser of reals, variables, non-linear expressions between parentheses, mathematical functions applied over non-linear expressions, mathematical constants and the parser of certain mathematical functions that needed to be treated individually. However, as you can see in the Fig. 51, for the variable “notlinOthers” to receive the parsing of the mathematical constants, it expects to receive the parsing of the variable “identifier” followed by the parsing of open and closed parentheses, returned the case class “Func(s,List())”, where the “s” is the result of parsing of the “identifier” variable (recalling that the “identifier” variable returns the parsing of the strings that start with a lowercase letter). As for receiving the parsing of mathematical functions applied to non-linear expressions, it can be seen in the Fig. 51 that the variable “notlinOthers” expects to receive parsing from the variable “identifier”, followed by a list of the parsing of non-linear expressions between parentheses (the function “argsFunction” returns this list of parsing of non-linear expressions), returning the case class “Func(s,arguments)”, where the “s” is the result of parsing the variable “identifier” and “arguments” is the parsing list of non-linear expressions. (Note: The full implementation of variable “notlinOthers” can be found in Appendix A.1.) For this reason, the way the parser has been implemented for mathematical constants and mathematical functions applied to non-linear expressions does not restrict the names given to them, so the parser will accept any name given to them as long as it conforms to the established grammar. In this way, it was necessary to introduce functions/instructions in the interpreter capable of verifying whether the names given to mathematical constants and mathematical functions are in fact supported by the tool. 68 As such, the solution found was to treat each of the mathematical functions and mathematical constants supported by the tool individually in the “apply” function of “Eval.scala”. As mentioned in Section 4.2, this function was responsible for calculating the numerical result of a given non-linear expression, and whenever there was a case class “Func( )”, it was checked whether the name and the list received as an arguments of that class corresponded to one of the mathematical functions/constants supported by the tool. If they did, the respective function was applied to the numerical result of the arguments received or the mathematical constant was returned, if one of the two did not correspond, an error message was returned. The version of this “apply” function, with only detection of unsupported mathematical functions/constants, can be found in the Fig. 52. Having implemented the previous error detection, it was found that it would be also useful to modify the previous function so that it returned an error message whenever a certain indeterminate form was encountered. These indeterminate forms can occur because there are arithmetic operators and mathematical functions whose domain is limited to a certain range of values. The indeterminate forms that will be treated are: • Divide a nonlinear expression by 0; • Compute the remainder of a nonlinear expression by 0; • Raising 0 to a negative number (such as 0∧(−1)); • Apply an arcsin or an arccos to a number outside its domain, as it can only be contained between -1 and 1; • Apply a square root to a negative number; • Apply a log or a log10 to a number negative or equal to 0. To identify the occurrence of these indeterminate forms, it was necessary to go to the previous function and make the following changes: • In case of finding a division, check if the divisor is zero. If it is zero, it returns an error, if it is different from 0, it performs the division; • In case of finding a remainder, check if the divisor is zero. If it is zero, it returns an error, if it is different from 0, it performs the remainder; 69 def apply ( state : Point , notlin : NotLin ) : Double ={ val res =notlin match { case Var(v) => state (v) case Value (v) => v case Add( l1 , l2 ) => apply ( state , l1 ) + apply ( state , l2 ) case Mult( l1 , l2 ) => apply ( state , l1 ) * apply ( state , l2 ) case Div( l1 , l2 ) => apply ( state , l1 ) / apply ( state , l2 ) case Res( l1 , l2 ) => apply ( state , l1 ) % apply ( state , l2 ) case Func( s , l i s t ) => ( s , l i s t ) match { case (”PI” , Nil ) => math. Pi case (”E” , Nil ) => math.E case (”max” , v1 : : v2 : : Nil ) => math .max( apply ( state , v1) , apply ( state , v2) ) case (”min” , v1 : : v2 : : Nil ) => math . min( apply ( state , v1) , apply ( state , v2) ) case (”pow” ,v1 : : v2 : : Nil ) => math.pow( apply ( state , v1) , apply ( state , v2) ) case (”exp” ,v : : Nil ) => math . exp ( apply ( state , v) ) case (” sin ” ,v : : Nil ) => math . sin ( apply ( state , v) ) case (”cos ” ,v : : Nil ) => math . cos ( apply ( state , v) ) case (”tan” ,v : : Nil ) => math . tan ( apply ( state , v) ) case (” arcsin ” ,v : : Nil ) => math . asin ( apply ( state , v) ) case (” arccos ” ,v : : Nil ) => math . acos ( apply ( state , v) ) case (”arctan” ,v : : Nil ) => math . atan ( apply ( state , v) ) case (” sinh ” ,v : : Nil ) => math . sinh ( apply ( state , v) ) case (”cosh” ,v : : Nil ) => math . cosh ( apply ( state , v) ) case (”tanh” ,v : : Nil ) => math . tanh ( apply ( state , v) ) case (” sqrt ” ,v : : Nil ) => math . sqrt ( apply ( state , v) ) case (” log ” ,v : : Nil ) => math. log ( apply ( state , v) ) case (”log10” ,v : : Nil ) => math. log10 ( apply ( state , v) ) case (_,_) => throw new RuntimeException ( s ”Unknown function ’${s }( ${( l i s t .map(Show. applyV) . toList ) . mkString ( ” ,”) }) ’ , or the number of arguments are incorr ect ”) } } res } Figure 52: The first version of the function “ apply ”of the “Eval.scala” • In the case of raising 0 to a negative number, check if the base is zero and de exponent is a negative number. If that is true, then it returns an error, otherwise, it performs the pow; • In the case of finding an arcsin , an arccos or a sqrt, check if using respectively one of these three mathematical functions on the numerical result of the argument the result is possible. If the 70 Figure 61: Symbolic plot resulting from the hybrid program: p:=2; v:=1; p’=0,v’=max(p, 2) for 1; 4.5.5 Verification of linearity of differential equations As mentioned in Section 4.3.2, after replacing the constant variables with their expressions and check for the presence of dynamic variables in the mathematical functions “max” and “min” within the differential equations, it was necessary to check if the resulting differential equations were indeed linear (since SageMath is unable to solve a wide range of non-linear differential equations). For this, it was created the function “verifyLinearityEqsDiff” in the “Utils.scala” file, which receives a program and returns the first occurrence of nonlinear differential equation. The representation of this function can be found in Fig. 62. def ve rifyLi nearit yEqsDi ff ( prog : Syntax ) : Option [ DiffEq ] ={ var d i f f e q s=extractDifEqs ( prog ) var varsDifEqs=extractVarsDifEqs ( prog ) var i t era t i on=0 var aux=0 for ( ls t eq D if f <- d i f f e q s ) { var aux=0 for (eqDiff <- lst e qD i ff ){ aux=extractVarsLinearExp ( eqDiff . e , varsDifEqs ( it e ration ) ) i f (aux > 1 ) return Some( eqDiff ) } it e r ati o n=i tera t ion + 1 } return None } Figure 62: Function “ verifyLinearityEqsDiff ” The function of the Fig. 62 starts by saving in the variable “diffeqs” the list of lists of differential equations coming from the parser of the program (each list of differential equations refers to the set of differential equations present in each atomic instruction), then it saves in the variable “varsDiffEqs” the list of lists of dynamic variables of each set of differential equations. 77 After saving the set of differential equations and their respective dynamic variables, variables “aux” and “iteration” were created. The variable “aux” will be used to store the integer referring to the linearity of each set of differential equations and variable “iteration” will be used to scan the list of lists of dynamic variables for each set of differential equations. Finally, two “for” cycles were performed in order to go to each list of differential equations (or in other words, each set) and check whether or not their expressions were linear, returning the first occurrence of nonlinear differential equation, or returning “None” if all the sets had linear expressions. To perform this function, it was necessary to create the functions “extractDifEqs”, “extractVarsDifEqs”, and “extractVarsLinearExp” in the “Utils.scala” file. As mentioned earlier, the function “extractDifEqs” takes a program and returns the list of lists of differential equations present in the program, where each list of differential equations represents the set of differential equations present in each atomic instruction. On the other hand, the function “extractVarsDifEqs” takes a program and returns the list of lists of dynamic variables present in each set of differential equations. The functions “extractDifEqs” and “extractVarsDifEqs” are represented in Fig. 63 and Fig. 64, respectively. def extractDifEqs ( prog : Syntax ) : List [ List [ DiffEq ] ] =prog match { case Atomic( as , de ) => return List ( de . eqs ) case Seq (Atomic( as , de ) , q) => List ( de . eqs )++extractDifEqs (q) case Seq (p , q) => extractDifEqs(p) ++ extractDifEqs(q) case While ( pre , c , p) => extractDifEqs ( pre ) ++ extractDifEqs (p) case ITE( ifP , thenP , elseP ) => extractDifEqs (thenP) ++ extractDifEqs ( elseP ) } Figure 63: Function “ extractDifEqs ” The function “extractVarsLinearExp”, on the other hand, takes a non-linear expression derived from one of the differential equations belonging to a set of differential equations, along with its corresponding list of dynamic variables from that set of differential equations. Its objective is to return an integer that indicates whether the expression is linear, non-linear, or if there is suspicion of it being non-linear (if it is greater than 1 it is non-linear or there is suspicion of it being non-linear, but if it is equal to 1 or 0 it is linear). (Note: Due to the dimension of the code, it was decided not to show the function “extractVarsLinearExp” in the sequence of the previous paragraph. As such, to see the code you can consult Appendix A.5.) Based on the operations performed within the expression, the function “extractVarsLinearExp” will return an integer indicating its linearity. For example, if the expression is a variable (class “‘Var”), the 78 def extractVarsDifEqs ( prog : Syntax ) : List [ List [ String ] ] ={ var e q s d i f f=extractDifEqs ( prog ) var listV a rs : List [ List [ String ] ]=List () for ( ls t eq D if f <- e q s d i f f ) { var aux : List [ String ]=List () for (eqDiff <- l s te q Di f f ){ i f (extractTotalVarsLinearExp(eqDiff .e)==0) { i f ( calc_doubles ( eqDiff . e ) !=0) aux=aux ++ List (( eqDiff . v) . v) el s e aux=aux }el s e aux=aux ++ List (( eqDiff . v) . v) } listVars=listVars ++ List (aux) } return listVars } Figure 64: Function “ extractVarsDifEqs ” function checks if the variable corresponds to one of the dynamic variables present in the argument. It returns 1 if it matches and 0 if it doesn’t. However, if the expression corresponds to “2*x+x*x” (where x is a dynamic variable), the function will return the maximum value among each of the terms, which in this case would be 2 since there are two dynamic variables multiplying in the second term. Although, some operations required special attention, such as division, where the integer corresponding to the linearity of the divisor is multiplied by 2. This is because even if it is a linear expression with one variable per term, the inclusion of the variable in the denominator invalidates the linearity. To summarise, this function does the following: • If the expression is a real number, it returns the value 0 because regardless of the real number, the expression remains linear; • If the expression has a variable, it returns 1 if it is dynamic and 0 if it is constant; • If the expression is an addition, it returns the maximum integer value obtained by applying this function to each term. The term that returns the highest integer value indicates potential nonlinearity; • If the expression is a multiplication, it checks if the term on the left-hand side contains variables. If it doesn’t have, it calculates its numerical value and checks if it is equal to 0. If it is equal to 0, it returns 0 because multiplying an expression by 0 results in 0, which is linear. However, if it is different from 0, it returns the result of applying this function to the right-hand side term, as it may 79 not be linear. Conversely, if the term on the left-hand side contains variables but the one on the right-hand side does not, a similar process is performed. Finally, if both terms contain variables, the result of applying this function to each term is summed; • If the expression is a division, the result of applying this function to the dividend term is added to twice the result of applying this function to the divisor term. This ensures that the presence of dynamic variables in the divisor will yield a number greater than 1, indicating that the expression is non-linear or requires further simplification to be linear; • If the expression is a remainder, the result of applying this function to the dividend term is added to twice the result of applying this function to the divisor term. This also guarantees that the presence of dynamic variables in the divisor will yield a number greater than 1, indicating that the expression is non-linear or requires further simplification to be linear; • If the expression is a mathematical function or a mathematical constant, the result is obtained from the function “‘funcextract”, which serves the same purpose as the function “extractVarsLinearExp” but specifically handles mathematical functions and mathematical constants. Upon analyzing the function “‘funcextract”, it is apparent that it follows the same methodology as the function “extractVarsLinearExp”. However, it is necessary to detail the method adopted for handling expressions that involve exponentiation. In this case, the approach is as follows: • If the exponent does not contain variables, it is checked whether its numerical value is 0 or 1. If it is 0, the function immediately returns the integer 0 because raising any expression to the power of 0 results in 1, which is always linear. If the exponent is 1, the function “extractVarsLinearExp” is applied to the base term because linearity depends solely on the base term; • If the exponent contains variables or the numeric value is different from 0 and 1, it is necessary to check whether the base contains variables or not. If the base contains variables (when referring to variables in this context, it always means dynamic variables), the value 2 is returned because an expression with variables raised to another expression with variables (or with a numeric value different from 0 and 1) is nonlinear or requires further simplification to be linear. Even so, if the base does not contain variables, it is verified whether the base term is 1. If it is, the function returns the integer 0 because raising any value to the power of an expression equal to 1 always results in 1, which is always linear. If the base term is different from 1, the function returns the integer 2 because the exponentiation is nonlinear or requires further simplification. 80 (Note: It should be noted that in the implementation of functions “extractVarsLinearExp” and “‘funcextract”, it was necessary to use the functions “extractTotalVarsLinearExp” and “calc_doubles”. The function “extractTotalVarsLinearExp” aims to return a non-zero integer if the expression contains variables (dynamic or constant) after numerical simplifications, and 0 if it does not contain variables. On the other hand, the function “calc_doubles” is responsible for calculating the resulting real value of an expression that does not contain variables. The implementation of both functions can be found in Appendix A.6.) Returning to the function “verifyLinearityEqsDiff”, an important aspect to highlight is how the linearity of a differential equation is determined. As mentioned earlier, each differential equation in the program is scanned using “for” loops, and the function “extractVarsLinearExp” is applied to the expression of each differential equation. Additionally, the list of dynamic variables present in the set of differential equations being analyzed is passed as an argument to the function “extractVarsLinearExp”. As previously mentioned, the function “extractVarsLinearExp” returns an integer that represents whether the expression is indeed linear. Based on this integer and using conditional statements, function “verifyLinearityEqsDiff” decides whether to return the differential equation or continue iterating through the “for loops. In the case where function “extractVarsLinearExp” returns the value 0 or 1, indicating that the expression is linear, function “verifyLinearityEqsDiff” continues iterating through the loops. However, if function “extractVarsLinearExp” returns a number greater than 1, indicating that the expression is nonlinear or requires simplification to assume linearity, the function “verifyLinearityEqsDiff” returns this differential equations. In the case where function “extractVarsLinearExp” never returns an integer greater than 1, function “verifyLinearityEqsDiff” completes the iteration through the differential equations and returns “None”. The functions “‘runAtomicWithTime” and “‘runAtomicWithBounds” from “Traj.scala” (as described in Section 4.3.2) will verify whether function “verifyLinearityEqsDiff” returns a differential equation or “None”. If it returns a differential equation, as discussed earlier, it means that this differential equation is nonlinear or need to be simplified, and the corresponding error message is returned. If it returns “‘None” it means that all the differential equations present in the atomic instruction were indeed linear, and the subsequent instructions are followed. Next, three examples to analyze the performance of detecting nonlinear differential equations will be discussed. The first example consists of the following program: 81 x:= 1; y:= 2; x’=sin (x) , y’=1for 1; By running the previous example, the error message from Fig. 65 is obtained. Error : When parsing G§15 x’= si n ( x) , y’=1 f or 1; − hprog .common. ParserException : There i s one d i f f e r e n t i a l equation that i s not l i n e a r or the semantic a na lyser s uspec ts that i t i s non−l i n e a r ( t ry s i m p l i f y i n g the differential equation ) : _x’= s in (_x) Figure 65: Error message returned by Lince The nonlinearity detection implemented in the tool detected that a differential equation in the previous program showed nonlinear behaviour, and that’s why the error message Fig. 65 was returned. It can be observed that the nonlinearity was present in the expression of the first differential equation, as applying a sine to a dynamic variable results in a nonlinear expression. The second example consists of the following program: x:= 1; y:= 2; x’=sin (x) ^( sin ( pi () ) ) , y’=1^x for 1; The symbolic plot of the Fig. 66 is obtained by running the previous example. Figure 66: Symbolic plot resulting from the hybrid program: x:=1; y:=2; x’=sin(x)∧(sin(pi())), y’=1∧(x) for 1; It can be seen that this program is an adaptation of the first example and still contains operations with nonlinear behavior, such as “sin(x)” and raising an expression to a variable. However, the nonlinear detection implemented in the tool is capable of performing numerical simplifications (as discussed earlier). Based on these numerical simplifications, the previous functions, when analyzing the nonlinearity of the expression “sin(x)∧(sin(pi()))”, recognized that “sin(pi())” evaluates to 0, and raising any expression (whether linear or not) to 0 always results in 1, which is indeed linear. Similarly, in the next expression, the 82 function identified that raising the value 1 to “x” is equivalent to 1, and that operation is linear. Therefore, both differential equations were considered linear and sent to SageMath, which determined their solutions. The remaining process can be carried out until obtaining the plots shown in Fig. 66. The third example consists of the following program: x:= 1; y:= 2; x’=sin (x - x) , y’=1for 1; When running the previous example, the error message of the Fig. 67 is obtained. \begin { l s t l i s t i n g }[ s t y l e=e r ro r ] Error : When parsing G§150 − hprog .common. ParserException : There i s one d i f f e r e n t i a l equation that i s not l i n e a r or the semantic a na lyser s uspec ts that i t i s non−l i n e a r ( t ry s i m p l i f y i n g the differential equation ) : _x’= s in (_x + (−1∗_x) ) Figure 67: Error message returned by Lince It can be observed that running the previous program resulted in an error indicating that the differential equation is nonlinear or need to be simplified. Since the implemented method for detecting nonlinearity only allows for numerical simplifications, symbolic simplifications are not performed. As a result, the expression “sin(x-x)” was considered nonlinear, and the previous error was raised. However, as indicated by the error message, if the user attempts to simplify the previous program, they will eventually eliminate the variables within the sine function, resulting in the linear equations “x’ = sin(0)” and “y’ = 1”, which can be solved. 4.5.6 Detection of SageMath’s inability to solve differential equations After implementing the detection of variables that were not assigned at the beginning of the program, variables on the right hand side of the initial assignments that were not previously assigned, unsupported mathematical functions/constants, indeterminate forms, inconsistent results and verification of linearity of differential equations, it was found that SageMath was unable to symbolically solve certain differential equations. For example, if you consider a mechanical system such as a mass-spring-damper system, as shown in the following figure: 83 Figure 68: Mass-spring-damper system [Tab21] To simulate through Lince, it is necessary to determine its differential equations. To determine the differential equations, initially it is necessary to determine the forces applied to each mass (in this example, it will be considered that the dampers function as friction applied to each individual block to simplify the analysis): • In mass 2, the applied forces are the force F(t), the elastic force exerted by spring 2 (Fk2), and the frictional force offered by damper 2 (Fb2); • In mass 1, the applied forces are the elastic force exerted by spring 1 (Fk1), the frictional force offered by damper 1 (Fb1) and the elastic force exerted by spring 2 (Fk2). Based on the reference [Alv11], the elastic force applied by a spring is defined as Fk=k∗yand the frictional force is Fb=b∗v, where yis the deformation of the spring, vis the velocity variation, b is the friction coefficient and kis the elasticity constant. Based on the forces applied to each mass and Newton’s second law, the following equations are obtained: •F(t)−Fk2−Fb2=m2∗d²y2/dt²⇔F(t)–k2(y2−y1)−b2(dy2/dt) = m2∗d²y2/dt² •Fk2–Fk1–Fb1=m1∗d²y1/dt²⇔k2(y2−y1)−k1(y1)−b1(dy1/dt) = m1∗d²y1/dt² Rearranging the previous differential equations so that the second derivative is on the left-hand side, the differential equations are now in the following format: •d²y2/dt²=F(t)/m2–(k2/m2)∗(y2−y1)–(b2/m2)∗dy2/dt •d²y1/dt²= (k2/m1)∗(y2−y1)−(k1/m1)∗y1−(b1/m1)∗dy1/dt Having the differential equations for each of the masses, the following hybrid program was implemented: 84 m1:= 1; m2:= 2; k1:= 3; k2:= 3; b1:= 1; b2:= 1; y1:= 0; v1:= 0; y2:= 0; v2:= 0; f:= 0; f:= 10; y2’=v2 , v2’=f /m2- ( k2/m2)*y2+(k2/m2)*y1 - ( b2/m2)*v2 , y1’=v1 , v1’=(k2/m1)*y2 - ( k2/m1)*y1 - ( k1/m1)*y1 - ( b1/m1)*v1 for 10; f:= 0; y2’=v2 , v2’=f /m2- ( k2/m2)*y2+(k2/m2)*y1 - ( b2/m2)*v2 , y1’=v1 , v1’=(k2/m1)*y2 - ( k2/m1)*y1 - ( k1/m1)*y1 - ( b1/m1)*v1 for 10; This program consists of pushing mass 2 with a constant force of 10N for 10 seconds and then releasing it. Running the previous example in Lince, the error message of the Fig. 69 is obtained. Er ror java . u t i l . NoSuchElementException # n u l l Figure 69: Error message returned by Lince This error message is not very informative, as a user receiving this error would not know what has happened. However, after debugging the outputs received from SageMath, it was found that the tool was unable to solve the systems of differential equations in this example, even though they are linear. This highlights the inability of SageMath to solve certain differential equations symbolically. Due to SageMath’s limitations in solving differential equations, it was decided to improve the error message provided to the user in order to inform him of what occurred and allow him to make his own decisions based on that information. During the debugging process of the previous example’s output, it was observed that SageMath consistently returns a string (that appears in the current version of SageMath as “g1634”) whenever it cannot determine the solution to a particular set of differential equations. Therefore, the file “LiveSageSolver.scala” was accessed and the “askSage” function , depicted in the Fig. 70, was modified. The “askSage” function is responsible for converting a list of differential equations into a format that SageMath can handle, sending it to SageMath, and receiving the result. However, the modification made 85 def askSage ( eqs : Lis t [ DiffEq ] ) : Option [ String ] ={ val instructions =genSage ( eqs ) val rep =askSage ( i ns tr uc ti on s ) i f ( rep . get . contains ( ”g1634”) ) { return throw new TimeoutException(s”Sage could not find the solution ( s ) to the d i f f e r e n t i a l equation ( s ) : ${Show( eqs )}” ) } el s e { return rep } } Figure 70: Function “ askSage ” was to check if the solution contains the previous string, and if it does, an error message is returned indicating that the user-provided differential equations cannot be solved by SageMath. (Note: Alternative approaches to detect that no good solution was found include checking if unknown functions were used, which are used by SageMath to explain how far it could solve the equations.) Thus, the error that resulted from running the previous program in Lince has been modified to the error message shown in Fig. 71. Sage could not fi n d the s o lu t i o n ( s ) to the d i f f e r e n t i a l equation ( s ) : _y2’=_v2 , _v2’=(10/(2) ) + (((( −1∗3) /(2) )∗_y2) + (((3/(2) )∗_y1) + ((( −1∗1) /(2) )∗_v2) ) ) ,_y1’=_v1 , _v1’=((3/(1) )∗_y2) + (((( −1∗3) /(1) )∗_y1) + (((( −1∗3) /(1) )∗_y1) + ((( −1∗1) /(1) )∗_v1) ) ) Figure 71: Error message returned by Lince Providing the user with information about the problem that occurred and which differential equations cannot be solved by SageMath. (Note: Even though SageMath is not able to solve the system of differential equations in the above example, this new version of Lince provides the option to obtain the solutions of the differential equations numerically using the numerical plot (as mentioned in Section 4.4). With this new capability, the user can simulate the previous hybrid program using the numerical plot and obtain the plot of the position of mass 1 and mass 2 as illustrated in the Fig. 72. 86 times longer than that of the autonomous vehicle) and if the variable “temp” was different from the value of the acceleration during braking (the variable “temp” stores the decision made by the driver, which can be to brake or accelerate). If both conditions were met, it was checked whether the vehicle needed to brake or not. If the vehicle did not need to brake, the value of the acceleration for the case of acceleration was stored in the variable “temp”. But if braking was necessary, the value of the acceleration for the case of braking was stored in the variable “temp”. If the value of “c” was different from 100, the driver did not make any decision, and the variable was incremented by one because it was still within the time interval to wait for the driver to make a decision. In the case of the previous decision of the driver being to brake, the variable “temp” had the value “aT” (acceleration for braking), so the counter was incremented because it was no longer necessary to reevaluate the driver’s decision (after initiating the braking, the car will continue to brake until it stops, without the need to evaluate a new decision). The verification of whether the vehicle needs to accelerate or brake to avoid colliding with the obstacle is based on the use of motion equations and the application of the discriminant binomial. The verification consists of two conditions. The first condition determines whether the vehicle’s position at the end of the decision-making time (the position it will be in when the driver makes the next decision), in the case of accelerating, will be lower than the position of the obstacle. To perform this condition, the following steps were taken: 1. New position of the vehicle: ph+vh*reaction_time+aA/2*reaction_time^2 2. New position of the obstacle (in this example, since the obstacle is stationary, the velocity “vl” and acceleration “al” are always 0): pl+vl *reaction_time+al /2*reaction_time^2 3. Condition (new position of the vehicle < new position of the obstacle): ph+vh*reaction_time+aA/2*reaction_time^2 < pl+vl *reaction_time+al /2*reaction_time^2 The second verification consists of checking whether the vehicle’s position will eventually surpass the position of the obstacle (collide) if the driver decides to accelerate and then decides to brake at the end of the decision-making time. To perform this condition, the following steps were followed: 1. New position of the vehicle if it accelerates: ph+vh*reaction_time+aA/2*reaction_time^2 93 2. New velocity of the vehicle if it accelerates: vh+aA*reaction_time 3. Position at time “t” if the driver decides to brake in the next decision-making: (ph+vh*reaction_time+aA/2* reaction_time ^2)+(vh+aA*reaction_time )* t + aT/2* t^2 4. New position of the obstacle at the end of the decision-making time: pl+vl *reaction_time+al /2*reaction_time^2 5. New velocity of the obstacle at the end of the decision-making time: vl+al*reaction_time 6. Position at time “t” of the obstacle after the decision-making time: ( pl+vl *reaction_time+al /2*reaction_time ^2)+(vl+al *reaction_time )*t + al /2* t^2 7. To check if there is any moment in time where the vehicle surpasses the obstacle, the expressions 3 and 6 are equalised, their discriminant binomial is extracted, and it is checked whether there are no solutions (i.e., if the discriminant is less than zero): (( vh+aA*reaction_time - vl - al *reaction_time ) ^2 -4*(ph+vh*reaction_time+ aA/2* reaction_time ^2 - pl+vl * reaction_time+al /2* reaction_time ^2) *(aT/2 - a l /2) )<0 The next step consisted of evaluating the decision of the vehicle with AEB. To do this, it is first checked if the variable “aux” (which stores the decision of the vehicle with AEB) was different from the value of the braking acceleration. If it was different from the braking acceleration, it would mean that the vehicle had chosen to accelerate instead of braking, a similar condition to the one explained earlier was used to determine if the vehicle needed to brake or accelerate and the decision was stored in the “aux” variable. If the vehicle had chosen to brake in the previous evaluation, no new decision was evaluated, and the vehicle continued braking. The implementation of the evaluation of the decision of the vehicle with AEB is as follows: // Vehicle with AEB i f (aux!=aT) then { i f ((p + v*sampling_time + aA/2*sampling_time^2 < pl+vl *sampling_time+al /2*sampling_time^2 ) && ( ( ( v+aA*sampling_time - vl - a l *sampling_time ) ^2 - 4*(p+v*sampling_time+aA/2*(sampling_time ^2) - ( pl +vl *sampling_time+a l /2*( sampling_time ^2) ) ) *(aT/2 - a l /2) )<0)) then { 94 aux:=aA; } el s e { aux:=aT; } } el s e skip ; Finally, it is necessary to use systems of differential equations to simulate the trajectory of the vehicles based on their previous decisions (Eq. (3.1) was used to simulate the trajectory of both vehicles, as it is working in 1D), and as well in the simulation of the position of the object over time. For this purpose, it was checked if both, the vehicle without AEB and the vehicle with AEB, had speeds equal to or less than 0 m/s (that is, if they have already come to a stop). If their speeds are less than or equal to 0 m/s, a system of differential equations is run in which the velocity and position of both vehicles remain unchanged. If one of them has a speed less than or equal to 0 m/s, another system of equations is run where the velocity and the position of that vehicle do not change, while the velocity and position of the other vehicle will vary according to the decision it had made. If both vehicles have positive speeds, then a system of equations is run where the position and velocity of both vehicles vary according to their previous decisions. The following code represents the implementation of the systems of differential equations: // Action i f (vh<=0) then { i f (v<=0) then p’=0 ,v’=0 ,ph ’ = 0 , vh ’ = 0 , pl ’=vl , v l ’=al for sampling_time ; el s e p’=v , v’=aux , ph’ = 0 , vh ’ = 0 , pl ’=vl , vl ’=al for sampling_time ; } el s e { i f (v<=0) then p’=0 ,v’=0 ,ph ’ = vh , vh ’ = temp , pl ’=vl , vl ’=al for sampling_time ; el s e p’=v , v’=aux , ph’ = vh , vh ’ = temp , pl ’=vl , vl ’=al for sampling_time ; } (Note: The program aimed at determining the decision-making of the AEB-equipped vehicle, as well as the program implementing the systems of differential equations, is evaluated during the “sampling_time”. The reason for evaluating the decision-making of the AEB-equipped vehicle during this decision time is because it is associated with this vehicle. However, the reason for evaluating the system of equations based on the “sampling_time” is because it is the smallest of the decision times, encompassing all actions of both the AEB-equipped and non-AEB-equipped vehicles.) (Note: The complete implementation of this program can be found in Appendix A.7.) When executing the entire program in Lince, you get the plot from Fig. 74. 95 Figure 74: Position of the vehicle with AEB (pink), position of the vehicle without AEB (blue), and object at 40 meters (green). It can be seen in the Fig. 74 that both vehicles manage to avoid the collision. However, the vehicle equipped with AEB is able to stop very close to the object, while the vehicle without AEB had to apply the brakes earlier to avoid the collision, stopping further away from the object If the position of the object is changed so that it is 30 meters away from the vehicles, the result of the simulation is depicted in Fig. 75. Figure 75: Position of the vehicle with AEB (pink), position of the vehicle without AEB (blue), and object at 30 meters (green). The vehicle with AEB still has the ability to avoid the collision as it has a shorter decision time and therefore started braking earlier. The vehicle without AEB only started braking after 1 second, which corresponds to its decision time, which was not enough to prevent the accident. If the initial distance to the obstacle is reduced to 5 meters, the result of the simulation becomes as shown in Fig. 76. The collision happens simply because the vehicle starts with a too high velocity to completely stop before hitting the obstacle. From this simulation, it is clear that AEB can significantly reduce accidents compared to conventional braking. In the given circumstances and with the specific vehicle, the AEB-enabled vehicle can prevent collisions with objects at a distance greater than 6.25 meters, while the vehicle without AEB can only prevent collisions with objects more than 33.89 metres away. 96 Figure 76: Position of the vehicle with AEB (pink), position of the vehicle without AEB (blue), and object at 5 meters (green). (Note: Remember that this example is based on the assumption that the vehicle without AEB is solely controlled by the driver, who decides to either accelerate or brake in exactly the same way as the vehicle with AEB. To determine whether braking or accelerating, the current position, velocity, and acceleration of both the vehicle and the object (based on sensors present in the vehicle) must be known, and calculations and comparisons based on the equations of motion must be performed. In real life, the driver operating a car without AEB will subjectively evaluate whether braking is necessary or not based on the speedometer and distance to the object. This makes the decision entirely dependent on human perception, which can lead to more drastic outcomes than those obtained in this simulation. Therefore, it is assumed that the impact of AEB would be even greater in real life.) Through this program, the performance of the AEB can be analyzed in other scenarios, such as: • Varying the initial velocities of both vehicles; • Modifying the values of acceleration and braking; • Changing the decision times of both vehicles. This analysis helps to understand how these factors impact the behavior of the system. 5.2 Adaptive Cruise Control The ACC is primarily associated with the “Complex decision-making” challenge in autonomous driving. Based on [Col23], ACC is a driver assistance system that uses a combination of sensors, radars, and cameras to monitor the distance to the vehicle ahead and automatically adjust the vehicle’s velocity to maintain a safe distance. The main goal of ACC is to reduce driver fatigue, enhance safety, and improve fuel efficiency on highways and long-distance traveling. It allows the vehicle to maintain a constant velocity 97 and automatically adjusts it according to the traffic ahead, relieving the need for the driver to manually control the accelerator and brakes in congested or variable traffic situations. Figure 77: Representative image of a vehicle with ACC [PP22]. In an attempt to test the performance of an ACC for various scenarios and comprehend how its configurations can affect the outcome, a program was implemented in the new version of Lince capable of simulating a situation where an ACC is used. This program involves a vehicle with ACC that aims to maintain a constant velocity. However, another vehicle appears in front of it with constant velocity, forcing the ACC to adjust its vehicle’s velocity to maintain a safe distance. The program was started by assigning the initial position and velocity of the vehicle with ACC, as well as the initial position and velocity of the vehicle in front: p:= 0; v:= 20; // I n i t i a l position and v elocity of the vehicle with ACC. pl:= 30; vl := 10; // I n i t i a l position and vel ocity of the vehicle in front . Next, the braking acceleration (“aT”) of the vehicle with ACC, as well as the acceleration (“aL”) of the vehicle in front, are assigned: aT:= -8; aL:= 0; The next step involved assigning the desired safety distance that the vehicle should maintain from the vehicle in front (“safety_distance”) and the value of the decision-making time by the ACC (“sampling_time”): safety_distance:= 10; sampling_time:= 0.01; Finally, a while loop is executed, running the program until reaching the time limit or the maximum number of cycles allowed by Lince. The program within the while loop begins by determining whether the ACC needs to brake or maintain the velocity in order to keep a safe distance from the car in front (this verification uses the same method as in the previous example, however, in this case, it was necessary to subtract the safe distance from the position of the front vehicle and consider that the vehicle maintains its velocity instead of accelerating, replacing “aA” with 0). If the verification determines that there are conditions to maintain the velocity, a set of differential equations of motion in 1D (see the set of differential 98 equations 3.1) is executed with the acceleration of the ACC vehicle as 0 m/s2, during the decision-making time. If the verification determines that braking is necessary, a set of differential equations of motion in 1D is executed with the acceleration of the ACC vehicle as “aT”, during the decision-making time as well. In both cases, the set of differential equations of motion in 1D for the vehicle in front remains the same, with its acceleration being equal to “aL”. The while loop and the program executed by it are as follows: while ( true ) do { i f ((p + v*sampling_time < ( pl - safety_distance ) + vl*sampling_time + aL/2*sampling_time^2) && ( ( ( v - v l + ( -aL) *sampling_time ) ^2 - 4*(p - ( pl - safety_distance ) + (v - vl )*sampling_time + ( -aL) /2*sampling_time^2) *(aT-aL) /2 ) <0)) then p’=v , v’=0 , pl ’=vl , vl ’=aL fo r sampling_time ; el s e p’=v , v’=aT, pl ’=vl , vl ’=aL for sampling_time ; } When executing the entire program in Lince, you obtain the plot from Fig. 78. Figure 78: Position of the vehicle with ACC (brown) and position of the vehicle in front (pink). (Note: The complete implementation of this program can be found in Appendix A.8.) Based on this hybrid program, it can be observed that the ACC-equipped vehicle can regulate its velocity to maintain a safe distance from the front vehicle (if the vehicle with ACC and the vehicle in front have the characteristics defined in the initial conditions). If the initial velocity of the ACC-equipped vehicle is changed to 35 m/s, the simulation result for the first 2 seconds is as depicted in Fig. 79. In this simulation the system was unable to avoid the collision between the vehicles even though it started braking as quickly as it could. The reason for the collision is that the braking capability of the ACC- equipped vehicle is not sufficient to maintain the safe distance and avoid collision when trying to maintain an initial constant speed of 35 m/s. Simulating cases where the system fails is equally important to understand the contributing factors. In addition to varying the initial speed of the ACC-equipped vehicle, it’s important to vary other param- 99 Figure 79: Position of the vehicle with ACC (brown) and position of the vehicle in front (pink), if the initial velocity of the vehicle with ACC was changed to 35 m/s eters to understand their influence on this system. These changes include: • Varying the initial position of the ACC-equipped vehicle; • Varying the position and initial velocity of the front vehicle; • Varying the braking capability of the ACC-equipped vehicle; • Varying the following distance; • Varying the decision time. 5.3 Missile vs Target In addition to systems related to autonomous vehicle driving, we also have the trajectory planning that a guided missile must follow to intercept the target. These missiles are designed to track the location of a moving target (using, for example, radars or thermal signatures) in order to accurately hit it, without human intervention [ABC22]. A hybrid program was thus developed in Lince to simulate a system in 2D capable of computing the missile’s trajectory to intercept the target, testing its behavior in different scenarios. To model this system, the following characteristics were considered: • The missile and the target can only move forward at a constant speed and perform turns with predefined magnitudes (to simplify); • Besides its own parameters, the missile only has access to the target’s position and velocity at each moment, without being able to predict its movement; 100 • The missile travels at a higher speed than the target. With knowledge of the aforementioned characteristics, a strategy was developed to determine when the missile needs to move forward, turn right, or turn left in order to hit the moving target. Since the missile can only know the target’s position and velocity at each moment, the strategy to determine the action the missile should take involves relating the target’s position and velocity to its own position and velocity. Due to this, the concept of relative position and velocity between the target and the missile was used. As mentioned in [Gee], position and velocity are concepts that involve a reference. For example, if it is said that car A is traveling at 100 km/h, it generally means that the car is traveling at 100 km/h relative to a pre-determined point at surface of the Earth. Based on this concept, and since the missile has access to its position relative to the point E(point Erepresents a given point on the surface of the Eart) (  PM E ) and the target’s position relative to the same reference (  PT E ), the target’s position relative to the missile ( PT M ) was calculated as follows:  PT M = PT E − PME (5.1) Similarly, the target’s velocity relative to the missile was calculated in a similar manner:  VT M = VT E − VME (5.2) (Note: Whenever the missile or the target are mentioned to be in a certain position or velocity without specifying the reference, it is understood that the reference is point E.) (Note: The graphs involving the positions and velocities of both the missile and the target will only consider scalar values in order to represent both vectors on the same graph, facilitating their analysis.) To exemplify, if the missile (point M) is at the position  PME = (0m, 20m)with velocity  VME = (20m/s, 15m/s)and the target (point T) is at the position  PT E = (40m, 50m)with velocity  VT E = (10m/s, 7.5m/s), using Eq. (5.1) the target’s position relative to the missile will be  PT M = (40m, 30m) and using Eq. (5.2) the target’s velocity relative to the missile will be  VT M = (−10m/s, −7.5m/s), as shown in the in Fig. 80. The direction of the missile and the target is defined by the vectors  VME and  VT E , respectively, and the vector  PT M represents not only the position of the target relative to the missile but also the direction that in that moment optimizes the minimization of the distance between the missile and the target. We observe from the previous graph that the directions of the missile, the target, and the vector  PT M are the same, meaning that at the moment when the missile’s decision-making system analyzes this situation, it will recognize that the direction in which the missile is moving is the same as the direction of the target and the direction that currently optimizes the minimization of the distance between the two 101 Figure 80: Graphical representation of the vectors  PME ,  VME ,  PT E ,  VT E ,  PT M , and  VT M [Geo22] objects. Therefore, a good decision by the decision-making system would be to make the missile move forward. However, if the target were to travel with a velocity of  VT E = (15m/s, 0), the graph would change to that of Fig. 81. Figure 81: Graphical representation of the vectors  PME ,  VME ,  PT E ,  VT E ,  PT M , and  VT M , with a different vector  VT E [Geo22] With the previous change, the direction of the missile remains the same as the direction of the vector  PT M , but now it differs from the direction of the target. By analysing this situation, the missile’s decisionmaking system could decide to let the missile move forward, since it was already in the direction that currently optimises the minimisation of the distance between itself and the target. However, by analysing the direction of the target, it becomes clear that the target is moving in a different direction from the missile and the vector  PT M , and in the next moment the target will move in that direction or a direction close to it (if it curves). Therefore, a good decision by the system would be to make the missile curve to the right, thus shortening the distance between the missile and the target in the next iteration. If, in addition to changing the target’s velocity to  VT E = (15m/s, 0m/s), the missile’s velocity is changed to  VME = (30m/s, 0m/s), the graph would change to that of Fig. 82. With the two previous changes, the missile’s direction becomes the same as the direction of the target, 102 Figure 87: 2D representation of the trajectories of the missile and the target when the initial position of the missile is changed to (700m, 300m) and the initial velocity of the missile is changed to (20m/s, −10m/s) (Note: If we analyse Fig. 87, we can see that the missile has decided to turn around (i.e. it did not take the shortest path). As mentioned earlier, the reason for this is that the strategy developed in the design of this hybrid program aims to make the angle tend towards 180 degrees, which does not always result in the shortest trajectory. Nevertheless, this strategy proves to be quite effective.) Finally, if in addition to altering the missile’s initial position and velocity, its turning capacity is reduced by half (meaning it completes a full turn in 40 seconds instead of 20 seconds), the plot of the missile’s and target’s positions from Lince, along with their 2D representation, are shown in Fig. 88 and Fig. 89, respectively. Figure 88: Position of the missile (x,y) and the target (xl,yl) as a function of time, when the initial position of the missile is changed to (700m, 300m) , the initial velocity of the missile is changed to (20m/s, −10m/s) and the turning capacity is changed to (1/40)2π Even with the reduction in the missile’s turning capability, the developed strategy was able to model a trajectory that enables the missile to collide with the target, albeit requiring more time (87.7 seconds) and 109 Figure 89: 2D representation of the trajectories of the missile and the target when the initial position of the missile is changed to (700m, 300m) , the initial velocity of the missile is changed to (20m/s, −10m/s) and the turning capacity is changed to (1/40)2π covering a greater distance than the previous simulation. Based on the previous simulations, it can be observed that the program (using the strategy developed in this section) is effective in executing the trajectory and allows the analysis of the behaviour of this system in different scenarios. In addition to the scenarios analysed so far, there are other very interesting ones to be simulated, such as: • Varying the target’s trajectory; • Changing the initial position and velocity of the target; • Modifying the target’s turning capability; • Adjusting the system’s decision time. 5.4 Modeling of other types of systems In addition to Lince being capable of simulating hybrid programs governed by Newtonian mechanics, such as the programs developed in the previous sections, it is also capable of simulating other types of systems, such as classical physical systems and On-Off systems, and to perform numerical analyses. The current section illustrates this aspect. Specifically in what concerns classical physical systems, the following simulations were performed: • Damped harmonic oscillator; 110 • Projectile motion without air resistance. Regarding On-Off systems, the following simulations were conducted: • RLC series electrical circuit; • Hydraulic system; Finally, for numerical analysis, the following simulations were performed: • Numerical derivative; • Numerical integration. There are several other systems that can be modeled similarly to the examples that will be discussed in the following subsections. For instance, thermal systems use sets of differential equations very similar to hydraulic systems, and as such, they are not covered in this work. 5.4.1 Damped harmonic oscillator The damped harmonic oscillator is a classical physical system that consists of an object subjected to a restoring force proportional to its displacement from an equilibrium position, while also experiencing a damping force proportional to its velocity [Top23]. Figure 90: Representative image of an assembly for studying damped harmonic motion [Exp21]. The differential equation that describes the motion of a damped harmonic oscillator is given by [Top23]: x′′ =−k m∗x−c m∗x′(5.5) where mis the mass of the object, xis the displacement of the object from the equilibrium position, cis the damping coefficient, and kis the spring constant that determines the restoring force. 111 (Note: Differential Eq. (5.5) arises from the use of Newton’s second law, where the restoring force is equal to k∗xand the damping force is equal to c∗x′.) Depending on the value of the damping coefficient, the damped harmonic oscillator can exhibit different regimes [Wik22]: •Underdamping: In this regime, the damping coefficient (c) is less than the critical value (2∗ sqrt(m∗k)). The amplitude of the oscillations gradually decreases over time. The lower the damping coefficient relative to the critical value, the more prolonged the oscillations will be before the amplitude significantly decreases. •Overdamping: In this regime, the damping coefficient (c) is greater than the critical value (2∗ sqrt(m∗k)). When the object is released under this regime, it quickly returns to its equilibrium position without oscillations. •Critical Damping: In this regime, the damping coefficient (c) is equal to the critical value (2∗ sqrt(m∗k)). This is the regime where the object reaches its equilibrium position more quickly, without exhibiting oscillations around it, similar to the overdamped regime. The critical value of the damping coefficient (c) is determined by the properties of the system, such as the mass (m) and the spring constant (k). Adjusting the damping coefficient relative to the critical value allows control over the behavior of the damped harmonic oscillator. These different regimes have applications in various fields of physics and engineering, such as designing vehicle suspension systems and RLC circuits [Ins23]. To analyze the behavior of the three regimes of the damped harmonic oscillator, a program was developed in Lince capable of simulating these regimes for a specific body oscillating under certain properties. Initially, one starts by defining the value of the body’s mass (m) and the value of the spring constant (k): m:= 1; // mass of the object k:= 2.32; // Spring constant Next, the value of the damping coefficient, initial position, and initial velocity is defined for each of the three regimes: // damping c o e f f i c i e n t and i n i t i a l values of the underdamping regime b_sc:= 1; //damping c o e f f i c i e n t xsc:= 2; // I n i t i a l position vsc:= 0; // I n i t i a l velo city 112 // damping c o e f f i c i e n t and i n i t i a l values of the overdamping regime b_Sc:= 3.5 ; //damping c o e f f i c i e n t regime xSc:= 2; // I n i t i a l position vSc:= 0; // I n i t i a l velo city // damping c o e f f i ci e n t and i n i t i a l values of the c r i t i c a l damping regime b_c:=2* sqrt (k*m) ; //damping c o e f f i c i e n t xc:= 2; // I n i t i a l position vc:= 0; // I n i t i a l veloc ity The variable xsc will represent the position of the body undergoing underdamped harmonic oscillator since its damping coefficient (b_sc) is less than 2∗sqrt(k∗m)(which is approximately equal to 3.046). On the other hand, the variable xSc will represent the position of the body undergoing overdamped harmonic oscillator since its damping coefficient (b_Sc) is greater than 2∗sqrt(k∗m). Finally, the variable xc will represent the position of the body undergoing critically damped harmonic oscillator since its damping coefficient (b_c) is equal to 2∗sqrt(k∗m). In the end, it is only necessary to execute the set of differential equations that define the damped harmonic oscillator (Eq. (5.5)) for each of the regimes for a duration of 15 seconds: // D i f f e r e n t i a l equations xsc’=vsc , vsc’=- xsc*k/mvsc*b_sc/m, xSc’=vSc , vSc’=-xSc*k/mvSc*b_Sc/m, xc’=vc , vc’=-xc*k/mvc*b_c/m for 15; Executing the previous program in Lince results in the plot shown in Fig. 91. Figure 91: Representation of the damped harmonic oscillator in the three regimes. In Fig. 91, one can visualize the behavior of the three regimes of the damped harmonic oscillator: the purple curve represents the underdamping regime, the orange curve represents the overdamping regime, and the brown curve represents the critical damping regime. As mentioned earlier in this chapter, it can be observed that the underdamping regime exhibits oscillations, unlike the other regimes. On the other hand, the overdamping regime takes longer to reach equilibrium compared to the critical damping regime. (Note: The complete implementation of this program can be found in Appendix A.10.) 113 5.4.2 Projectile motion without air resistance The projectile motion without air resistance is a classical physical system that describes the motion of an object launched in the air without the influence of air resistance [Ope22]. Figure 92: Representative image of a projectile motion [Phy23b]. The differential equations describing this 2D physical system can be found in reference [Phy23a], and based on Eq. (3.2) from Chapter 3, they can be written as follows: x′=vx, y′=vy, vx′= 0, vy′=−g(5.6) Considering “g” as the gravitational acceleration and assuming that the projectile is launched from a given position (x0,y0) with a given initial velocity v0at an angle θ, the initial velocity in the xdirection is v0∗cos(θ)and the initial velocity in the ydirection is v0∗sin(θ). However, since no forces act on the projectile in the xdirection throughout the motion, the sum of the resulting forces in the xdirection is zero (Frx= 0), leading to a constant velocity (vx′= 0) in that direction. On the other hand, in the ydirection, the weight of the projectile is the only force acting and it points in the opposite direction. Therefore, F ry =m∗vy′⇔ −m∗g=m∗vy′⇔vy′=−g, meaning that the projectile travels along the yaxis with a constant acceleration equal to −g[Wal18]. The utility of this physical system can be found in various everyday applications, some of them are found in the following areas [Dew23]: •Sports: Projectile motion is encountered in various sports such as basketball, golf, and baseball. Understanding the principles of projectile motion helps athletes calculate the optimal launch angle and velocity for achieving desired trajectories and distances; •Engineering: The understanding of projectile motion without air resistance is crucial in fields like ballistics, artillery, and aerospace engineering. It is employed to determine the trajectory and range of projectiles, aiding in the design and optimization of weapons, rockets, and other projectile-based systems; 114 Due to the usefulness of this physical system, it was decided to develop a program in Lince capable of simulating this system. To do so, we started by defining the initial position, the magnitude of the initial launch velocity, the gravitational acceleration, the launch angle, and the initial velocity component in each of the axes: x:= 2; y:= 2; v0:= 10; g:= 9 . 8 ; theta:=pi () /4; vx:=v0*cos ( theta ) ; vy:=v0* s in ( theta ) ; Next, the system of differential equations 5.6 was executed until the projectile reached the ground (that is, until the y-axis became less than or equal to zero): x’=vx , y’=vy , vx’=0 ,vy’=-g until_0 .01 (y<=0); Running the previous program resulted in the plot shown in Fig. 93. Figure 93: Position of the projectile in the “x” and “y” coordinates Through this program, users can adjust the initial parameters to obtain the graph of the projectile launch according to the characteristics they have defined. This allows them to analyze how the projectile would behave with those specific characteristics and gain a better understanding of this type of physical system. (Note: The complete implementation of this program can be found in Appendix A.11.) 5.4.3 RLC series electrical circuit The RLC series electrical circuit is a system composed of a resistor (R), an inductor (L), a capacitor (C) and a voltage source connected in series. In this case, the circuit is considered as an On-Off system, which means that the voltage source is turned on and off over time. For an RLC series circuit, the differential equation describing the variation of voltage across the capacitor over time is derived for the following laws [CC06]: 115 Figure 94: Representative image of a RLC series electrical circuit [CC06]. • Kirchhoff’s second law gives V s =vc +vL +vR, where V s is the voltage at the source, vc is the voltage at the capacitor, vL is the voltage at the inductor and vR is the voltage at the resistor; • Ohm’s law gives vR =R∗iR,ic=C∗vc′,vL =L∗i′ Land ic=iL=iR=i(Ris the resistance, Cis the capacitance, Lis the inductance, iRis the current in the resistor, icis the current in the capacitor and iLis the current in the inductor); Based on these two laws and the expressions established by them it follows that [CC06]: V s = vc +vL +vR ⇔V s =vc +L∗i′+R∗i⇔V s =vc +L∗C∗vc′′ +R∗C∗vc′⇔vc′′ = −vc′∗(R/L)−vc/(L∗C) + V s/(L∗C); Converting the previous differential equation to a system of differential equations following the Lince grammar, gives the following set of differential equations: vc′=dvc, dvc′=−dvc ∗(r/l)−vc/(l∗c) + vs/(l∗c)(5.7) On the other hand, the RLC series circuit can operate in different regimes depending on the values of the components (α=R/(2 ∗L)and w0= 1/√L∗C) [int23]: •Critically damped regime: In this regime, the circuit quickly reaches a state of equilibrium without oscillations. This occurs when α=w0; •Underdamped regime: In this regime, the circuit exhibits oscillations and the amplitude decreases exponentially. This regime occurs when α < w0; •Overdamped regime: In this regime, the circuit returns to state of equilibrium more slowly than in the critically damped regime without oscillations. This regime occurs when α > w0. The RLC circuit has many applications, some of them involve [rlc23]: • Oscillator circuits, radio receivers, and television sets where they are used for tuning purposes; • Signal processing and communication systems. 116 Given that RLC circuits are widely used in various everyday applications, it was decided to simulate the behavior of three RLC series circuits, each operating in a different regime, where the voltage source is turned on for a certain period and then turned off (On-Off system). This simulation will allow users to analyze how the voltage across the capacitor in an RLC circuit varies in each regime when the voltage source is switched on and off. To perform this simulation, a hybrid program was developed in Lince. This hybrid program begins by initializing the initial voltage of the capacitor in each regime (vc_rac is the voltage in the critically damped regime, vc_rsa is the voltage in the underdamped regime, and vc_rSa is the voltage in the overdamped regime), the respective derivative of the voltage (dvc_rac is the derivative of the voltage in critically damped regime, dvc_rsa is the derivative of the voltage in the underdamped regime, and dvc_rSa is the derivative of the voltage in the overdamped regime) and the initial voltage of the voltage source (vs): vc_rac:= 0; vc_rsa:= 0; vc_rSa:= 0; dvc_rac:= 0; dvc_rsa:= 0; dvc_rSa:= 0; vs:= 10; Next, the value of the inductance (l), capacitance (c), and the resistance values for each circuit were defined according to their respective regimes (r_rac is the resistance in the critically damped regime, r_rsa is the resistance in the underdamped regime, and r_rSa is the resistance overdamped regime): l:= 0.047; c:= 0.047; r_rac:= 2; r_rsa:= 0 . 5 ; r_rSa:= 4; To choose the value of resistance for each regime, the expression of αwas equated with the expression of w0and the value of the resistance required for the circuit to operate in the critical regime was extracted: α=w0⇔R/(2 ∗L) = 1/√L∗C⇔R= (2 ∗L)/√L∗C⇔R= (2 ∗0.047)/√0.047 ∗0.047 ⇔R= 2. Thus to obtain the critically damped regime, the resistance value must be equal to 2 (r_rac=2), to obtain the underdamped regime the resistance value must be less than 2 (r_rsa<=2) so that αis less than w0, and to obtain the overdamping regime the resistance value must be greater than 2 (r_rSa >= 2) so that αis greater than w0. The next step was to run a system of differential equations that describes the voltage variation in the capacitor (see Differential equations 5.7) for each regime for a duration of 1 second while the voltage 117 source was connected with a value of 10: vc_rac’=dvc_rac , dvc_rac’=-dvc_rac*r_rac/ l - vc_rac /( l *c )+vs /( l *c ) , vc_rsa’=dvc_rsa , dvc_rsa’=-dvc_rsa*r_rsa/ l - vc_rsa /( l *c )+vs /( l *c ) , vc_rSa’=dvc_rSa , dvc_rSa’=-dvc_rSa*r_rSa/ l - vc_rSa/( l *c )+vs /( l *c ) for 1; The final step is to turn off the voltage source and run the aforementioned system of equations: vs:= 0; vc_rac’=dvc_rac , dvc_rac’=-dvc_rac*r_rac/ l - vc_rac /( l *c )+vs /( l *c ) , vc_rsa’=dvc_rsa , dvc_rsa’=-dvc_rsa*r_rsa/ l - vc_rsa /( l *c )+vs /( l *c ) , vc_rSa’=dvc_rSa , dvc_rSa’=-dvc_rSa*r_rSa/ l - vc_rSa/( l *c )+vs /( l *c ) for 1; By executing the aforementioned hybrid program, the plot in Fig. 95 was obtained, representing the variation of voltage across the capacitor over time. Figure 95: Variation of voltage across the capacitor for critically damped regime (green), for underdamed regime (orange), and for overdamped regime (grey). Based on the simulation of this system using this hybrid program, it can be observed that the behavior of the three regimes aligns with the description provided at the beginning of this section. This allows the user to visually understand the system’s behavior and explore variations in the initial parameters and the On-Off time of the voltage source, providing insights into how the system responds to these changes. (Note: The complete implementation of this program can be found in Appendix A.12.) 5.4.4 Hydraulic system Hydraulic systems are systems that use fluids, such as water or oil, to transmit energy and perform mechanical tasks [aad23]. Hydraulic systems have a wide range of practical applications in various sectors: •Amusement Park Rides: Hydraulic systems are crucial for ensuring the safety of amusement park rides. These systems can handle significant forces and repetitive motions, while also providing precise control over pressure. This precision is essential for controlling the spinning, pushing, lifting, and speeding of the rides in a regulated manner, guaranteeing the riders’ safety. In addition to their 118 Through these hybrid programs, it is concluded that the real and numerical representations are quite similar demonstrating the capability of this new version of Lince to perform numerical derivatives and integrals using Eqs. (5.9) to (5.11). 125 Chapter 6 Conclusions and future work 6.1 Conclusions Through the completion of this dissertation project, the Lince tool, which previously had constraints and limitations, was improved and transformed into a more versatile hybrid program simulation tool, with greater simulation capabilities. These improvements include the addition of a wide range of linguistic constructs, the ability to use non-linear expressions, grammatical relaxation, improved error detection, grammatical structuring, bug fixes in parsers and the interpreter, and the possibility of determining the solutions of differential equations numerically. As a consequence, Lince evolved into a more capable tool of modelling hybrid programs, especially those governed by Newtonian mechanics, something that was previously impossible to implement with the precision and simplicity achieved in the current version of Lince. The enhancement was driven by the need to have programs performing instructions with high complexity on both discrete and continuous levels. A myriad of hybrid programs, including AEB,ACC, and the guided missile trajectory system, were designed and tested in the new version of Lince, demonstrating its applicability to the modelling of such systems. Not only this, we also presented the simulation and modelling of other systems, such as purely physical systems, on-off systems and numerical analyses. Therefore these enhancements made to the tool exceed the original objectives of this study, which solely sought to introduce novel linguistic constructs to enable the modelling of a wider spectrum of hybrid programs, particularly those governed by Newtonian mechanics. Such enhancements have converted the tool into a simulator for hybrid programs that is not only more proficient but also more user-friendly. This work has opened up new possibilities in simulating complex systems and it is predicted that the contributions presented will inspire further research and practical applications in this rapidly advancing field. 126 6.2 Prospect for future work During the execution of a dissertation project, potential improvements or issues often arise that cannot be implemented or resolved due to time constraints. It is thus important to identify these potential improvements or issues, highlight their significance, and, if possible, provide strategies for their implementation or mitigation to encourage future contributions. As such, throughout the execution of this dissertation project, a set of potential improvements and issues were identified. How the implementation or mitigation of these could positively impact the tool was explored, and strategies for their application or mitigation were considered. This resulted in the following proposals for future work: •Improving trajectory generation from the symbolic graph - As mentioned in Section 4.4, SageMath’s inability to handle large symbolic expressions prevented the use of the symbolic graph in the simulation of certain hybrid programs. As discussed in that chapter, this problem was mitigated by creating a solver that solved differential equations using a numerical method, and creating the numerical graph that allowed the simulation (albeit with some inaccuracy) of programs that encountered this problem in the symbolic graph. However, the ideal approach would be to improve the method of calculating trajectories from the symbolic graph, thus avoiding the inaccuracy introduced by the numerical graph. This improvement could involve numerically calculating only the symbolic expressions that approach the limit that SageMath can handle. This way, only symbolic expressions that would cause issues due to their length would be numerically simplified, reducing the error propagation introduced by the numerical plot; •Configuration of Lince’s Graphs - Lince’s graphical interface allows some manipulation of graphs, such as zooming in, zooming out, selecting, and determining which trajectories to visualize. However, it would be a significant enhancement to the tool if the graphical interface allowed the user to select some parameters and create an n-dimensional graph that relates nvariables. As the first suggestion of an enhancement, it would be useful allow the user to select important parameters for the simulation of hybrid programs, such as the number of samples (Nyquist’s theorem); the maximum number of loop iterations; the algorithm for obtaining numerical solutions to differential equations (assuming that other algorithms are involved); and which variables appear in the graphs, among others. In order to implement this enhancement, a procedure similar to the one used, for example, to support the configuration of the time limit for the simulation of hybrid programs, already implemented in the old version of Lince, would be necessary. 127 As the second suggestion, it would be useful to allow the user to visualize the behaviour of variables in a faster and more convenient way (similar to the 2D representation of missile and target trajectories in Section 5.3), instead of having to rely on the “Chart Studio” editor. A possible implementation of this improvement would be to configure a parameter in the Lince platform to select the type of graph (variables over time, 2D or 3D) and the relationship between variables (for example, in a 2D graph, variable ‘a’ is associated with the x-axis and variable ‘b’ with the y-axis, both defining a trajectory). In the case of a 2D or 3D graph, the interpreter would need to collect relevant variable values along their trajectories and then project these values onto their respective axes to create a trajectory. •Enabling Direct Use of Differential Equation Solutions - In this new version of Lince, the continuous behavior of variables can only be described by differential equations. However, allowing the use of trajectory equations (i.e., solutions to differential equations) to model continuous behavior offers greater flexibility to the user, enabling them to directly write the desired trajectory equations instead of initially having to model the system’s differential equations. The strategy for incorporating the use of trajectory equations involves creating syntax for them, extending the parser to support the use of these equations alongside differential equations, making the interpreter compatible with the use of trajectory equations (if the continuous behavior is described by these equations, there is no need to resort to SageMath or numerical methods to determine solutions since these expressions are the solutions themselves), and adding error handling for these equations; •Further Exploration of the Case Studies - The case studies developed in this project highlighted the capabilities of this new version of Lince, as well as its applicability in various areas. However modelling other systems, such as systems based on PID controllers, would be an interesting and challenging task for this new version, as would the in-depth exploration of existing case studies (for example, modelling the trajectory of a missile that always seeks the shortest path and has the ability to decelerate). This would put Lince to the test in different scenarios, allowing the detection of possible anomalies or enriching improvements, as well as testing its applicability; •Collaboration with the Community - Publicizing this tool in the academic and/or development community would provide valuable feedback and potential future collaborations, such as studying whether the tool satisfies certain properties based on CTL logic, as well as identifying bugs and potential improvements. 128 Bibliography [aad23] aadityacademy. What is hydraulic: Definition, principle, properties, advantages. https: //aadityacademy.com/hydraulic/, 2023. [ABC22] Science ABC. How are missiles able to ’pursue’ targets when they make evasive turns? https://www.scienceabc.com/innovation/ how-guided-missiles-work-guidance-control-system-line-of-sight-pursuit-navigation. html, 2022. [Ack22] Team Ackodrive. Autonomous emergency braking (aeb) in cars and how it works. https: //ackodrive.com/car-guide/autonomous-emergency-braking/, 2022. [Acu] Proctor Acura. Technology guide: What is an automatic braking system? https://www. proctoracura.com/automatic-braking-system-guide. [ALRF+22] Alvin Alexander, Ben Luo, Julien Richard-Foy, Jonathan, Xhudik, and Adrien Piquerez. Scala for javascript developers. https://docs.scala-lang.org/scala3/book/ scala-for-javascript-devs.html, 2022. [Alv11] Bruno Miguel Pedro Alves. e-Book para Controlo Digital: Teoria, Matemática, Modelos e Simulações . PhD thesis, Minho University, 2011. [Ato23] AtoZmath.com. 1. formula & example-1 (table data). https://atozmath.com/example/ CONM/TwoPointFormula.aspx?q=3&q1=E1, 2023. [Aut] Automate. An overview of machine vision and autonomous vehicles. https://www.automate.org/blogs/ an-overview-of-machine-vision-and-autonomous-vehicles. [BDL06] Gerd Behrmann, Alexandre David, and Kim G Larsen. A tutorial on uppaal 4.0. Department of computer science, Aalborg university , 2006. 129 [BG11] Radhakisan Baheti and Helen Gill. Cyber-physical systems. The impact of control technology , 12(1):161–166, 2011. [BLL+95] Johan Bengtsson, Kim Larsen, Fredrik Larsson, Paul Pettersson, and Wang Yi. Uppaal—a tool suite for automatic verification of real-time systems. In International hybrid systems workshop , pages 232–243. Springer, 1995. [Blo23] Main Blog. Meeting the challenge of water supply systems in high-rise buildings. https://blog.bermad.com/building-and-construction/ meeting-the-challenge-of-water-supply-in-high-rise-buildings, 2023. [CC06] Chaniotakis and Cory. Examples of transient rc and rl circuits. Spring , 2006. [CCD] CCDCOE. Cybersecurity considerations in autonomous ships. https://ccdcoe.org/ library/publications/cybersecurity-considerations-in-autonomous-ships/. [CNN23] Nadia Leigh-Hewitson CNN. We’re still waiting for self-driving cars, but autonomous boats are already here. https://edition.cnn.com/travel/article/ autonomous-boats-spc-intl/index.html, 2023. [Col23] Collimator. What is adaptive cruise control? https://www.collimator.ai/ reference-guides/what-is-adaptive-cruise-control, 2023. [Cue] Cuemath. Angle between two vectors - formula, how to find? AngleBetweenTwoVectors-Formula,HowtoFind? [DBN+94] Ayumu Doi, Tetsuro Butsuen, Tadayuki Niibe, Takeshi Takagi, Yasunori Yamamoto, and Hirofumi Seni. Development of a rear-end collision avoidance system with automatic brake control. Jsae Review , 15(4):335–340, 1994. [DdMBJ] A Barbosa Daniele de Moraes and Yaro Burian Jr. Iniciação científica: Instrumentos digitais e teorema da amostragem. [Dew23] DewWool. 20 examples of projectile motion. https://dewwool.com/ 20-examples-of-projectile-motion/, 2023. [Doc22] Scala Documentation. Regular expression patterns. https://docs.scala-lang.org/tour/ regular-expression-patterns.html, 2022. 130 [Dun23] Jack Dunhill. New hypersonic missile engine could have almost double the range, claim chinese researchers, 2023. [DZX+21] Mahdi Dibaei, Xi Zheng, Youhua Xia, Xiwei Xu, Alireza Jolfaei, Ali Kashif Bashir, Usman Tariq, Dongjin Yu, and Athanasios V Vasilakos. Investigating the prospect of leveraging blockchain and machine learning to secure vehicular networks: A survey. IEEE Transactions on Intelligent Transportation Systems , 23(2):683–700, 2021. [ECT23] ECT/UFRN. Integração numérica - método do trapézio - ect/ufrn. https://cn.ect.ufrn. br/index.php?r=conteudo%2Finteg-trapezio, 2023. [EMO01] Hilding Elmqvist, Sven Erik Mattsson, and Martin Otter. Object-oriented and hybrid modeling in modelica. Journal Européen des systèmes automatisés , 35(4):395–404, 2001. [Exp21] Net Explanations. Damped oscillations. https://www.netexplanations.com/ damped-oscillations/, 2021. [FCK+22] Akimasa Fujiwara, Makoto Chikaraishi, Diana Khan, Atsufumi Ogawa, Yoshihiro Suda, Toshikazu Yamasaki, Takaharu Nishino, and Shutaro Namba. Autonomous bus pilot project testing and demonstration using light rail transit track. International Journal of Intelligent Transportation Systems Research , 20(2):359–378, 2022. [FMQ+15] Nathan Fulton, Stefan Mitsch, Jan-David Quesel, Marcus Völp, and André Platzer. Keymaera x: An axiomatic tactical theorem prover for hybrid systems. In International Conference on Automated Deduction , pages 527–538. Springer, 2015. [For23] World Economic Forum. Could autonomous aircraft make make flying safer and more sustainable? https://www.weforum.org/agenda/2023/08/ autonomous-aircraft-could-make-flying-safer-easier-to-access-and-more-sustainable/, 2023. [Gee] GeeksforGeeks. Relative motion velocity in two dimensions: Formulas & examples. https: //www.geeksforgeeks.org/relative-motion-in-two-dimension/. [Gee19a] GeeksforGeeks. Scala: Abstract type members. https://www.geeksforgeeks.org/ scala-abstract-type-members/, 2019. [Gee19b] GeeksforGeeks. Scala: Arrays. https://www.geeksforgeeks.org/scala-arrays/, 2019. 131 [Gee19c] GeeksforGeeks. Scala: Case class and case object. https://www.geeksforgeeks.org/ scala-case-class-and-case-object/, 2019. [Gee19d] GeeksforGeeks. Scala: Functions - basics. https://www.geeksforgeeks.org/ scala-functions-basics/, 2019. [Gee21] GeeksforGeeks. Scala string. https://www.geeksforgeeks.org/scala-string/, 2021. [Geo22] GeoGebra. Geogebra clássico. https://www.geogebra.org/classic?lang=pt-PT, 2022. [GNP] Sergey Goncharov, Renato Neves, and José Proença. Lince: Lightweight prototyping of hybrid programs. [GNP19] Sergey Goncharov, Renato Neves, and José Proença. Lince: Lightweight prototyping of hybrid programs (full version). 2019. [GNP20a] Sergey Goncharov, Renato Neves, and José Proença. Implementing hybrid semantics: From functional to imperative. In International Colloquium on Theoretical Aspects of Computing , pages 262–282. Springer, 2020. [GNP20b] Sergey Goncharov, Renato Neves, and José Proença. Implementing hybrid semantics: From functional to imperative (extended version). Technical report, CISTER-Research Centre in Realtime and Embedded Computing Systems, 2020. [GS15] Jeffery B Greenblatt and Susan Shaheen. Automated vehicles, on-demand mobility, and environmental impacts. Current sustainable/renewable energy reports , 2:74–81, 2015. [GST09] Rafal Goebel, Ricardo G Sanfelice, and Andrew R Teel. Hybrid dynamical systems. IEEE Control Systems , 29(2):28–93, 2009. [HDCW+19] Carl-Johan Hoel, Katherine Driggs-Campbell, Krister Wolff, Leo Laine, and Mykel J Kochenderfer. Combining planning and deep reinforcement learning in tactical decision making for autonomous driving. IEEE transactions on intelligent vehicles , 5(2):294–305, 2019. [Hea22] IronRod Health. Implantable device monitoring. https://www.ironrod.health/ implantable-device-monitoring, 2022. 132 [Hen16] Marcos Luiz Henrique. Mini curso: Análise numérica e computacional aplicada a equações diferenciais. Universidade Federal de Goiás , Nov 2016. [HHMS16] Corey D Harper, Chris T Hendrickson, Sonia Mangones, and Constantine Samaras. Estimating potential increases in travel with autonomous vehicles for the non-driving, elderly and people with travel-restrictive medical conditions. Transportation research part C: emerging technologies , 72:1–9, 2016. [HLLDS09] WPMH Heemels, D Lehmann, J Lunze, and B De Schutter. Introduction to hybrid systems. Handbook of Hybrid Systems Control–Theory, Tools, Applications , 2, 2009. [HP22] Daseon Hong and Sungsu Park. Avoiding obstacles via missile real-time inference by reinforcement learning. Applied Sciences , 12(9):4142, 2022. [Hu14] Fei Hu. Cyber-physical systems . Taylor & Francis Group LLC, 2014. [II17] Viktória Ilková and Adrian Ilka. Legal aspects of autonomous vehicles—an overview. In 2017 21st international conference on process control (PC) , pages 428–433. IEEE, 2017. [IIIR22] Mohamad Issa, Adrian Ilinca, Hussein Ibrahim, and Patrick Rizk. Maritime autonomous surface ships: Problems and challenges facing the regulatory process. Sustainability , 14(23):15630, 2022. [Ins23] What’s Insight. Damped oscillation: Formula and daily life examples. https:// whatsinsight.org/damped-oscillation/, 2023. [int23] intmathcom RSS. 8. Damping and the Natural Response in RLC Circuits. https://www. intmath.com/differential-equations/8-2nd-order-de-damping-rlc.php, 2023. [KHdW15] Miltos Kyriakidis, Riender Happee, and Joost CF de Winter. Public opinion on automated driving: Results of an international questionnaire among 5000 respondents. Transportation research part F: traffic psychology and behaviour , 32:127–140, 2015. [KST+21] B Ravi Kiran, Ibrahim Sobh, Victor Talpaert, Patrick Mannion, Ahmad A Al Sallab, Senthil Yogamani, and Patrick Pérez. Deep reinforcement learning for autonomous driving: A survey. IEEE Transactions on Intelligent Transportation Systems , 23(6):4909–4926, 2021. [KW17] Philip Koopman and Michael Wagner. Autonomous vehicle safety: An interdisciplinary challenge. IEEE Intelligent Transportation Systems Magazine , 9(1):90–96, 2017. 133 [LDVF+11] Salvatore Luongo, Vittorio Di Vito, Giancarmine Fasano, Domenico Accardo, Lidia Forlenza, and Antonio Moccia. Automatic collision avoidance system: design, development and flight tests. In 2011 IEEE/AIAA 30th Digital Avionics Systems Conference , pages 5C1–1. IEEE, 2011. [Lex23] Lexology. Legal challenges in autonomous flight: Things to consider before investing in an aircraft that flies itself. https://www.lexology.com/library/detail.aspx?g= e847b797-2239-4097-9013-7bfda4c9af9e, 2023. [Lib23] LibreTexts. 2.5: Numerical integration - midpoint, trapezoid, simpson’s rule. https://math.libretexts.org/Courses/Mount_Royal_University/MATH_ 2200%3A_Calculus_for_Scientists_II/2%3A_Techniques_of_Integration/ 2.5%3A_Numerical_Integration_-_Midpoint%2C_Trapezoid%2C_ Simpson%27s_rule, 2023. [Lim22] Acervo Lima. Classe e objeto em scala – acervo lima. https://acervolima.com/ classe-e-objeto-em-scala/, 2022. [Mai15] Gabrielle Maioli. Métodos numéricos para equações diferencias ordinárias. 2015. [Mar21] Piping Mart. 8 applications of hydraulic systems in daily life. https://blog. thepipingmart.com/other/8-applications-of-hydraulic-systems-in-daily-life/, 2021. [Mar23] Flying Cars Market. Cybersecurity and the challenges of self-driving aircraft. https://flyingcarsmarket.com/ cybersecurity-and-the-challenges-of-self-driving-aircraft/, 2023. [Mat21] Matics. What is cps (cyber physical system). https://matics.live/glossary/ cyber-physical-system/, 2021. [Mat23] MathWorks. MATLAB Simulink. https://www.mathworks.com/products/simulink. html, 2023. [MBZ22] MBZUAI. Would you fly in a plane piloted solely by ai? https://mbzuai.ac.ae/news/ would-you-fly-in-a-plane-piloted-solely-by-ai/, 2022. 134