problems generating interval information - answer-set-programming

Given a a binary function over time, I try to extract the information about the intervals occuring in this function.
E.g. I have the states a and b, and the following function:
a, a, b, b, b, a, b, b, a, a
Then i would want a fact interval(Start, Length, Value) like this:
interval(0, 2, a)
interval(2, 3, b)
interval(5, 1, a)
interval(6, 2, b)
interval(8, 2, a)
Here is what I got so far:
time(0..9).
duration(1..10).
value(a;b).
1{ function(T, V): value(V) }1 :- time(T).
interval1(T, Length, Value) :-
time(T), duration(Length), value(Value),
function(Ti, Value): Ti >= T, Ti < T + Length, time(Ti).
:- interval1(T, L, V), function(T + L, V).
#show function/2.
#show interval1/3.
This actually works kinda well, but still not correctly, this is my output, when I run it with clingo 4.5.4:
function(0,b)
function(1,a)
function(2,b)
function(3,a)
function(4,b)
function(5,a)
function(6,b)
function(7,a)
function(8,b)
function(9,a)
interval1(0,1,b)
interval1(1,1,a)
interval1(2,1,b)
interval1(3,1,a)
interval1(4,1,b)
interval1(5,1,a)
interval1(6,1,b)
interval1(7,1,a)
interval1(8,1,b)
interval1(9,1,a)
interval1(9,10,a)
interval1(9,2,a)
interval1(9,3,a)
interval1(9,4,a)
interval1(9,5,a)
interval1(9,6,a)
interval1(9,7,a)
interval1(9,8,a)
interval1(9,9,a)
which has only one bug: all the intervals at T == 9 (except for the one where L == 1)
So I tried to add the following constraint, to get rid of those:
:- interval1(T, L, V), not time(T + L - 1).
which in my mind translates to "it is prohibited, to have an interval, such that T + L is not a time"
But now clingo said the problem would be unsatisfiable.
So I tried another solution, which should do the same, but in a little less general way:
:- interval1(T, L, V), T + L > 10.
Which also made the whole thing unsolvable.
Which I really don't understand, I'd just expect both of those rules to just get rid of the intervals, that run out of the function.
So why do they completely kill all elements of the model?
Also, during my experiments, I replaced the function rule with:
function(
0, a;
1, a;
2, b;
3, b;
4, b;
5, b;
6, a;
7, b;
8, a;
9, a
).
Which would make the whole thing unsatisfiable even without the problematic constraints, why is that?
So yeah ... I guess, I fundamentally missunderstood something, and I would be really greatfull if someone would tell me what exactly that is.
Best Regards
Uzaku

The programs with constraints are inconsistent because in ASP any program which contains both the fact a. and the constraint :-a. is inconsistent. You are basically saying that a is true, and, at the same time, a cannot be true.
In your case, for example, you have a rule which tells that interval1(9,10,a) is true for some function, and, on the other hand, you have a constraint which says that interval(9,10,a) cannot be true, so you get inconsistency.
A way to get rid of the undesired intervals would be, for example, to add the extra atom in the definition of an interval, e.g:
interval1(T, Length, Value) :-
time(T), duration(Length), value(Value),
time(T+Length-1), % I added this
function(Ti, Value): Ti >= T, Ti < T + Length, time(Ti).
Now the program is consistent.
I couldn't reproduce the inconsistency for the specific function you have provided. For me, the following is consistent:
time(0..9).
duration(1..10).
value(a;b).
%1{ function(T, V): value(V) }1 :- time(T).
function(0,a).
function(1,a).
function(2,b).
function(3,b).
function(4,b).
function(5,b).
function(6,a).
function(7,b).
function(8,a).
function(9,a).
interval1(T, Length, Value) :-
time(T), duration(Length), value(Value),
time(T+Length-1),
function(Ti, Value): Ti >= T, Ti < T + Length, time(Ti).
#show function/2.
#show interval1/3.
This is what I get in the output:
$ clingo test 0
clingo version 4.5.4
Reading from test
Solving...
Answer: 1
function(0,a) function(1,a) function(2,b) function(3,b) function(4,b) function(5,b) function(6,a) function(7,b) function(8,a) function(9,a) interval1(0,1,a) interval1(1,1,a) interval1(0,2,a) interval1(6,1,a) interval1(8,1,a) interval1(9,1,a) interval1(8,2,a) interval1(2,1,b) interval1(3,1,b) interval1(2,2,b) interval1(4,1,b) interval1(3,2,b) interval1(2,3,b) interval1(5,1,b) interval1(4,2,b) interval1(3,3,b) interval1(2,4,b) interval1(7,1,b)
SATISFIABLE
Models : 1
Calls : 1
Time : 0.002s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 0.000s
We are getting more intervals than needed, since some of them are not maximal, but I am leaving this for you to think about :)
Hope this helps.

Related

ASP Clingo - getting the exact count of atoms

I'm looking forward to assign a specific count of persons to a specific shift. For example I got six persons and three different shifts. Now I have to assign exact two persons to every shift. I tried something like this but..
NOTE: this won't work, so please edit as fast as possible to misslead people, I even removed the "." after it so nobody is copying it:
person(a)
person(b)
person(c)
person(d)
person(e)
person(f)
shift("mor")
shift("aft")
shift("nig")
shiftCount(2).
{ assign(P,S) : shift(S)} = 1 :- person(P).
% DO NOT COPY THIS! SEE RIGHT ANSWER DOWN BELOW
:- #count{P : assign(P,"mor")} = K, shiftCount(K).
:- #count{P : assign(P,"aft")} = K, shiftCount(K).
:- #count{P : assign(P,"nig")} = K, shiftCount(K).
#show assign/2.
Is this possible to count the number of assigned shifts, so I can assign exactly as many people as a given number?
The output of the code above (when the "." are inserted) is:
clingo version 5.5.0
Reading from stdin
Solving...
Answer: 1
assign(a,"nig") assign(b,"aft") assign(c,"mor") assign(d,"mor")
assign(e,"mor") assign(f,"mor")
SATISFIABLE
Models : 1+
Calls : 1
Time : 0.021s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 0.000s
Here you can defently see, that the morning ("mor") shift is used more than two times, as difined in the shiftCount. What do I need to change to get the wanted result?
Replace your 3 lines constraints with
{assign(P,S): person(P)} == K :- shift(S), shiftCount(K).
or alternatively if you want to use the constraint writing:
:- {assign(P,S): person(P)} != K, shift(S), shiftCount(K).
First line states: For a given shiftCount K and for every shift S: the number of assignments over all people P for this shift S is K.
The constraint reads: it can not be the case for a shiftCount K and a shift S that the number of assignments over all people P to the shift S is not K.
Please do not alter your question / sample code dramatically since this may leads to the case that this answer won't work anymore.

How does this prime number checking function work

Can anybody please help me how this code works,
I am not getting it by myself, some help would be greatly appreciated.
Prime number in scala using recusion:
def isPrime(n: Int): Boolean = {
def isPrimeUntil(t: Int): Boolean =
if (t<=1) true
else n%t != 0 && isPrimeUntil(t-1)
isPrimeUntil(n/2)
}
The number n is prime if and only if there's no number t such that t != 1, t!= n, n % t = 0.
So, if you find some number from 2 to n-1 such that n % t = 0, n is composite, otherwise it is prime.
One more thing, you may see that there's no need to search for divisors among the numbers greater than n/2.
So, all the algorithm does is checks n % d for each t from n/2 to 2. As soon as it is found, the algorithms stops ans says it's composite (returns False). Otherwise it gets to t = 1 and assures the number is prime (returns True).
Just to mention, it's enough to consider the numbers from ceil(sqrt(n)) to 2, which results in better time complexity (O(sqrt(n)) vs O(n)).
isPrime(7) --> isPrimeUntil(3) --> (3 <= 1)? no
(7%3 != 0)? yes
isPrimeUntil(2) --> (2 <= 1)? no
(7%2 != 0)? yes
isPrimeUntil(1) --> (1 <= 1)? yes
isPrime(7) is true. No divisor was found between 1 and 7/2.
isPrime(9) --> isPrimeUntil(4) --> (4 <= 1)? no
(9%4 != 0)? yes
isPrimeUntil(3) --> (3 <= 1)? no
(9%3 != 0)? no
isPrime(9) is false. Found that 9 is divisible by 3.
If you have a local Scala REPL, you should paste this function in there and play around with it. If not, there's always Scastie. I made a Scastie snippet, in which I changed the formatting to my liking, added comments and a demo range.
There are examples of Scala that make it look almost like Malbolge. This one is not that bad.
Let's follow it through with a composite number like 102. Calling isPrime(102) causes isPrimeUntil(51) to be invoked (as 51 is half 102). Since 51 is greater than 1, the nested function calculated 102 % 51, which is 0, so, by "short-circuit evaluation" of logical AND, the nested function should return false.
Now let's try it with 103. Calling isPrime(103) causes isPrimeUntil(51) to be invoked (as 51 is half 103 and the remainder of 1 is simply discarded). Since 51 is greater than 1, the nested function calculated 103 % 51, which is 1, so the nested function calls itself as primeUntil(50). Since 50 is greater than 1, the... so on and so forth until calling itself as primeUntil(1). Since t == 1, primeUntil returns true and the recursion stops.
This gives the wrong answer for negative composite numbers. Plus, as others have mentioned, it is inefficient to start the recursion at n/2. This would be an improvement:
def isPrime(n: Int): Boolean = {
def isPrimeUntil(t: Int): Boolean = {
if (t <= 1) true else n % t != 0 && isPrimeUntil(t - 1)
}
isPrimeUntil(Math.floor(Math.sqrt(Math.abs(n))).toInt)
}
Hmm... it's still giving the wrong answer for −1, 0, 1. But hopefully now you understand this function.

Set/sequence summation operator?

I have a set, S = { 1, 2, 3, 4, 5 }.
If I wanted to sum this in standard logic it's just ∑S (no MathJax on SO so I can't format this nicely).
What's the VDM equivalent? I don't see anything in the numerics/sets section of the language reference.
There isn't a standard library function to do this (though perhaps there should be). You would sum a set with a simple recursive function:
sum: set of nat +> nat
sum(s) ==
if s = {}
then 0
else let e in set s in
e + sum(s \ {e})
measure card s;
The "let" selects an arbitrary element from the set, and then add that to the sum of the remainder. The measure says that the recursion always deals with smaller sets.
This should work:
sum(S)
But you could find this very easily.

Solving a triangle procedure

Solving a triangle means finding all possible triangles when some of its sides a,b and c and angles A,B,C (A is the the angle opposite to a, and so on...) are known. This problem has 0, 1, 2 or infinitely many solutions.
I want to write a procedure to solve triangles. The user would feed the procedure with some datas amongst a,b,c,A,B,and C (if it is necessary for the sake of simplicity, you can assume that the user will avoid situations where there are infinitely many solutions) and the procedure will compute the other ones. The usual requires to use the Law of Sines or the Law of Cosines, depending on the situation.
Since it is for a Maths class where I also want to show graphs of functions, I will implement it in Maple. If Maple is not suitable for your answer, please suggest another language (I am reasonably competent in Java and beginner in Python for example).
My naive idea is to use conditional instructions if...then...else to determine the case in hand but it is a little bit boring. Java has a switch that could make things shorter and clearer, but I am hoping for a smarter structure.
Hence my question: Assume that some variables are related by known relations. Is there a simple and clear way to organize a procedure to determine missing variables when only some values are given?
PS: not sure on how I should tag this question. Any suggestion is welcome.
One approach could be to make all of the arguments to your procedure optional with default values that correspond to the names: A, B, C, a, b, c.
Since we can make the assumption that all missing variables are those that are not of type 'numeric', it is easy for us to then quickly determine which variables do not yet have values and give those as the values to a solve command that finds the remaining sides or angles.
Something like the following could be a good start:
trisolve := proc( { side1::{positive,symbol} := A, side2::{positive,symbol} := B, side3::{positive,symbol} := C,
angle1::{positive,symbol} := a, angle2::{positive,symbol} := b, angle3::{positive,symbol} := c } )
local missing := remove( hastype, [ side1, side2, side3, angle1, angle2, angle3 ], numeric );
return solve( { 180 = angle1 + angle2 + angle3,
side1/sin(angle1*Pi/180)=side2/sin(angle2*Pi/180),
side1/sin(angle1*Pi/180)=side3/sin(angle3*Pi/180),
side2/sin(angle2*Pi/180)=side3/sin(angle3*Pi/180),
side1^2=side2^2+side3^2-2*side2*side3*cos(angle1) },
missing );
end proc:
The following call:
trisolve( side1 = 1, angle1 = 90, angle2 = 45 );
returns:
[B = (1/2)*sqrt(2), C = (1/2)*sqrt(2), c = 45]

Calculating prime numbers in Scala: how does this code work?

So I've spent hours trying to work out exactly how this code produces prime numbers.
lazy val ps: Stream[Int] = 2 #:: Stream.from(3).filter(i =>
ps.takeWhile{j => j * j <= i}.forall{ k => i % k > 0});
I've used a number of printlns etc, but nothings making it clearer.
This is what I think the code does:
/**
* [2,3]
*
* takeWhile 2*2 <= 3
* takeWhile 2*2 <= 4 found match
* (4 % [2,3] > 1) return false.
* takeWhile 2*2 <= 5 found match
* (5 % [2,3] > 1) return true
* Add 5 to the list
* takeWhile 2*2 <= 6 found match
* (6 % [2,3,5] > 1) return false
* takeWhile 2*2 <= 7
* (7 % [2,3,5] > 1) return true
* Add 7 to the list
*/
But If I change j*j in the list to be 2*2 which I assumed would work exactly the same, it causes a stackoverflow error.
I'm obviously missing something fundamental here, and could really use someone explaining this to me like I was a five year old.
Any help would be greatly appreciated.
I'm not sure that seeking a procedural/imperative explanation is the best way to gain understanding here. Streams come from functional programming and they're best understood from that perspective. The key aspects of the definition you've given are:
It's lazy. Other than the first element in the stream, nothing is computed until you ask for it. If you never ask for the 5th prime, it will never be computed.
It's recursive. The list of prime numbers is defined in terms of itself.
It's infinite. Streams have the interesting property (because they're lazy) that they can represent a sequence with an infinite number of elements. Stream.from(3) is an example of this: it represents the list [3, 4, 5, ...].
Let's see if we can understand why your definition computes the sequence of prime numbers.
The definition starts out with 2 #:: .... This just says that the first number in the sequence is 2 - simple enough so far.
The next part defines the rest of the prime numbers. We can start with all the counting numbers starting at 3 (Stream.from(3)), but we obviously need to filter a bunch of these numbers out (i.e., all the composites). So let's consider each number i. If i is not a multiple of a lesser prime number, then i is prime. That is, i is prime if, for all primes k less than i, i % k > 0. In Scala, we could express this as
nums.filter(i => ps.takeWhile(k => k < i).forall(k => i % k > 0))
However, it isn't actually necessary to check all lesser prime numbers -- we really only need to check the prime numbers whose square is less than or equal to i (this is a fact from number theory*). So we could instead write
nums.filter(i => ps.takeWhile(k => k * k <= i).forall(k => i % k > 0))
So we've derived your definition.
Now, if you happened to try the first definition (with k < i), you would have found that it didn't work. Why not? It has to do with the fact that this is a recursive definition.
Suppose we're trying to decide what comes after 2 in the sequence. The definition tells us to first determine whether 3 belongs. To do so, we consider the list of primes up to the first one greater than or equal to 3 (takeWhile(k => k < i)). The first prime is 2, which is less than 3 -- so far so good. But we don't yet know the second prime, so we need to compute it. Fine, so we need to first see whether 3 belongs ... BOOM!
* It's pretty easy to see that if a number n is composite then the square of one of its factors must be less than or equal to n. If n is composite, then by definition n == a * b, where 1 < a <= b < n (we can guarantee a <= b just by labeling the two factors appropriately). From a <= b it follows that a^2 <= a * b, so it follows that a^2 <= n.
Your explanations are mostly correct, you made only two mistakes:
takeWhile doesn't include the last checked element:
scala> List(1,2,3).takeWhile(_<2)
res1: List[Int] = List(1)
You assume that ps always contains only a two and a three but because Stream is lazy it is possible to add new elements to it. In fact each time a new prime is found it is added to ps and in the next step takeWhile will consider this new added element. Here, it is important to remember that the tail of a Stream is computed only when it is needed, thus takeWhile can't see it before forall is evaluated to true.
Keep these two things in mind and you should came up with this:
ps = [2]
i = 3
takeWhile
2*2 <= 3 -> false
forall on []
-> true
ps = [2,3]
i = 4
takeWhile
2*2 <= 4 -> true
3*3 <= 4 -> false
forall on [2]
4%2 > 0 -> false
ps = [2,3]
i = 5
takeWhile
2*2 <= 5 -> true
3*3 <= 5 -> false
forall on [2]
5%2 > 0 -> true
ps = [2,3,5]
i = 6
...
While these steps describe the behavior of the code, it is not fully correct because not only adding elements to the Stream is lazy but every operation on it. This means that when you call xs.takeWhile(f) not all values until the point when f is false are computed at once - they are computed when forall wants to see them (because it is the only function here that needs to look at all elements before it definitely can result to true, for false it can abort earlier). Here the computation order when laziness is considered everywhere (example only looking at 9):
ps = [2,3,5,7]
i = 9
takeWhile on 2
2*2 <= 9 -> true
forall on 2
9%2 > 0 -> true
takeWhile on 3
3*3 <= 9 -> true
forall on 3
9%3 > 0 -> false
ps = [2,3,5,7]
i = 10
...
Because forall is aborted when it evaluates to false, takeWhile doesn't calculate the remaining possible elements.
That code is easier (for me, at least) to read with some variables renamed suggestively, as
lazy val ps: Stream[Int] = 2 #:: Stream.from(3).filter(i =>
ps.takeWhile{p => p * p <= i}.forall{ p => i % p > 0});
This reads left-to-right quite naturally, as
primes are 2, and those numbers i from 3 up, that all of the primes p whose square does not exceed the i, do not divide i evenly (i.e. without some non-zero remainder).
In a true recursive fashion, to understand this definition as defining the ever increasing stream of primes, we assume that it is so, and from that assumption we see that no contradiction arises, i.e. the truth of the definition holds.
The only potential problem after that, is the timing of accessing the stream ps as it is being defined. As the first step, imagine we just have another stream of primes provided to us from somewhere, magically. Then, after seeing the truth of the definition, check that the timing of the access is okay, i.e. we never try to access the areas of ps before they are defined; that would make the definition stuck, unproductive.
I remember reading somewhere (don't recall where) something like the following -- a conversation between a student and a wizard,
student: which numbers are prime?
wizard: well, do you know what number is the first prime?
s: yes, it's 2.
w: okay (quickly writes down 2 on a piece of paper). And what about the next one?
s: well, next candidate is 3. we need to check whether it is divided by any prime whose square does not exceed it, but I don't yet know what the primes are!
w: don't worry, I'l give them to you. It's a magic I know; I'm a wizard after all.
s: okay, so what is the first prime number?
w: (glances over the piece of paper) 2.
s: great, so its square is already greater than 3... HEY, you've cheated! .....
Here's a pseudocode1 translation of your code, read partially right-to-left, with some variables again renamed for clarity (using p for "prime"):
ps = 2 : filter (\i-> all (\p->rem i p > 0) (takeWhile (\p->p^2 <= i) ps)) [3..]
which is also
ps = 2 : [i | i <- [3..], and [rem i p > 0 | p <- takeWhile (\p->p^2 <= i) ps]]
which is a bit more visually apparent, using list comprehensions. and checks that all entries in a list of Booleans are True (read | as "for", <- as "drawn from", , as "such that" and (\p-> ...) as "lambda of p").
So you see, ps is a lazy list of 2, and then of numbers i drawn from a stream [3,4,5,...] such that for all p drawn from ps such that p^2 <= i, it is true that i % p > 0. Which is actually an optimal trial division algorithm. :)
There's a subtlety here of course: the list ps is open-ended. We use it as it is being "fleshed-out" (that of course, because it is lazy). When ps are taken from ps, it could potentially be a case that we run past its end, in which case we'd have a non-terminating calculation on our hands (a "black hole"). It just so happens :) (and needs to ⁄ can be proved mathematically) that this is impossible with the above definition. So 2 is put into ps unconditionally, so there's something in it to begin with.
But if we try to "simplify",
bad = 2 : [i | i <- [3..], and [rem i p > 0 | p <- takeWhile (\p->p < i) bad]]
it stops working after producing just one number, 2: when considering 3 as the candidate, takeWhile (\p->p < 3) bad demands the next number in bad after 2, but there aren't yet any more numbers there. It "jumps ahead of itself".
This is "fixed" with
bad = 2 : [i | i <- [3..], and [rem i p > 0 | p <- [2..(i-1)] ]]
but that is a much much slower trial division algorithm, very far from the optimal one.
--
1 (Haskell actually, it's just easier for me that way :) )