Referencing previous state in Promela LTL statement - model-checking

I'm getting started with Promela, and I'm having trouble expressing some LTL formulas.
An example is the following sequence value that I'd like to assert is monotonically increasing. Intuitively I want to write that in the next state, sequence is >= its previous value, but looking through documentation, I don't see a way to express this. Is there a method for expressing this type of formula?
byte sequence = 0;
ltl p0 { [] sequence >= prev(sequence) }
... processes that manipulate sequence ...
Assuming that it's possible to express the monotonically increasing property of sequence above, I'm wondering if there is a syntax for wildcard array indexing. Similar to the above example, I intuitively want to reference all previous index entries.
byte values[N];
byte index = 0;
ltl p1 { values[0..index-1] are monotonically increasing }
... processes ...
Thanks a lot for your help. Promela seems really great :)

AFAIK,
Monotonically Non-decreasing Sequence.
Linear Temporal Logic has a X operator that allows one to express a property that refers to a boolean condition holding in the next state, as opposed to the previous state.
However, one cannot directly compare an integer value of the current state with that of the next state within an LTL formula, because X evaluates to a Boolean value.
In theory, what one can do is to encode the <= operator over the integer as a Boolean property by bit-blasting it, e.g. by means of some clever use of the modulo operator or bitwise operations (it should not be too hard with unsigned variables) and a bit-to-bit comparison of the corresponding Boolean values (see final note).
From a modeling point of view, however, the easiest approach is to enrich your model with a prev_value variable and simply check that in each state the property prev_value <= cur_value holds. Notice that in this case you should use the d_step command to group together the two value assignments, so that they are conflated within a single state with no intermediate transitions, e.g.
...
byte prev_value;
byte cur_value;
...
d_step {
prev_value = cur_value;
cur_value = ... non-blocking function ...
}
Otherwise, the invariant property relating prev_value to cur_value may result to be broken on the corresponding automaton for some state s_i. (note: this would actually not hinder the verification of the specific LTL property you are interested in, but it can be an issue with other formulas)
Wildcard Indexing.
If I understand correctly, you want to express a property s.t. --in each state-- only memory locations from 0 up to index-1 are required to be monotonically non-decreasing, with index being a variable which can change value (arbitrarily?).
The structure of such property should be:
ltl p1 {
[] (
((1 <= index) -> "... values[0] is monotonically non-decreasing ...") &&
((2 <= index) -> "... values[1] is monotonically non-decreasing ...") &&
((3 <= index) -> "... values[2] is monotonically non-decreasing ...") &&
...
((N <= index) -> "... values[N-1] is monotonically non-decreasing ...")
)
}
I believe the answer to your question is no. However, I suggest you to use macros for the C preprocessor to simplify the encoding of your properties and avoid writing the same things over and over again.
Note:
Let's take curr_int and next_int 0-1 Integer variables s.t. next_int is equal to the value of curr_int in the next state (aka, curr_int is the previous value of next_int), and a curr Boolean variable s.t. curr is true if and only if curr_int is equal to 1.
Then, by the LTL semantics, X curr is true if and only if curr_int (next_int) is equal to 1 in the next (current) state.
Consider the following truth-table for state s_i:
curr_int | next_int | curr_int <= next_int
0 | 0 | 1
0 | 1 | 1
1 | 0 | 0
1 | 1 | 1
From the above definitions, we can rewrite it as:
curr | X curr | EXPR
false | false | true
false | true | true
true | false | false
true | true | true
From the truth-table it's can be seen that EXPR corresponds to
!curr v (X curr)
which can be more elegantly rewritten as
curr -> (X curr)
Thich is our final LTL-encodeable version of curr_int <= next_int for a given state s_i, when both are 0-1 Integer variables.

There is no such symbol in Promela. Yet any Past Time LTL formula can be translated into Future Time LTL (probably even more cumbersome one).
Not sure though is there an easy way to compare values of variables in different states.
Also check LTL specification pattern repository for past.
See discusssion in CS stackexhange
https://cstheory.stackexchange.com/questions/29444/do-past-time-ltl-and-future-time-ltl-have-the-same-expressiveness

Related

Difference between `==` and `and`

def pos_neg(a, b, negative):
if negative:
return (a < 0 and b < 0)
else:
return ((a < 0 == b > 0) or (a > 0 == b < 0))
so basically I tried some basic problems.
I just started out and went to https://codingbat.com/prob/p162058 to try it and don't understand why if I were to replace the '==' with 'and' it would work? Thanks.
Oh, I got it now, thanks guys. :D
(this python community is fire!!!)
Since you're learning, you might be interested in seeing that this is an equivalent function.
basically it does a bit wise & and returns true if the result is < 0
else a bit wise exclusive or and returns true if the result is < 0
def pos_neg(a , b, negative):
if negative:
return (a & b) < 0 # both sign bits set (i.e. neg), return true
else:
return (a ^ b) < 0 # different signs, return true
In both cases, it is the sign bit of the result that is of concern. If the bit is set then the value will be negative (hence the comparison to < 0)
and is a logical operator and returns true only when both the expressions we are using it on are true.
== is used for comparisons and returns true when both expressions are equal; they don't need to be true.
To give you an example False == False will return True but False and False will return False.
This "==" means equals to, belonging to Python Comparison Operators, used to compare two values.
and language keyword "and" it is for Python Logical Operators used to combine conditional statements.
You should check out this, it may solve others doubts you have.
W3Schools
All your relational operator usages (i.e. a < 0, b < 0, etc.) result to a boolean value and thus these are known as boolean expressions.
When you put a < 0, think of it like a test of: "is a less than 0, true or false?".
So, if both a and b are negative (i.e. less than zero), their expressions will return true.
So on the line return a < 0 and b < 0, replacing and with == is like saying return true == true. Without the change it'd be return true and true.
Note: This does not mean == is the same as and. == checks for equality of the left-hand side to the right-hand side (e.g. 1 == 1) and gives a true or false value depending on the result of equality. and checks for if the left-hand side results to a true statement and if the right-hand side results to a true statement in order to result to a true expression.

How can I use Haskell exception for index negative

I am trying to solve one of my Haskell question. The question asks me to that extracts a slice of a list of integers. Function should take a list and two indexes new list number contains between two indexes.
For this function;
First index should smaller than second index
First index cannot be negative number
we cannot use any built-in functions
example:
makeSlice [1,2,3,4,5] 2 3
[3,4]
makeSlice [1,2,3,4,5] (-1) 3
*** Exception: First index cannot be negative
I tried a few option but below function if I give positive number I am getting "First index cannot be negative" exception
makeSlice :: [a] -> Int -> Int -> [a]
makeSlice [] _ _ =[]
makeSlice (h:t) i k
|k < 0 = []
| i>k = error "First index cannot be greater than second index (i > k)"
| i< 0 = error "First index cannot be negative (i < 0)!"
| i>0 = makeSlice t (i - 1) (k - 1)
| otherwise = h:makeSlice t (i -1 ) (k - 1)
Can you help me to find where I am making wrong?
Add terminating condition for your recursion. On each call you subtract one from i and when it reaches below 0 you just throw error.
Probably the easiest approach to this uses the Prelude take and drop functions to process the list. Then you just need to do the bounds checking:
slice :: Int -> Int -> [a] -> Either String [a]
slice from to lst
| from < 0 = Left "First index cannot be negative (i < 0)!"
| to < from = Left "First index cannot be greater than second index (i > k)"
| otherwise = Right $ take (to - from) $ drop from $ lst
Here I'm using Either to report either success or failure. On the one hand that disagrees with the problem as stated; on the other, it gives callers a chance to handle the error without immediately terminating the program, which is more polite.

Not showing output python, no error showing

Let us consider polynomials in a single variable x with integer coefficients: for instance, 3x^4 - 17x^2 - 3x + 5. Each term of the polynomial can be represented as a pair of integers (coefficient,exponent). The polynomial itself is then a list of such pairs.
We have the following constraints to guarantee that each polynomial has a unique representation:
Terms are sorted in descending order of exponent
No term has a zero coefficient
No two terms have the same exponent
Exponents are always nonnegative
For example, the polynomial introduced earlier is represented as
[(3,4),(-17,2),(-3,1),(5,0)]
The zero polynomial, 0, is represented as the empty list [], since it has no terms with nonzero coefficients.
Write Python functions for the following operations:
addpoly(p1,p2) ?
def addpoly(p1,p2):
p1=[]
p2=[]
for i in range(0,len(p1)):
for j in range(0,len(p2)):
L=[]
if p1[i][1]==p2[j][1]:
L=L[p1[i][0]+p2[j][0]][p1[i][1]]
elif p1[i][1]!=p2[j][1]:
L=L+p1[i][j]
L=L+p2[i][j]
print("L")
You are reassigning the p1 and p2 arguments to empty lists at the top of your function. This means you will always be checking for i in range(0, 0), which is an empty range. In other words, nothing in your loop will be executed. This is why you are not seeing any output. You are not seeing any error messages, because there is nothing wrong with your syntax, the problem is with the logic.
My math skills are nonexistent, so I cannot comment on the accuracy of most of the logic in your code, but for sure you need to get rid of the first two lines of your function (p1 = [] and p2 = []) or your function will do nothing.
Also, make sure to print the variable L rather than the string "L" to print your list:
print(L)
try this code
def addpoly(p1,p2):
L=[]
for i in range(0,len(p1)):
for j in range(0,len(p2)):
if p1[i][1] == p2[j][1] and p1[i][0]+p2[j][0] != 0 :
L.append((p1[i][0]+p2[j][0],p1[i][1]))
elif p1[i][1] == p2[j][1] and p1[i][0]+p2[j][0] == 0 :
pass
elif i == j:
L.append(p2[i])
L.append(p1[i])
return (L)

Scala String Similarity

I have a Scala code that computes similarity between a set of strings and give all the unique strings.
val filtered = z.reverse.foldLeft((List.empty[String],z.reverse)) {
case ((acc, zt), zz) =>
if (zt.tail.exists(tt => similarity(tt, zz) < threshold)) acc
else zz :: acc, zt.tail
}._1
I'll try to explain what is going on here :
This uses a fold over the reversed input data, starting from the empty String (to accumulate results) and the (reverse of the) remaining input data (to compare against - I labeled it zt for "z-tail").
The fold then cycles through the data, checking each entry against the tail of the remaining data (so it doesn't get compared to itself or any earlier entry)
If there is a match, just the existing accumulator (labelled acc) will be allowed through, otherwise, add the current entry (zz) to the accumulator. This updated accumulator is paired with the tail of the "remaining" Strings (zt.tail), to ensure a reducing set to compare against.
Finally, we end up with a pair of lists: the required remaining Strings, and an empty list (no Strings left to compare against), so we take the first of these as our result.
The problem is like in first iteration, if 1st, 4th and 8th strings are similar, I am getting only the 1st string. Instead of it, I should get a set of (1st,4th,8th), then if 2nd,5th,14th and 21st strings are similar, I should get a set of (2nd,5th,14th,21st).
If I understand you correctly - you want the result to be of type List[List[String]] and not the List[String] you are getting now - where each item is a list of similar Strings (right?).
If so - I can't see a trivial change to your implementation that would achieve this, as the similar values are lost (when you enter the if(true) branch and just return the acc - you skip an item and you'll never "see" it again).
Two possible solutions I can think of:
Based on your idea, but using a 3-Tuple of the form (acc, zt, scanned) as the foldLeft result type, where the added scanned is the list of already-scanned items. This way we can refer back to them when we find an element that doesn't have preceeding similar elements:
val filtered = z.reverse.foldLeft((List.empty[List[String]],z.reverse,List.empty[String])) {
case ((acc, zt, scanned), zz) =>
val hasSimilarPreceeding = zt.tail.exists { tt => similarity(tt, zz) < threshold }
val similarFollowing = scanned.collect { case tt if similarity(tt, zz) < threshold => tt }
(if (hasSimilarPreceeding) acc else (zz :: similarFollowing) :: acc, zt.tail, zz :: scanned)
}._1
A probably-slower but much simpler solution would be to just groupBy the group of similar strings:
val alternative = z.groupBy(s => z.collect {
case other if similarity(s, other) < threshold => other
}.toSet ).values.toList
All of this assumes that the function:
f(a: String, b: String): Boolean = similarity(a, b) < threshold
Is commutative and transitive, i.e.:
f(a, b) && f(a. c) means that f(b, c)
f(a, b) if and only if f(b, a)
To test both implementations I used:
// strings are similar if they start with the same character
def similarity(s1: String, s2: String) = if (s1.head == s2.head) 0 else 100
val threshold = 1
val z = List("aa", "ab", "c", "a", "e", "fa", "fb")
And both options produce the same results:
List(List(aa, ab, a), List(c), List(e), List(fa, fb))

number as an object, or storing properties of a number

in designing an algebraic equation modelling system, I had this dilemma: we cannot associate properties to a number, if I turn the number to a table with a field "value" for example, I can overload arithmetic operators, but not the logic operator since that only works when both operands have same metatable, while my users will compare "x" with numbers frequently.
For example, here is a minimal equation solver system:
x = 0
y = 0
eq1 = {function() return 2*x + 3*y end, rhs = 1 }
eq2 = {function() return 3*x + 2*y end, rhs = 2 }
p = {{x,y},{eq1, eq2}}
solve(p)
The "solve()" will process table "p" to get all coefficients of the equation system and rhs. However, it is essential, a user can associate properties to "x" and "y", for example, lower bound, upper bound. I tries using table,
x = {val=0, lb=0, ub=3}
y = {val=1,lb=3,ub=5}
....
and write metamethods for "x" and "y" such that arithmetic operating will act on x.val and y.val. However, in a scripting environment, we also need to compare "x" with numbers, i.e., "if x>0 then ...". And I stuck here. An ugly solution is to ask users to use x.val, y.val everywhere in modelling the equation and scripting. Does anyone here has similar need to associate properties to a number, and the number can still be used in arithmetic/logic operations?
Something like this could work:
x = {val = 10}
mt = {}
mt.__lt = function (op1, op2)
if (type(op1) == 'table') then a = op1.val else a = op1 end
if (type(op2) == 'table') then b = op2.val else b = op2 end
return a < b
end
setmetatable(x, mt)
print(x < 5) -- prints false
print(x < 15) -- prints true
print(x < x) -- prints false
print(5 < x) -- prints true
Of course, you would write similar methods for the other operators (__add, __mul, __eq and so on).
If you'd rather not use type()/reflection, you can use an even dirtier trick that takes advantage of the fact that unary minus is well, unary:
mt = {}
mt.__unm = function (num) return -(num.val) end
mt.__lt = function (a, b) return -(-a) < -(-b) end
This is rather simple if you have access to the debug library, do you?
debug.setmetatable(0, meta)
meta will be the metatable of ALL numbers. This will solve your logical overloading problem.
However if you would prefer assigning properties to numbers, there is a way you could do this, I wrote a quick example on how one would do so:
local number_props = {
{val="hi"},
{val="hi2"}
}
debug.setmetatable(0,{__index=function(self,k)return number_props[self][k]end})
print((1).val, (2).val)

Resources