Defining a Fact in Alloy which constrains an Airplane's capacity - alloy

I'm trying to define an Alloy Fact, in the below specification, which would prevent adding a Person to an Airplane's set of passengers, unless there's enough capacity. Furthermore, I would like to add another Fact, which would disallow the removal of a Person from an Airplane's passenger set, unless the latter's cardinality exceeded zero.
Any help would be much appreciated.
Cheers,
Phiroc
PS Here's my first stab at the initial Fact:
a'.onboard <= a'.capacity implies
no p and add [a,a',p] and del [a',a'',p] implies a.onboard = a''.onboard
... According to Daniel Jackson, it's invalid because the condition before the implied keyword could potentially be false. Furthermore, it doesn't have the expected effect of preventing the number of passengers from exceeding the airplane capacity, when running the model. For instance, you sometimes get sets with cardinality 4, although capacity is 2, when you execute the model...
sig Person {}
sig Airplane {onboard: set Person, capacity: Int}
fact {
some a,a': Airplane | disj [a.onboard, a'.onboard]
}
pred show(a: Airplane) {
#a.onboard > 0
a.capacity = 2
}
run show for 10 but 2 Airplane
pred add (a, a': Airplane, p: Person) {
a'.onboard = a.onboard + p
}
pred del (a, a': Airplane, p: Person) {
a'.onboard = a.onboard - p
}
assert delUndoesAdd {
all a,a',a'': Airplane, p: Person |
no p and add [a,a',p] and del [a',a'',p] implies a.onboard = a''.onboard
}
assert addIdempotence {
all a,a',a'': Airplane, p: Person |
add [a,a',p] and add [a',a'',p] implies a'.onboard = a''.onboard
}
check delUndoesAdd for 10 but 3 Airplane
check addIdempotence for 3

I think I've found a solution.
sig Person {}
sig Airplane {onboard: set Person, capacity: Int}
fact {
some a,a': Airplane | disj [a.onboard, a'.onboard]
}
fact {
all a: Airplane | a.capacity = 3 and #a.onboard <= a.capacity
}
pred show(a: Airplane) {
}
run show for 10 but 2 Airplane
pred add (a, a': Airplane, p: Person) {
a'.onboard = a.onboard + p
}
pred del (a, a': Airplane, p: Person) {
a'.onboard = a.onboard - p
}
assert delUndoesAdd {
all a,a',a'': Airplane, p: Person |
no p and add [a,a',p] and del [a',a'',p] implies a.onboard = a''.onboard
}
assert addIdempotence {
all a,a',a'': Airplane, p: Person |
add [a,a',p] and add [a',a'',p] implies a'.onboard = a''.onboard
}
check delUndoesAdd for 10 but 3 Airplane
check addIdempotence for 3

Related

How to sum more than two numbers in Alloy Analyzer?

I am trying to sum all the numbers in a set in Alloy.
For instance, in the signature abc, I want the value to be the sum of a.value + b.value + c.value, which is 4+1+3=8.
However, if I use "+", it gives me the union set and not the sum.
PS. I know there is the "plus" (as I used it in sig sumab), but this only allows me to sum two values.
Thanks
open util/integer
sig a{value: Int}
{
value = 4
}
sig b{value: Int}
{
value = 1
}
sig c{value: Int}
{
value = 3
}
sig abc{value: set Int}
{
value = a.value + b.value + c.value
}
sig sumab{
value : Int
}
{
value = plus[a.value, b.value]
}
pred add{}
run add for 4 int, exactly 1 sumab, exactly 1 a, exactly 1 b, exactly 1 c, exactly 1 abc
Note: I wrote this in pseudo-code, it may help to get to an answer:
fun plusN [setInt : set de Int] : Int { // function "plusN" should take a set of integers "setInt", return an integer
if #setInt = 2 //if only two numbers in set, sum them
then plus[max setInt , min setInt]
else // if more than 2, use recursion
plusN [max setInt , plusN[{setInt - max setInt}]]
}
Note 2. The function sum may seem to be a good idea, but if I sum 1+1+1=1, the result will be 1 intead of 3 as the only number in the set is 1.
Alloy comes with a built-in sum function, so just do sum[value].
As mentioned in this answer, Alloy has a sum keyword (different than the sum function) which can be used.
The general format is:
sum e: <set> | <expression involving e>
Variable sig values
Here's a simple example that sums the number of sales during a day for a restaurant's three meals. In particular, note the use of the sum keyword in fun sum_sales.
one sig Restaurant { total_sales: Int }
abstract sig Meal { sales: Int }
one sig Breakfast, Lunch, Dinner in Meal {}
// Each meal only falls in one category
fact { disj[Breakfast, Lunch, Dinner] }
// Every meal is in some category
fact { Breakfast + Lunch + Dinner = Meal }
// Keep the numbers small because the max alloy int is 7
fact { all m: Meal | m.sales <= 4 }
// Negative sales don't make sense
fact { all m: Meal | m.sales >= 0 }
fun sum_sales: Int { sum m: Meal | m.sales }
fact { Restaurant.total_sales = sum_sales }
This works even when all meals have the same number of sales (1 + 1 + 1 = 3), as shown in this check.
check { (all m: Meal | m.sales = 1) => Restaurant.total_sales = 3 }
Here are some other ways to play around with the example.
check {
{
// One meal with three sales
#{ m: Meal | m.sales = 3 } = 1
// Two meals with one sale
#{ m: Meal | m.sales = 1 } = 2
} => Restaurant.total_sales = 5
}
run { Restaurant.total_sales = 5 }
Constant sig values
Another way you might want to use this is to have the value associated with each type of Meal be constant, but allow the number of Meals to vary. You can model this with a relation mapping each meal type to a number of sales as follows.
one sig Restaurant { total_sales: Int }
abstract sig Meal {}
lone sig Breakfast, Lunch, Dinner in Meal {}
// Each meal only falls in one category
fact { disj[Breakfast, Lunch, Dinner] }
// Every meal is in some category
fact { Breakfast + Lunch + Dinner = Meal }
fun meal_sales: Meal -> Int {
Breakfast -> 2
+ Lunch -> 2
+ Dinner -> 3
}
fun sum_sales: Int { sum m: Meal | m.meal_sales }
fact { Restaurant.total_sales = sum_sales }
check { #Meal = 3 => Restaurant.total_sales = 6 }
run { Restaurant.total_sales = 5 }

Predicate not consistent

I have to realize an application which permits to reserve a seat in a store. There are no sintax error, but I don't understand why terminal reply me "predicate not consistent". Can u help me?
This is my code:
open util/integer
sig Email{}
sig CF{}
sig Time{
hour: one Int,
minute:one Int,
second: one Int
}
abstract sig RegisteredUser{
email: one Email
}
sig User extends RegisteredUser{
cf: one CF
}
sig SM extends RegisteredUser{
cf: one CF,
store: one Store
}
sig Location{}
sig Date{}
abstract sig Status {}
//only one of this can be true
one sig Waiting extends Status {}
one sig Expired extends Status{}
one sig Pending extends Status{}
sig Ticket{
owner:one User,
date: one Date,
time: one Time,
status : one Status,
}
sig Visit{
owner:one User,
date: one Date,
time: one Time,
duration:one Time,
status : one Status,
products: some Product,
category: some Category,
}
//tickets are assumed with a default duration time of 15 min and entrance one for time, so 4*8=32 visit per day
sig TicketQueue {
max_visit:one Int,
ticket: some Ticket,
manager: one SM
}
sig VisitQueue{
category: some Category,
visit: some Visit,
manager: one SM
}
sig Store{
max_simultaneous: one Int,
location: one Location,
visitqueue: one VisitQueue,
ticketqueue: one TicketQueue,
product_category: some Category
}
sig Category{
simultaneous_seats: one Int,
}
sig Product{
category: one Category
}
// Constraints
// Registration data for the system are unique(Unique username and Fiscal Code)
fact registrationDataUniqueness {
no disjoint u1, u2: RegisteredUser | u1.email = u2.email
no disjoint u1,u2: User | u1.cf = u2.cf
no disjoint s1,s2: SM | s1.cf = s2.cf
no disjoint s:SM, u:User | s.cf=u.cf
}
//Ticket and Visit can have only one of status' values defined before
fact requestConsistency {
all s: Status | (s = Waiting && s != Expired && s !=Pending ) || (s != Waiting && s = Expired && s != Pending) || (s !=Waiting && s != Expired && s = Pending)
}
//SM can manage only one Store
fact StoreUniqueness{
no disjoint s1,s2: SM |s1.store=s2.store
}
// the same ticket or visit cannot be of two or more different user
fact UserUniqueness{
no disjoint t1,t2: Ticket | t1.owner=t2.owner
no disjoint v1,v2: Visit | v1.owner=v2.owner
}
//different products can not be of the same category
fact CategoryUniqueness{
no disjoint p1,p2: Product | p1.category=p2.category
}
//different stores can't have the same ticket or visit queue
fact QueueUniqueness{
no disjoint s1,s2: Store | s1.ticketqueue=s2.ticketqueue
no disjoint s1,s2: Store | s1.visitqueue=s2.visitqueue
}
//different tickets cannot have the same time
fact TimeUniqueness{
no disjoint t1,t2: Ticket | t1.time = t2.time
}
//for semplicity,in the visit/ticket queue, we consider "active" only visit/ticket with Waiting status
fact StatusQueue{
all tq:TicketQueue | tq.ticket.status=Waiting
all vq:VisitQueue | vq.visit.status=Waiting
}
//one ticket/visit can not belong to two or more different queue
fact ReservationUniqueness{
no disjoint tq1,tq2:TicketQueue | tq1.ticket=tq2.ticket
no disjoint vq1,vq2:VisitQueue | vq1.visit=vq2.visit
}
//SM is unique for a specific store, and its related ticket/visit queue
fact SMUniqueness{
no disjoint s1,s2: Store | s1.ticketqueue.manager=s2.ticketqueue.manager
and s1.visitqueue.manager=s2.visitqueue.manager
and s1.ticketqueue.manager=s2.visitqueue.manager
and s1.visitqueue.manager=s2.ticketqueue.manager
}
//different tickets/visits associated with the same user have different time
fact UniqueTimeUser {
all u: User, t1, t2: Ticket, v1,v2:Visit | ((u in t1.owner) and (u in t2.owner) and (u in v1.owner) and (u in v2.owner)
and (t1 != t2) and (v1 !=v2))
implies (t1.time != t2.time)
and (v1.time != v2.time)
}
//different ticket and visit associated with the same user have different time
fact UniqueTimeUser2 {
all u: User, t: Ticket, v:Visit | ((u in t.owner) and (u in v.owner) )
implies (v.time != t.time)
}
//Maximum number of visit with the same time for category
fact MaxTime{
all v:Visit, c: Category |(( c in v.category)) implies #v.time< c.simultaneous_seats
}
//Considering meaningfull integer value
fact PossibleValues{
all c: Category | c.simultaneous_seats>1 and c.simultaneous_seats<5
all s: Store | s.max_simultaneous >0 and s.max_simultaneous<50
all t: Ticket | t.time.hour>7 and t.time.hour<21 and ((t.time.minute=15) || (t.time.minute=30) || (t.time.minute=45)) and t.time.second=0
all v: Visit | v.time.hour>7 and v.time.hour<21 and ((v.time.minute=15) || (v.time.minute=30) || (v.time.minute=45)) and v.time.second=0 and v.duration.hour=0 and v.duration.minute>0 and v.duration.minute=<30 and v.duration.second=0
all tq: TicketQueue | tq.max_visit=32
}
pred addTicket[ t :Ticket,ti,ti':Time, tq, tq':TicketQueue]{
//precondition
ti' not in Ticket.time
#tq.ticket< tq.max_visit //seats available
//postconditions
tq'.manager= tq.manager
tq'.ticket= tq.ticket+t
t in tq'.ticket
#tq'.ticket< tq.max_visit
all t': Ticket | t' in tq.ticket implies t' in tq'.ticket
}
pred show{
#User = 4
#Store = 2
#SM = 2
#Category = 3
#TicketQueue = 2
#VisitQueue= 2
#Category = 5
some v, v': Visit | v.time != v'.time
#Ticket = 5
#Visit=5
}
run show for 4
This is the complete response of Alloy terminal:
Executing "Run show for 4"
Solver=sat4j Bitwidth=4 MaxSeq=4 SkolemDepth=1 Symmetry=20
15098 vars. 840 primary vars. 17697 clauses. 28ms.
No instance found. Predicate may be inconsistent. 1ms.
Have you run unsat core (using the MiniSAT with Unsat Core solver)? That might give you a hint. Another thought: I would simplify the model first and then only add features as you need them. I'm not sure that you really need to split the times into hours, minutes and seconds. That adds a lot of solver complexity, perhaps needlessly.
General observations:
Some inconsistences in your show predicate:
#Category = 3
#Category = 5
Your scope is definitely too small. You can't expect 5 Visit elements if you have a general scope of 4.
I'd rewrite your show predicate and run command as follows:
pred show{
some v, v': Visit | v.time != v'.time
}
run show for 10 but 7 Int, exactly 4 User, exactly 2 Store, exactly 2 SM, exactly 3 Category, exactly 2 TicketQueue, exactly 2 VisitQueue, exactly 5 Ticket, exactly 5 Visit
Notice the 7 Int.
It means that your model will contain int type atoms that represent all the integers you can express with a bitwidth of 7 (interval is [-64,63]).
As Daniel wrote, i'd also advise to stay as abstract as possible when you model in Alloy and thus to prefer concepts over quantitative values.
I concur with the previous advice of simplifying and would add to use check statements to test as you go. I'm not an expert with Alloy, so I take it slow and test early and often.
One thing that sticks out to me immediately is that your "show" predicate seems to be specifying multiplicities for some signatures that are greater than those allowed by the run statement ("for 4"). I've never specified multiplicity in a predicate that way, so I don't know how Alloy handles that. Offhand, those seem like contradictory constraints.
Also, I figured this out the hard way, but Alloy counts instances (atoms) of extended signatures as instances (atoms) of the parent(s). So, be aware of that.

How to express Nothing else in the set?

[Update] I spent a lot of time studying #Hovercouch's fantastic solution (see his solution below). I took his solution, along with Peter Krien's insights and wrote up a summary: 3 ways to model the set of non-negative even numbers. I welcome your comments.
I am trying to create an Alloy model that defines a set of integers. I want to constrain the set to the integers 0, 2, 4, ...
I want to use a "generative" approach to defining the set:
0 is in the set.
If i is in the set, then i+2 is in the set.
Nothing else is in the set.
I am struggling with the last one - nothing else is in the set. How do I express that?
Below is the Alloy model that I created.
one sig PositiveEven {
elements: set Int
}
pred generate_set_members {
0 in PositiveEven.elements
all i: Int | i in PositiveEven.elements => i.plus[2] in PositiveEven.elements
// Nothing else is in the set - How to express this?
}
The simplest way to do this would be to create a relationship that maps each number N to N+2, and then take the reflexive-transitive closure of that relationship over 0.
one sig PositiveEven {
elements: set Int
}
one sig Generator {
rel: Int -> Int
} {
all i: Int | i.rel = i.next.next
}
pred generate_set_members {
PositiveEven.elements = 0.*(Generator.rel)
}
assert only_positive_elements {
generate_set_members =>
all i: Int | i in PositiveEven.elements <=> i >= 0 and i.rem[2] = 0
}
Note that you cannot use i.plus[2] instead of i.next.next, because Alloy integers overflow to negative.
What do you think of this:
let iset[min,max,step] = { i : Int |
i>= min
and i<max
and i.minus[min].div[step].mul[step]
= i.minus[min] }
pred show[ s : set Int ] {
iset[ 0, 10, 2 ] = s
}
run show for 0 but 8 int
The visualiser does not show the Int types so look in the Tree or Text view.

How to define Heap datastructure in Alloy (Homework)

As a homework, I have to define a heap data structure in Alloy.
I have come up with these rules
A node can have up to 1 father, left-son, right-son, left-brother and right-brother. It also has exactly 1 value and 1 level (as in how deep in the heap it is).
A node can have right-son if it has left-son.
A node cannot be in transitive closure over any of its relations (father, left-son, right-son, left-brother, right-brother).
The relations have to point to distinct nodes.
A node has a value and values must belong to a node.
A node's value must be less than the node's sons' values.
If a node has left-son and not left-brother, then the rightmost brother of its father has a right-son.
Node is its left-brother's right-brother and so on for all its relations.
Node's father's level is one less than node's level.
If there is a node with level two less, then all the nodes with that level must have both sons.
For any 2 nodes m, n that have the same level, m must be in transitive closure over left-brother of n, or in transitive closure over right-brother.
The question is twofold
A) I am not sure whether these rules are sufficient, or whether there is a better way to solve this altogether. (I think I could just resolve this all by having node consist of index and a value and transcribe heap-in-array algorithm into Alloy, but that seems rather inelegant.)
B) I have trouble implementing some of these rules.
I have implemented rules 1, 2, 3, 4, 5, 6, 7, 8 and 9. At least I think I did, and the generated graph does not contradict my expectations.
I do not know how to implement the last 2.
Also, the code I have so far:
open util/ordering [Key] as KO
open util/ordering [Level] as LO
sig Key{}
sig Level{}
sig Node {
key: one Key,
level: one Level,
father: lone Node,
left_brother: lone Node,
right_brother: lone Node,
left_son: lone Node,
right_son: lone Node
}
// There's exactly one root
fact {
one n : Node | n.father = none
}
// Every key has to belong to some node
fact {
all k : Key | some n:Node | n.key = k
}
fact {
all n : Node | (n.left_son != none && n.right_son != none) => #(KO/nexts[n.key] & (n.left_son.key + n.right_son.key)) = 2
}
// Son's father's son shall be Son etc
fact {
all n : Node | all m : Node | (n.left_son = m) => m.father = n
}
fact {
all n : Node | all m : Node | (n.right_son = m) => m.father = n
}
fact {
all n : Node | all m : Node | (m.father = n) => (n.left_son = m || n.right_son = m)
}
// Is this redundant?
fact {
all n : Node | all m : Node | (n.left_brother = m) => (m.right_brother = n)
}
fact {
all n : Node | all m : Node | (n.right_brother = m) => (m.left_brother = n)
}
// If a node has right-son, it must have a left-son.
fact {
all n : Node | (n.right_son != none) => (n.left_son != none)
}
// node having left son and left brother means that his left brother has a right son
fact {
all n: Node | (n.left_son != none && n.left_brother != none) => (n.left_brother.right_son != none)
}
// nodes father must be a level higher.
fact {
all n : Node | (n.father != none) => (LO/prev[n.level] = n.father.level)
}
// FIXME: this is wrong: There needs to be difference of 2 levels, not just a single level.
fact {
all n : Node | all m : Node | (LO/prevs[m.level] & n.level = n.level) => (n.left_son != none && n.right_son != none)
}
// TODO: If 2 nodes are in the same level, then they must be in left-brother* or right-brother* relation
// ????
// No node can be its own father
fact {
all n : Node | n.father != n
}
// No node can be in transitive closure over its ancestors
fact {
no n : Node | n in n.^father
}
// No node cannot be its own brother, son, etc...
fact {
all n: Node | n.left_brother != n
}
// Nor in its transitive closure
fact {
no n: Node | n in n.^left_brother
}
fact {
all n: Node | n.right_brother != n
}
fact {
no n: Node | n in n.^right_brother
}
fact {
all n: Node | n.left_brother != n
}
fact {
no n: Node | n in n.^left_brother
}
fact {
all n: Node | n.right_son != n
}
fact {
no n: Node | n in n.^right_son
}
fact {
all n: Node | n.left_son != n
}
fact {
no n: Node | n in n.^left_son
}
// All node relatives have to be distinct
fact {
all n: Node | n.left_son & n.right_son = none && n.left_brother & n.right_brother = none && (n.left_brother + n.right_brother) & (n.left_son + n.right_son) = none
&& (n.right_son + n.left_son + n.left_brother + n.right_brother) & n.father = none
}
run{}
For 10. something along the lines of
all m : Node | some father.father.m implies some m.left and m.right
would work, which is equivalent to
fact {
all m, n : Node | (n.father.father != none && n.father.father.level = m.level) => (m.left_son != none && m.right_son != none)
}
For 11., you can formulate it quite straightforwardly from the textual definition (of course, with using appropriate operators, namely for transitive closure).
As a general suggestion, try not to formulate such direct questions about homework problems (see this discussion). Since this answer comes pretty late, I think it's fine to try to give you some hints.

Creating an object for each relation in Alloy

I have the following def. in Alloy:
sig A {b : set B}
sig B{}
sig Q {s: A , t: B}
I want to add a set of constraints such that for each relation b1:b there exists one and only one Q1:Q where Q1.s and Q1.t refers to the source and target of b1, respectively. For example, if I have an instance which contains A1 and B1 and b1 connects them (i.e., b1: A1->B1), then I also would like to have a Q1 where Q1.s=A1 and Q1.t=B1.
Obviously number (cardinality) of Q is equal to number (cardinality) of b relation.
I managed to write such a constraint as bellow:
t in s.b
all q1,q2:Q | q1.s=q2.s and q1.t=q2.t => q1=q2
all a1:A,b1:B | a1->b1 in b => some q:Q | q.s=a1 and q.t=b1
I am wondering if anyone has a bit more concise way to express my intentions in terms of an alloy fact. I am open to use Alloy util package if it makes life easier.
Thanks
sig A { b : set B }
sig B {}
sig Q { ab : A -> B }{ one ab }
fact { b = Q.ab and #Q = #b }
I would complete the #user1513683 answer by adding two relations s and t to make it the complete answer to the question:
sig A { b : set B }
sig B {}
sig Q { ab : A -> B , s:A, t:B}{ one ab and t=ab[s]}
fact { b = Q.ab and #Q = #b }

Resources