Full text
University of Minho School of Engineering Rui Carlos Azevedo Carvalho Adding Uncertainty to Real-Time Programming august 2023
University of Minho School of Engineering Rui Carlos Azevedo Carvalho Adding Uncertainty to Real-Time Programming Masters Dissertation Master’s in Informatics Engineering Dissertation supervised by Renato Neves august 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 would like to start by expressing my gratitude towards Professor Renato Neves for the all the guidance throughout this project and for the incredible help in every step of this dissertation. His vast expertise was invaluable not only for completing this dissertation but also to greatly improve my knowledge in this research area. I would also like to thank Juliana Souza, who acted like a co-supervisor, not only for the scientific contribution which served as the foundation for this dissertation, but also for all the knowledge, related to the more theoretical parts of programming languages and mathematics, and support during this whole year. Finally, I would like to thank my parents, Carlos and Arminda, as well as my brother Luís, for the incredible support and encouragement they always gave me during every part of my life which was fundamental to keep me focused on my education which helped me a lot to now be able to complete this dissertation. This work was financed 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/CCICOM/4280/2021. The author was also financed by National Funds through the Portuguese funding agency, FCT - Fundação para a Ciência e a Tecnologia, within project LA/P/0063/2020. 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, august 2023 Rui Carlos Azevedo Carvalho iii
Abstract In this dissertation we cover the implementation in Haskell of an interpreter for a while-language capable of handling both hybrid and probabilistic effects. The interpreter is supported by both operational and denotational semantics which were devised in this dissertation as well. We started by studying a pre-existing syntax and operational semantics of a programming language capable of performing wait calls and probabilistic choices through a random-number-generator. We then redefined this semantics to another one that is more suitable for statistical analysis in programming. Next we performed another iteration over these two semantics, more specifically we extended them to support full hybrid behaviour, traditionally used to encode interactions between digital devices and physical processes such as movement and time. We also devised two denotational semantics corresponding to the operational semantics mentioned before, as a way of providing a mathematical abstraction, through the use of monads, to the programs of our language. Not only this, we also implemented a domain specific language embedded into Haskell, which thus provides to the hybrid programmer all the expressive power that Haskell offers in addition to a palette of combinators designed specifically for the hybrid domain. Such gives rise to an expressivity power much greater than what the aforementioned while-language can provide. Lastly, we presented and analysed several deterministic hybrid programs, such as cruise controllers, and added subtle probabilistic elements to them that reflect certain real-word scenarios. Such an addition lead from one possible execution to several possible executions; and most notably some of the latter revealed safety issues introduced by the probabilistic elements. All in all this dissertation has both theoretical and practical contributions that form a stepping stone towards a rigorous engineering discipline of probabilistic hybrid systems. Keywords Formal Methods, Hybrid Systems, Cyber-Physical Systems, Theory of Programming Languages, Functional Programming iv
Resumo Através desta dissertação descrevemos uma implementação em Haskell de um interpretador para uma linguage while capaz de lidar tanto com o efeito híbrido como com o efeito probabilístico. O interpretador é suportado por semânticas operacionais e denotacionais que foram definidas também nesta dissertação. Primeiramente, abordamos uma sintaxe e semântica operacional pré-existentes de uma linguagem capaz de realizar chamadas de espera e escolhas probabilísticas, através de um gerador de números aleatórios. De seguida, redefinimos esta semântica numa outra que é mais apropriada para a análise estatística dos programas. Consequentemente, realizamos uma outra iteração sobre estas semânticas sendo que as estendemos para suportarem totalmente o comportamento híbrido, tradicionalmente utilizado para representar interações entre dispositivos digitais e físicos, tais como movimento e tempo. Criámos também duas semânticas denotacionais, correspondentes às semânticas anteriores, de modo a fornecer uma abstração matemática, através da utilização de mónadas, para os possíveis programas da nossa linguagem. Para além disto, foi implementada uma domain specific language incorporada em Haskell, o que providencia ao programador híbrido todo o poder que o Haskell oferece conjugado com combinadores definidos especialmente para o domínio híbrido. Tal dá origem a um poder expressivo muito maior do que aquele que a linguagem while supramencionada pode providenciar. Por fim, abordaram-se vários exemplos de programas híbridos determinísticos, tais como sistemas de cruise control , aos quais foram adicionados elementos probabilísticos subtis que refletem cenários do mundo real. Esta adição fez com que fossemos de uma execução para uma variedade de execuções possíveis; e mais notávelmente alguns dos sistemas revelaram problemas relacionados com a segurança quando os elementos probabílisticos foram introduzidos. Em suma, esta dissertação apresenta contribuições teóricas e práticas que se traduzem num passo em direção a uma dísciplina de engenharia rigorosa sobre sístemas híbridos probabilísticos. Palavras-chave Métodos Formais, Sistemas Híbridos, Sistemas Ciber-Físicos, Teoria das Linguagens de Programação, Programação Funcional v
Contents 1 Introduction 1 1.1 Context and motivation ................................ 1 1.2 Contributions ..................................... 1 1.3 Roadmap ....................................... 3 2 State of the Art 5 2.1 Core concepts of monad-based programming ..................... 5 2.1.1 The notion of a monad ............................ 5 2.1.2 Monad composition ............................. 8 2.1.3 The power of monads in programming .................... 11 2.2 Probabilistic programming .............................. 15 2.2.1 An overview ................................. 15 2.2.2 Monads for probabilistic programming .................... 16 2.3 Hybrid systems .................................... 18 2.3.1 The concept and main challenges ....................... 18 2.3.2 Their role in modern technology ....................... 19 2.3.3 Modelling and analysis ............................ 19 2.4 Hybrid programming ................................. 21 2.4.1 An overview ................................. 21 2.4.2 Monads for hybrid programming ....................... 23 3 A probabilistic while language with hybrid behaviour 24 3.1 Combining probabilistic behaviour with program duration ................ 24 3.1.1 Syntax .................................... 24 3.1.2 Operational semantics ............................ 25 3.2 Incorporating full hybrid behaviour ........................... 29 vi
harbours probabilistic operations. To be more specific, the main contributions of the present dissertation are the following: • The implementation of parser and an interpreter for a while-language capable of handling both hybrid and probabilistic behaviour. • The implementation of a flexible visualisation module for a proper analysis of the behaviour of probabilistic hybrid systems. • A thorough study of possible operational semantics for the while-language above. This resulted in the development of two complementary semantics for the language, both integrated in the interpreter. One semantics is based on random-number-generators and performs real-time simulations and the other works explicitly with distributions and does not perform real-time wait calls. The former runs slower (when timed events are present) but might be useful in cases where we wish to include the errors associated with wait calls to the operating system, while the latter is faster but only takes into consideration the theoretical wait times. • We gave first steps towards denotational counterparts to the two previously mentioned operational semantics. This helps to root our interpreter in strong mathematical foundations, from which we can capitalise to reason about probabilistic hybrid programming. For example, reasoning about program equivalence often recurs to denotational semantics [25]. • Then in order to boost the flexibility and expressivity of the aforementioned while-language, we implemented a domain specific language (DSL) embedded in Haskell, which allows the use of elements present in the while-language in conjunction with functions from Haskell, such as folds or maps, as well as combinators created specifically for the DSL. • Finally we developed several hybrid programs combined with probabilistic elements, using both the while-language and the DSL. We analysed and reported how probabilistic behaviour affects the respective results. Notably, some programs presented no problems when using the deterministic approach, but as soon as small levels of uncertainty were introduced, we obtained right away trajectories that indicated safety related problems. This tool expands the modelling capabilities of Lince [5] allowing us to see different trajectories, by adding a few elements of uncertainty. Figure 1shows this in action, as in the left side we have a deterministic trajectory, where we try to maintain a particle at a fixed distance, but due to error accumulation when 2
accelerating or decelerating it, the particle tends to get further and further away [5]. As we mentioned before we cannot expect an action to be made in an exact amount of time, there is always some kind of uncertainty in these moments. The tool we built, which we named ProbLince, allows us to specify this uncertainty in the model, leading to a multitude of trajectories. In some of these the particle moves away faster than others, which leads us to observe the strength of uncertainty and what kind of problems we can detect by having it ingrained in our models. (a) Naive particle position (b) Probabilistic naive particle position Figure 1: Simulation of a particle position with ProbLince 1.3 Roadmap This dissertation is divided into seven chapters with the following content: • Chapter 1: goes over the context, motivation, main contributions and structure of this dissertation. • Chapter 2: covers the state of the art of the techniques used to implement our parser and interpreter. It also gives an overview of probabilistic and hybrid programming, and establishes the mathematical background, namely elements of category theory, such as Kleisli categories and monads. • Chapter 3: describes the syntax and operational semantics of our while-language, which mixes probabilistic elements with hybrid behaviour. • Chapter 4: goes over the implementation details such as the architecture of the developed tool, and how some key parts of both the parser and interpreter were implemented. 3
• Chapter 5: discusses the implementation details of the DSL, describes its combinators and shows how the DSL it differs from the previous while-language. • Chapter 6: presents some case studies, how they were implemented in our tool, and the results obtained. • Chapter 7: concludes the dissertation and discusses possible lines of future work. Finally there are two appendices. The first contains the grammar used by the parser, while the second has the installation commands and user guide for the implemented tools. 4
Chapter 2 State of the Art In this chapter we reveal some of the key concepts in the literature, which support this dissertation and the tool we implemented. We start by going over the concept of a monad and how it can be used to capture computational effects, as well as the techniques to combine them into a single monad capable of handling all the different effects at once. Afterwards, we cover the definition of probabilistic programming and its characteristics. We also uncover some well known languages for implementing probabilistic programs, but more importantly some implementations which follow a monadic approach. In the final two sections we dive into the concept of hybrid systems, by revealing what they are, their importance and the challenges associated with them. We will also go over the notion of hybrid programming and how we can use monads to capture the hybrid effect and why this approach is an advantage when compared to other ways of modelling hybrid systems. 2.1 Core concepts of monad-based programming 2.1.1 The notion of a monad Before going over the actual definition of a monad, we start by looking at a fruitful connection between monads and programming. In [36,37] E. Moggi established an important connection between functions and complex programs, by pointing out that the latter could be seen as functions (or more generally, morphisms) A→T B, which map values of some generic type Ato computations T B over a generic type B. This provides an uniform and flexible view of various side effects. One of the most common ones are exceptions, as they appear in many software products. If we think for example about the head function, which outputs the first element of a given list, we quickly notice the existence of the empty list 5
case, where an exception should be raised together with an appropriate message. So the final computation over a list corresponds to two possibilities, either we output the first element of the list or an exception. Even though there are many side effects (which means there are several maps like the one mentioned above) these present intrinsic common characteristics: indeed in every instance we can consider how computations should be handled along sequential composition, and how an input value should be embedded into a computation [37]. This yields naturally the following definition. Definition 1 (Kleisli triple).A Kleisli triple over a category Cis comprised of the following elements [36,37]: • A mapping on objects Obj(C)→Obj(C); • For every C-object Xa morphism ηX:X→T X, which allows the embedding of a value into a computation; • A function (−)∗which lifts a morphism A→T B to a morphism T A →T B, corresponding to the way computations are handled along sequential composition. Moreover (−)∗needs to respect a certain set of coherence laws detailed in [36,37]. It is at this point that the notion of a monad naturally appears in the context of programming: Kleisli triples and monads are in bijective correspondence to each other. Definition 2 (Monad).A monad over a category Cis a triple comprised of the following elements [37]: • A functor T:C→C; • A natural transformation η:Id →T; • A natural transformation µ:TT →T. Moreover certain coherence laws about the interaction between ηand µneed to be respected. These are detailed for example in [37]. Very briefly, from a Kleisli triple we obtain the endofunctor Tof the equivalent monad by defining Tf = (η·f)∗, and for every C-object Athe morphism µA:T T A →T A is defined by (idT A)∗. Conversely if we take a monad and want to obtain the corresponding Kleisli triple we have to apply a constraint to the endofunctor Tso it only deals with objects of the category and the Kleisli lifting (−)∗ is defined by f∗=µ·Tf. See more details in [37]. This bijective correspondence between Kleisli 6
triples and monads is useful, because in certain aspects it is easier to work with one view instead of the other [37]. Below we have the definitions of some well-known monads, which are crucially used in various software products – we will work in the category of sets and functions, but many of these examples can be actually generalised to categories satisfying certain conditions. Definition 3 (Exception monad).Exceptions can be viewed as the possibility of obtaining two kinds of result: the concrete value, which corresponds to the result of the computation, or a message, which is an error or exception e∈Ethat was thrown during the execution of the program. In [37] we have a Kleisli triple which defines this type of computation, but we can consider the following monadic definition of the exception monad (E[E], in which Eis the set of exceptions): •E[E]X=X+E •ηX=i1 •µX= [id, i2] Note in the definition above the use of the injection functions i1and i2, as well as the function [f, g]. These are detailed in [39,42] and correspond to a coproduct diagram: Ai1// f (( Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q QA+B [f,g] B i2 oo g vvmmmmmmmmmmmmmmmm C Definition 4 (State monad, S).The state monad provides mutable states s∈Sto the programmer. One use case of this monad was presented in [52] where P. Wadler uses it to count the number of reduction steps a computation takes to terminate. Its definition is given again in [37], but by adapting it into the monadic view we obtain: •S X = (X×S)S •ηX(x) = λs.(x, s) •µX(g) = λs.f(s′)with g(s) = (f, s′) Definition 5 (Writer monad, W).The writer monad is used for aggregating data along computations. This is useful for example to debug programs or to keep track of which resources were used. Technically the monad is parametrised by a monoid (M,·, i)and the Kleisli triple definition is presented in [37]; by adapting the latter to the monadic perspective we obtain: 7
•W X =X×M •ηX(x) = (x, i) •µX((x, m′), m) = (x, m ·m′) Definition 6 (Generalised writer monad).Consider a monoid (M,·, i). A monoid module is a set Eequipped with a map ▷:M×E→E(monoid action) that satisfies the laws i▷e =eand (m·n)▷ e =m ▷ (n▷e). Every monoid module yiels a Kleisli triple defined by [25,23], •W[M]X=X×M+E •ηX(x) = i1(x, i) •–f∗(i1(x, m)) = i1(y, m ·n)if f(x) = i1(y, n) –f∗(i1(x, m)) = i2m▷eif f(x) = i2e –f∗(i2e) = i2e Where W[M]is the functor of the generalised writer monad (W[M]). 2.1.2 Monad composition As already mentioned, the implementation of interpreters is a frequent case [52,32] in which different monads are need to capture different functionalities of the underlying language. For example, we may have a language that is able to not only throw exceptions but also to read internal stores. The first functionality uses the previously defined exception monad whilst the second involves the also previously defined state monad [52]. Indeed this problem of considering different functionalities in a single interpreter was already highlighted in different contexts [52,49], in all cases modularity being a desirable tenet. In other words, the problem calls for techniques to combine the functionalities ( i.e. the corresponding monads) in a principled way, a quest that has been taken using different approaches in the past years. We briefly overview some of them next. A standard way of combining monads is to see them as equational theories (whenever possible) and to take advantage of existing results from categorical algebra to combine them. This allows us to consider for example coproducts and tensors of monads (in algebraic form) [35]. One disadvantage of this approach is that in some cases it is not applicable [17]. Two other standard ways of combining monads is via the notion of a distributive law [17,12,16,43] and monad transformers [34,32]. We will focus on the last two, because we take advantage of them in our work. 8
Definition 7 (Distributive law).The definition of the distributive law is given in [17]. If we have two generic monad instances, Mand T, and we wish to combine them into the monad MT , then we would need to first define a function which allows the following transformation: T M X λ −→ MTX. In order to prove that this function is in fact a distributive we need to prove that the diagrams below commute: T X T ηM ηM > > > > > > > > > > > > > > > > > TM X λ //MT X M X ηT M MηT > > > > > > > > > > > > > > > > > TM X λ //MT X TMM X λM// T µM MTM X Sλ //MMT X µS T TM X λ //MT X TT M X T λ // µT M TMT X λT//MT T X M µT TM X λ //MT X The distributive law yields a new monad MT defined by the following triple [17]: (MT, ηM T· ηT, M µT·µM T T ·MλT). Unfortunately such laws present limitations, specifically there might not always exist a distributive law between two monads, a prime example being the powerset and distribution monads [55]. Some alternative theories were thus created to cover some of these limitations, such as weak distributive laws [35,41,17]. Additionally, in [55] Zwart and Mardsen reveal a set of theorems which demonstrate the situations where it is impossible to define a distributive law, even covering some concrete monadic combinations where the specification of a distributive law fails. 9
Although not always rooted in mathematical foundations, monad transformers are used extensively in Haskell programming, specially in the cases concerning interpreters (mentioned above) [52]. These differ from distributive laws, as the idea is to create a transformer associated with different monads, such as the state monad transformer or the exception monad transformer [35,34]. The following example gives a code fragment of the state monad transformer which receives a monad Tand returns a new monad able to manipulate internal states: Example 1 (State monad transformer).The type below is the result of instantiating the state monad transform with a generic monad t(StateT t a), using Haskell’s notation, (see more details in [34, page 338] and [35, page 136]): State -> t (a, State) The combined monad supports both the state monad operations as well as operations associated with the monad t. An interesting aspect to notice is that this transformer does correspond to any distributive law (see more in [35]), for the reason that the monad tis sandwiched between (a, State)and (−)State. A downside of monad transformers is that we need to define the transformer for each monad we want to use, which in some cases its quite difficult to know how to do or even impossible (as it happens with the IO monad) [35]. Also a thing to be careful about monad transformers is that the order in which they are used matters [35]. In other words, if we have the stack of transformers StateT State (ExceptT String Identity) a we will obtain a value of the following type: State -> Identity (Either String (a, State)) and now we switch the order of both transformers we to ExceptT String (StateT State Identity ) a we get, State -> (Identity (Either String a, State)) Both two types are significantly different, and thus the order in which monad transformers are applied should be properly planned. As mentioned before, in order to use monad transformers one needs to define them for the monads we want to use. In particular their definition requires us to define the lifting operation. Generically, this transformation follows the type lift :: t a -> mt (t a) which is described in more detail in [32]. In this case tis a generic monad and mt is the monad transformer. Let us illustrate this with an example. 10
Example 2 (Application of the lift function).As we mentioned before, every monad transformer has an associated lift function. In the case of the state monad transformer (StateT) that function has the following signature (with tbeing a generic monad): lift :: t a -> StateT State t a If we admit the exception monad transformer has a function named throw, which receives a message (String) and throws it as an exception, we would obtain a computation of type Except String a. If we wish combine this effect with the effect of the state monad, we could use the monad transformer mentioned above, resulting in the following signature: StateT String (Except String) a Now if we wanted to use the functions associated with the exception monad, such as the throw function, we have to use the lift function mentioned before, as we need to include an exception monadic computation into the state transformer: T lift ·throw (( Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q throw ”exception”//Except String T lift StateT State (Except String T) In this case, Tis the functor of a generic monad. 2.1.3 The power of monads in programming Monad-based programming presents a large number of advantages. An important one is that functional languages tend to be pure, which means they do not allow side effects, by default, on their functions. As a result, it becomes problematic to implement certain features or programs that are usually easy to implement in other programming languages. Monads allow us to overcome this as they allow the introduction of side effects in a modular way as they handle all the complexity of performing impure operations [51,52]. There are a lot of use cases for monad which illustrate their usefulness, but in order to be exhaustive, we will dive in into two which are relevant for the implementation of ProbLince. The first one, are the previously mentioned monadic interpreters and the second is monadic parsing. 11
which returns an infinite list of indenpendent samples from a distribution, and the sampler function, which transforms a Sampler monadic computation into an IO computation: ghci > take 10 <$> (sampler . independent . runWriterT $ drawUniform) [(0.0,""),(1.0,""),(0.0,""),(1.0,""),(1.0,""),(0.0,""),(0.0,""),(0.0,"") ,(0.0,""),(0.0,"")] Listing 2.8: Obtaining 10 samples of writer computations from a binary distribution In the example above we have taken the 10 first results of a list of infinite independent samples. Now, in this case we do not have the guarantee that our samples are biased or not. Because of this, we can use the inference algorithms of the library, such as the Metropolis-Hastings algorithm, to obtain a more adequate collection of samples [56]. 2.3 Hybrid systems 2.3.1 The concept and main challenges Hybrid systems are characterised by producing behaviour with both discrete and continuous components. From an engineering perspective, one can regard them as systems comprised of two parts: a physical one, which can be the motion of a vehicle or the temperature of a heater, and a digital part which controls (and is influenced by) the first [45,44]. Specifically, the latter takes in the information of the cyberphysical interaction and uses it to make decisions that affect the behaviour of the physical part of the system. Acceleration and deceleration or stopping a cooling process are prime examples of this, among many others. A recurring concrete example of a hybrid system is that of a vehicle whose velocity is being monitored and controlled by a computer. In this case, the velocity corresponds to the physical effect that is changing at every time instant (continuous behaviour) and when it reaches a certain value the software triggers the brakes which slows down the vehicle (discrete behaviour) [46,44]. Such a behavioural pattern is common in automotive systems. There are many challenges associated with the design and analysis of such systems. These mostly arise from the complexity that gets introduced by combining two kinds of behaviour ( i.e. continuous and discrete) which interact with each other in intricate and often surprising ways. Consequentially, this leads to the number one difficulty which is to find good formalisms to model correctly hybrid behaviour. Of course these formalisms are also required to facilitate the verification of the correctness of the model in a rigorous way. It is important to perform this verification for both types of behaviour simultaneously: doing 18
it so separately may result in incorrect conclusions [38,46]. On one hand, just looking at the continuous behaviour results in imprecisions as the discrete behaviour affects, even if just from time to time, the continuous behaviour. On the other hand, by discretising things we loose information about the system that is crucial for the verification process [46]. 2.3.2 Their role in modern technology The relevancy of hybrid systems is largely associated with the vast range of fields they exist in and the number of examples we can find today, which will only continue to grow in the future. These systems can be seen in the medical field, with devices ranging all the way from pacemakers to robots capable of assisting surgeries in operating rooms. Additionally, self-driven vehicles (including cars, planes, and satellites) are also hybrid systems, as they have software on board that is responsible for changing the speed and movement of the vehicle in order to adapt to the circumstances of the surrounding environment [38,47]. Yet another example is that of smart power grids and how they are used to control the flow of electricity to the places where it is most needed. In order to do this a proper management system and devices are installed for the purpose of monitoring the flow. This application could become very useful as the number of people that produce their own power, through solar panels for example, is increasing. These panels produce energy that could be used by the smart grid to perform a more efficient administration of the electricity flow [30]. Other examples can be checked in [31]. Notably in the power grid example malfunctions can lead to power outages, with direct impact not only on the general population but also on factories and other types of services [30,47]. Actually all the examples above are critical systems, in the sense that a malfunction can result in catastrophic events. Safety concerns thus become a central aspect in the design of these systems [30]. Simple tests to ensure this safety are not enough as they might not cover all the different scenarios which these systems will face and so, some bugs might still be present in the final implementation [45]. In the words of E. Dijkstra “Program testing can be used to show the presence of bugs, but never to show their absence!” [19, 1970, page 7]. Due to this fact there is a pressing need to find more suitable ways of designing and verifying hybrid systems [45]. 2.3.3 Modelling and analysis As previously mentioned, there is a pressing need to find good formalisms for the design and analysis of hybrid systems. Extensive research has been done in this direction in the past few years. We give a brief overview next. 19
Hybrid automata and Kleene algebra One of the main topics of this research revolves around the idea of modelling hybrid systems as automata with hybrid characteristics [25]. Specifically this theory is described in [27] where T. Henzinger presents the idea of modelling a hybrid system as a graph in which the nodes represent locations and the edges represent possible transitions (discrete behaviour) between locations. Continuous behaviour is specified via differential equations inside locations. Example 4 (Hybrid automaton that models a car braking system).The following hybrid automaton is inspired in the thermostat example present in [27] and in the train control example in [46] and models a car braking system: Brakes off v′= 10 −0.05v v≤35 Brakes on v′=−5 v≥15 v > 30 v < 20 Figure 2: Car braking system modelled by an hybrid automaton The automaton presents two valid locations in which the system can be in. In the first one the brakes are off and the car is gaining speed according to the respective differential equation. As for the second one, the braking system is triggered and thus speed decreases. There is one transition each way dictating when the braking system can be (de)activated. Finally, there is information in the locations namely conditions (often called invariants) which have to be true when the system is in that location. Note that when the system is in a location and the respective invariant becomes false the system is forced to leave that location. This example shows perfectly how the formalism of hybrid automata tries to incorporate the prominent aspect of hybrid systems: continuous behaviour (physical process) is specified by the differential equations in the locations and the discrete behaviour (digital process) affects it by switching the location and thus the ‘active’ differential equation. The authors in [23,25] refer to another relevant topic in the quest for hybrid systems formalisms: the idea of creating algebras to model hybrid systems, such as the ones present in [29] and [46], based on Kleene algebra theory. 20
Non-determinism vs. a modular perspective of hybrid behaviour The aforementioned formalisms have an important drawback: non-determinism is present by default in the corresponding models. This makes it difficult to study pure hybrid computation which is always mingled with non-determinism [23]. An alternative approach, advocated for example in [23,25], is to study first pure hybrid computation and subsequently its combination with other effects (including non-determinism). It is actually possible to draw a parallel between this idea of stacking effects and a central topic of monadbased programming, namely that of monad composition. In this case, we could have for example a monad for hybrid behaviour and another for non-determinism or probabilistic behaviour and consider a proper combination [23]. This more modular approach towards hybrid systems has the benefit of separating challenges conceptually and at different levels. This has implications for example in the development of semantics for hybrid systems [23,25]. Also for our case it has strong implications in what concerns the addition of probabilistic effects to hybrid systems: it is certainly easier to combine probabilities with pure hybrid behaviour than to combine probabilities with hybrid behaviour mingled with non-determinism. Indeed the task of combining probabilities with non-determinism alone has already made extensive amounts of ink flow [16]. 2.4 Hybrid programming Now that we have established what a hybrid system is and what monad-based programming consists of, we analyse the connection between these two fields. More concretely in this section we recall the concept of hybrid programming and how it can be frammed in a monadic setting. 2.4.1 An overview Hybrid programming is based on the idea of extending programming languages with differential equations. Similarly to probabilistic programming (recall our previous description), this allows to take advantage of concepts and techniques from programming theory to model and analyse hybrid systems [25]. Example 5 (Hybrid Program).An example of a hybrid program is given in [25, page 1 (Online version)]: while true do { if v <= 10 then (v' = 1 for 1) else (v' = -1 for 1) } 21
Listing 2.9: Cruise controller It implements a cruise control system in which the velocity of the vehicle (variable v) is controlled by accelerating the vehicle for one time unit if the observed value is less or equal than 10, or decelerating for the same amount of time if the velocity rises above 10. The program shows exactly the key points of hybrid programming in the sense that it allows the use of classical computing elements, in this case while-loop and conditionals, with other elements that are connected to a physical process, i.e. the continuous change in velocity through the use of differential equations. As an example of hybrid languages we have HybCore, a deterministic language that follows a monadic approach, specifically it involves a monad that frames hybrid behaviour as a computational effect. This language is particularly useful as it integrates the tool Lince, which allows to analyse hybrid programs via simulations of their execution [25]. There are also hybrid programming languages that follow a nonmonadic approach and are also non-deterministic, such as the ones described in [46,15]. Additionally there are DSLs embedded into Haskell, such as Yampa [14,28], which uses combinators to compose specific forms of hybrid behaviour. Yampa shows an interesting approach to how a DSL could be implemented; in fact it inspired the development of our own DSL (detailed in Chapter 5). In order to verify a hybrid program it is important that the underlying programming language has a well-established semantics. The latter can be divided into different categories but here we focus on two: operational semantics and denotational semantics [25,53]. Operational semantics reveals the reduction steps that occur in a program’s execution and how they affect the internal state of the computer on which the program is running. This is useful to develop interpreters for the language as it shows exactly how a program should behave over time [37,25]. As for the denotational semantics, it consists on providing mathematical foundation to the language. This particularly useful, as it allows us to reason about the programs written in this language abstractly, without being encumbered by syntactic particularities. This is useful to not only better understand the language but also to reason about the correctness of programs and the equivalency between two programs. In the case of the HybCore, the denotational semantics revolves around a specific monad which will be detailed next [25,23,37]. 22
2.4.2 Monads for hybrid programming Now that both types of semantics were briefly introduced, we will focus more in the denotational part as it is where we can observe how a specific monad can be used to capture hybrid effects. Interestingly, this monad is a particular instance of the generalised writer monad (which described in the definition 6), and involves a monoid-module of trajectories [23,25] which we detail next. The basic idea of this monoidmodule is that hybrid behaviour can be encoded in trajectories [0, r)→Rnwhere r∈R≥0and nis a natural number. The value rcan be seen as the duration of the hybrid effect whilst ncorresponds to the number of variables being changed over time. It is possible that the hybrid effect runs ad infinitum (think for example of while-loops) so we also wish to consider trajectories of the type [0,∞)→Rn. Now, there is clearly a trivial trajectory [0,0) →Rnwhich corresponds to an instantaneous hybrid effect. And we can concatenate trajectories which corresponds in some sense to ‘extending over time’ an hybrid effect with another. Let us give a formal definition of this description Definition 8 (Monoid module of trajectories).Fix a natural number n. The monoid component is the triple (⨿r∈R≥0[0, r)⇒Rn,++,! : [0,0) →Rn)where ++ is defined by, (r1, e1) ++ (r2, e2) = (r1+r2, t 7→ if t < r1then e1(t)else e2(t−r1)) The module component is given by the set ⨿r∈[0,∞][0, r)⇒Rntogether ++ extended in the obvious way as the module operation. In the next chapter we will give concrete details on how this monad can be used to give semantics to a hybrid programming language. For now, it is relevant to mention that although this monad is suitable to handle hybrid effects, it raises problems in its Haskell implementation. More concretely, after joining two trajectories with the multiplication function, one cannot discern exactly the instant where the first trajectory ends and the second one starts. This leads to problems related to the visualisation of trajectories. We thus changed the definition of the previous monoid-module to another which is capable of handling hybrid effects and does not carry the described problem. We will give more details about this problem and the altered monoid-module in the following chapter. 23
Chapter 3 A probabilistic while language with hybrid behaviour As mentioned in Introduction, our main goal is to implement a language that harbours both probabilistic and hybrid effects. In order to accomplish this we will first look at a pre-existent language that supports probabilistic choice and a very specific hybrid effect: that of wait calls which halt a machine for a specific amount of seconds [48]. We will first detail the syntax of this language and then its semantics. Subsequently, we will go over the necessary changes to the syntax and semantics of the language which will allows us to fully incorporate both the hybrid and probabilistic effects. Finally, the last section of this chapter covers the denotational semantics which serves as a mathematical foundation for this language, using a monadic approach such as the one present in [25]. 3.1 Combining probabilistic behaviour with program duration 3.1.1 Syntax We first focus on the syntactic structure [48] of what we call deterministic terms. These can be either real numbers (R), variables (of a predetermined countable set Var ) or applications of arithmetic operations. More formally deterministic terms are described by the grammar: d ::= a a ∈R | x x ∈Var | d op d op ∈{+,-,×,÷} Listing 3.1: Deterministic terms syntax The programming language supports more general terms which can be either deterministic terms or probabilistic terms; the latter case amounts to a coin() operator which implements an unbiased coin toss by returning a random binary value. These more general terms also allow the usage of basic arithmetic operations: 24
t ::= d deterministic term | coin() sample from {0,1} | d op d op ∈{+,-,×,÷} Listing 3.2: Terms syntax Booleans conditions are also present in the language. We can observe in the grammar below that one is able to perform comparisons between deterministic terms or use standard logical operators like the ‘or operator (||)‘ between tests: b ::= true | false | d == d | d < d | d > d comparison of deterministic terms | b && b | b || b |!b Boolean combinations of tests Listing 3.3: Tests syntax Finally we present the grammar associated to programs, which reveals not only standard program constructs but wait calls as well: e ::= skip | x := t assignment | e ; e sequential composition |if bthen eelse e conditional |while bdo e while loop | wait t do e wait calls Listing 3.4: Programs syntax 3.1.2 Operational semantics In this subsection we present operational semantics for the previous language in two different styles: the first uses a random number generator (RNG)mto calculate the output of a program that starts its execution in some initial state s. Technically, the RNG consists of an infinite list of random binary values which will be used to interpret the coin toss operation. States on the other hand consist of maps between variables and real numbers, and can be seen as the computer’s memory. The second style of semantics discards the RNG and returns not a single output but a distribution of outputs. Note that, the first operational semantics is part of a pre-existent work [48], as we mentioned before. 25
Notably, the language presented above reveals some cases where errors might occur ( e.g division by 0). In this case, we designed both the operational and denotational semantics as if they do not happen, because we are only trying to capture the hybrid and probabilistic behaviours. With respect to the implementation, we implemented the capability of handling errors to produce a more complete tool (catching the division by 0 cases), even though these semantics do not specify them. Both styles of semantics have their merits. The first is closer to how probabilistic languages are actually implemented and has a good performance w.r.t. execution. The second has a worse performance but is closer to a monadic style of programming which allows us to appeal to several results about monads (for example monad composition). In both cases the semantics boil down to a set of deductive rules describing the outputs of a program under specific assumptions – the computation of the output a program will thus consist in a proof tree of these deductive rules. Let us make the previous explanations about the two semantics more concrete by presenting them in full detail next. We start with the semantics that uses a RNG. The expression (e, s, m)⇓(s′, m′, d) denotes that program ein initial state sand with generator mreturns the new state s′in dseconds; its execution consumes part of the generator which results in m′. Furthermore, the operation JtK(s, m) obtains the value of the term twhen given a state sand the probabilistic resource m. The same thing applies to the test terms, where JbK(s, m)obtains the boolean value of the term b. Let us now present the deductive rules for this language [48]. The first rule refers to the assignment of values to variables. In this case, we assign the value tto the variable xi. Firstly, this program needs to obtain the value of the term tusing the initial resources (s, m), which gives a value aand the possibly altered value of the probabilistic resource m′. The output of this program will then change the state of the variables by assigning the value ato the variable xi. The program is instantaneous which results in it being associated with a duration of zero seconds: JtK(s, m) = (a, m′) (asg) (xi:= t, s, m)⇓(s[i→a], m′,0) The following rule refers to the situation where we are sequencing the program skip with any other. Note that skip is a trivial command that does not take any time to execute and does not alter any of the resources. In contrast, the generic program ecan be a wait call or a variable assignment or even a program which does a coin toss, so we can have different types of outcome. The outcome of the sequence between of skip and ewill be the outcome of the program e: (skip) (skip, s, m)⇓(s, m, 0) 26
As for the sequencing between two generic programs e1and e2we need to run the first program and then feed its outcome to the second one. In the end, the duration of this sequence will be the sum of the duration of both programs: (e1, s, m)⇓(s′, m′, d′) (e2, s′, m′)⇓(s′′, m′′, d′′) (seq) (e1;e2, s, m)⇓(s′′, m′′, d′+d′′) The following rule covers the wait call mechanism. It requires first to obtain the value of the term t, which can change the probabilistic resource mas explained before. Then we need to execute the program eand obtain its result as this will be used in the conclusion of the rule. Finally, the final duration will be equal to the sum between the time it took to run the program eand the value of the term t: JtK(s, m) = (a, m′) (e, s, m′)⇓(s′, m′′, d′) (wait) (wait tdo e, s, m)⇓(s′, m′′, a +d′) As for the if statement rules, they are divided into two, the case where the associated Boolean condition is true and the one where it is false. If the first case occurs the program which will be executed will be e1 and so the output of the conditional statement will be the output of this program. A similar case happens when the condition is false, but in this case it is e2that executes: JbK(s, m) = true (e1, s, m)⇓(s′, m′, d′) (if-true) (if bthen e1else e2, s, m)⇓(s′, m′, d′) JbK(s, m) = false (e2, s, m)⇓(s′, m′, d′) (if-false) (if bthen e1else e2, s, m)⇓(s′, m′, d′) As for the while loop rules, we can also verify the existence of two separate rules, one where the condition of the loop is true and so we need to perform one iteration of the program inside its body, and another where the condition is false and so the loop ends. In the first case the output of the program is the output of the program e, whilst in the latter the program does nothing to both the memory and the probabilistic resource and has a duration of zero: JbK(s, m) = true (e;while bdo e, s, m)⇓(s′, m′, d′) (wh-true) (while bdo e, s, m)⇓(s′, m′, d′) JbK(s, m) = false (wh-false) (while bdo e, s, m)⇓(s, m, 0) We will now present the second style of semantics, which is our redefinition of the semantics above, by discarding the RNG and returning not a single output but a distribution of outputs. In this setting it is often convenient to represent a distribution µ:A→[0,1] in algebraic form, µ(a1)·a1+· · · +µ(an)·an 27
JbK(s) = true (e;while bdo e, s, d)⇓∑n ipi·(ri, si, di) (wh-true) (while bdo e, s, d)⇓∑n ipi·(ri, si, di) JbK(s) = false (wh-false) (while bdo e, s, d)⇓1·(skip, s, d) 3.3 Denotational semantics After developing a suitable operational semantics for a language capable of handling both hybrid and probabilistic behaviour, we also developed a denotational semantics for the language. Although the specification of a denotational semantics was not necessary to implement this language (the operational semantics are enough to do it), we decided to go ahead and do it in order to create a mathematical foundation for the language. 3.3.1 Denotational semantics based on a random number generator Similarly to the operational semantics we also divided the denotational semantics in two cases: one in which we use a RNG and the other in which the outputs of a program are distributions and not singular values. Analogously to [25], we will use a function p7→ JpKwhich maps a program pto its interpretation JpK(also known as denotation). This function will be used to interpret every program construct, such as conditionals and while-loops, and the set of all resulting interpretations is the denotational semantics of our while-language. We start by describing the denotational semantics based on the RNG. In a nutshell, the semantics based on a RNG regards program denotations JpKas functions of the type Rn×{0,1}ω→W[M](Rn×{0,1}ω). In more detail, we use the generalised writer monad instantiated with the monoid-module of trajectories to produce and concatenate the trajectories that programs output. Then the inputs for these programs are pairs comprised of the values of all variables in the computation ( i.e. the internal memory) Rnand an infinite list of binary values {0,1}ω, which will be used to make random decisions ( i.e. it corresponds to the random number generator which will be used in coin tosses). Finally the programs output the same type of pair, corresponding to the new internal memory of the machine and the RNG. It is also important to mention that both denotational semantics assume that systems of differential equations in the language always have a unique solution ϕ:Rn×[0,∞)→Rn. Let us now analyse the semantics of each program construct. Regarding the program ”skip”, it 34
corresponds to just applying the unit function of the monad, because this program intuitively does nothing: Rn× {0,1}ω JskipK '' ηW[M] //W[M] (Rn× {0,1}ω) As for the sequence of two programs pand qwe start by first interpreting the first program and then interpreting the second one. Note that we need to use the multiplication function of the adopted monad to merge these two computations into one: Rn× {0,1}ω Jp;qK JpK//W[M] (Rn× {0,1}ω) W[M]JqK W[M] (Rn× {0,1}ω)W[M] (W[M] (Rn× {0,1}ω)) µW[M] oo In what regards assigments x:= t, we first need to interpret the term t. We do this via a function σof the type Rn× {0,1}ω→R× {0,1}ωwhich was already used in the previous operational semantics. Afterwards, a function update is used to change the value of the variable xaccording to the value provided by σ. To sum up, we have: Rn× {0,1}ω Jx:=tK ⟨π1,σ t⟩//Rn×R× {0,1}ω (update x)×id W[M] (Rn× {0,1}ω)Rn× {0,1}ω ηW[M] oo Next, in order to interpret conditionals we will need a function ψto interpret the Boolean terms associated to conditionals. Such a function is described in the following diagram: Rn× {0,1}ω ψ b )) S S S S S S S S S S S S S S S S S S S S S S S S S S S ⟨b,id⟩//B×(Rn× {0,1}ω) ∼ = Rn× {0,1}ω+Rn× {0,1}ω Then for the interpretation function of conditionals we have the diagram: Rn× {0,1}ω Jif bthen pelse qK** V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V ψ b //Rn× {0,1}ω+Rn× {0,1}ω [JpK,JqK] W[M] (Rn× {0,1}ω) 35
Finally we show to interpret differential statements x′ 1=t1, . . . , x′ n=tnfor t. As previously mentioned we can assume the existence of a unique solution ϕ:Rn×[0,∞)→Rn, and we also have the function σ:Rn× {0,1}ω→R× {0,1}ω. With these data is straightforward to build a function of the type Rn× {0,1}ω→⨿r∈[0,∞)(Rn)[0,r]× {0,1}ωwhich given an initial state sand probabilistic resource mreturns a trajectory corresponding to the solution of the system of differential equations with initial condition sand restricted to the duration specified by t(the probabilistic resource on the output corresponds to the consumption of mcaused by interpreting t). Let us denote this function as f. Now the denotation of the program x′ 1=t1, . . . , x′ n=tnfor tis simply the morphism composition, Rn× {0,1}ωf// Jx′ 1=t1,...,x′ n=tnfor tK ⨿r∈[0,∞)(Rn)[0,r]× {0,1}ω ∼ = W[M](Rn× {0,1}ω)⨿r∈[0,∞)(Rn)[0,r)×(Rn× {0,1}ω) i1 oo After defining the diagrams above we can summarise the denotational semantic rules in the following list of rules: JskipK=ηW[M] Jx:= tK=ηW[M]·((update x)×id)· hπ1, σ ti Jp;qK=µW[M]·W[M]JqK·JpK Jif bthen pelse qK= [JpK,JqK]·∼ =·hb, idi Jx′ 1=t1, . . . , x′ n=tnfor tK=i1·∼ =·f Listing 3.9: Summary of the random number generator denotational semantics Note that there is no interpretation for wait calls as they are a specific case of a system of differential equation where the derivative of every variable is equal to zero: x′ 1= 1, . . . , x′ n= 0 for t. Additionally there is also no interpretation of while loops. This is due to the complexity associated to their interpretation, which usually involves fixpoint constructs and is out of the scope of this dissertation. Keeping it brief, in this case we would need to prove for example that the monad used as the basis of this interpretation is an Elgot monad [22] as it was done in [23,25,24]. Because the specification of the denotational semantics is already an extra component beyond this dissertation, we leave the completion of the denotational semantics with the interpretation of while loops as a future research line. 36
3.3.2 Denotational semantics based on distributions Before moving on to the definition of the denotational semantics, we needed to define a new monad capable of handling distributions. This is done by combining the generalised writer monad with the distribution monad. In order to achieve this combination, we need to reference the concept of strong monads. This is because both monads in the case fit into this category. Strong monads differ from regular monads as they possess a new natural transformation, τ, called strength. This natural transformation allows the mapping of type A×TB to values of type T(A×B)[37,51]. Theorem 1. The following diagram shows a possible distributive law between a generic monad Tand the generalised writer monad W[M]: T X ×M+E λ τ+id //T(X×M) + E id +i2 T(X×M+E)T(X×M)+(X×M+E) [T i1,ηT] oo By observing the diagram above it is possible to observe that the following function is a distributive law between both monads, [T i1, ηT]·(id +i2)·(τ+id) = [T i1·τ, ηT·i2] Proof. The proof of this theorem can be observed in the appendix C.1. Now that we have a distributive law between these two monads, we can now replace the generic monad Twith the distribution monad (D) and create what we call the probabilistic generalised writer monad (DW[M], in which Mis a monoid-module). Analogous to the previous denotational semantics, we will use the interpretation function JpKbut this time we will drop the randomly generated infinite list and use the probabilistic version of the generalised writer monad mentioned above: Rn→DW [M](Rn). Like previously, the skip function does not do anything, so we will just use the unit of the monad DW [M]. Rn JskipK (( ηDW [M] //DW [M]Rn The sequence between two programs, pand q, is interpreted as a function which starts by interpreting the program p, followed by the program papplied to the resulting memory of variables. Finally, the µ function of the monad is used to merge the two computations. 37
Rn Jp;qK JpK//DW [M]Rn DW [M]JqK DW [M]RnDW[M] (DW [M]Rn) µDW [M] oo The assignment interpretation starts by interpreting the term tby using a similar function to the one present in the denotational semantics based on a RNG:σof type Rn→DR. Afterwards we also use the function update to alter the value of the variable xto be equal to the calculated value of term t. Rn Jx:=tK )) S S S S S S S S S S S S S S S S S S S S S S S S S S S S S ⟨σ t,id⟩//DR×Rn DηW[M]·D(update x)·τ DW [M] (Rn) Again the interpretation of if statements uses the function ψto obtain a coproduct between memories of variables, corresponding to the cases where the boolean value of the test bis either true or false: Rn ψ b (( R R R R R R R R R R R R R R R R R R R R R R R R R R R ⟨b,id⟩//B×Rn ∼ = Rn+Rn By using this function we can apply the interpretation of either the program por qto the coproduct which will result in a single monadic computation: Rn Jif bthen pelse qK)) R R R R R R R R R R R R R R R R R R R R R R R R R R R R ψ b //Rn+Rn [JpK,JqK] DW [M]Rn With respect to the interpretation of systems of differential equations, we again have the functions f and ϕ(similar to the ones defined in subsection 3.3.1), as well as the function σ(redefined above), which we can use to interpret the differential statements: 38
Rnf// Jx′ 1=t1,...,x′ n=tnfor tK D(⨿r∈[0,∞)(Rn)[0,r]) ∼ = DW [M]RnD(⨿r∈[0,∞)(Rn)[0,r)×(Rn)) D i1 oo The following set of rules reveal the denotational semantics for simulating hybrid programs: JskipK=ηDW [M] Jx:= tK=D ηW[M]·D(update x)·τhσ t, idi Jp;qK=µDW [M]·DW [M]JqK·JpK Jif bthen pelse qK= [JpK,JqK]·∼ =·hb, idi Jx:= ufor tK=D i1·∼ =·f Listing 3.10: Summary of the denotational semantics based on distributions As it happened in the previous semantics, the rules for the wait calls and while loops are also absent, for the exact same reasons. 39
Chapter 4 An interpreter for a probabilistic hybrid language In this chapter we present the main details of our interpreter for a probabilistic hybrid while-language. We start with a broad overview of the system’s architecture. We then discuss how the operational semantic rules – the core engine of the interpreter – were implemented. We give special focus to the most prominent rules namely sequential composition and those concerning differential statements. 4.1 Implementation architecture The implementation of our interpreter can be divided into three main components. The first one is the parser of the language: it takes a probabilistic hybrid program, written in the syntax previously described, and parses it into a Haskell structure. The interpreter then takes this structure and uses the operational semantics to evaluate the program. Finally the visualisation component draws the histograms and/or plots extracted from the data obtained from the evaluation. On the whole, this provides a flexible and automated ways of analysing the program at hand, with the obvious advantage of finding potential problems early in the game. Let us analyse these three components in more detail. The parser was implemented via the aforementioned parsec library [9]. It is at this stage that we find possible syntactic errors in the program and report them back to the user if they exist. The second component has the task of evaluating the parsed program. Recall that we defined two corresponding operational semantics in the previous chapter, one that uses a RNG and the other that returns probabilistic outputs. Both styles of semantics are implemented in our tool. However, when implementing them we decided to add another characteristic to the first semantics, which consists in performing real-time wait calls to the operating system when calculating systems of differential equations or wait commands. This allows the programmer to take into consideration the delays in the operating system if he wishes to do so. From now on we will name this form of evaluation as real-time execution (RTE). As for the second semantics, we implemented it as it is, so it does not perform real-time wait calls. 40
This second form of evaluation was named probabilistic execution (PRE). Thus the evaluator takes the parsed program and depending on the user choice, it can either evaluate with one semantics or the other. Because we are dealing with systems of ordinary differential equations (ODE) we used an Haskell library to solve them. This ODE solver [4] uses internally the GNU scientific library [3]. Finally the visualisation component receives the relevant data from the evaluator and creates either histograms or plots, depending on the user input, via the charts library [2]. Figure 3depicts these components and how they interact, as well as the inputs and outputs of each one. We have decided to name our interprer ProbLince as an homage to the tool Lince which also interprets hybrid programs but does not support probabilistic behaviour [25]. Figure 3: Implementation architecture 4.2 Parser As mentioned before we are using parsec to implement the parser for the language. Recall that this library allows to implement simple parsers, for example for deterministic or Boolean terms, and then combine them through a variety of combinators. These parsers will parse the input text and structure the data according to a pre-determined Haskell datatype. Let us take the parser of terms as an example. 41
First we defined an Haskell data type called “Term” which incorporates all the possible values we can face when parsing a term, such as the coin operator and the deterministic term. In relation to the syntax showed in the previous chapter, we took the liberty of adding new, convenient elements, like the normal and rand (see [18]) operators which correspond to normal and uniform distributions (note that both cases are continuous distributions), respectively. We also have arithmetic operations such as multiplication and subtraction. All possibilities of what a term can be are detailed in the following code fragment. data Term = DetTerm DTerm | COIN | RAND | NORMAL Term Term | NegateT Term | AddT Term Term | SubT Term Term | MultT Term Term | DivT Term Term deriving Show Listing 4.1: Term data type After defining this structure we implemented the respective parser allowing us to transform the input text into a value of this data type. The following code fragment shows the main function for parsing a term and how we dealt with the precedences of multiplication and division in relation to addition and subtraction. In order to do this we used the “chainl1” combinator, for which we already explained via an example, how it solves the problem of precedence. parseTerm :: Parsec String st Term parseTerm = chainl1 parseAritTerm op where op = try (spaces >> string "+" >> spaces >> return AddT) <|> try (spaces >> string "-" >> spaces >> return SubT) parseAritTerm :: Parsec String st Term parseAritTerm = chainl1 parseAritFactor op where op = try (spaces >> string "*" >> spaces >> return MultT) <|> try (spaces >> string "/" >> spaces >> return DivT) Listing 4.2: Term parser Let us now take a look at another part of our parsing system, namely the parser of programs. Similarly 42
to before, we defined a data type called “Instruction” which corresponds to the possible programs of our language, such as assignments and differential statements. The only change we did in relation to the syntax of the language was creating a declaration instruction, which is very similar to the assignment case. We did this in order to force the declaration of a variable before using it. data Instruction = SKIP | Decl String Term | Asg String Term | Seq Instruction Instruction | Cond Test (Instruction ,Instruction) | Wh Test Instruction | Wait Term Instruction | Diff DiffSystem Term deriving Show Listing 4.3: Data type correspondent to the possible programs of our language As for the parser itself we again had to handle precedence, this time connected to the sequence operator: the idea is to parse the program “p;q” into the construct “Seq P Q”, in which “P” and “Q” are the parsed versions of “p” and “q”, respectively. If we do not apply any type of precedence when parsing the sequence operator, then the programs “p” and “q” would be parsed independently and we could not apply the left associative Seq constructor to their results. Because of this we separated both the parser for the sequence operator, through the function “parseSeq”, and the other programs through the function “parseInstruction”. Notably, the latter uses the <|> combinator to define a choice between the different parsers for the different possible types of program; also try operator as a lookahead is needed because different programs may start with the same prefix. parseSeq :: Parsec String st Instruction parseSeq = (chainl1 (L.whiteSpace hybridLangLexer *> parseInstruction) op) where op = char ';' *> return Seq parseInstruction :: Parsec String st Instruction parseInstruction = try parseSkip <|> try parseDecl <|> try parseAsg <|> try parseCond <|> try parseWh <|> try parseWait <|> parseDiff 43
Chapter 5 Designing an embedded domain specific language In this chapter we discuss the implementation details of another tool we developed, which has the benefit of providing more expressive power to the programmer in comparison to the previous language. Specifically it corresponds to a DSL embedded in Haskell which allows the user to take advantage of all features of Haskell to write probabilistic hybrid programs – note that previously we were restricted to a while-language. This allows us to use many features present in Haskell ( e.g. folds or maps), which means we can write down hybrid programs in an entirely different manner. We will go over some of the new data types that were created specifically for this tool, as well as the available methods of program evaluation, and a set of combinators for combining different probabilistic hybrid computations. 5.1 Overview There are many DSLs available, such as [13,11], or even the previously mentioned Yampa language [28]. These can be divided into two types: they can be either shallowly or deeply embedded into another language. In the first type we have a translation of the program into an intermediate structure, which is then evaluated. The second type does not use this structure, which means the terms are directly evaluated by the language [21]. For our case we adopt the second type by deeply embedding our language into Haskell. The monads developed before are still a central part of our DSL, but with slight adjustments which we briefly explain next. We changed the mutable state of both monads to accommodate either probabilistic resources (in the case of evaluations based on random number generators) or the memory (in the case of evaluations based on probabilistic outputs). Obviously we had to adapt the functions exported in the monad modules to now use the resources or memory inside the mutable state. This is relevant for example when adding a new variable to the program. The resulting monad stacks are described in the following code block. 50
type RteM = StateT ((Int , Bool), Resources) (WriterT Trj (ExceptT RunException IO)) type PreM = StateT ((Int , Bool), Memory) (WriterT Trj (ExceptT RunException Prob)) Listing 5.1: The new monad stacks 5.2 Representing discrete events and main combinators A new data type we created for this DSL was the DEvent, which corresponds to possible discrete events. This data type has two constructors one referring to the wait call and another to a system of differential equations. data DEvent = Wait | DiffSystem [String] (Double -> [Double] -> [Double]) Listing 5.2: Discrete events data type There also function such as “preDEvent” and “rteDEvent” which receive one of these discrete events as input as as a certain duration, and produce a RTE or PRE monadic computation, essentially building the trajectory of the variables. These trajectories can either correspond to evaluations based on a random number generator (in the RTE case) or evaluations based on distributions (in the PRE case) over outputs. Next, now that we have these individual evaluations, we implemented a specific set of combinators to combine them. As an example we have the sequential and infinite combinators. The first is the counterpart of the sequence operator in the while-language: it receives two evaluations and composes them based on the continuation flag of the first evaluation. The second combinator uses the sequential combinator and a recursive call to itself to create an infinite sequence of evaluations. Obviously, the execution will stop once we reach the time instant we wish to evaluate (the sequential combinator performs this check). sequential :: RteM () -> RteM () -> RteM () sequential e1 e2 = do e1 continue <- stop if continue then e2 else return () 51
Listing 5.3: Sequential combinator In the same way we have combinators for evaluations, we also have combinators for discrete events. One of the more interesting ones is the interleaving combinator, which runs two events for small periods of time and checks a condition between each run. Once the condition is true an evaluation is triggered, as presented next in code. interleave :: DEvent -> DEvent -> Double -> RteM Bool -> RteM () -> RteM () interleave e1 e2 dur c e3 = do b <- c if bthen e3 else sequential (sequential (rteDEvent e2 dur) ( rteDEvent e1 dur)) (interleave e1 e2 dur c e3) Listing 5.4: Interleave combinator This combinator is particularly interesting to model the collision of particles or balls. For example in Figure 4it is possible to observe two trajectories, corresponding to two balls. The blue line corresponds to a ball which is dropped from a height of 800 m and the red line to another which is thrown from a height of 1000 m. By using the interleaving combinator their trajectories will be simulated for a few seconds and after that a check will be done in order to know if those two collide. If it happens then the collision effect will take place and if it does not then the simulation will keep on going. If we wanted we could combine this interleaving operation with the infinite combinator to continue with the simulation until hitting a certain duration or the ground. 52
Figure 4: Interleaving combinator test - ball collision There are some other combinators implemented, like the after combinator which performs a wait call for a certain duration passed as input followed by an evaluation, or the untilC combinator which performs an evaluation until a prescribed condition is met. Because our DSL is embedded into Haskell we can further extend the list of combinators by Haskell’s capabilities. As an example, we could create a combinator which receives a list of evaluations, and joins them all into one monadic computation by using Haskell’s foldl function and the sequential combinator. We do not pursue this further in the dissertation, because the implementation of the DSL itself is already out of its scope. 53
Chapter 6 Case studies In this chapter we explore our interpreter ProbLince via several case-studies. We start by presenting programs that model different distributions and compare them against the expected results. Afterwards, we implement more complex hybrid programs, starting the analysis of deterministic approaches and then adding a layer of uncertainty. We also analyse the role that uncertainty plays in these programs and how it may break some safety aspects of those systems. 6.1 Modelling some known distributions In this section we present the implementation of different probabilistic programs in our language and verify whether the output we observe is the one expected. 6.1.1 Uniform distribution The following program draws from a Bernoulli trial to determine how much time it should wait before updating variable “x”: var x := 0; wait coin() do { x := 2 } Listing 6.1: Simple coin toss program with wait call Since the coin operator value is obtained either by drawing a value from a randomly generated binary list or by sampling a value from a binary distribution, we expect to observe a uniform distribution when analysing how much time the program took to halt. More specifically, we expected to observe that in half of the cases the program lasts 0 seconds and 1 second in the other half. The following histogram provided 54
by ProbLince is the result of evaluating the program and performing 100 samples out of the resulting distribution: Figure 5: wait call for 100 runs By observing these results we see that the results are not completely uniform, which seems to go against what we intended. This is because we simulated the program for a low number of trials. The following histograms show two more evaluation of this program where we used 1000 and 10000 trials. Through the results below we can verify that the distribution gets closer and closer to the uniform distribution as we increase the amount of samples: 55
Figure 6: wait call for 1000 runs Figure 7: wait call for 10000 runs 6.1.2 Negative exponential distribution The next example we want to analyse was obtained from [18]. The objective of this example is to see how many coin tosses are needed to obtain the value 1: var x := 0; 56
var r := 0; while (x == 0) do { x := coin(); r := r + 1 } Listing 6.2: Program that flips a coin until the value is zero For each toss (cycle iteration) the probability of obtain the value 0 or 1 is 1 2. The probability of performing two coin flips is 1 2×1 2=1 4, so the probability of halting after nexecutions is 2−n[18]. The following histograms are the result of the execution of this program for 100, 500 and 1000 runs. In these, we can observe that they all generate a negative exponential distribution (as expected) and in the majority of cases the program does perform only two coin flips until obtaining the value 1. Similarly to the previous example, the distribution becomes clearer once we increase the number of executions: Figure 8: Negative exponential program execution result for 100 runs 57
Figure 9: Negative exponential program execution result for 500 runs Figure 10: Negative exponential program execution result for 1000 runs 6.1.3 Normal distribution One of the more interesting examples present in [18] is the random walk program. The program consists in a series of steps in a 2D grid where in each one of those we perform two coin tosses which decide the direction the next step is going to be. Before moving on to our implementation of the 2D random 58
walk we present a simpler version of the problem by considering only one dimension. Thus the program starts in the origin (xvariable equal to 0) and we throw a random coin which will determine if either we increment the value of xor decrement it (moving along the x axis). Another adaptation we had to perform to the example in [18] is the restriction in the number of steps we let the program do. This is because the program could be infinite, and by adding this constraint we guarantee that it will halt. var s := 1; var steps := 10; var x := coin(); if (x == 0) then {x := -1} else {skip}; var position := x; while (s < steps) do { x := coin(); if (x == 0) then {x := -1} else {skip}; position := position + x; s := s + 1 } Listing 6.3: 1D random walk implementation Now, if we evaluate this program we should verify that value of the position follows a normal distribution around the initial position (origin of the grid). The following figures show the results we obtained for 100, 500 and 1000 evaluations, respectively. 59
Figure 19: Probabilistic basic hybrid composition (Uniform distribution) 6.2.2 Bouncing Ball The next example corresponds to a ball that is launched from 10 m high with a velocity of 5 m/s. The ball is pulled down by the gravitational acceleration of the Earth (9.8 m/s2) until it hits the floor and bounces. In order to determine whether the ball has hit the floor, the condition in the while-loop below is checked every 0.01 seconds and while true the ball continues to fall with the aforementioned acceleration. The variable “c” makes the program stop after four bounces (this example is adapted from [5]). var v:= 5; var p:= 10; var c:= 0; while (c < 4) do { while (!(p < 0 && v < 0)) do {v'=-9.8,p'=v for 0.01}; v:=-0.5*v; c:=c+1 } Listing 6.8: Bouncing ball implementation The results we obtain (figure 20) are the exactly same as the ones shown in [5], which is an extra indicator of the correctness of our implementation. 66
Figure 20: Bouncing ball simulation After modelling this system, we again added probabilistic elements to it. For this case we took into account the fact that it is impossible to determine with exact precision the elasticity of the ball – which is reflected in a degree of uncertainty w.r.t. the dampening factor associated to hitting the ground. If we specify this factor as a normal distribution around the value of 0.5 we obtain the following program: var v:= 5; var p:= 10; var c:= 0; var factor := normal(0.5,0.02); while (c < 4) do { while (!(p < 0 && v < 0)) do {v'=-9.8,p'=1*v for 0.01}; v:=-factor*v; c:=c+1 } Listing 6.9: Probabilistic bouncing ball implementation The result we then obtain when sampling from the resulting distribution is very different from the original one. In some cases the ball does not bounce as high, which results in less time to performs the four bounces. In other cases, we see the exact opposite. 67
Figure 21: Probabilistic Bouncing ball evaluation 6.2.3 Cruise Control system The next example corresponds to a specific cruise control system. Its objective is to maintain the vehicle’s speed around a determined value (the example is adapted from [5]). var p:=0; var v:=2; while true do { if (v <10 || v == 10) then {p':=v,v':=5 for 1} else {p':=v,v':=-2 for 1} } Listing 6.10: Cruise control system The figure 22 shows the variations in the velocity of the vehicle and how it is kept around the chosen value. We also observe the progression of its movement by analysing the line in blue which indicates its positioning. 68
Figure 22: Cruise control system One could point out that the system is well implemented as it keeps the vehicle moving at a controlled pace with the velocity around a fixed value. However, one of the main issues with this type of system is that one cannot know with exact precision for how long the vehicle will accelerate or decelerate – some margins of error have to be considered, as mentioned before in this dissertation. We thus update the program to include some kind of error associated with how long we run the systems of differential equations, resulting in the following program: var p:=0; var v:=2; while true do { if (v < 10 || v == 10) then {p'=v,v'=5 for rand() + 1} else {p'=v,v'=-2 for rand() + 2} } Listing 6.11: Probabilistic cruise control system After evaluating this program and obtaining a few samples, we observed several possible trajectories that this vehicle could perform. 69
Figure 23: Probabilistic cruise control system If we look at the original program (figure 22) and corresponding trajectory we see that around the 5 second mark the position is around the value of 50. In the new probabilistic model (figure 23), we observe several trajectories where the value for the position is higher than 50 for the exact same time instant. This could indicate the existence of a problem with the system if we consider that 50 was the limit in terms of safety for the value of the position. For example, any value higher than that could entail that the vehicle would hit an obstacle or a car ahead of it. This safety concern becomes clearer in the next example where a program of another cruise control system was implemented. This time we have two different vehicles, a leader and a follower. The idea is that the latter should follow the former as close as possible but without crashing (the example is adapted from [5] and further details can be consulted there). var p:= 0; var v := 2; var pl:= 50; var vl := 10; while true do { if ((p + v + 2.5 < pl + 10) && (((v-5)*(v-5) + 4*(p + v + 2.5 - pl - 10)) < 0)) then {p'=v,v'=5,pl'=10 for 1} else {p'=v,v'=-2,pl'=10 for 1} } Listing 6.12: Adaptive cruise control 70
By evaluating the previous model we obtain the following result, which tells that indeed a close but safe distance is being kept. Figure 24: Adaptive cruise control system However, if we add a margin of error to the duration of acceleration and decelaration we obtain a very different result. var p:= 0; var v := 2; var pl:= 50; var vl := 10; while true do { if ((p + v + 2.5 < pl + 10) && (((v-5)*(v-5) + 4*(p + v + 2.5 - pl - 10)) < 0)) then {p'=v,v'=5,pl'=10 for rand() + 1} else {p'=v,v'=-2,pl:=10 for rand() + 2} } Listing 6.13: Probabilistic adaptive cruise control In fact the evaluation of the new program (figure 25) now provides possible trajectories in which the follower clearly hits the leader. The margins of error that were added might not be realistic but show how important it is to acknowledge their existence and the types of mistakes we can catch when we are able to include them in our programs. 71
Figure 25: Probabilistic adaptive cruise control Yet another change we could implement in our system is to use a smaller value for the acceleration. Updating the model with these adjustments and evaluating with the same margins of error produced a situation where all of the follower’s trajectories do not intersect the leader’s trajectory. var p:= 0; var v := 2; var pl:= 50; var vl := 10; while true do { if ((p + v + 2.5 < pl + 10) && (((v-5)*(v-5) + 4*(p + v + 2.5 - pl - 10)) < 0)) then {p'=0.65*v,v'=5,pl '=10 for rand() + 1} else {p'=0.65*v,v'=-2,pl'=10 for rand() + 2} } Listing 6.14: Probabilistic adaptive cruise control 72
Figure 26: Probabilistic adaptive cruise control with acceleration constraints 6.2.4 Landing System The following hybrid program describes a landing system of an spacecraft. In order to perform a soft landing the landing process was divided into three stages corresponding to strong, medium, and soft deceleration (the example is adapted from [5]). var y := 10000; var v := -1000; var a:= 0; var g:= 10; while (y > 1000 || y == 1000) do { if (v < -100 || v == -100) then a := (100 - g) else a:= -g; y' = 1*v, v' = 1*a for 1 }; while (y > 25 || y == 25) do { if (v < -20 || v == -20) then a := (20 - g) else a:= -g; y' = 1*v, v' = 1*a for 1 }; while (y > 1 || y == 1) do { if (v < -1 || v == -1) then a := (15 - g) else a:= -g; y' = 1*v, v' = 1*a for 1 } 73
Listing 6.15: Landing system The result we obtained for this system is the same as the one observed in [5], where the aircraft performs a smooth landing and reaches the ground around the 140 second mark. Figure 27: Landing System In the program above we are again ‘running’ the system of differential equations for an exact amount of time. But as pointed out previously, we cannot know with exact precision for how long they will actually run. So we can enhance our model to include margins of error, even if they are really small. By doing so we obtain the following: var y := 10000; var v := -1000; var a:= 0; var g:= 10; while (y > 1000 || y == 1000) do { if (v < -100 || v == -100) then a := (100 - g) else a:= -g; y' := v, v' := a for 1 + rand()*0.25 }; while (y > 25 || y == 25) do { if (v < -20 || v == -20) then a := (20 - g) else a:= -g; y' := v, v' := a for 1 + coin()*0.25 }; 74
while (y > 1 || y == 1) do { if (v < -1 || v == -1) then a := (15 - g) else a:= -g; y' := v, v' := a for 0.01 + rand() * 0.1 } Listing 6.16: Probabilistic landing system The result we get shows different trajectories, some of them revealing the possibility of the spacecraft landing much earlier than in the original model. This could become hazardous as the fall might be too fast for the crew to handle, or the materials of the aircraft might not be prepared for such an abrupt descent. Figure 28: Probabilistic Landing System 6.2.5 Thermostat Thermostats can also be written down as hybrid programs. These systems are present in many places ranging from rooms in regular houses to industrial freezers which keep large quantities of food or other materials with a constant temperature. So an error in the implementation of these devices can lead to a great loss in terms of materials and money [31]. We have decided to model a specific thermostat by analysing the thermostat system present in [31]. However, differently from our previous case-studies we used our DSL to implement the system. We used the DSL instead of the while-language to show its capabilities and also to illustrate how to use this tool when modelling hybrid systems. The following code block shows some of the constants which were used such as the initial temperature, 75
companies or the general population, we could have situations where no water was being distributed, which could lead to major problems. Figure 32: Probabilistic water tank 82
Chapter 7 Conclusions and future work In this dissertation we started by covering some of the core concepts of monads and discussed their connection to programming. We also saw some techniques to combine them, such as distributive laws and monad transformers. Then via some well-known examples, such as monadic interpreters, we observed that we can use individual monads to capture specific computational effects ( e.g. probabilistic behaviour) and subsequently combine them, through the aforementioned methods, to obtain a composite monad capable of handling all the effects at hand. We then moved to the notion of a hybrid system and verified the ample amount of examples they cover in today’s world. We gave a special emphasis to the ones classified as critical, where any type of failure may cause a catastrophe. That lead us to review some of the more well-known theories used to design and analyse hybrid systems rigorously. In this context, we also saw that hybrid effects can be captured by a monad, and briefly discussed the benefits of studying hybrid systems from a monadic view – among other things, we gave particular emphasis to the benefit of studying hybrid computation combined with other effects under the lenses of monad composition. We then initiated the process of specifying and implementing a while-language capable of handling both probabilistic and hybrid behaviours. We began by reviewing the syntax and operational semantics of a language which deals with wait calls only and probabilistic choice (using a random number generator). Subsequently we devised two operational semantics for probabilistic and full hybrid behaviour ( i.e. not just wait calls). We also created two complementary denotational semantics, revolving around two different monads, to provide a mathematical foundation to the language. Afterwards we presented our interpreter of a probabilistic hybrid while-language, whose core engine consists of the two aforementioned operational semantics for probabilistic and full hybrid behaviour. Recall as well that both semantics were implemented by recurring to monads and monad transformers in Haskell, which had the benefit of providing a high level of modularity to our implementation. We also created a visualisation module which allowed to produce histograms and/or trajectories so one can properly analyse 83
the behaviour of hybrid programs. All in all, this tool facilitates the design and analysis of hybrid programs, promoting an early testing of ideas and concepts and thus giving indications that the software being developed will behave as expected. Not only this, we also devised an embedded DSL which in essence offers a more expressive language to the hybrid programmer – with all features present in Haskell and with a palette of combinators created specifically for the hybrid paradigm. Finally, we used both probLince and the DSL to design and analyse different hybrid programs. First we evaluated deterministic versions of these programs from which we could verify totally safe trajectories. We then introduced uncertainty to these models, usually associated with the amount of time the differential system ‘runs’ for, and checked whether or not the results presented differences when compared to the original versions. In the majority of cases we found that just a little amount of uncertainty would result in vastly different outcomes, with many safety related concerns. A prime example is the adaptive cruise controller: the deterministic version showed no collisions between two vehicles, but the addition of subtle probabilistic elements introduced possibilities of collision. We thus conclude that uncertainty plays a big part in how hybrid systems should be designed and implemented, as it can quickly lead to undesired outcomes, not always easy to observe. Furthermore, the existence of hybrid modelling tools such as probLince becomes increasingly important as they allow us to be more certain about the design of hybrid systems, which will continue to be more and more present in our daily lives. After the recap of what was achieved in this dissertation and the conclusions we obtained, we list some ideas to be explored in the future: • We intend to complete our denotational semantics by adding a definition of the interpretation of while loops. A possible way of doing this is to prove that the generalised writer monad combined with the distribution monad is Elgot. • Another interesting line of future work is to add new functionalities to the operational semantics, such as the ability to catch and handle exceptions. This would allow us to handle problematic operations, such as division by 0, in a consistent manner. • It would also be interesting to explore the addition of new probabilistic elements. As an example, both the sample and score functions could be implemented as they are central in many probabilistic languages. This would provide new ways of writing down probabilistic hybrid programs, allowing us to specify more complex systems. 84
• Soundness and adequacy are very well-known properties that connect denotational and operational semantics [23,25]. In a nutshell, these properties entail that both styles of semantics agree with each other. It would therefore be useful to establish these properties for the operational and denotational semantics that we devised. • Finally our tool allows to evaluate hybrid programs in a multitude of scenarios but only a finite amount of them. To be able to cover all scenarios, and thus achieve full verification of a hybrid program, we would need to use for example logical machinery as it happens in [10]. It would therefore be very useful to add some form of logical machinery to probLince so that we have a way of fully verifying hybrid programs. It would be particularly interesting to specify logical formulas with temporal elements, allowing us to ask questions like: “Is there a moment where the vehicle stops after 50 meters?”. 85
Bibliography [1] Cabal. URL https://cabal.readthedocs.io/en/3.4/index.html. [Online] Last accessed on 2023-07-20. [2] Chart. URL https://hackage.haskell.org/package/Chart. [Online] Last accessed on 2023-01-14. [3] Ordinary Differential Equations — GSL 2.7 documentation. URL https://www.gnu.org/ software/gsl/doc/html/ode-initval.html. [Online] Last accessed on 2023-07-31. [4] hmatrix-gsl. URL //hackage.haskell.org/package/hmatrix-gsl. [Online] Last accessed on 2023-08-5. [5] lince. URL http://arcatools.org/assets/lince.html#fulllince. [Online] Last accessed on 2023-07-20. [6] Data map. URL https://hackage.haskell.org/package/containers-0.4.0.0/ docs/Data-Map.html. [Online] Last accessed on 2023-08-08. [7] monad-bayes, . URL https://hackage.haskell.org/package/monad-bayes. [Online] Last accessed on 2023-07-31. [8] Control.Monad.Random.Lazy, . URL https://hackage.haskell.org/package/ MonadRandom-0.5.3/docs/Control-Monad-Random-Lazy.html. [Online] Last accessed on 2023-01-14. [9] parsec. URL https://hackage.haskell.org/package/parsec. [Online] Last acessed 2023-01-14. [10] Uppaal. URL https://uppaal.org/. [Online] Last accessed on 2023-07-31. 86
[11] Lennart Augustsson, Howard Mansell, and Ganesh Sittampalam. Paradise: a two-stage DSL embedded in Haskell. In Proceedings of the 13th ACM SIGPLAN international conference on Functional programming , ICFP ’08, pages 225–228, New York, NY, USA, September 2008. Association for Computing Machinery. ISBN 978-1-59593-919-7. doi: 10.1145/1411204.1411236. URL https://dl.acm.org/doi/10.1145/1411204.1411236. [12] Marcello M. Bonsangue, Helle Hvid Hansen, Alexander Kurz, and Jurriaan Rot. Presenting Distributive Laws. Logical Methods in Computer Science , Volume 11, Issue 3, August 2015. doi: 10.2168/LMCS-11(3:2)2015. URL https://lmcs.episciences.org/1578. Online version: https://arxiv.org/abs/1503.02447. [13] Marco Devesas Campos and L. S. Barbosa. Implementation of an Orchestration Language as a Haskell Domain Specific Language. Electronic Notes in Theoretical Computer Science , 255:45–64, November 2009. ISSN 1571-0661. doi: 10.1016/j.entcs.2009.10.024. URL https://www. sciencedirect.com/science/article/pii/S1571066109004447. [14] Antony Courtney, Henrik Nilsson, and John Peterson. The yampa arcade. In Proceedings of the 2003 ACM SIGPLAN Workshop on Haskell , Haskell ’03, page 7–18, New York, NY, USA, 2003. Association for Computing Machinery. ISBN 1581137583. doi: 10.1145/871895.871897. URL https://doi.org/10.1145/871895.871897. [15] P.J.L. Cuijpers and M.A. Reniers. Hybrid process algebra. The Journal of Logic and Algebraic Programming , 62(2):191–245, 2005. ISSN 1567-8326. doi: https://doi.org/10.1016/ j.jlap.2004.02.001. URL https://www.sciencedirect.com/science/article/pii/ S1567832604000232. [16] Fredrik Dahlqvist and Renato Neves. Compositional semantics for new paradigms: probabilistic, hybrid and beyond, April 2018. URL http://arxiv.org/abs/1804.04145. arXiv:1804.04145 [cs]. [17] Fredrik Dahlqvist, Louis Parlant, and Alexandra Silva. Layer by layer – combining monads. In Bernd Fischer and Tarmo Uustalu, editors, Theoretical Aspects of Computing – ICTAC 2018 , pages 153– 172, Cham, 2018. Springer International Publishing. ISBN 978-3-030-02508-3. Online version: https://arxiv.org/abs/1712.01113. [18] Fredrik Dahlqvist, Alexandra Silva, and Dexter Kozen. Semantics of Probabilistic Programming: A Gentle Introduction. In Gilles Barthe, Joost-Pieter Katoen, and Alexandra 87
Silva, editors, Foundations of Probabilistic Programming , pages 1–42. Cambridge University Press, 1 edition, December 2020. ISBN 978-1-108-77075-0 978-1-108-48851-8. doi: 10.1017/9781108770750.002. URL https://www.cambridge.org/core/product/ identifier/9781108770750%23c1/type/book_part. [19] EW Dijkstra. Notes on structured programming . 1970. [20] Martin Erwig and Steve Kollmansberger. Kollmansberger, S.: Functional pearls: Probabilistic functional programming in Haskell. J. Funct. Program. 16(1), 21-34. J. Funct. Program. , 16:21–34, January 2006. doi: 10.1017/S0956796805005721. [21] Jeremy Gibbons and Nicolas Wu. Folding domain-specific languages: deep and shallow embeddings (functional Pearl). In Proceedings of the 19th ACM SIGPLAN international conference on Functional programming , pages 339–347, Gothenburg Sweden, August 2014. ACM. ISBN 978-1-4503-2873- 9. doi: 10.1145/2628136.2628138. URL https://dl.acm.org/doi/10.1145/2628136. 2628138. [22] Sergey Goncharov. Uniform elgot iteration in foundations. Schloss Dagstuhl - Leibniz-Zentrum für Informatik, 2021. doi: 10.4230/LIPICS.ICALP.2021.131. URL https://drops.dagstuhl. de/opus/volltexte/2021/14200/. Online version: https://arxiv.org/abs/2102.11828. [23] Sergey Goncharov and Renato Neves. An adequate while-language for hybrid computation. In Proceedings of the 21st International Symposium on Principles and Practice of Declarative Programming , PPDP ’19, New York, NY, USA, 2019. Association for Computing Machinery. ISBN 9781450372497. doi: 10.1145/3354166.3354176. URL https://doi.org/10.1145/3354166.3354176. Online version: https://arxiv.org/abs/1902.07684. [24] Sergey Goncharov, Julian Jakob, and Renato Neves. A semantics for hybrid iteration. 2018. doi: 10.4230/LIPICS.CONCUR.2018.22. URL http://drops.dagstuhl.de/opus/volltexte/ 2018/9560/. Online version: https://arxiv.org/abs/1807.01053. [25] Sergey Goncharov, Renato Neves, and José Proença. Implementing hybrid semantics: From functional to imperative. In Violet Ka I. Pun, Volker Stolz, and Adenilso Simao, editors, Theoretical Aspects of Computing – ICTAC 2020 , pages 262–282, Cham, 2020. Springer International Publishing. ISBN 978-3-030-64276-1. Online version: https://arxiv.org/abs/2009.14322. 88
[26] Noah D. Goodman, Vikash K. Mansinghka, Daniel Roy, Keith Bonawitz, and Joshua B. Tenenbaum. Church: A language for generative models. In Proceedings of the Twenty-Fourth Conference on Uncertainty in Artificial Intelligence , UAI’08, page 220–229, Arlington, Virginia, USA, 2008. AUAI Press. ISBN 0974903949. Online version: https://arxiv.org/abs/1206.3255. [27] T.A. Henzinger. The theory of hybrid automata. In Proceedings 11th Annual IEEE Symposium on Logic in Computer Science , pages 278–292, July 1996. doi: 10.1109/LICS.1996.561342. ISSN: 1043-6871. [28] Paul Hudak, Antony Courtney, Henrik Nilsson, and John Peterson. Arrows, Robots, and Functional Reactive Programming . Springer Berlin Heidelberg, Berlin, Heidelberg, 2003. ISBN 978- 3-540-44833-4. doi: 10.1007/978-3-540-44833-4_6. URL https://doi.org/10.1007/ 978-3-540-44833-4_6. [29] Peter Höfner and Bernhard Möller. An algebra of hybrid systems. The Journal of Logic and Algebraic Programming , 78(2):74–97, January 2009. ISSN 1567-8326. doi: 10.1016/ j.jlap.2008.08.005. URL https://www.sciencedirect.com/science/article/pii/ S1567832608000799. [30] Stamatis Karnouskos. Cyber-Physical Systems in the SmartGrid. In 2011 9th IEEE International Conference on Industrial Informatics , pages 20–23, Lisbon, Portugal, July 2011. IEEE. ISBN 978- 1-4577-0435-2. doi: 10.1109/INDIN.2011.6034829. URL http://ieeexplore.ieee.org/ document/6034829/. [31] Tomas Krilavičius. Bestiarium of Hybrid Systems. January 2005. [32] J. E. Labra Gayo, J. M. Cueva Lovelle, M. C. Luengo Díez, and A. Cernuda del Río. Specification of Logic Programming Languages from Reusable Semantic Building Blocks. Electronic Notes in Theoretical Computer Science , 64:220–233, September 2002. ISSN 1571-0661. doi: 10.1016/ S1571-0661(04)80352-9. URL https://www.sciencedirect.com/science/article/ pii/S1571066104803529. [33] Daan Leijen and Erik Meijer. Parsec: A practical parser library. Electronic Notes in Theoretical Computer Science , 41(1):1–20, 2001. [34] Sheng Liang, Paul Hudak, and Mark Jones. Monad transformers and modular interpreters. In Proceedings of the 22nd ACM SIGPLAN-SIGACT symposium on Principles of programming lan- 89
guages , POPL ’95, pages 333–343, New York, NY, USA, January 1995. Association for Computing Machinery. ISBN 978-0-89791-692-9. doi: 10.1145/199448.199528. URL https: //doi.org/10.1145/199448.199528. [35] Christoph Lüth and Neil Ghani. Composing monads using coproducts. ACM SIGPLAN Notices , 37 (9):133–144, September 2002. ISSN 0362-1340. doi: 10.1145/583852.581492. URL https: //dl.acm.org/doi/10.1145/583852.581492. [36] Eugenio Moggi. Computational lambda-calculus and monads. In [1989] Proceedings. Fourth Annual Symposium on Logic in Computer Science , pages 14–23, June 1989. doi: 10.1109/LICS.1989. 39155. [37] Eugenio Moggi. Notions of computation and monads. Information and Computation , 93(1):55–92, 1991. ISSN 0890-5401. doi: https://doi.org/10.1016/0890-5401(91)90052-4. URL https:// www.sciencedirect.com/science/article/pii/0890540191900524. Selections from 1989 IEEE Symposium on Logic in Computer Science. [38] Renato Neves. Hybrid programs . PhD thesis, Minho University, 2018. [39] José Nuno Oliveira. Program design by calculation. Draft of textbook in preparation , 2018. [40] Hugo Paquet and Sam Staton. LazyPPL: laziness and types in non-parametric probabilistic programs. In Advances in Programming Languages and Neurosymbolic Systems Workshop , 2021. URL https: //openreview.net/forum?id=yHox9OyegeX. [41] Daniela Petrişan and Ralph Sarkis. Semialgebras and Weak Distributive Laws. Electronic Proceedings in Theoretical Computer Science , 351:218–241, December 2021. ISSN 2075-2180. doi: 10.4204/ EPTCS.351.14. URL http://arxiv.org/abs/2106.13489v3. [42] Benjamin C Pierce. Basic category theory for computer scientists . MIT press, 1991. ISBN 9780262660716. [43] Maciej Piróg and Sam Staton. Backtracking with cut via a distributive law and left-zero monoids. Journal of Functional Programming , 27:e17, 2017. ISSN 0956-7968, 1469-7653. doi: 10.1017/S0956796817000077. URL https://www.cambridge.org/core/product/ identifier/S0956796817000077/type/journal_article. 90
[44] André Platzer. Logical Analysis of Hybrid Systems: Proving Theorems for Complex Dynamics . Springer, Heidelberg, 2010. ISBN 978-3-642-14508-7. [45] André Platzer. Logical foundations of cyber-physical systems , volume 662. Springer, 2018. ISBN 978-3-319-63587-3. doi: https://doi.org/10.1007/978-3-319-63588-0. [46] André Platzer. Differential Dynamic Logic for Hybrid Systems. Journal of Automated Reasoning , 41 (2):143–189, August 2008. ISSN 1573-0670. doi: 10.1007/s10817-008-9103-8. URL https: //doi.org/10.1007/s10817-008-9103-8. [47] Jianhua Shi, Jiafu Wan, Hehua Yan, and Hui Suo. A survey of Cyber-Physical Systems. In 2011 International Conference on Wireless Communications and Signal Processing (WCSP) , pages 1–6, Nanjing, China, November 2011. IEEE. ISBN 978-1-4577-1010-0 978-1-4577-1009-4 978-1-4577- 1007-0 978-1-4577-1008-7. doi: 10.1109/WCSP.2011.6096958. URL http://ieeexplore. ieee.org/document/6096958/. [48] Juliana Souza and Renato Neves. Personal Communication, 2022. [49] Guy L. Steele. Building interpreters by composing monads. In Proceedings of the 21st ACM SIGPLANSIGACT symposium on Principles of programming languages , POPL ’94, pages 472–492, New York, NY, USA, February 1994. Association for Computing Machinery. ISBN 978-0-89791-636-3. doi: 10.1145/174675.178068. URL https://doi.org/10.1145/174675.178068. [50] David Tolpin, Jan Willem van de Meent, Hongseok Yang, and Frank Wood. Design and implementation of probabilistic programming language anglican. arXiv preprint arXiv:1608.05263 , 2016. [51] Philip Wadler. Comprehending monads. In Proceedings of the 1990 ACM conference on LISP and functional programming , LFP ’90, pages 61–78, New York, NY, USA, May 1990. Association for Computing Machinery. ISBN 978-0-89791-368-3. doi: 10.1145/91556.91592. URL https: //doi.org/10.1145/91556.91592. [52] Philip Wadler. The essence of functional programming. In Proceedings of the 19th ACM SIGPLANSIGACT symposium on Principles of programming languages , POPL ’92, pages 1–14, New York, NY, USA, February 1992. Association for Computing Machinery. ISBN 978-0-89791-453-6. doi: 10.1145/143165.143169. URL https://doi.org/10.1145/143165.143169. [53] Glynn Winskel. The formal semantics of programming languages: an introduction . MIT press, 1993. ISBN 9780262731034. 91
Figure 33: ProbLince command test B.2 Domain specific language The DSL is specified as a Haskell library, which allows it to be used by other projects. First clone the repository and then move the folder probLince-DSL to the desired location ( e.g. local dependency folder of another cabal project). To make the package available to the .cabal file, we first need to update the cabal.project file. If no file exists, one should be created. Then add the following line: packages: {path to the folder}/probLinceDSL.cabal ./*.cabal Next change the build-depends section of the cabal file to include the library: build -depends: base ^ >=4.16.4.0, probLinceDSL By doing these steps, we can now import the library inside a Haskell project and use its features. To know more details about the usage of cabal to create an Haskell project visit the documentation in [1]. 98
Appendix C Proofs C.1 Proof of theorem 1 Proof. In order to prove that the following function is indeed a distributive law between a generic monad Tand the generalised writer monad, we need to prove that the four diagrams commute: λ= [T i1·τ, ηT·i2] We will start by proving that the following equation holds: [T i1·τ, ηT·i2]·W[M]ηT=ηT. By developing the left side of the equation we obtain, [Ti1·τ, ηT·i2] ·W[M]ηT ={ definition of W[M]} [Ti1·tau, ηT·i2] ·(ηT×id +id) ={ coproduct laws } [Ti1·τ·(ηT×id), ηT·i2] ={ strong monad laws } [Ti1·ηT, ηT·i2] ={ naturality of η} [η·i1, ηT·i2] ={[f·g, f ·k] = f·[g, k]and [i1, i2] = id } ηT Which matches the right side of the equation. Thus the diagram commutes and we can move on to the next equation: [T i1·τ, ηT·i2]·ηW[M] T=T ηW[M]. Again, starting with the left-hand side of the equation we get, [Ti1·τ, ηT·i2]·ηW[M] ={ def. ηW[M]} [Ti1·τ, ηT·i2]·i1· hid, ii ={ coproduct laws } Ti1·τ· hid, ii ={ strong functor laws } Ti1·Thid, ii 99
={T f ·T g =T(f·g)} TηW[M] It is possible to observe that we also obtain the same value as the one in the right side of the equation. So this diagram also commutes, which takes us to the third proof: λ·W[M]µT=µT W[M]·Tλ ·λT. λ·W[M]µT ={ def. λ, def. W[M]} [Ti1·τ, η ·i2]·((µT×id) + id) ={ coproduct laws } [Ti1·τ·(µT×id), ηT·i2] ={ strong monad laws } [Ti1·µT·T τ ·τ, ηT·i2] ={ naturality of µT} [µT·TT i1·Tτ ·τ, ηT·i2] ={ monad laws } [µT·TT i1·Tτ ·τ, µT·T ηT·ηT·i2] ={coproduct laws} µT·[TT i1·Tτ ·τ, T ηT·ηT·i2] ={ naturality of η} µT·[TT i1·Tτ ·τ, T ηT·T i2·ηT] ={ absorption + } µT·[TT i1·Tτ, T ηT·T i2]·(τ+ηT) ={ coproduct and functorial laws } µT·T[Ti1·τ, η ·i2]·[Ti1·τ, T i2·ηT] ={ naturality of η} µT·T[Ti1·τ, η ·i2]·[Ti1·τ, ηT·i2] ={λdefinition } µT·Tλ ·λ This ends the proof as both sides of the equation match, which means the diagram commutes. Lastly, we need to verify if the equation λ·µW[M] T=TµW[M]·λW[M]·WDEλholds. So, by developing the left side of the equation we obtain: Tµ ·λ·W[M]λ ={def. λ, fusion-+, def functor W[M]} [Tµ ·T i1·τ, T µ ·η·i2]·(λ×id +id) ={absorption + } [Tµ ·T i1·τ·(λ×id), Tµ ·η·i2] ={def µ, natural-η} [T[((id ×(·)) ·assocr +▷)·distl, i2]·T i1·τ·(λ×id), Tµ ·T i2·η] 100
={Functor laws, coproduct cancellation } [T(((id ×(·)) ·assocr +▷)·distl)·τ·(λ×id), T µ ·Ti2·η] ={def µ, functor laws, coproduct cancellation } [T(((id ×(·)) ·assocr +▷)·distl)·τ·(λ×id), T i2·η] ={ strong functor laws, natural-η} [T(((id ×(·)) ·assocr +▷)·distl)·T undistl ·[Ti1·τ, T i2·η]·(τ×id +id)·distl, η ·i2] ={ Functor laws, distl ·undistl =id} [T((id ×(·)) ·assocr +▷)·[Ti1·τ, T i2·η]·(τ×id +id)·distl, η ·i2] ={ Fusion + } [[T((id ×(·)) ·assocr +▷)·Ti1·τ, T ((id ×(·)) ·assocr +▷)·Ti2·η]·(τ×id +id)·distl, η ·i2] ={ Absorption + } [[T((id ×(·)) ·assocr +▷)·Ti1·τ·(τ×id), T ((id ×(·)) ·assocr +▷)·Ti2·η]·distl, η ·i2] ={ Strong functor laws } [[Ti1·τ·((id ×(·)) ·assocr), T ((id ×(·)) ·assocr +▷)·Ti2·η]·distl, η ·i2] ={ Functor laws, Natural-i2} [[Ti1·τ·((id ×(·)) ·assocr), T (i2·▷)·η]·distl, η ·i2] ={ Natural-η} [[Ti1·τ·((id ×(·)) ·assocr), η ·i2·▷]·distl, η ·i2] ={ Absorption + } [[Ti1·τ, η ·i2]·((id ×(·)) ·assocr +▷)·distl, η ·i2] ={λdef } [λ·((id ×(·)) ·assocr +▷)·distl, λ ·i2] ={ Fusion + } λ·[((id ×(·)) ·assocr +▷)·distl, i2] ={ def µ} λ·µ This allows us to verify that the last equation also holds and so the last diagram also commutes, ending the proof of the theorem.