How to generate a Buchi Automaton from a LTL formula? - model-checking

How can I generate a Buchi Automaton starting from an LTL formula?
e.g.
[] (a <-> ! b)
That is,
At all times in the future
if a is true b is false
if b is true a is false

One option is to use gltl2ba, which is based on ltl2ba.
LTL Formulas
An LTL formula may contain propositional symbols, boolean operators,
temporal operators, and parentheses.
Propositonal Symbols:
true, false
any lowercase string
Boolean operators:
! (negation)
-> (implication)
<-> (equivalence)
&& (and)
|| (or)
Temporal operators:
G (always) (Spin syntax : [])
F (eventually) (Spin syntax : <>)
U (until)
R (realease) (Spin syntax : V)
X (next)
Use spaces between any symbols.
(source: ltl2ba webpage)
Example: generate a Buchi Automaton from the next LTL formula:
[](a <-> ! b)
This reads: it is always true that a if and only if !b (and viceversa). That is, this is the formula you want to encode.
The following command generates the never claim associated with the LTL formula, and also the Buchi Automaton (option -g).
~$ ./gltl2ba -f "[](a <-> ! b)" -g
never { /* [](a <-> ! b) */
accept_init:
if
:: (!b && a) || (b && !a) -> goto accept_init
fi;
}
More examples are available here.

Related

Partial Function Application in Concatenative Programming Languages

Say I have a haskell function f n l = filter (n<) l where it takes an integer n and list l and returns all of the integers in l greater then n.
I'm trying to figure out how to best write this function in a language like Joy. I've generally had good luck with converting the haskell function to pointfree form f = filter . (<) and then trying to rewrite it in Joy from there. But I can't figure out how to simulate partial function application in a concatenative language.
So far, I've tried to do something like swap [[>] dip] filter, but it seems like there must be a better/cleaner way to write this.
Also, I'm experimenting with writing my own concatenative language and was wondering if lazy-evaluation could be compatible with concatenative languages.
swap [[>] dip] filter won’t work because it assumes n is accessible for each call to the quotation by which you’re filtering; that implies filter can’t leave any intermediate values on the stack while it’s operating, and > doesn’t consume n. You need to capture the value of n in that quotation.
First “eta”-reduce the list parameter:
l n f = l [ n > ] filter
n f = [ n > ] filter
Then capture n by explicitly quoting it and composing it with >:
n f = n quote [ > ] compose filter
(Assuming quote : a -> (-> a) a.k.a. unit, takes a value and wraps it in a quotation and compose : (A -> B) (B -> C) -> (A -> C) a.k.a. cat, concatenates two quotations.)
Then just “eta”-reduce n:
f = quote [ > ] compose filter
I put “eta” in scare quotes because it’s a little more general than in lambda calculus, working for any number of values on the stack, not just one.
You can of course factor out partial application into its own definition, e.g. the papply combinator in Cat, which is already defined as swons (swap cons) in Joy, but can also be defined like so:
DEFINE
papply (* x [F] -- [x F] *)
== [unit] dip concat ;
f (* xs n -- xs[>=n] *)
== [>] papply filter .
In Kitten this could be written in a few different ways, according to preference:
// Point-free
function \> compose filter
// Local variable and postfix
-> n; { n (>) } filter
// Local variable and operator section
-> n; \(n <) filter
Any evaluation strategy compatible with functional programming is also compatible with concatenative programming—popr is a lazy concatenative language.

Custom Eq Instance for Data Type

I'm having some issues getting to create my own Eq instance for my data type.
This is my code:
data Doc = Empty -- Adds ""
| Text String
| NewLine -- Adds "\n"
| Concat Doc Doc -- Joins two Doc's
instance (Eq Doc) => Eq (Doc) where
Concat a1 b1 == Concat a2 b2 = True
_ == _ = False
My objective is that it only returns True when the final Doc is the same, for example:
*Main> Concat (Concat (Text "The ") (Text "birds"))(Concat Empty NewLine) == Concat Empty (Text "The birds\n")
This should be True and with the code I have it does return True, but it's returning True every single time, even if I have totally different sentences.
I've been battling around with this for a while and searched around but came up with nothing. Any of you guys have any idea or suggestion as to what I'm doing wrong here?
Thanks in advance!
There are two questions here, so let's take them in turn.
What's wrong with my definition?
You define any two Concat documents as equal, regardless of what they contain. You also define any other values as inequal, regardless of what they contain. This means that, for instance,
Concat (Text "foo") Newline == Concat (Text "bar") Newline
gives True, while
Text "foo" == Text "foo"
gives False.
Let's write a definition for structural equality instead: two Docs are equal if they have the same structure:
instance Eq Doc where
-- Concats are equal if the things they are concat-ing are equal
Concat a b == Concat a' b' = a == a' && b == b'
-- Newlines are always equal
NewLine = NewLine = True
-- Two texts are equal if the text they contain is equal
Text a = Text a' = a == a'
-- Everything else is inequal
_ = _ = False
How can I write an Eq instance that doesn't care about structure, only whether the generated documents are the same?
If we want to compare the generated documents, we can do just that:
instance Eq Doc where
doc == doc' = generate doc == generate doc'
assuming that generate :: Doc -> String does what it says. We can also use on from Data.Function to write this as
(==) == (==) `on` generate
As William mentions in the comments, this "does not satisfy the equality constraints". However, there is precedent for this: the diagrams package considers two diagrams to be equivalent if they generate the same instructions for drawing a diagram. The reasoning behind this is explored in the paper introducing Diagrams:
The particularly attentive reader may have noticed something
strange about this Semigroup instance: (<>) is not associative!
d1 <> (d2 <> d3) and (d1 <> d2) <> d3 are not equal, since they result
in trees of two different shapes. However, intuitively it seems that
d1 <> (d2 <> d3) and (d1 <> d2) <> d3 are still “morally” the same, that is,
they are two representations of “the same” diagram. We can formalize
this idea by considering Diagram as a quotient type, using some
equivalence relation other than structural equality. In particular, associativity
does hold if we consider two diagrams d1 and d2 equivalent
whenever unD d1 ≡ unD d2, where unD::Diagram → [Prim]
“compiles” a Diagram into a flat list of primitives.
According to your code, any Concat will be equal to another Concat. Let's try to check the equality by hand:
Concat NewLine (Text "Huh") == Concat (Text "Example") (Text "Concat")
= True -- inserted definition of `==`
We never look at the elements of your Concat. But at some point we have to check that Newline == Text "Example" and return False. An important hint is that you never inspect a1, b1 and so on. As soon as we try to use them, the instance comes naturally:
instance Eq Doc where
Concat a1 b1 == Concat a2 b2 = a1 == a2 && b1 == b2
Text ... == ... = -- left as exercise
Newline ... == ... = -- left as exercise
_ == _ = False

Is there an xor (exclusive or) infix operator in TLA+?

Does TLA+ have an xor operator defined as part of the language itself, or do I have to define my own?
Under the assumption that A \in BOOLEAN /\ B \in BOOLEAN, what is known in propositional logic as "XOR" is inequality:
A # B
which under the same assumption is equivalent to ~ (A <=> B). When A, B take non-Boolean values, these two formulas are not necessarily equivalent. The following axiom could describe the operator <=>
THEOREM
ASSUME
/\ A \in BOOLEAN
/\ B \in BOOLEAN
PROVE
(A <=> B) = (A = B)
For non-Boolean values of A and B, the value of A <=> B is not specified.
In the moderate interpretation of Boolean operators it is unspecified whether A <=> B takes non-Boolean values for non-Boolean A or B.
In the liberal interpretation of Boolean operators, \A A, B: (A <=> B) \in BOOLEAN, as described in the TLA Version 2: A Preliminary Guide.
See also page 10 (which defines the Boolean operators for Boolean values of the arguments) and Sec. 16.1.3 of the TLA+ book. The formula
(A \/ B) /\ ~ (A /\ B)
is meaningful also for non-Boolean values of the identifiers A and B (TLA+ is untyped). So
(15 \/ "a") /\ ~ (15 /\ "a")
is a possible value. I do not know if TLA+ specifies whether this formula has the same value as
15 # "a"
See also the comment on Appendix A, Page 201, line 10 of Practical TLA+.

On control flow structures in Haskell (multiple if-then-else)

I want to translate the following procedural program to Haskell [written in pseudocode]:
f(x) {
if(c1(x)) {
if(c2(x)) {
return a(x);
}
else if (c3(x)) {
if(c4(x)) {
return b(x);
}
}
return d(x);
}
I have written the following implementation:
f x =
if (c1 x) then
if(c2 x) then
a x
else if (c3 x) then
if (c4 x) then
b x
else d x
else d x
else d x
Unfortunately it contains (else d x) three times.
Is there a better way to implement the function? (i.e, to return (d x) if none of the conditions was met?)
I understand that we could combine conditions c1 and c2 into (c1 x) && (c2 x) to make the number of if's smaller, but my conditions c1, c2, c3, c4 are indeed very long and if I combine them I will get a condition which takes more than one line.
Easiest, most apparent solution
If you're using GHC, you can turn on
{-# LANGUAGE MultiWayIf #-}
and your entire thing becomes
f x = if | c1 x && c2 x -> a x
| c1 x && c3 x && c4 x -> b x
| otherwise -> d x
Slightly more advanced and flexible solution
However, it's not always you want to blindly replicate imperative code in Haskell. Often, it's useful to think of your code as data instead. What you are really doing is setting up a list of requirements that x must satisfy, and then if x satisfies those requirements you take some action on x.
We can represent this with actual lists of functions in Haskell. It would look something like
decisions :: [([a -> Bool], a -> b)]
decisions = [([c1, c2], a)
,([c1, c3, c4], b)]
,([], d)]
Here, we should read this as, "if x satisfies both c1 and c2, take action a on x" and so on. Then we can define f as
f x = let maybeMatch = find (all ($ x) . fst) decisions
match = fromMaybe (error "no match!") maybeMatch
result = snd match
in result x
This works by walking through the list of requirements and finding the first set of decisions that x satisfy (maybeMatch). It pulls that out of the Maybe (you might want some better error handling there!) Then it chooses the corresponding function (result), and then it runs x through that.
Very advanced and flexible solution
If you have a really complex tree of decisions, you might not want to represent it with a flat list. This is where actual data trees come in handy. You can create a tree of the functions you want, and then search that tree until you hit a leaf node. That tree might in this example look something like
+-> c1 +-> c2 -> a
| |
| +-> c3 -> c4 -> b
+-> d
In other words, if x satisfies c1, it's gonna see if it satisfies c2 too, and if it does take action a on x. If it doesn't, it goes on to the next branch with c3, and so on, until it reaches an action (or has walked through the entire tree).
But first you're going to need a data type to tell the difference between a requirement (c1, c2 etc.) and an action (a, b etc.)
data Decision a b = Requirement (a -> Bool)
| Action (a -> b)
Then you build a tree of decisions as
decisions =
Node (Requirement (const True))
[Node (Requirement c1)
[Node (Requirement c2)
[Node (Action a) []]
,Node (Requirement c3)
[Node (Requirement c4)
[Node (Action b) []]]
,Node (Action d) []]
This looks more complicated than it is, so you should probably invent a neater way of expressing decision trees. If you define the functions
iff = Node . Requirement
action = flip Node [] . Action
you can write the tree as
decisions =
iff (const True) [
iff (c1) [
iff (c2) [
action a
],
iff (c3) [
iff (c4) [
action b
]
]
],
action d
]
and suddenly it's very similar to the imperative code you started with, despite the fact that it's valid Haskell code that's just building a data structure! Haskell is powerful for defining custom little "languages inside the language" like this.
Then you need to search through the tree for the first action you can reach.
decide :: a -> Tree (Decision a b) -> Maybe b
decide x (Node (Action f) _) = Just (f x)
decide x (Node (Requirement p) subtree)
| p x = asum $ map (decide x) subtree
| otherwise = Nothing
This uses a little bit of Maybe magic (asum) to stop at the first successful hit. This in turn means it will not compute the conditions of any branch in vain (which is efficient and important if the computations are expensive) and it should handle infinite decision trees just fine.
You can make decide even more general, taking full advantage of the Alternative class, but I've chosen to specialise it for Maybe so as to not write a book about this. Making it even more general might allow you to have fancy monadic decisions too, which would be very cool!
But, lastly, as a very simple example of this in action – take the Collatz conjecture. If you give me a number, and ask me what the next number should be, I can build a decision tree to find out. The tree may look like this:
collatz =
iff (> 0) [
iff (not . even) [
action (\n -> 3*n + 1)
],
action (`div` 2)
]
so the number has to be bigger than 0, and then if it's odd you multiply by three and add one, otherwise you halve it. Test runs show that
λ> decide 3 collatz
Just 10
λ> decide 10 collatz
Just 5
λ> decide (-4) collatz
Nothing
You can probably imagine much more interesting decision trees.
Edit like a year later: The generalisation to Alternative is actually very simple, and fairly interesting. The decide function gets the new look
decide :: Alternative f => a -> Tree (Decision a b) -> f b
decide x (Node (Action f) _) = pure (f x)
decide x (Node (Requirement p) subtree)
| p x = asum $ map (decide x) subtree
| otherwise = empty
(that's a total of only three changes, for those keeping count.) What this gives you is the opportunity to assemble "all" actions the input satisfies by using the applicative instance of lists instead of Maybe. This reveals an "error" in our collatz tree – if we look carefully at it, we see it says that all odd and positive integers n turn to 3*n +1 but it also says that all positive numbers turn to n/2. There is no additional requirement that says the number has to be even.
In other words, the (`div` 2) action is only under the (>0) requirement and nothing else. This is technically incorrect, but it happens to work if we just get the first result (which is basically what using the Maybe Alternative instance does). If we list all results, we also get an incorrect one.
When is getting multiple results interesting? Maybe we're writing the decision tree for an AI, and we want to humanise the behaviour by first getting all the valid decisions, and then picking one of them at random. Or ranking them based on how good they are in the circumstances, or something else.
You could use guards and a where clause:
f x | cb && c2 x = a x
| cb && c3 x && c4 x = b x
| otherwise = d x
where cb = c1 x
If you're just worried about writing them out then that's what where blocks are for
f x =
case () of
() | c1 && c2 -> a x
| c1 && c3 && c4 -> b x
| otherwise -> d x
where
c1 = ...
c2 = ...
c3 = ...
c4 = ...
Not that I'm using the case trick to introduce a new place for guard statements. I can't use guards on the function definition itself because the where clause won't scope over all of the guards. You could use if just the same, but guards have nice pass-through semantics.
There's another pattern you can use: I wouldn't use it in your specific example but there are very similar situations where I have used it.
f x = case (c1 x, c2 x, c3 x, c4 x) of
(True,True,_,_) -> a x
(True,False,True,True) -> b x
_ -> d x
Only the bare minimum evaluation required to choose which path to take will actually be evaluated: it won't actually evaluate c2 x unless c1 x is True.

2 Haskell Questions

I have 2 Question about 2 haskell functions
flipSymbol :: Model -> Atom -> Model This function must take a Model and an Atom and flip the truth value of the atom in the model. Now I was thinking of writing this function like this:...
flipSymbol m a = map f m
where
f (atom, value) = if a == atom then (atom, not value) else (atom, value)
Is there a better way?
The second one is a something more complicated and I need some help with it if possible..
In order to check the satisfiability of a formula in a given model we propagate the effects of assigning a truth value to an atom in a formula. Assume an atom to which we assign the value True. The following effects
can be applied to the formula:
The positive literals have the same True value and, therefore, any clauses that contain them are removed from the formula. This is to indicate that these clauses could be satisfied and hence no longer affect the satisfiability of the formula.
The negated literals have a value of False and are, therefore, removed from any clause they are in. This is to indicate that these clauses are still not satisfied and can only be made true by one of the other literals obtaining a value of True. In the case where False is assigned to the atom, the positive literals will now be false and should be removed
from their clauses while the negative literals will become true and have their clauses removed from the formula.
For example, in the formula (P _ Q _ R) ^ (:P _ Q _ :R) ^ (P _ :Q), assume we assign True to P. Then the clauses containing P, ie. (P _ Q _ R) and (P _ :Q) are removed from the formula, whereas :P is removed from any clause it is in, ie. (:P _ Q _ :R). This results in the formula (Q _ :R). On the other hand, if we assign False to P, we then remove (:P _ Q _ :R) from the formula and P from its clauses, thus obtaining (Q _ R) ^ (:Q).
The overall formula is satisfiable if it can be reduced to the empty list since in this case all the clauses were satisfied. If there is an empty list within the overall formula then that means that a clause was not satisfied and hence the formula can not be satisfied with the assignment that led to this state.
assign :: (Atom,Bool) -> Formula -> Formula The assign function should take an (Atom,Bool) pair and a formula and propagate the effects of assigning the given truth value to the atom in the formula as described above.
The code(on which I received help from here also):
module Algorithm where
import System.Random
import Data.Maybe
import Data.List
type Atom = String
type Literal = (Bool,Atom)
type Clause = [Literal]
type Formula = [Clause]
type Model = [(Atom, Bool)]
type Node = (Formula, ([Atom], Model))
-- This function takess a Clause and return the set of Atoms of that Clause.
atomsClause :: Clause -> [Atom]
atomsClause = undefined
-- This function takes a Formula returns the set of Atoms of a Formula
atoms :: Formula -> [Atom]
atoms = nub . map snd
-- This function returns True if the given Literal can be found within
-- the Clause.
isLiteral :: Literal -> Clause -> Bool
isLiteral = isLiteral = any . (==)
-- this function takes a Model and an Atom and flip the truthvalue of
-- the atom in the model
flipSymbol :: Model -> Atom -> Model -- is this ok?
flipSymbol m a = map f m where
f (atom, value) = if a == atom
then (atom, not value)
else (atom, value)
assign :: (Atom,Bool) -> Formula -> Formula
assign = undefined --any advice here?
At a glance, I can't see any way to improve your first formula, maybe you may use logical functions instead of a if-then-else, it's faster:
flipSymbol m a = map f m where
f (atom, value) = (atom, value /= (a == atom))
Notice: /= for Bool is basically xor.
To your last question:
The basic idea is to compare the Atoms, incorporate the Bool-values and fiddeling around with logical ops to get your result. Basically, it looks like this:
assign :: (Atom,Bool) -> Formula -> Formula
assign (a,b) = map . (map f) where
f (x,b) = (x,(x==a)&&b)

Resources