1 constraints and logic programming all problems involving finite domains (including booleans, and...

53
1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming (LP) alone. (after all, finite domains are a subset of the Herbrand Universe: constants). Why should one move towards Constraint Programming (CP), rather than staying within LP? Greater Efficiency: Most combinatorial problems are more easily solved by constraint propagation than simple generate and test implememted in LP. Greater Expressiveness: Specific constraints are harder to express in LP (e.g. conditional constraints, global constraints).

Upload: internet

Post on 17-Apr-2015

124 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

1

Constraints and Logic Programming

• All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming (LP) alone.

(after all, finite domains are a subset of the Herbrand Universe: constants).

• Why should one move towards Constraint Programming (CP), rather than staying within LP?

– Greater Efficiency:

• Most combinatorial problems are more easily solved by constraint propagation than simple generate and test implememted in LP.

– Greater Expressiveness:

• Specific constraints are harder to express in LP (e.g. conditional constraints, global constraints).

Page 2: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

2

Constraints and Logic Programming

• If propagation of constraints is so important for solving constraint (satisfaction / optimisation) problems why not to abandon LP altogether and move towards Constraint Logic Programming (CLP).

– Modelling - Declarativeness

• LP features such as unification (allowing flexible input/output parameters) and backtracking provide a declarative style of programming where constraints can be very easily expressed.

– Natural extension:

• The semantics of LP already assume a special type of constraint processing – equality of Herbrand terms.

• All that CLP requires is an extension of this constraint solving capabilities to other useful domains.

Page 3: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

3

Operational Semantics of CLP

• The operational semantics of CLP (LP is a special case) can be described as a transition system on states.

• The state of a constraint solving system can be abstracted by a tuple

<G, C, S > where

– G is a set of constraints (goals) to solve– C is the set of active constraints– S is a set of passive constraints

• Sets C, S are considered the Constraint Store.

• A derivation is just a sequence of transitions.

• A state that cannot be rewritten is a final state.

• An executor of CLP (LP) aims at finding successful final states of derivations starting with a query.

Page 4: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

4

Operational Semantics of CLP

• A derivation is failed if it is finite and its final state is fail.

• A derivation is successful if it is finite and processes all the constraints, i.e. it ends in a state with form

<Ø, C, S >

• The state transitions are the following

S(elect): Select a goal (constraint)

• It is assumed that

– A computation rule selects some goal g, among those still to be considered.

– This goal requires some constraint c to be solved and/or further goals, G’, to be considered

g requires solving constraint c and other goals G’

< G {g}, C, S > s < G G’,C, S {c} >

Page 5: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

5

Operational Semantics of CLP

• The other transition rules require the existence of two functions, infer(C,S) and consistent(C), adequate to the domains that are considered.

• I(nfer): Process a constraint, inferring its consequences

• C(heck): Check teh consistency of the Store

(C’, S’) = infer(C,S)

< G, C, S > i < G, C’, S’ >

consistent (C)

< G, C, S > c < G, C, S >

¬ consistent (C)

< G, C, S > c fail

Page 6: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

6

Operational Semantics of CLP

In Logic Programming

• Handling a goal g is simply checking whether there is a clause h ← B whose head h matches the goal. In this case, the equality constraint between Herbrand terms g=h is added to the passive store.

• Function infer(C,S) performs unification of the terms included in g and h, after applying all substitutions included in C

function infer(C, g=h)if unify(g↑C,h↑C, C’) then infer=(success,

C’)else infer = (fail,_);

end function

• Checking consistency is simply checking whether the previous unification has returned success or failure (in practice the two functions are of course merged).

g is a goal h B < G {g}, C, S > s < G B, C, S {h = g} >

Page 7: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

7

Operational Semantics of CLP• For example, assuming that

– C = {X / f(Z), Y / g(Z,W)} % a solved form

– G includes goal p(Z,W)

– there is a clause p(a,b) :- B.

then the following transitions take place, when goal p(Z,W) is “called”

< G , {X/f(Z), Y/g(Z,W)}, {} >

→s % goal selection

< G\{g}B, {X/f(Z), Y/g(Z,W)}, {p(Z,W) = p(a,b)}} >

→i,c % unification

< G\{g}B, {X/f(a), Y/g(a,b), Z/a, W/b}, {} >

Page 8: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

8

Operational Semantics of CLP

In Constraint Logic Programming

• Handling a goal g is as before. Handling a constraint in a certain domain, usually built-in, simply places the constraint in set S.

.

• Function infer(C,S) propagates the constraint to the active store, by methods that depend on the constraint system used. Tipically,

– It attempts to reduce the values in the domains of the variables; or

– obtain a new solved form (like in unification)

• Checking consistency also depends on the constraint system.

– It checks whether a domain has become empty; or

– It was not possible to obtain a solved form.

g is a constraint< G {g}, C, S > s < G, C, S {g} >

Page 9: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

9

Operational Semantics of CLP

A positive example

• Assuming that variables A and B can take values in 1..3, then the constraint store may be represented as

C,S = {A in 1..3, B in 1..3}, { }

• Rule S: If the constraint selected by rule S is A > B, then the store becomes

C,S = {A in 1..3, B in 1..3}, { A > B}

• Rule I: The Infer rule propagates this constraint to the active store, which becomes

C,S = {A in 2..3, B in 1..2, A > B}, { }

• Rule C: The system does not find any inconsitency in the active store, so the system does not change..

Page 10: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

10

Operational Semantics of CLP

A negative example

• Assuming that variables A and B can take, respectively values in the sets {1,3,5} and {2,4,6}. The constraint store may be represented as

C,S = { A in {1,3,5} B in {2,4,6}, { }

• Rule S: If the constraint selected by rule S is A = B, the store becomes

C,S = { A in {1,3,5} B in {2,4,6} }, { A = B }

• Rule I: The rule propagates this constraint to the active store. Since no values are common to A and B, their domains become empty

C,S = {A in {}, B in {} }, { }

• Rule C: This rule finds the empty domains and makes the transition to fail (signaling the system to backtrack in order to find alternative successful derivations).

Page 11: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

11

(C)LP solutions

• In LP and CLP, solutions are obtained, by inspecting the constraint store of the final state of a successful derivation.

• In systems that maintain a solved form, (like LP, but also constraint systems CLP(B) for booleans, and CLP(Q), for rationals), solutions are obtained by projection of the store to the relevant variables.

For example if the initial goal was p(X,Y) and the final store is

{X/f(Z,a), Y/g(a,b), W/c}

then the solution is the projection to variables X and Y

{X/f(Z,a), Y/g(a,b), W/c}

• In systems where a solved form is not maintained, solutions require some form of enumeration. For example, from

C = {X in 2..3, Y in 1..2, X > Y},

the solutions <X=2;Y=1>, <X=3;Y=1> and <X=3;Y=1>, are obtained by enumeration.

Page 12: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

12

Restrições Booleanas

• O domínio dos Booleanos (ou variáveis 0/1) tem especial aplicação em aplicações

– Envolvendo circuitos digitais

• Exemplo: Circuito semi-somador

– Em problemas envolvendo escolhas binárias

• Exemplo: Rainhas

– Em problemas que envolvam conjuntos

B

G1

G2

AC

S

Page 13: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

13

Restrições Booleanas

• Nas restrições booleanas (de igualdade) podem ser utilizadas os habituais operadores (not, and, or, nand, nor, xor, ...).

Modelo do semi-somador

C = and(A,B)

S = xor(A,B)

B

G1

G2

AC

S

Page 14: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

14

Restrições Booleanas

• As restrições (correspondentes às variáveis Booleanas) podem ser igualmente expressas com esses operadores

Modelo das 4-rainhas

or(Q1, Q2, Q3, Q4) % Linha 1

and(Q1,Q2) = 0 % Linha 1

....

and(Q1, Q6) = 0 % Diagonal

Q1 Q2 Q3 Q4

Q5 Q6 Q7 Q8

Q9 Q10 Q11 Q12

Q13 Q14 Q15 Q16

Page 15: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

15

Restrições Booleanas

• A satisfação de restrições booleanas pode ser abordada de várias formas diferentes

– Simbolicamente

• Unificação booleana

– SAT

• Colocação de todas as restrições na forma clausal

• Resolução construtiva (retrocesso) ou reparativa (pesquisa local)

– Domínios finitos

• O domínio 0/1 é um domínio finito com 2 valores

• Resolução comum aos domínios finitos

Page 16: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

16

Restrições Booleanas

• Para verificar a satisfação de restrições booleanas de uma forma simbólica é conveniente converter todas as restrições de forma a usar apenas,

– os operadores

+ (ou-exclusivo) e · (conjunção),

– constantes booleanas

0 e 1 ( e outras constantes, dependentes do domínio)

– variáveis

denotadas por letras maiúsculas

• Isto é sempre possível, já que o conjunto {0, 1, +, ·} é completo.

Page 17: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

17

Restrições Booleanas

• Com efeito, dados os termos arbitrários a e b, todos os operadores e constantes podem ser expressos através destes operadores

a b = a · b

a b = a + b + a · b

a = 1 + a

a b = 1 + a + a · b

a b = 1 + a + b

• Termos arbitrários serão denotados por minúsculas

Page 18: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

18

Restrições Booleanas

• Mais formalmente, o tuplo < A, 0, 1, +, · >, em que A é um qualquer domínio (contendo os elementos 0 e 1), constitui um anel booleano se se verificarem as seguintes propriedades

• Associatividadea+(b+c) = (a+b)+c a·(b·c) = (a·b)·c

• Comutatividadea + b = b + a a·b = b·a

• Distribuição a+(b·c) = (a+b)·(a+c) a·(b+c) = a·b+a·c

• Elemento Neutroa+0 = a a·1 = a

• Exclusividade e Idempotência a+a = 0 a·a = a

• Elemento Absorventea·0 = 0

Page 19: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

19

Restrições Booleanas

• As restrições booleanas que consideraremos resumem-se à igualdade, já que todas as outras se podem exprimir em função da igualdade.

• Por exemplo, dada a equivalência

a b a b = a a b = b a restrição de inclusão de conjuntos acima pode ser reescrita em termos de igualdade como

a + b + a·b = b

a + b + b + a·b = b + b

a + a·b = 0

a·b = a

Page 20: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

20

Restrições Booleanas

• Conjuntos

– A constante 1 corresponde ao conjunto U (Universal)

– A constante 0 corresponde ao conjunto Ø (Vazio)

– O operador + corresponde à União Exclusiva

– O operador · corresponde à Intersecção

• De notar que no caso de conjuntos, uma vez definido os elementos que contém o conjunto universal, para além das constantes 0 e 1, o domínio A contém todos os subconjuntos de U.

Page 21: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

21

Restrições Booleanas• Circuitos digitais

– A constante 1 corresponde ao H– A constante 0 corresponde ao L– O operador + corresponde ao XOR– O operador · corresponde ao AND

A

C

D

B

E

F

G

H

I

G1

G2

G3

G4

G5

• E = A + B +A·B

• F = 1 +B·C• G = C·D• H = 1 + E·F• I = 1 + F·G

Page 22: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

22

Unificação Booleana• A implementação de CLP(B) mantem as restrições numa forma

resolvida, obtida através da unificação booleana.

• Uma restrição booleana tem a forma t1 = t2 (em que os dois

termos Booleanos, t1 e t2 são formados exclusivamente a partir dos

operadores + e ·.

• A restrição booleana t1 = t2 pode ser satisfeita sse existir um

unificador booleano para os dois termos t1 e t2.

• Um unificador booleano é uma substituição de variáveis por termos booleanos que garante que os dois termos tomam o mesmo valor booleano.

• Os unificadores booleanos serão designados através de letras gregas.

Page 23: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

23

Unificação Booleana

 • Exemplo: Os termos t1=1+A e t2 = A·B podem ser unificados

com o unificador

= {A/1, B/0}

• Com efeito, denotando por t (ou simplesmente t) a aplicação da

substituição ao termo t, temos

t1 = (1+A){A/1, B/0}= 1 + 1 = 0

t2 = (A·B){A/1, B/0}= 1 · 0 = 0

o que garante a satisfação da restrição de igualdade t1 = t2.

Page 24: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

24

Unificação Booleana• Em geral, dados dois termos Booleanos, t1 e t2, pode haver mais do

que um unificador mais geral.

• Exemplo: A unificação dos termos t1 = 1 + A·B e t2= C + D pode ser obtida por qualquer um dos seguintes unificadores mais gerais

1 = { C / 1 + A·B + D}

2 = { D / 1 + A·B + C}

3 = { A / 1 + C + D, B / 1}

4 = { A / 1, B / 1 + C + D}

• Com efeito,

t1 1 = (1+A·B){C/1+A·B+D} = 1+A·Bt2 1 = (C+D){C/1+A·B+D}=(1+A·B+D)+D = 1+A·Be

t1 2 = (1+A·B){D/1+A·B+C} = 1+A·Bt2 2 = (C+D){D/1+A·B+C}= C+(1+A·B+C) = 1+A·B

Page 25: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

25

Unificação Booleana• Existem outros unificadores (menos gerais) que podem ser obtidos

através de instâncias dos anteriores, isto é, da composição de unificadores mais gerais com outras substituições.

• Por exemplo, a substituição λ obtida pela composição de 1 com a

substituição {A/0}

λ = {C/1+A·B+D } o {A / 0}

= {C/1+D, A/0}

ainda é um unificador dos termos t1=1+A·B e t2=C+D

t1 λ = (1+A·B) {C/1+D, A/0} = 1+0·B = 1

t2 λ = (C+D) {C/1+D, A/0} = (1+D+D) = 1

Page 26: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

26

Algoritmo de Unificação Booleana

• Tendo em atenção que a restrição t1 = t2 é equivalente a t1+t2=0,

a unificação dos termos t1 e t2 equivale a anular o termo t1+t2.

• As condições em que um termo t se pode anular, podem ser analisadas através dos pontos seguintes.

1. O anulamento de um termo constante t é trivialmente verificável:

1. se t = 0 o termo já é nulo;

2. se t = 1 o termo não é anulável.

• Dada a propriedade distributiva, um termo t, não constante, pode sempre ser reescrito na forma a·U+b (em que U é uma qualquer das variáveis que ocorrem em t) pondo U “em evidência”.

Page 27: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

27

Algoritmo de Unificação Booleana

3. Um termo t = a·U + b só se pode anular, se tivermos ou a = 1 ou b = 0 (na situação contrária, em que fosse a = 0 e b = 1, teríamos t = 1 0, independentemente do valor de U).

4. Essa condição (a = 1 ou b = 0) é garantida se e só se anular o termo (1 + a)·b.

5. Uma vez garantida esta condição, constata-se que

– se a = 0 (e b = 0), então a variável U pode tomar um valor arbitrário (pois 0 = 0·U + 0)

– se a = 1, então a variável U tem de tomar o valor b (pois neste caso temos 0 = 1·U + b)

Page 28: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

28

Algoritmo de Unificação Booleana

6. A atribuição de valores a U nestes termos pode ser implementada com o recurso a uma nova variável booleana, (isto é, que não ocorra em t). Chamando _U a essa variável a condição anterior é equivalente à substituição

U = (1+a)·_U + b

7. Com efeito,

• se a = 0 (e b = 0 ) temos U = _U, ou seja U pode tomar um valor arbitrário, já que a variável _U, sendo uma variável nova, não está associada a quaisquer restrições;

• Se a = 1 temos U = (1+1)·_U + b, ou seja U = b, como

pretendido.

Page 29: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

29

Algoritmo de Unificação Booleana

• Estas considerações podem ser materializadas no predicado unif_bool, especificado abaixo.

• O predicado recebe os termos t1 e t2 a unificar, e sucede se o

predicado anula suceder, retornando a substituição retornada por este predicado.

predicado unif_bool(in: t1, t2; out: );

t t1 + t2;

unif_bool anula(t,);fim predicado.

• Passemos agora à implementação do predicado anula.

Page 30: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

30

Algoritmo de Unificação Booleana

predicado anula (in: t; out: );caso t = 0: anula = Verdade, = {};caso t = 1: anula = Falso;caso contrário:

A·u + B t; s (1+A)·B;

se anula(s,σ) entãoanula Verdade; {U/(1+A)·_U+B} o σ

senãoanula = Falso

fim sefim caso

fim predicado.

Page 31: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

31

Algoritmo de Unificação Booleana

{U/(1+A)·_U+B} o σ

• De notar que a substituição retornada pelo predicado anula é obtida pela composição das substituições {U/(1+A)·U+B} e σ obtida na chamada recursiva do predicado (se este suceder).

• Exemplo: Satisfazer a restrição X + X·Z = Y·Z + 1  Unifica X+X·Z e Y·Z+1

anula X+X·Z+Y·Z+1 = (1+Z)·X+Y·Z+1 % Ax·X+Bx

anula (1+(1+Z))·(Y·Z+1) % (1+Ax)·Bx

= Z·(Y·Z+1) = Z·Y+Z % Ay·X+By

anula (1+Z)·Z %(1+Ay)·By

= 0

Page 32: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

32

Algoritmo de Unificação Booleana

Unifica X+X·Z e Y·Z+1

anula X+X·Z+Y·Z+1 = (1+Z)·X+Y·Z+1

anula (1+(1+Z))·(Y·Z+1)=Z·Y+Z %(1+Ax)·Bx

anula (1+Z)·Z = 0 %(1+Ay)·By

σz = {}

σy = {Y/(1+Ay)·_Y+By} o σz

= {Y/(1+Z) ·_Y+Z} o {}

= {Y/(1+Z) ·_Y+Z}

σx = {X/(1+Ax)·_Y+Bx} o σy

= {X/(1+1+Z)·_X + Y·Z+1} o {Y/(1+Z)·_Y+Z}

= {X/ Z·_X +Y·Z+1} o {Y/(1+Z)·_Y+Z}

= {X/ Z·_X +((1+Z)·_Y+Z)·Z+1, Y/(1+Z)·_Y+Z}

= {X/ Z·_X +Z+1, Y/(1+Z)·_Y+Z}

= {X/ Z·_X +Z+1, Y/(1+Z)·_Y+Z}

Page 33: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

33

Restrições Booleanas

• Desta forma a restrição X+X·Z = Y·Z+1 é satisfazível, já que a unificação dos termos X+X·Z e Y·Z+1 sucede retornando o unificador booleano mais geral

= {X/Z·_X +Z+1, Y/(1+Z)·_Y+Z}

• Podemos confirmar este resultado, verificando que

(X+X·Z) = (Z·_X+Z+1)+(Z·_X+Z+1)·Z

= (Z·_X+Z+1)+Z·_X

= Z+1

e que

(Y·Z+1) = ((1+Z)·_Y+Z)·Z+1)

= Z+1

Page 34: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

34

Restrições Booleanas

= {X/Z·_X +Z+1, Y/(1+Z)·_Y+Z}

• Podemos pois concluir que a restrição X + X·Z = Y·Z + 1 pode ser satisfeita independentemente do valor da variável Z, dado que o unificador mais geral não a menciona)

• Numa análise mais pormenorizada

– se Z=0 então X = 1 e Y =_Y (i.e. Y pode tomar qualquer valor)

– se Z=1 então X =_X e Y = 1 (i.e. X pode tomar qualquer valor)

• O unificador tem pois como instâncias fechadas (ground), os unificadores {X/1, Y/0, Z/0}, {X/1, Y/1, Z/0}, {X/0, Y/1, Z/1}, {X/1, Y/1, Z/1},

Page 35: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

35

Aplicações

• Um domínio de eleição para a utilização de restrições booleanas é o domínio dos circuitos digitais.

• Exemplo:

1. Modelar o circuito abaixo através de um conjunto de restrições booleanas

2. Verificar em que condições a saída toma o valor 1.

CG1FG4

DG2

EG3

B

A

R1: C = 1 + A·B

R2: D = 1 + A·C

R3: E = 1 + B·C

R4: F = 1 + D·E

Page 36: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

36

Aplicações1. Restrições que modelam o circuito

R1: C = 1 + A·B R2: D = 1 + A·C

R3: E = 1 + B·C R4: F = 1 + D·E

Resolução das Restrições

R1: Resolvendo R1 obtemos a substituição 1

C = 1 + A·B 1 ={C / 1 + A·B}

R2: Aplicando 1 temos

R2’: R2 1 : D = (1+A·C){C/1+A·B}

D = (1+A·(1+A·B))

D = 1 + A + A·B

Resolvendo esta restrição obtemos a substituição

’2 = {D / 1 + A + A·B}

Page 37: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

37

Aplicações

Compondo 2’ com 1

obtemos

2 = 1

o 2’

= {C/1+A·B} o {D/1+A+A·B}

= {C/1+A·B, D/1+A+A·B}

R3: Aplicando 2 temos

R3’: R3 2 : E = (1+B·C) {D/1+A+A·B, C/1+A·B}: E = 1+B·(1+A·B): E = 1+B·(1+A·B)

Resolvendo R3’ obtemos a substituição

3’ = {E/1+B+A·B}

Compondo 3’ com 2 obtemos

3 = 2

o 3’

= {E/1+B+A·B} o {D/1+A+A·B} o {C/1+A·B}

= {E/1+B+A·B, D/1+A+A·B, C/1+A·B}

Page 38: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

38

AplicaçõesR4: Aplicando 3 temos

R4’: R4 3

: F = (1+D·E) {E/1+B+A·B, D/1+A+A·B, C/1+A·B}

: F = 1+(1+A+A·B)·(1+B+A·B)

: F = 1+1+B+A·B+A+A·B+A·B+A·B+A·B+A·B

: F = A + B

Resolvendo R4’ obtemos a substituição

4’ = {F/A+B}

Combinando 4’ com 3

obtemos

4 = 3

o 4’

= {E/1+B+A·B, D/1+A+A·B, C/1+A·B}o{F/A+B}

= {E/1+B+A·B, D/1+A+A·B, C/1+A·B, F/A+B}

Interpretando 4 concluímos que o circuito com 4 portas nand implementa

um ou-exclusivo, já que F / A + B.

Page 39: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

39

Aplicações2. Que entradas impõe a saída igual a 1

Para representar esta situação acrescenta-se a restrição R5: F = 1.

R5: Aplicando 4 temos

R5’ :R5 4

:(F = 1) {E/1+B+A·B, D/1+A+A·B, C/1+A·B, F/A+B}

: A+B = 1

Resolvendo R5’ obtem-se a substituição 5’ = {A/1+B}. Compondo esta

substituição 5’ com 4

obtem-se

5 = 4 o 5

= {E/1+B+A·B, D/1+A+A·B, C/1+A·B, F/A+B}o{A/1+B}

= {E/1+B, D/B, C/1, F/1, A/1+B}

De 5, e em particular do par A/1+B, conclui-se que para o circuito ter uma

saída 1, as suas entradas devem ser complementares, i.e. ou A=0 e B=1 ou A=0 e B=1

Page 40: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

40

Restrições Booleanas no SICStus Prolog

Uma vez carregado o SICStus Prolog o módulo de Restrições Booleanas, através da directiva

 :- use_module(library(clpb)).

As restrições Booleanas podem ser verificadas através do predicado sat(E) , em que a igualdade é representada por ‘=:=’ e os operadores + e · através de # e *, respectivamente.

 Exemplos:

 1. ?- sat(A#B=:=F).

sat(A=:=B#F)?

% A restrição A+B=F é satisfazível, com a substituição A/B+F

Page 41: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

41

Restrições Booleanas no SICStus Prolog

2. ?- sat(A*B=:=1#C*D). sat(A=\=C*D#B)?  

% A restrição A·B=1+C·D é satisfazível, com substituição A/1+C·D+B

3. ?- sat(A#B=:=1#C*D), sat(C#D=:=B).

sat(B=:=C#D),

sat(A=\=C*D#C#D) ?

% As restrições A+B=1+C·D e B=C+D são satisfeitas com a substituição

{A/1+C·D+C+D, B/C+D} 

 Nota: Atenção à notação das respostas.

A=:= Exp corresponde a A / Exp

A=\= Exp corresponde a A / 1+ Exp

Page 42: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

42

Restrições Booleanas no SICStus Prolog

Um exemplo mais completo, relativo ao circuito anterior

:- use_module(library(clpb)).

nand_gate(X,Y,Z):-

sat(X*Y =:= 1#Z).

circuit(A,B,[C,D,E],F):-

nand_gate(A,B,C),

nand_gate(A,C,D),

nand_gate(B,C,E),

nand_gate(D,E,F).

CG1FG4

DG2

EG3

B

A

Page 43: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

43

Restrições Booleanas no SICStus PrologAlguma interacção com o sistema

| ?- circuit(A,B,[C,D,E],1).C = 1,E = A,sat(B=\=A),sat(D=\=A) ?

Comparando-se esta resposta com 5 anterior

5 = {E/1+B, D/B, C/1, F/1, A/1+B}

constata-se que são ambas “variantes” do unificador mais geral.

CG1

FG4

DG2

EG3

B

A

Page 44: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

44

Restrições Booleanas no SICStus Prolog

Outra interacção| ?- circuit(A,B,[C,D,E],F).

sat(C=:=_A*F#F#_A),sat(A=\=_A*F#_B*F#F#_A),sat(B=\=_A*F#_B*F#_A),sat(D=\=_B*F),sat(E=\=_B*F#F) ? ;

A comparação com 4 anterior é um pouco menos óbvia ...

4 = {E/1+B+A·B, D/1+A+A·B, C/1+A·B, F/A+B}

1+A·B = 1+ (1+_A·F+_B·F+F+_A)· (1+_A·F+_B·F+_A) = 1+((1+_A·F+_B·F+_A)+F)·(1+_A·F+_B·F+_A)

= 1+(1+_A·F+_B·F+_A)+(1+_A·F+_B·F+_A)·F= 1+ 1+_A·F+_B·F+_A + F+_A·F+_B·F+_A·F= F+_A+_A·F= C

CG1

FG4

DG2

EG3

B

A

Page 45: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

45

Restrições Booleanas no SICStus Prolog

Padrões de Teste de Avarias (Stuck-at-0/1) num semi-somador

• Objectivo: Obter uma saída diferente entre– o circuito correcto e – o circuito com falhas

• Definir um predicado tp/2 que dado um conjunto de falhas F indique as entradas que detectam essas falhas

tp(F, [I1, I2])

B

G1

G2

AC

S

Page 46: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

46

Restrições Booleanas no SICStus Prolog

• Primeiro, convem definir o comportamento de cada gate (sem falhas) por intermédio das correspondentes restrições booleanas.

• Uma gate sem falhas é representada por 3 argumentos– 1. Tipo da gate Número de identificação da gate no circuito– 2. Lista de– 3. Saída

gate(or, [I1,I2],Z):- sat(I1+I2 =:= Z).gate(nor, [I1,I2],Z):- sat(I1+I2 =\= Z).gate(xor, [I1,I2],Z):- sat(I1#I2 =:= Z).gate(and, [I1,I2],Z):- sat(I1*I2 =:= Z).gate(nand,[I1,I2],Z):- sat(I1*I2 =\= Z).gate(not,[I1],Z):- sat(I1 =\= Z).

Page 47: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

47

Restrições Booleanas no SICStus Prolog

• Em segundo lugar, é necessário especificar o comportamento de uma gate, incluindo o caso em que ela esteja avariada. Uma gate é representada por 5 argumentos

– 1. Número de identificação da gate no circuito– 2. Lista de falhas no circuito. Cada falha é representada por um par N/B

em que N é o identificador da gate e B o tipo de falha (stuck-at-0 ou stuck-at-1).

– 3. Tipo da gate– 4. Lista de entradas da gate– 5. Saída da gate

gate(N,F,_,_,0):- % a saída é 0, se member(N/0, F), !. % a gate está stuck-at-0

gate(N,F,_,_,1):- % a saída é 1, se member(N/1, F), !. % a gate está stuck-at-1

gate(_,_,T,I,S):- % caso contrário, a gate gate(T,I,S). % tem comportamento normal

Page 48: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

48

Restrições Booleanas no SICStus Prolog

• Em terceiro lugar, há que definir o que é um circuito Semi-somador em termos das suas componentes, que podem naturalmente estar avariadas.

semi_somador(F, [I1,I2],[S,C]):- % F é o conjunto gate(1, F, and, [I1,I2], C), % de falhas gate(2, F, xor, [I1,I2], S).

• O predicado member/2 é o habitual.

member(H,[H|_]).member(H,[_|T]):- member(H,T).

I2

G1

G2

I1C

S

Page 49: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

49

Restrições Booleanas no SICStus Prolog

• Finalmente, há que comparar um circuito com falhas F e um circuito sem falhas, de forma a que uma das saídas, pelo menos, seja diferente.

tp(F, [I1, I2]):- semi_somador([],[I1, I2], [S1,C1]), semi_somador(F, [I1, I2], [S2,C2]), gate(xor, [S1, S2], S), gate(xor, [C1, C2], C), gate(or,[S,C],1).

1[]

F

I1

I2

S2

C2

S1

C1

S

C

Page 50: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

50

Restrições Booleanas no SICStus Prolog

Alguma interacção com o sistema

| ?- tp([1/0],[I1,I2]).I1 = 1,I2 = 1 ? ;no

% A avaria G1 (and) stuck-at-0, é detectada se ambas as entradas forem 1

| ?- tp([1/1],[I1,I2]).sat(I1=:=_A*I2#_A) ? ;no

% A avaria G1 (and) stuck-at-1, é detectada se uma das entradas for 0.. (I2 = 1 → I1 = 0).

| ?- tp([2/0],[I1,I2]).sat(I1=\=I2) ? ;no

% A avaria G2 (xor) stuck-at-0, é detectada se as entradas forem diferentes.

| ?- tp([2/1],[I1,I2]).I2 = I1 ? ;no

% A avaria G2 (xor) stuck-at-1, é detectada se as entradas forem iguais.

I2

G1

G2

I1C

S

Page 51: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

51

Restrições Booleanas no SICStus Prolog

N Rainhas

Para modelar o problemas das rainhas há que garantir que

– Em todas as linhas há exactamente uma rainha

• Em todas as linhas há uma ou mais rainhas

• Em todas as linhas há uma ou menos rainhas

– Em todas as colunas há exactamente uma rainha

• Em todas as colunas há uma ou mais rainhas

• Em todas as colunas há uma ou menos rainhas

– Em todas as diagonais há uma ou menos rainhas

Page 52: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

52

Restrições Booleanas no SICStus Prolog

• Eis uma possível solução

rainhas_3([Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9]):- um_ou_mais( [Q1, Q2, Q3]), % linha 1 um_ou_menos([Q1, Q2, Q3]), ... um_ou_mais( [Q1, Q4, Q7]), % coluna 1 um_ou_menos([Q1, Q4, Q7]),

... um_ou_menos([Q2,Q6]), um_ou_menos([Q1, Q5, Q9]), % diagonais \ um_ou_menos([Q4,Q8]), um_ou_menos([Q2,Q4]), um_ou_menos([Q3, Q5, Q7]), % diagonais / um_ou_menos([Q6,Q8]).

Page 53: 1 Constraints and Logic Programming All problems involving finite domains (including booleans, and sets) may be solved, in principle, with logic programming

53

Restrições Booleanas no SICStus Prolog% Uma ou mais rainhas

um_ou_mais(L):- % L = [A,B,C,...,Z] or_exp(L, Exp), % Exp = A+B+C+...+Z sat(Exp =:= 1). % A+B+C+...+Z = 1

or_exp([H], H).or_exp([H|T], H + T_exp):- or_exp(T, T_exp).

% Uma ou menos rainhas

um_ou_menos([_]).um_ou_menos([H1,H2|T]):- sat(H1 * H2 =:= 0), % A1*A2 = 0 um_ou_menos([H1|T]), % idem para outros pares com A1 um_ou_menos([H2|T]). % idem para outros pares sem A1