eyeprolog 1.3.78 → 1.3.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1975 @@
1
+ /* CLP(B): Constraint Logic Programming over Boolean Variables
2
+
3
+ Author: Markus Triska
4
+ E-mail: triska@metalevel.at
5
+ WWW: https://www.metalevel.at
6
+ Copyright (C): 2019-2025 Markus Triska
7
+
8
+ Permission is hereby granted, free of charge, to any person
9
+ obtaining a copy of this software and associated documentation
10
+ files (the "Software"), to deal in the Software without
11
+ restriction, including without limitation the rights to use, copy,
12
+ modify, merge, publish, distribute, sublicense, and/or sell copies
13
+ of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be
17
+ included in all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
23
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
24
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26
+ DEALINGS IN THE SOFTWARE.
27
+
28
+ */
29
+
30
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
31
+ CLP(B): Constraint Logic Programming over Boolean Variables.
32
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
33
+
34
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
35
+ Public operators.
36
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
37
+
38
+ :- module(clpb, [op(300, fy, ~),
39
+ op(500, yfx, #),
40
+ sat/1,
41
+ taut/2,
42
+ labeling/1,
43
+ sat_count/2,
44
+ weighted_maximum/3,
45
+ random_labeling/2
46
+ ]).
47
+
48
+ % EyeProlog activates operators from explicit directives while parsing the
49
+ % defining module; Scryer and Trealla also infer these from module exports.
50
+ :- op(300, fy, ~).
51
+ :- op(500, yfx, #).
52
+
53
+ :- use_module(library(assoc)).
54
+ :- use_module(library(between)).
55
+ :- use_module(library(atts)).
56
+ :- use_module(library(lists)).
57
+ :- use_module(library(iso_ext)).
58
+ :- use_module(library(random)).
59
+ :- use_module(library(pairs)).
60
+ :- use_module(library(dcgs)).
61
+ :- use_module(library(error), [domain_error/3, type_error/3]).
62
+ :- use_module(library(debug), [bb_get/2, bb_put/2, bb_b_put/2]).
63
+
64
+ :- attribute
65
+ clpb/1,
66
+ clpb_bdd/1,
67
+ clpb_atom/1,
68
+ clpb_hash/1,
69
+ clpb_max/1,
70
+ clpb_omit_boolean/1,
71
+ clpb_visited/1.
72
+
73
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
74
+ Compatibility predicates.
75
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
76
+
77
+ must_be(What, Term) :- must_be(What, unknown(Term)-1, Term).
78
+
79
+ must_be(acyclic, Where, Term) :- !,
80
+ ( acyclic_term(Term) ->
81
+ true
82
+ ; domain_error(acyclic_term, Term, Where)
83
+ ).
84
+ must_be(list, Where, Term) :- !,
85
+ ( acyclic_term(Term), clpz_list(Term, Where) -> true
86
+ ; type_error(list, Term, Where)
87
+ ).
88
+ must_be(list(What), Where, Term) :- !,
89
+ must_be(list, Where, Term),
90
+ maplist(must_be(What, Where), Term).
91
+ must_be(ground, _, Term) :- !,
92
+ functor(Term, _, _).
93
+
94
+ must_be(Type, _, Term) :-
95
+ error:must_be(Type, Term).
96
+
97
+ clpz_list(Nil, _) :- Nil == [].
98
+ clpz_list(Ls, Where) :-
99
+ ( var(Ls) ->
100
+ instantiation_error(Ls, Where)
101
+ ; Ls = [_|Rest],
102
+ clpz_list(Rest, Where)
103
+ ).
104
+
105
+
106
+ instantiation_error(Term) :- instantiation_error(Term, unknown(Term)-1).
107
+
108
+ instantiation_error(_, Goal-Arg) :-
109
+ throw(error(instantiation_error, instantiation_error(Goal, Arg))).
110
+
111
+
112
+ domain_error(Expectation, Term) :-
113
+ domain_error(Expectation, Term, unknown(Term)-1).
114
+
115
+
116
+ type_error(Expectation, Term) :-
117
+ type_error(Expectation, Term, unknown(Term)-1).
118
+
119
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
120
+ Compatibility predicates.
121
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
122
+
123
+ :- meta_predicate(include(1, ?, ?)).
124
+
125
+ include(_, [], []).
126
+ include(Goal, [L|Ls0], Ls) :-
127
+ ( call(Goal, L) ->
128
+ Ls = [L|Rest]
129
+ ; Ls = Rest
130
+ ),
131
+ include(Goal, Ls0, Rest).
132
+
133
+ :- meta_predicate(exclude(1, ?, ?)).
134
+
135
+ exclude(_, [], []).
136
+ exclude(Goal, [L|Ls0], Ls) :-
137
+ ( call(Goal, L) ->
138
+ Ls = Rest
139
+ ; Ls = [L|Rest]
140
+ ),
141
+ exclude(Goal, Ls0, Rest).
142
+
143
+ :- meta_predicate(partition(2,?,?,?,?)).
144
+
145
+ partition(_, [], [], [], []).
146
+ partition(Pred, [H|T], L, E, G) :-
147
+ call(Pred, H, Diff),
148
+ partition_(Diff, H, Pred, T, L, E, G).
149
+
150
+ partition_(<, H, Pred, T, [H|Rest], E, G) :-
151
+ partition(Pred, T, Rest, E, G).
152
+ partition_(=, H, Pred, T, L, [H|Rest], G) :-
153
+ partition(Pred, T, L, Rest, G).
154
+ partition_(>, H, Pred, T, L, E, [H|Rest]) :-
155
+ partition(Pred, T, L, E, Rest).
156
+
157
+ :- meta_predicate(partition(1,?,?,?)).
158
+
159
+ partition(Pred, Ls0, As, Bs) :-
160
+ include(Pred, Ls0, As),
161
+ exclude(Pred, Ls0, Bs).
162
+
163
+ goal_expansion(get_attr(Var, Module, Value), (var(Var),get_atts(Var, Access))) :-
164
+ Access =.. [Module,Value].
165
+
166
+ goal_expansion(put_attr(Var, Module, Value), put_atts(Var, Access)) :-
167
+ Access =.. [Module,Value].
168
+
169
+ goal_expansion(del_attr(Var, Module), (var(Var) -> put_atts(Var, -Access);true)) :-
170
+ Access =.. [Module,_].
171
+
172
+
173
+ /** Constraint Logic Programming over Boolean variables
174
+
175
+ ## Introduction
176
+
177
+ This library provides CLP(B), Constraint Logic Programming over
178
+ Boolean variables. It can be used to model and solve combinatorial
179
+ problems such as verification, allocation and covering tasks.
180
+
181
+ CLP(B) is an instance of the general CLP(_X_) scheme,
182
+ extending logic programming with reasoning over specialised domains.
183
+
184
+ The implementation is based on reduced and ordered Binary Decision
185
+ Diagrams (BDDs).
186
+
187
+ Benchmarks and usage examples of this library are available from:
188
+ [*https://www.metalevel.at/clpb/*](https://www.metalevel.at/clpb/)
189
+
190
+ ## Boolean expressions
191
+
192
+ A _Boolean expression_ is one of:
193
+
194
+ | `0` | false |
195
+ | `1` | true |
196
+ | _variable_ | unknown truth value |
197
+ | _atom_ | universally quantified variable |
198
+ | `~` _Expr_ | logical NOT |
199
+ | _Expr_ `+` _Expr_ | logical OR |
200
+ | _Expr_ `*` _Expr_ | logical AND |
201
+ | _Expr_ `#` _Expr_ | exclusive OR |
202
+ | _Var_ `^` _Expr_ | existential quantification |
203
+ | _Expr_ `=:=` _Expr_ | equality |
204
+ | _Expr_ `=\=` _Expr_ | disequality (same as #) |
205
+ | _Expr_ `=<` _Expr_ | less or equal (implication) |
206
+ | _Expr_ `>=` _Expr_ | greater or equal |
207
+ | _Expr_ `<` _Expr_ | less than |
208
+ | _Expr_ `>` _Expr_ | greater than |
209
+ | `card(Is,Exprs)` | cardinality constraint (_see below_) |
210
+ | `+(Exprs)` | n-fold disjunction (_see below_) |
211
+ | `*(Exprs)` | n-fold conjunction (_see below_) |
212
+
213
+ where _Expr_ again denotes a Boolean expression.
214
+
215
+ The Boolean expression `card(Is,Exprs)` is true iff the number of true
216
+ expressions in the list `Exprs` is a member of the list `Is` of
217
+ integers and integer ranges of the form `From-To`. For example, to
218
+ state that precisely two of the three variables `X`, `Y` and `Z` are
219
+ `true`, you can use `sat(card([2],[X,Y,Z]))`.
220
+
221
+ `+(Exprs)` and `*(Exprs)` denote, respectively, the disjunction and
222
+ conjunction of all elements in the list `Exprs` of Boolean
223
+ expressions.
224
+
225
+ Atoms denote parametric values that are universally quantified. All
226
+ universal quantifiers appear implicitly in front of the entire
227
+ expression. In residual goals, universally quantified variables always
228
+ appear on the right-hand side of equations. Therefore, they can be
229
+ used to express functional dependencies on input variables.
230
+
231
+ ## Interface predicates
232
+
233
+ The most frequently used CLP(B) predicates are:
234
+
235
+ * `sat(+Expr)`
236
+ True iff the Boolean expression Expr is satisfiable.
237
+
238
+ * `taut(+Expr, -T)`
239
+ If Expr is a tautology with respect to the posted constraints, succeeds
240
+ with *T = 1*. If Expr cannot be satisfied, succeeds with *T = 0*.
241
+ Otherwise, it fails.
242
+
243
+ * `labeling(+Vs)`
244
+ Assigns truth values to the variables Vs such that all constraints
245
+ are satisfied.
246
+
247
+ The unification of a CLP(B) variable _X_ with a term _T_ is equivalent
248
+ to posting the constraint sat(X=:=T).
249
+
250
+ ## Examples
251
+
252
+ Here is an example session with a few queries and their answers:
253
+
254
+ ```
255
+ ?- use_module(library(clpb)).
256
+ true.
257
+
258
+ ?- sat(X*Y).
259
+ X = 1, Y = 1.
260
+
261
+ ?- sat(X * ~X).
262
+ false.
263
+
264
+ ?- taut(X * ~X, T).
265
+ T = 0, clpb:sat(X=:=X).
266
+
267
+ ?- sat(X^Y^(X+Y)).
268
+ clpb:sat(X=:=X), clpb:sat(Y=:=Y).
269
+
270
+ ?- sat(X*Y + X*Z), labeling([X,Y,Z]).
271
+ X = 1, Y = 0, Z = 1
272
+ ; X = 1, Y = 1, Z = 0
273
+ ; X = 1, Y = 1, Z = 1.
274
+
275
+ ?- sat(X =< Y), sat(Y =< Z), taut(X =< Z, T).
276
+ T = 1, clpb:sat(X=:=X*Y), clpb:sat(Y=:=Y*Z).
277
+
278
+ ?- sat(1#X#a#b).
279
+ clpb:sat(X=:=a#b).
280
+ ```
281
+
282
+ The pending residual goals constrain remaining variables to Boolean
283
+ expressions and are declaratively equivalent to the original query.
284
+ The last example illustrates that when applicable, remaining variables
285
+ are expressed as functions of universally quantified variables.
286
+
287
+ ## Obtaining BDDs
288
+
289
+ By default, CLP(B) residual goals appear in (approximately) algebraic
290
+ normal form (ANF). This projection is often computationally expensive.
291
+ We can assert `clpb:clpb_residuals(bdd)` to see the BDD representation
292
+ of all constraints. This results in faster projection to residual
293
+ goals, and is also useful for learning more about BDDs. For example:
294
+
295
+ ```
296
+ ?- asserta(clpb:clpb_residuals(bdd)).
297
+ true.
298
+
299
+ ?- sat(X#Y).
300
+ node(3)- (v(X, 0)->node(2);node(1)),
301
+ node(1)- (v(Y, 1)->true;false),
302
+ node(2)- (v(Y, 1)->false;true).
303
+ ```
304
+
305
+ Note that this representation cannot be pasted back on the toplevel,
306
+ and its details are subject to change. Use copy_term/3 to obtain
307
+ such answers as Prolog terms.
308
+
309
+ The variable order of the BDD is determined by the order in which the
310
+ variables first appear in constraints. To obtain different orders,
311
+ we can for example use:
312
+
313
+ ```
314
+ ?- sat(+[1,Y,X]), sat(X#Y).
315
+ node(3)- (v(Y, 0)->node(2);node(1)),
316
+ node(1)- (v(X, 1)->true;false),
317
+ node(2)- (v(X, 1)->false;true).
318
+ ```
319
+
320
+ ## Enabling monotonic CLP(B)
321
+
322
+ In the default execution mode, CLP(B) constraints are _not_ monotonic.
323
+ This means that _adding_ constraints can yield new solutions. For
324
+ example:
325
+
326
+ ```
327
+ ?- sat(X=:=1), X = 1+0.
328
+ false.
329
+
330
+ ?- X = 1+0, sat(X=:=1), X = 1+0.
331
+ X = 1+0.
332
+ ```
333
+
334
+ This behaviour is highly problematic from a logical point of view, and
335
+ it may render [*declarative
336
+ debugging*](https://www.metalevel.at/prolog/debugging)
337
+ techniques inapplicable.
338
+
339
+ Assert `clpb:monotonic` to make CLP(B) *monotonic*. If this mode is
340
+ enabled, then you must wrap CLP(B) variables with the functor
341
+ `v/1`. For example:
342
+
343
+ ```
344
+ ?- asserta(clpb:monotonic).
345
+ true.
346
+
347
+ ?- sat(v(X)=:=1#1).
348
+ X = 0.
349
+ ```
350
+
351
+ ## Example: Pigeons
352
+
353
+ In this example, we are attempting to place _I_ pigeons into _J_ holes
354
+ in such a way that each hole contains at most one pigeon. One
355
+ interesting property of this task is that it can be formulated using
356
+ only _cardinality constraints_ (`card/2`). Another interesting aspect
357
+ is that this task has no short resolution refutations in general.
358
+
359
+ In the following, we use [*Prolog DCG
360
+ notation*](https://www.metalevel.at/prolog/dcg) to describe a
361
+ list `Cs` of CLP(B) constraints that must all be satisfied.
362
+
363
+ ```
364
+ :- use_module(library(clpb)).
365
+ :- use_module(library(clpz)).
366
+ :- use_module(library(lists)).
367
+ :- use_module(library(dcgs)).
368
+
369
+ pigeon(I, J, Rows, Cs) :-
370
+ length(Rows, I), length(Row, J),
371
+ maplist(same_length(Row), Rows),
372
+ transpose(Rows, TRows),
373
+ phrase((all_cards(Rows,[1]),all_cards(TRows,[0,1])), Cs).
374
+
375
+ all_cards([], _) --> [].
376
+ all_cards([Ls|Lss], Cs) --> [card(Cs,Ls)], all_cards(Lss, Cs).
377
+ ```
378
+
379
+ Example queries:
380
+
381
+ ```
382
+ ?- pigeon(9, 8, Rows, Cs), sat(*(Cs)).
383
+ false.
384
+
385
+ ?- pigeon(2, 3, Rows, Cs), sat(*(Cs)),
386
+ append(Rows, Vs), labeling(Vs),
387
+ maplist(portray_clause, Rows).
388
+ [0,0,1].
389
+ [0,1,0].
390
+ etc.
391
+ ```
392
+
393
+ ## Example: Boolean circuit
394
+
395
+ Consider a Boolean circuit that express the Boolean function =|XOR|=
396
+ with 4 =|NAND|= gates. We can model such a circuit with CLP(B)
397
+ constraints as follows:
398
+
399
+ ```
400
+ :- use_module(library(clpb)).
401
+
402
+ nand_gate(X, Y, Z) :- sat(Z =:= ~(X*Y)).
403
+
404
+ xor(X, Y, Z) :-
405
+ nand_gate(X, Y, T1),
406
+ nand_gate(X, T1, T2),
407
+ nand_gate(Y, T1, T3),
408
+ nand_gate(T2, T3, Z).
409
+ ```
410
+
411
+ Using universally quantified variables, we can show that the circuit
412
+ does compute =|XOR|= as intended:
413
+
414
+ ```
415
+ ?- xor(x, y, Z).
416
+ clpb:sat(Z=:=x#y).
417
+ ```
418
+
419
+ ## Acknowledgments
420
+
421
+ The interface predicates of this library follow the example of
422
+ [*SICStus Prolog*](https://sicstus.sics.se).
423
+
424
+ Use SICStus Prolog for higher performance in many cases.
425
+
426
+ */
427
+
428
+
429
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
430
+ Each CLP(B) variable belongs to exactly one BDD. Each CLP(B)
431
+ variable gets an attribute (in module "clpb") of the form:
432
+
433
+ index_root(Index,Root)
434
+
435
+ where Index is the variable's unique integer index, and Root is the
436
+ root of the BDD that the variable belongs to.
437
+
438
+ Each CLP(B) variable also gets an attribute in module clpb_hash: an
439
+ association table node(LID,HID) -> Node, to keep the BDD reduced.
440
+ The association table of each variable must be rebuilt on occasion
441
+ to remove nodes that are no longer reachable. We rebuild the
442
+ association tables of involved variables after BDDs are merged to
443
+ build a new root. This only serves to reclaim memory: Keeping a
444
+ node in a local table even when it no longer occurs in any BDD does
445
+ not affect the solver's correctness. However, apply_shortcut/4
446
+ relies on the invariant that every node that occurs in the relevant
447
+ BDDs is also registered in the table of its branching variable.
448
+
449
+ A root is a logical variable with a single attribute ("clpb_bdd")
450
+ of the form:
451
+
452
+ Sat-BDD
453
+
454
+ where Sat is the SAT formula (in original form) that corresponds to
455
+ BDD. Sat is necessary to rebuild the BDD after variable aliasing,
456
+ and to project all remaining constraints to a list of sat/1 goals.
457
+
458
+ Finally, a BDD is either:
459
+
460
+ *) The integers 0 or 1, denoting false and true, respectively, or
461
+ *) A node of the form
462
+
463
+ node(ID, Var, Low, High, Aux)
464
+ Where ID is the node's unique integer ID, Var is the
465
+ node's branching variable, and Low and High are the
466
+ node's low (Var = 0) and high (Var = 1) children. Aux
467
+ is a free variable, one for each node, that can be used
468
+ to attach attributes and store intermediate results.
469
+
470
+ Variable aliasing is treated as a conjunction of corresponding SAT
471
+ formulae.
472
+
473
+ You should think of CLP(B) as a potentially vast collection of BDDs
474
+ that can range from small to gigantic in size, and which can merge.
475
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
476
+
477
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
478
+ Type checking.
479
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
480
+
481
+ is_sat(V) :- var(V), !, non_monotonic(V).
482
+ is_sat(v(V)) :- var(V), !.
483
+ is_sat(v(I)) :- integer(I), between(0, 1, I).
484
+ is_sat(I) :- integer(I), between(0, 1, I).
485
+ is_sat(A) :- atom(A).
486
+ is_sat(~A) :- is_sat(A).
487
+ is_sat(A*B) :- is_sat(A), is_sat(B).
488
+ is_sat(A+B) :- is_sat(A), is_sat(B).
489
+ is_sat(A#B) :- is_sat(A), is_sat(B).
490
+ is_sat(A=:=B) :- is_sat(A), is_sat(B).
491
+ is_sat(A=\=B) :- is_sat(A), is_sat(B).
492
+ is_sat(A=<B) :- is_sat(A), is_sat(B).
493
+ is_sat(A>=B) :- is_sat(A), is_sat(B).
494
+ is_sat(A<B) :- is_sat(A), is_sat(B).
495
+ is_sat(A>B) :- is_sat(A), is_sat(B).
496
+ is_sat(+(Ls)) :- must_be(list, Ls), maplist(is_sat, Ls).
497
+ is_sat(*(Ls)) :- must_be(list, Ls), maplist(is_sat, Ls).
498
+ is_sat(X^F) :- var(X), is_sat(F).
499
+ is_sat(card(Is,Fs)) :-
500
+ must_be(list(ground), Is),
501
+ must_be(list, Fs),
502
+ maplist(is_sat, Fs).
503
+
504
+ :- dynamic(monotonic/0).
505
+
506
+ non_monotonic(X) :-
507
+ ( var_index(X, _) ->
508
+ % OK: already constrained to a CLP(B) variable
509
+ true
510
+ ; monotonic ->
511
+ instantiation_error(X)
512
+ ; true
513
+ ).
514
+
515
+ :- meta_predicate(bdd_nodes(1, ?, ?)).
516
+ :- meta_predicate(bdd_nodes_(1, ?, ?, ?)).
517
+ :- meta_predicate(with_aux(1, ?)).
518
+
519
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
520
+ Rewriting to canonical expressions.
521
+ Atoms are converted to variables with a special attribute.
522
+ A global lookup table maintains the correspondence between atoms and
523
+ their variables throughout different sat/1 goals.
524
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
525
+
526
+ % elementary
527
+ sat_rewrite(V, V) :- var(V), !.
528
+ sat_rewrite(I, I) :- integer(I), !.
529
+ sat_rewrite(A, V) :- atom(A), !, clpb_atom_var(A, V).
530
+ sat_rewrite(v(V), V).
531
+ sat_rewrite(P0*Q0, P*Q) :- sat_rewrite(P0, P), sat_rewrite(Q0, Q).
532
+ sat_rewrite(P0+Q0, P+Q) :- sat_rewrite(P0, P), sat_rewrite(Q0, Q).
533
+ sat_rewrite(P0#Q0, P#Q) :- sat_rewrite(P0, P), sat_rewrite(Q0, Q).
534
+ sat_rewrite(X^F0, X^F) :- sat_rewrite(F0, F).
535
+ sat_rewrite(card(Is,Fs0), card(Is,Fs)) :-
536
+ maplist(sat_rewrite, Fs0, Fs).
537
+ % synonyms
538
+ sat_rewrite(~P, R) :- sat_rewrite(1 # P, R).
539
+ sat_rewrite(P =:= Q, R) :- sat_rewrite(~P # Q, R).
540
+ sat_rewrite(P =\= Q, R) :- sat_rewrite(P # Q, R).
541
+ sat_rewrite(P =< Q, R) :- sat_rewrite(~P + Q, R).
542
+ sat_rewrite(P >= Q, R) :- sat_rewrite(Q =< P, R).
543
+ sat_rewrite(P < Q, R) :- sat_rewrite(~P * Q, R).
544
+ sat_rewrite(P > Q, R) :- sat_rewrite(Q < P, R).
545
+ sat_rewrite(+(Ls), R) :- foldl(or, Ls, 0, F), sat_rewrite(F, R).
546
+ sat_rewrite(*(Ls), R) :- foldl(and, Ls, 1, F), sat_rewrite(F, R).
547
+
548
+ or(A, B, B + A).
549
+
550
+ and(A, B, B * A).
551
+
552
+ must_be_sat(Sat) :-
553
+ must_be(acyclic, Sat),
554
+ ( is_sat(Sat) -> true
555
+ ; no_truth_value(Sat)
556
+ ).
557
+
558
+ no_truth_value(Term) :- domain_error(clpb_expr, Term).
559
+
560
+ parse_sat(Sat0, Sat) :-
561
+ must_be_sat(Sat0),
562
+ sat_rewrite(Sat0, Sat),
563
+ term_variables(Sat, Vs),
564
+ maplist(enumerate_variable, Vs).
565
+
566
+ enumerate_variable(V) :-
567
+ ( var_index_root(V, _, _) -> true
568
+ ; clpb_next_id('$clpb_next_var', Index),
569
+ put_attr(V, clpb, index_root(Index,_)),
570
+ put_empty_hash(V)
571
+ ).
572
+
573
+ var_index(V, I) :- var_index_root(V, I, _).
574
+
575
+ var_index_root(V, I, Root) :- get_attr(V, clpb, index_root(I,Root)).
576
+
577
+ put_empty_hash(V) :-
578
+ empty_assoc(H0),
579
+ put_attr(V, clpb_hash, H0).
580
+
581
+ sat_roots(Sat, Roots) :-
582
+ term_variables(Sat, Vs),
583
+ maplist(var_index_root, Vs, _, Roots0),
584
+ term_variables(Roots0, Roots).
585
+
586
+ %% sat(+Expr) is semidet.
587
+ %
588
+ % True iff Expr is a satisfiable Boolean expression.
589
+
590
+ sat(Sat0) :-
591
+ ( phrase(sat_ands(Sat0), Ands), Ands = [_,_|_] ->
592
+ maplist(sat, Ands)
593
+ ; parse_sat(Sat0, Sat),
594
+ sat_bdd(Sat, BDD),
595
+ sat_roots(Sat, Roots),
596
+ roots_and(Roots, Sat0-BDD, And-BDD1),
597
+ maplist(del_bdd, Roots),
598
+ maplist(=(Root), Roots),
599
+ root_put_formula_bdd(Root, And, BDD1),
600
+ is_bdd(BDD1),
601
+ satisfiable_bdd(BDD1)
602
+ ).
603
+
604
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
605
+ Posting many small sat/1 constraints is better than posting a huge
606
+ conjunction (or negated disjunction), because unneeded nodes are
607
+ removed from node tables after BDDs are merged. This is not
608
+ possible in sat_bdd/2 because the nodes may occur in other BDDs. A
609
+ better version of sat_bdd/2 or a proper implementation of a unique
610
+ table including garbage collection would make this obsolete and
611
+ also improve taut/2 and sat_count/2 in such cases.
612
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
613
+
614
+ sat_ands(X) -->
615
+ ( { var(X) } -> [X]
616
+ ; { X = (A*B) } -> sat_ands(A), sat_ands(B)
617
+ ; { X = *(Ls) } -> sat_ands_(Ls)
618
+ ; { X = ~Y } -> not_ors(Y)
619
+ ; [X]
620
+ ).
621
+
622
+ sat_ands_([]) --> [].
623
+ sat_ands_([L|Ls]) --> [L], sat_ands_(Ls).
624
+
625
+ not_ors(X) -->
626
+ ( { var(X) } -> [~X]
627
+ ; { X = (A+B) } -> not_ors(A), not_ors(B)
628
+ ; { X = +(Ls) } -> not_ors_(Ls)
629
+ ; [~X]
630
+ ).
631
+
632
+ not_ors_([]) --> [].
633
+ not_ors_([L|Ls]) --> [~L], not_ors_(Ls).
634
+
635
+ del_bdd(Root) :- del_attr(Root, clpb_bdd).
636
+
637
+ root_get_formula_bdd(Root, F, BDD) :- get_attr(Root, clpb_bdd, F-BDD).
638
+
639
+ root_put_formula_bdd(Root, F, BDD) :- put_attr(Root, clpb_bdd, F-BDD).
640
+
641
+ roots_and(Roots, Sat0-BDD0, Sat-BDD) :-
642
+ foldl(root_and, Roots, Sat0-BDD0, Sat-BDD),
643
+ rebuild_hashes(BDD).
644
+
645
+ root_and(Root, Sat0-BDD0, Sat-BDD) :-
646
+ ( root_get_formula_bdd(Root, F, B) ->
647
+ Sat = F*Sat0,
648
+ bdd_and(B, BDD0, BDD)
649
+ ; Sat = Sat0,
650
+ BDD = BDD0
651
+ ).
652
+
653
+ bdd_and(NA, NB, And) :-
654
+ apply(*, NA, NB, And),
655
+ is_bdd(And).
656
+
657
+ %% taut(+Expr, -T) is semidet
658
+ %
659
+ % Tautology check. Succeeds with T = 0 if the Boolean expression Expr
660
+ % cannot be satisfied, and with T = 1 if Expr is always true with
661
+ % respect to the current constraints. Fails otherwise.
662
+
663
+ taut(Sat0, T) :-
664
+ parse_sat(Sat0, Sat),
665
+ ( T = 0, \+ sat(Sat) -> true
666
+ ; T = 1, tautology(Sat) -> true
667
+ ; false
668
+ ).
669
+
670
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
671
+ The algebraic equivalence: tautology(F) <=> \+ sat(~F) does NOT
672
+ hold in CLP(B) because the quantifiers of universally quantified
673
+ variables always implicitly appear in front of the *entire*
674
+ expression. Thus we have for example: X+a is not a tautology, but
675
+ ~(X+a), meaning forall(a, ~(X+a)), is unsatisfiable:
676
+
677
+ sat(~(X+a)) = sat(~X * ~a) = sat(~X), sat(~a) = X=0, false
678
+
679
+ The actual negation of X+a, namely ~forall(A,X+A), in terms of
680
+ CLP(B): ~ ~exists(A, ~(X+A)), is of course satisfiable:
681
+
682
+ ?- sat(~ ~A^ ~(X+A)).
683
+ %@ X = 0,
684
+ %@ sat(A=:=A).
685
+
686
+ Instead, of such rewriting, we test whether the BDD of the negated
687
+ formula is 0. Critically, this avoids constraint propagation.
688
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
689
+
690
+ tautology(Sat) :-
691
+ ( phrase(sat_ands(Sat), Ands), Ands = [_,_|_] ->
692
+ maplist(tautology, Ands)
693
+ ; catch((sat_roots(Sat, Roots),
694
+ roots_and(Roots, _-1, _-Ands),
695
+ sat_bdd(1#Sat, BDD),
696
+ bdd_and(BDD, Ands, B),
697
+ B == 0,
698
+ % reset all attributes
699
+ throw(tautology)),
700
+ tautology,
701
+ true)
702
+ ).
703
+
704
+ satisfiable_bdd(BDD) :-
705
+ ( BDD == 0 -> false
706
+ ; BDD == 1 -> true
707
+ ; ( bdd_nodes(var_unbound, BDD, Nodes) ->
708
+ bdd_variables_classification(BDD, Nodes, Classes),
709
+ partition(var_class, Classes, Eqs, Bs, Ds),
710
+ domain_consistency(Eqs, Goal),
711
+ aliasing_consistency(Bs, Ds, Goals),
712
+ maplist(unification, [Goal|Goals])
713
+ ; % if any variable is instantiated, we do not perform
714
+ % any propagation for now
715
+ true
716
+ )
717
+ ).
718
+
719
+ var_class(_=_, <).
720
+ var_class(further_branching(_,_), =).
721
+ var_class(negative_decisive(_), >).
722
+
723
+ unification(true).
724
+ unification(A=B) :- A = B. % safe_goal/1 detects safety of this call
725
+
726
+ var_unbound(Node) :-
727
+ node_var_low_high(Node, Var, _, _),
728
+ var(Var).
729
+
730
+ universal_var(Var) :- get_attr(Var, clpb_atom, _).
731
+
732
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
733
+ By aliasing consistency, we mean that all unifications X=Y, where
734
+ taut(X=:=Y, 1) holds, are posted.
735
+
736
+ To detect this, we distinguish two kinds of variables among those
737
+ variables that are not skipped in any branch: further-branching and
738
+ negative-decisive. X is negative-decisive iff every node where X
739
+ appears as a branching variable has 0 as one of its children. X is
740
+ further-branching iff 1 is not a direct child of any node where X
741
+ appears as a branching variable.
742
+
743
+ Any potential aliasing must involve one further-branching, and one
744
+ negative-decisive variable. X=Y must hold if, for each low branch
745
+ of nodes with X as branching variable, Y has high branch 0, and for
746
+ each high branch of nodes involving X, Y has low branch 0.
747
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
748
+
749
+ aliasing_consistency(Bs, Ds, Goals) :-
750
+ phrase(aliasings(Bs, Ds), Goals).
751
+
752
+ aliasings([], _) --> [].
753
+ aliasings([further_branching(B,Nodes)|Bs], Ds) -->
754
+ { var_index(B, BI) },
755
+ aliasings_(Ds, B, BI, Nodes),
756
+ aliasings(Bs, Ds).
757
+
758
+ aliasings_([], _, _, _) --> [].
759
+ aliasings_([negative_decisive(D)|Ds], B, BI, Nodes) -->
760
+ { var_index(D, DI) },
761
+ ( { DI > BI,
762
+ always_false(high, DI, Nodes),
763
+ always_false(low, DI, Nodes),
764
+ var_or_atom(D, DA), var_or_atom(B, BA) } ->
765
+ [DA=BA]
766
+ ; []
767
+ ),
768
+ aliasings_(Ds, B, BI, Nodes).
769
+
770
+ var_or_atom(Var, VA) :-
771
+ ( get_attr(Var, clpb_atom, VA) -> true
772
+ ; VA = Var
773
+ ).
774
+
775
+ always_false(Which, DI, Nodes) :-
776
+ phrase(nodes_always_false(Nodes, Which, DI), Opposites),
777
+ maplist(with_aux(unvisit), Opposites).
778
+
779
+ nodes_always_false([], _, _) --> [].
780
+ nodes_always_false([Node|Nodes], Which, DI) -->
781
+ { which_node_child(Which, Node, Child),
782
+ opposite(Which, Opposite) },
783
+ opposite_always_false(Opposite, DI, Child),
784
+ nodes_always_false(Nodes, Which, DI).
785
+
786
+ which_node_child(low, Node, Child) :-
787
+ node_var_low_high(Node, _, Child, _).
788
+ which_node_child(high, Node, Child) :-
789
+ node_var_low_high(Node, _, _, Child).
790
+
791
+ opposite(low, high).
792
+ opposite(high, low).
793
+
794
+ opposite_always_false(Opposite, DI, Node) -->
795
+ ( { node_visited(Node) } -> []
796
+ ; { node_var_low_high(Node, Var, Low, High),
797
+ with_aux(put_visited, Node),
798
+ var_index(Var, VI) },
799
+ [Node],
800
+ ( { VI =:= DI } ->
801
+ { which_node_child(Opposite, Node, Child),
802
+ Child == 0 }
803
+ ; opposite_always_false(Opposite, DI, Low),
804
+ opposite_always_false(Opposite, DI, High)
805
+ )
806
+ ).
807
+
808
+ further_branching(Node) :-
809
+ node_var_low_high(Node, _, Low, High),
810
+ Low \== 1,
811
+ High \== 1.
812
+
813
+ negative_decisive(Node) :-
814
+ node_var_low_high(Node, _, Low, High),
815
+ ( Low == 0 -> true
816
+ ; High == 0 -> true
817
+ ; false
818
+ ).
819
+
820
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
821
+ Instantiate all variables that only admit a single Boolean value.
822
+
823
+ This is the case if: The variable is not skipped in any branch
824
+ leading to 1 (its being skipped means that it may be assigned
825
+ either 0 or 1 and can thus not be fixed yet), and all nodes where
826
+ it occurs as a branching variable have either lower or upper child
827
+ fixed to 0 consistently.
828
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
829
+
830
+ domain_consistency(Eqs, Goal) :-
831
+ maplist(eq_a_b, Eqs, Vs, Values),
832
+ Goal = (Vs = Values). % propagate all assignments at once
833
+
834
+ eq_a_b(A=B, A, B).
835
+
836
+ consistently_false_(Which, Node) :-
837
+ which_node_child(Which, Node, Child),
838
+ Child == 0.
839
+
840
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
841
+ In essentially one sweep of the BDD, all variables can be classified:
842
+ Unification with 0 or 1, further branching and/or negative decisive.
843
+
844
+ Strategy: Breadth-first traversal of the BDD, failing (and thus
845
+ clearing all attributes) if the variable is skipped in some branch,
846
+ and moving the frontier along each time.
847
+
848
+ A formula is only satisfiable if it is a tautology after all (also
849
+ implicitly) existentially quantified variables are projected away.
850
+ However, we only need to check this explicitly if at least one
851
+ universally quantified variable appears. Otherwise, we know that
852
+ the formula is satisfiable at this point, because its BDD is not 0.
853
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
854
+
855
+ bdd_variables_classification(BDD, Nodes, Classes) :-
856
+ nodes_variables(Nodes, Vs0),
857
+ variables_in_index_order(Vs0, Vs),
858
+ ( partition(universal_var, Vs, [_|_], Es) ->
859
+ foldl(existential, Es, BDD, 1)
860
+ ; true
861
+ ),
862
+ phrase(variables_classification(Vs, [BDD]), Classes),
863
+ maplist(with_aux(unvisit), Nodes).
864
+
865
+ variables_classification([], _) --> [].
866
+ variables_classification([V|Vs], Nodes0) -->
867
+ { var_index(V, Index) },
868
+ ( { phrase(nodes_with_variable(Nodes0, Index), Nodes) } ->
869
+ ( { maplist(consistently_false_(low), Nodes) } -> [V=1]
870
+ ; { maplist(consistently_false_(high), Nodes) } -> [V=0]
871
+ ; []
872
+ ),
873
+ ( { maplist(further_branching, Nodes) } ->
874
+ [further_branching(V, Nodes)]
875
+ ; []
876
+ ),
877
+ ( { maplist(negative_decisive, Nodes) } ->
878
+ [negative_decisive(V)]
879
+ ; []
880
+ ),
881
+ { maplist(with_aux(unvisit), Nodes) },
882
+ variables_classification(Vs, Nodes)
883
+ ; variables_classification(Vs, Nodes0)
884
+ ).
885
+
886
+ nodes_with_variable([], _) --> [].
887
+ nodes_with_variable([Node|Nodes], VI) -->
888
+ { Node \== 1 },
889
+ ( { node_visited(Node) } -> nodes_with_variable(Nodes, VI)
890
+ ; { with_aux(put_visited, Node),
891
+ node_var_low_high(Node, OVar, Low, High),
892
+ var_index(OVar, OVI) },
893
+ { OVI =< VI },
894
+ ( { OVI =:= VI } -> [Node]
895
+ ; nodes_with_variable([Low,High], VI)
896
+ ),
897
+ nodes_with_variable(Nodes, VI)
898
+ ).
899
+
900
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
901
+ Node management. Always use an existing node, if there is one.
902
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
903
+
904
+ make_node(Var, Low, High, Node) :-
905
+ ( Low == High -> Node = Low
906
+ ; low_high_key(Low, High, Key),
907
+ ( lookup_node(Var, Key, Node) -> true
908
+ ; clpb_next_id('$clpb_next_node', ID),
909
+ Node = node(ID,Var,Low,High,_Aux),
910
+ register_node(Var, Key, Node)
911
+ )
912
+ ).
913
+
914
+ make_node(Var, Low, High, Node) -->
915
+ % make it conveniently usable within DCGs
916
+ { make_node(Var, Low, High, Node) }.
917
+
918
+
919
+ % The key of a node for hashing is determined by the IDs of its
920
+ % children.
921
+
922
+ low_high_key(Low, High, node(LID,HID)) :-
923
+ node_id(Low, LID),
924
+ node_id(High, HID).
925
+
926
+
927
+ rebuild_hashes(BDD) :-
928
+ bdd_nodes(nodevar_put_empty_hash, BDD, Nodes),
929
+ maplist(re_register_node, Nodes).
930
+
931
+ nodevar_put_empty_hash(Node) :-
932
+ node_var_low_high(Node, Var, _, _),
933
+ empty_assoc(H0),
934
+ put_attr(Var, clpb_hash, H0).
935
+
936
+ re_register_node(Node) :-
937
+ node_var_low_high(Node, Var, Low, High),
938
+ low_high_key(Low, High, Key),
939
+ register_node(Var, Key, Node).
940
+
941
+ register_node(Var, Key, Node) :-
942
+ get_attr(Var, clpb_hash, H0),
943
+ put_assoc(Key, H0, Node, H),
944
+ put_attr(Var, clpb_hash, H).
945
+
946
+ lookup_node(Var, Key, Node) :-
947
+ get_attr(Var, clpb_hash, H0),
948
+ get_assoc(Key, H0, Node).
949
+
950
+
951
+ node_id(0, false).
952
+ node_id(1, true).
953
+ node_id(node(ID,_,_,_,_), ID).
954
+
955
+ node_aux(Node, Aux) :- arg(5, Node, Aux).
956
+
957
+ node_var_low_high(Node, Var, Low, High) :-
958
+ Node = node(_,Var,Low,High,_).
959
+
960
+
961
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
962
+ sat_bdd/2 converts a SAT formula in canonical form to an ordered
963
+ and reduced BDD.
964
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
965
+
966
+ sat_bdd(V, Node) :- var(V), !, make_node(V, 0, 1, Node).
967
+ sat_bdd(I, I) :- integer(I), !.
968
+ sat_bdd(V^Sat, Node) :- !, sat_bdd(Sat, BDD), existential(V, BDD, Node).
969
+ sat_bdd(card(Is,Fs), Node) :- !, counter_network(Is, Fs, Node).
970
+ sat_bdd(Sat, Node) :- !,
971
+ Sat =.. [F,A,B],
972
+ sat_bdd(A, NA),
973
+ sat_bdd(B, NB),
974
+ apply(F, NA, NB, Node).
975
+
976
+ existential(V, BDD, Node) :-
977
+ var_index(V, Index),
978
+ bdd_restriction(BDD, Index, 0, NA),
979
+ bdd_restriction(BDD, Index, 1, NB),
980
+ apply(+, NA, NB, Node).
981
+
982
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
983
+ Counter network for card(Is,Fs).
984
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
985
+
986
+ counter_network(Cs, Fs, Node) :-
987
+ same_length([_|Fs], Indicators),
988
+ fill_indicators(Indicators, 0, Cs),
989
+ phrase(formulas_variables(Fs, Vars0), ExBDDs),
990
+ maplist(unvisit, Vars0),
991
+ % The counter network is built bottom-up, so variables with
992
+ % highest index must be processed first.
993
+ variables_in_index_order(Vars0, Vars1),
994
+ reverse(Vars1, Vars),
995
+ counter_network_(Vars, Indicators, Node0),
996
+ foldl(existential_and, ExBDDs, Node0, Node).
997
+
998
+ % Introduce fresh variables for expressions that are not variables.
999
+ % These variables are later existentially quantified to remove them.
1000
+ % Also, new variables are introduced for variables that are used more
1001
+ % than once, as in card([0,1],[X,X,Y]), to keep the BDD ordered.
1002
+
1003
+ formulas_variables([], []) --> [].
1004
+ formulas_variables([F|Fs], [V|Vs]) -->
1005
+ ( { var(F), \+ is_visited(F) } ->
1006
+ { V = F,
1007
+ put_visited(F) }
1008
+ ; { enumerate_variable(V),
1009
+ sat_rewrite(V =:= F, Sat),
1010
+ sat_bdd(Sat, BDD) },
1011
+ [V-BDD]
1012
+ ),
1013
+ formulas_variables(Fs, Vs).
1014
+
1015
+ counter_network_([], [Node], Node).
1016
+ counter_network_([Var|Vars], [I|Is0], Node) :-
1017
+ foldl(indicators_pairing(Var), Is0, Is, I, _),
1018
+ counter_network_(Vars, Is, Node).
1019
+
1020
+ indicators_pairing(Var, I, Node, Prev, I) :- make_node(Var, Prev, I, Node).
1021
+
1022
+ fill_indicators([], _, _).
1023
+ fill_indicators([I|Is], Index0, Cs) :-
1024
+ ( memberchk(Index0, Cs) -> I = 1
1025
+ ; member(A-B, Cs), between(A, B, Index0) -> I = 1
1026
+ ; I = 0
1027
+ ),
1028
+ Index1 is Index0 + 1,
1029
+ fill_indicators(Is, Index1, Cs).
1030
+
1031
+ existential_and(Ex-BDD, Node0, Node) :-
1032
+ bdd_and(BDD, Node0, Node1),
1033
+ existential(Ex, Node1, Node),
1034
+ % remove attributes to avoid residual goals for variables that
1035
+ % are only used as substitutes for formulas
1036
+ del_attrs(Ex).
1037
+
1038
+
1039
+ del_attrs(Var) :-
1040
+ ( var(Var) ->
1041
+ put_atts(Var, [
1042
+ -clpb(_),
1043
+ -clpb_bdd(_),
1044
+ -clpb_atom(_),
1045
+ -clpb_hash(_),
1046
+ -clpb_max(_),
1047
+ -clpb_omit_boolean(_),
1048
+ -clpb_visited(_)
1049
+ ])
1050
+ ; true
1051
+ ).
1052
+
1053
+
1054
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1055
+ Compute F(NA, NB).
1056
+
1057
+ We use a DCG to thread through an implicit argument G0, an
1058
+ association table F(IDA,IDB) -> Node, used for memoization.
1059
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1060
+
1061
+ apply(F, NA, NB, Node) :-
1062
+ empty_assoc(G0),
1063
+ phrase(apply(F, NA, NB, Node), [G0], _).
1064
+
1065
+ apply(F, NA, NB, Node) -->
1066
+ ( { integer(NA), integer(NB) } -> { once(bool_op(F, NA, NB, Node)) }
1067
+ ; { apply_shortcut(F, NA, NB, Node) } -> []
1068
+ ; { node_id(NA, IDA), node_id(NB, IDB), Key =.. [F,IDA,IDB] },
1069
+ ( state(G0), { get_assoc(Key, G0, Node) } -> []
1070
+ ; apply_(F, NA, NB, Node),
1071
+ state(G0, G),
1072
+ { put_assoc(Key, G0, Node, G) }
1073
+ )
1074
+ ).
1075
+
1076
+ apply_shortcut(+, NA, NB, Node) :-
1077
+ ( NA == 0 -> Node = NB
1078
+ ; NA == 1 -> Node = 1
1079
+ ; NB == 0 -> Node = NA
1080
+ ; NB == 1 -> Node = 1
1081
+ ; false
1082
+ ).
1083
+
1084
+ apply_shortcut(*, NA, NB, Node) :-
1085
+ ( NA == 0 -> Node = 0
1086
+ ; NA == 1 -> Node = NB
1087
+ ; NB == 0 -> Node = 0
1088
+ ; NB == 1 -> Node = NA
1089
+ ; false
1090
+ ).
1091
+
1092
+
1093
+ apply_(F, NA, NB, Node) -->
1094
+ { var_less_than(NA, NB),
1095
+ !,
1096
+ node_var_low_high(NA, VA, LA, HA) },
1097
+ apply(F, LA, NB, Low),
1098
+ apply(F, HA, NB, High),
1099
+ make_node(VA, Low, High, Node).
1100
+ apply_(F, NA, NB, Node) -->
1101
+ { node_var_low_high(NA, VA, LA, HA),
1102
+ node_var_low_high(NB, VB, LB, HB),
1103
+ VA == VB },
1104
+ !,
1105
+ apply(F, LA, LB, Low),
1106
+ apply(F, HA, HB, High),
1107
+ make_node(VA, Low, High, Node).
1108
+ apply_(F, NA, NB, Node) --> % NB < NA
1109
+ { node_var_low_high(NB, VB, LB, HB) },
1110
+ apply(F, NA, LB, Low),
1111
+ apply(F, NA, HB, High),
1112
+ make_node(VB, Low, High, Node).
1113
+
1114
+
1115
+ node_varindex(Node, VI) :-
1116
+ node_var_low_high(Node, V, _, _),
1117
+ var_index(V, VI).
1118
+
1119
+ var_less_than(NA, NB) :-
1120
+ ( integer(NB) -> true
1121
+ ; node_varindex(NA, VAI),
1122
+ node_varindex(NB, VBI),
1123
+ VAI < VBI
1124
+ ).
1125
+
1126
+ bool_op(+, 0, 0, 0).
1127
+ bool_op(+, 0, 1, 1).
1128
+ bool_op(+, 1, 0, 1).
1129
+ bool_op(+, 1, 1, 1).
1130
+
1131
+ bool_op(*, 0, 0, 0).
1132
+ bool_op(*, 0, 1, 0).
1133
+ bool_op(*, 1, 0, 0).
1134
+ bool_op(*, 1, 1, 1).
1135
+
1136
+ bool_op(#, 0, 0, 0).
1137
+ bool_op(#, 0, 1, 1).
1138
+ bool_op(#, 1, 0, 1).
1139
+ bool_op(#, 1, 1, 0).
1140
+
1141
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1142
+ Access implicit state in DCGs.
1143
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1144
+
1145
+ state(S) --> state(S, S).
1146
+
1147
+ state(S0, S), [S] --> [S0].
1148
+
1149
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1150
+ Unification. X = Expr is equivalent to sat(X =:= Expr).
1151
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1152
+
1153
+ verify_attributes(Var, Other, Gs) :-
1154
+ % format("~w = ~w\n", [Var,Other]),
1155
+ ( get_attr(Var, clpb, index_root(I,Root)) ->
1156
+ ( integer(Other) ->
1157
+ ( between(0, 1, Other) ->
1158
+ root_get_formula_bdd(Root, Sat, BDD0),
1159
+ bdd_restriction(BDD0, I, Other, BDD),
1160
+ root_put_formula_bdd(Root, Sat, BDD),
1161
+ Gs = [satisfiable_bdd(BDD)]
1162
+ ; no_truth_value(Other)
1163
+ )
1164
+ ; atom(Other) ->
1165
+ root_get_formula_bdd(Root, Sat0, _),
1166
+ Gs = [root_rebuild_bdd(Root, Sat0)]
1167
+ ; % due to variable aliasing, any BDDs may become unordered,
1168
+ % so we need to rebuild the new BDD from the conjunction
1169
+ % after the unification is in place
1170
+ root_get_formula_bdd(Root, Sat0, _),
1171
+ Sat = Sat0*OtherSat,
1172
+ parse_sat(Other, OtherSat),
1173
+ sat_roots(Sat, Roots),
1174
+ phrase(formulas_(Roots), [F|Fs]),
1175
+ foldl(and, Fs, F, And),
1176
+ maplist(del_bdd, Roots),
1177
+ maplist(=(NewRoot), Roots),
1178
+ Gs = [root_rebuild_bdd(NewRoot, And)]
1179
+ )
1180
+ ; Gs = []
1181
+ ).
1182
+
1183
+
1184
+ formulas_([]) --> [].
1185
+ formulas_([Root|Roots]) -->
1186
+ ( { root_get_formula_bdd(Root, F, _) } ->
1187
+ [F]
1188
+ ; []
1189
+ ),
1190
+ formulas_(Roots).
1191
+
1192
+ root_rebuild_bdd(Root, Formula) :-
1193
+ parse_sat(Formula, Sat),
1194
+ sat_bdd(Sat, BDD),
1195
+ is_bdd(BDD),
1196
+ root_put_formula_bdd(Root, Formula, BDD),
1197
+ satisfiable_bdd(BDD).
1198
+
1199
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1200
+ Support for project_attributes/2.
1201
+
1202
+ This is called by the toplevel as
1203
+
1204
+ project_attributes(+QueryVars, +AttrVars)
1205
+
1206
+ in order to project all remaining constraints onto QueryVars.
1207
+
1208
+ All CLP(B) variables that do not occur in QueryVars
1209
+ need to be existentially quantified, so that they do not occur in
1210
+ residual goals. This is very easy to do in the case of CLP(B).
1211
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1212
+
1213
+ project_attributes(QueryVars0, _) :-
1214
+ include(clpb_variable, QueryVars0, QueryVars),
1215
+ maplist(var_index_root, QueryVars, _, Roots0),
1216
+ sort(Roots0, Roots),
1217
+ maplist(remove_hidden_variables(QueryVars), Roots).
1218
+
1219
+ clpb_variable(Var) :- var_index(Var, _).
1220
+
1221
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1222
+ All CLP(B) variables occurring in BDDs but not in query variables
1223
+ become existentially quantified. This must also be reflected in the
1224
+ formula. In addition, an attribute is attached to these variables
1225
+ to suppress superfluous sat(V=:=V) goals.
1226
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1227
+
1228
+ remove_hidden_variables(QueryVars, Root) :-
1229
+ root_get_formula_bdd(Root, Formula, BDD0),
1230
+ maplist(put_visited, QueryVars),
1231
+ bdd_variables(BDD0, HiddenVars0),
1232
+ exclude(universal_var, HiddenVars0, HiddenVars),
1233
+ maplist(unvisit, QueryVars),
1234
+ foldl(existential, HiddenVars, BDD0, BDD),
1235
+ foldl(quantify_existantially, HiddenVars, Formula, ExFormula),
1236
+ root_put_formula_bdd(Root, ExFormula, BDD).
1237
+
1238
+ quantify_existantially(E, E0, E^E0) :- put_attr(E, clpb_omit_boolean, true).
1239
+
1240
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1241
+ BDD restriction.
1242
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1243
+
1244
+ bdd_restriction(Node, VI, Value, Res) :-
1245
+ empty_assoc(G0),
1246
+ phrase(bdd_restriction_(Node, VI, Value, Res), [G0], _),
1247
+ is_bdd(Res).
1248
+
1249
+ bdd_restriction_(Node, VI, Value, Res) -->
1250
+ ( { integer(Node) } -> { Res = Node }
1251
+ ; { node_var_low_high(Node, Var, Low, High) } ->
1252
+ ( { integer(Var) } ->
1253
+ ( { Var =:= 0 } -> bdd_restriction_(Low, VI, Value, Res)
1254
+ ; { Var =:= 1 } -> bdd_restriction_(High, VI, Value, Res)
1255
+ ; { no_truth_value(Var) }
1256
+ )
1257
+ ; { var_index(Var, I0),
1258
+ node_id(Node, ID) },
1259
+ ( { I0 =:= VI } ->
1260
+ ( { Value =:= 0 } -> { Res = Low }
1261
+ ; { Res = High }
1262
+ )
1263
+ ; { I0 > VI } -> { Res = Node }
1264
+ ; state(G0), { get_assoc(ID, G0, Res) } -> []
1265
+ ; bdd_restriction_(Low, VI, Value, LRes),
1266
+ bdd_restriction_(High, VI, Value, HRes),
1267
+ make_node(Var, LRes, HRes, Res),
1268
+ state(G0, G),
1269
+ { put_assoc(ID, G0, Res, G) }
1270
+ )
1271
+ )
1272
+ ; { domain_error(node, Node) }
1273
+ ).
1274
+
1275
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1276
+ Relating a BDD to its elements (nodes and variables).
1277
+
1278
+ Note that BDDs can become quite big (easily millions of nodes), and
1279
+ memory space is a major bottleneck for many problems. If possible,
1280
+ we therefore do not duplicate the entire BDD in memory (as in
1281
+ bdd_ites/2), but only extract its features as needed.
1282
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1283
+
1284
+ bdd_nodes(BDD, Ns) :- bdd_nodes(ignore_node, BDD, Ns).
1285
+
1286
+ ignore_node(_).
1287
+
1288
+ % VPred is a unary predicate that is called for each node that has a
1289
+ % branching variable (= each inner node).
1290
+
1291
+ bdd_nodes(VPred, BDD, Ns) :-
1292
+ phrase(bdd_nodes_(VPred, BDD), Ns),
1293
+ maplist(with_aux(unvisit), Ns).
1294
+
1295
+ bdd_nodes_(VPred, Node) -->
1296
+ ( { node_visited(Node) } -> []
1297
+ ; { call(VPred, Node),
1298
+ with_aux(put_visited, Node),
1299
+ node_var_low_high(Node, _, Low, High) },
1300
+ [Node],
1301
+ bdd_nodes_(VPred, Low),
1302
+ bdd_nodes_(VPred, High)
1303
+ ).
1304
+
1305
+ node_visited(Node) :- integer(Node).
1306
+ node_visited(Node) :- with_aux(is_visited, Node).
1307
+
1308
+ bdd_variables(BDD, Vs) :-
1309
+ bdd_nodes(BDD, Nodes),
1310
+ nodes_variables(Nodes, Vs).
1311
+
1312
+ nodes_variables(Nodes, Vs) :-
1313
+ phrase(nodes_variables_(Nodes), Vs),
1314
+ maplist(unvisit, Vs).
1315
+
1316
+ nodes_variables_([]) --> [].
1317
+ nodes_variables_([Node|Nodes]) -->
1318
+ { node_var_low_high(Node, Var, _, _) },
1319
+ ( { integer(Var) } -> []
1320
+ ; { is_visited(Var) } -> []
1321
+ ; { put_visited(Var) },
1322
+ [Var]
1323
+ ),
1324
+ nodes_variables_(Nodes).
1325
+
1326
+ unvisit(V) :- del_attr(V, clpb_visited).
1327
+
1328
+ is_visited(V) :- get_attr(V, clpb_visited, true).
1329
+
1330
+ put_visited(V) :- put_attr(V, clpb_visited, true).
1331
+
1332
+ with_aux(Pred, Node) :-
1333
+ node_aux(Node, Aux),
1334
+ call(Pred, Aux).
1335
+
1336
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1337
+ Internal consistency checks.
1338
+
1339
+ To enable these checks, assert clpb:validation/0.
1340
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1341
+
1342
+ :- dynamic(validation/0).
1343
+
1344
+ is_bdd(BDD) :-
1345
+ ( validation ->
1346
+ bdd_ites(BDD, ITEs),
1347
+ pairs_values(ITEs, Ls0),
1348
+ sort(Ls0, Ls1),
1349
+ ( same_length(Ls0, Ls1) -> true
1350
+ ; domain_error(reduced_ites, (ITEs,Ls0,Ls1))
1351
+ ),
1352
+ ( member(ITE, ITEs), \+ registered_node(ITE) ->
1353
+ domain_error(registered_node, ITE)
1354
+ ; true
1355
+ ),
1356
+ ( member(I, ITEs), \+ clpb_ordered(I) ->
1357
+ domain_error(ordered_node, I)
1358
+ ; true
1359
+ )
1360
+ ; true
1361
+ ).
1362
+
1363
+ clpb_ordered(_-ite(Var,High,Low)) :-
1364
+ ( var_index(Var, VI) ->
1365
+ greater_varindex_than(High, VI),
1366
+ greater_varindex_than(Low, VI)
1367
+ ; true
1368
+ ).
1369
+
1370
+ greater_varindex_than(Node, VI) :-
1371
+ ( integer(Node) -> true
1372
+ ; node_var_low_high(Node, Var, _, _),
1373
+ ( var_index(Var, OI) ->
1374
+ OI > VI
1375
+ ; true
1376
+ )
1377
+ ).
1378
+
1379
+ registered_node(Node-ite(Var,High,Low)) :-
1380
+ ( var(Var) ->
1381
+ low_high_key(Low, High, Key),
1382
+ lookup_node(Var, Key, Node0),
1383
+ Node == Node0
1384
+ ; true
1385
+ ).
1386
+
1387
+ bdd_ites(BDD, ITEs) :-
1388
+ bdd_nodes(BDD, Nodes),
1389
+ maplist(node_ite, Nodes, ITEs).
1390
+
1391
+ node_ite(Node, Node-ite(Var,High,Low)) :-
1392
+ node_var_low_high(Node, Var, Low, High).
1393
+
1394
+ %% labeling(+Vs) is multi.
1395
+ %
1396
+ % Enumerate concrete solutions. Assigns truth values to the Boolean
1397
+ % variables Vs such that all stated constraints are satisfied.
1398
+
1399
+ labeling(Vs0) :-
1400
+ must_be(list, Vs0),
1401
+ maplist(labeling_var, Vs0),
1402
+ variables_in_index_order(Vs0, Vs),
1403
+ maplist(indomain, Vs).
1404
+
1405
+ labeling_var(V) :- var(V), !.
1406
+ labeling_var(V) :- V == 0, !.
1407
+ labeling_var(V) :- V == 1, !.
1408
+ labeling_var(V) :- domain_error(clpb_variable, V).
1409
+
1410
+ variables_in_index_order(Vs0, Vs) :-
1411
+ maplist(var_with_index, Vs0, IVs0),
1412
+ keysort(IVs0, IVs),
1413
+ pairs_values(IVs, Vs).
1414
+
1415
+ var_with_index(V, I-V) :-
1416
+ ( var_index_root(V, I, _) -> true
1417
+ ; I = 0
1418
+ ).
1419
+
1420
+ indomain(0).
1421
+ indomain(1).
1422
+
1423
+
1424
+ %% sat_count(+Expr, -Count) is det.
1425
+ %
1426
+ % Count the number of admissible assignments. Count is the number of
1427
+ % different assignments of truth values to the variables in the
1428
+ % Boolean expression Expr, such that Expr is true and all posted
1429
+ % constraints are satisfiable.
1430
+ %
1431
+ % A common form of invocation is `sat_count(+[1|Vs], Count)`: This
1432
+ % counts the number of admissible assignments to `Vs` without imposing
1433
+ % any further constraints.
1434
+ %
1435
+ % Examples:
1436
+ %
1437
+ % ```
1438
+ % ?- sat(A =< B), Vs = [A,B], sat_count(+[1|Vs], Count).
1439
+ % Vs = [A,B], Count = 3, clpb:sat(A=:=A*B).
1440
+ %
1441
+ % ?- length(Vs, 120),
1442
+ % sat_count(+Vs, CountOr),
1443
+ % sat_count(*(Vs), CountAnd).
1444
+ % Vs = [...],
1445
+ % CountOr = 1329227995784915872903807060280344575,
1446
+ % CountAnd = 1.
1447
+ % ```
1448
+
1449
+
1450
+
1451
+ sat_count(Sat0, N) :-
1452
+ catch((parse_sat(Sat0, Sat),
1453
+ sat_bdd(Sat, BDD),
1454
+ sat_roots(Sat, Roots),
1455
+ roots_and(Roots, _-BDD, _-BDD1),
1456
+ % we mark variables that occur in Sat0 as visited ...
1457
+ term_variables(Sat0, Vs),
1458
+ maplist(put_visited, Vs),
1459
+ % ... so that they do not appear in Vs1 ...
1460
+ bdd_variables(BDD1, Vs1),
1461
+ partition(universal_var, Vs1, Univs, Exis),
1462
+ % ... and then remove remaining variables:
1463
+ foldl(universal, Univs, BDD1, BDD2),
1464
+ foldl(existential, Exis, BDD2, BDD3),
1465
+ variables_in_index_order(Vs, IVs),
1466
+ foldl(renumber_variable, IVs, 1, VNum),
1467
+ bdd_count(BDD3, VNum, Count0),
1468
+ var_u(BDD3, VNum, P),
1469
+ % Do not unify N directly, because we are not prepared
1470
+ % for propagation here in case N is a CLP(B) variable.
1471
+ N0 is 2^(P - 1)*Count0,
1472
+ % reset all attributes and Aux variables
1473
+ throw(count(N0))),
1474
+ count(N0),
1475
+ N = N0).
1476
+
1477
+ universal(V, BDD, Node) :-
1478
+ var_index(V, Index),
1479
+ bdd_restriction(BDD, Index, 0, NA),
1480
+ bdd_restriction(BDD, Index, 1, NB),
1481
+ apply(*, NA, NB, Node).
1482
+
1483
+ renumber_variable(V, I0, I) :-
1484
+ put_attr(V, clpb, index_root(I0,_)),
1485
+ I is I0 + 1.
1486
+
1487
+ bdd_count(Node, VNum, Count) :-
1488
+ ( integer(Node) -> Count = Node
1489
+ ; node_aux(Node, Count),
1490
+ ( integer(Count) -> true
1491
+ ; node_var_low_high(Node, V, Low, High),
1492
+ bdd_count(Low, VNum, LCount),
1493
+ bdd_count(High, VNum, HCount),
1494
+ bdd_pow(Low, V, VNum, LPow),
1495
+ bdd_pow(High, V, VNum, HPow),
1496
+ Count is LPow*LCount + HPow*HCount
1497
+ )
1498
+ ).
1499
+
1500
+
1501
+ bdd_pow(Node, V, VNum, Pow) :-
1502
+ var_index(V, Index),
1503
+ var_u(Node, VNum, P),
1504
+ Pow is 2^(P - Index - 1).
1505
+
1506
+ var_u(Node, VNum, Index) :-
1507
+ ( integer(Node) -> Index = VNum
1508
+ ; node_varindex(Node, Index)
1509
+ ).
1510
+
1511
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1512
+ Pick a solution in such a way that each solution is equally likely.
1513
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1514
+
1515
+ %% random_labeling(+Seed, +Vs) is det.
1516
+ %
1517
+ % Select a single random solution. An admissible assignment of truth
1518
+ % values to the Boolean variables in Vs is chosen in such a way that
1519
+ % each admissible assignment is equally likely. Seed is an integer,
1520
+ % used as the initial seed for the random number generator.
1521
+
1522
+ single_bdd(Vars0) :-
1523
+ maplist(monotonic_variable, Vars0, Vars),
1524
+ % capture all variables with a single BDD
1525
+ sat(+[1|Vars]).
1526
+
1527
+ random_labeling(Seed, Vars) :-
1528
+ must_be(list, Vars),
1529
+ set_random(seed(Seed)),
1530
+ ( ground(Vars) -> true
1531
+ ; catch((single_bdd(Vars),
1532
+ once((member(Var, Vars),var(Var))),
1533
+ var_index_root(Var, _, Root),
1534
+ root_get_formula_bdd(Root, _, BDD),
1535
+ bdd_variables(BDD, Vs),
1536
+ variables_in_index_order(Vs, IVs),
1537
+ foldl(renumber_variable, IVs, 1, VNum),
1538
+ phrase(random_bindings(VNum, BDD), Bs),
1539
+ maplist(del_attrs, Vs),
1540
+ % reset all attribute modifications
1541
+ throw(randsol(Vars, Bs))),
1542
+ randsol(Vars, Bs),
1543
+ true),
1544
+ maplist(call, Bs),
1545
+ % set remaining variables to 0 or 1 with equal probability
1546
+ include(var, Vars, Remaining),
1547
+ maplist(maybe_zero, Remaining)
1548
+ ).
1549
+
1550
+ maybe_zero(Var) :-
1551
+ ( maybe -> Var = 0
1552
+ ; Var = 1
1553
+ ).
1554
+
1555
+ random_bindings(_, Node) --> { Node == 1 }, !.
1556
+ random_bindings(VNum, Node) -->
1557
+ { node_var_low_high(Node, Var, Low, High),
1558
+ bdd_count(Node, VNum, Total),
1559
+ bdd_count(Low, VNum, LCount) },
1560
+ ( { weighted_maybe(LCount, Total) } ->
1561
+ [Var=0], random_bindings(VNum, Low)
1562
+ ; [Var=1], random_bindings(VNum, High)
1563
+ ).
1564
+
1565
+ weighted_maybe(K, N) :-
1566
+ random_integer(0, N, X),
1567
+ X < K.
1568
+
1569
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1570
+ Find solutions with maximum weight.
1571
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1572
+
1573
+ %% weighted_maximum(+Weights, +Vs, -Maximum) is multi.
1574
+ %
1575
+ % Enumerate weighted optima over admissible assignments. Maximize a
1576
+ % linear objective function over Boolean variables Vs with integer
1577
+ % coefficients Weights. This predicate assigns 0 and 1 to the
1578
+ % variables in Vs such that all stated constraints are satisfied, and
1579
+ % Maximum is the maximum of `sum(Weight_i*V_i)` over all admissible
1580
+ % assignments. On backtracking, all admissible assignments that
1581
+ % attain the optimum are generated.
1582
+ %
1583
+ % This predicate can also be used to _minimize_ a linear Boolean
1584
+ % program, since negative integers can appear in Weights.
1585
+ %
1586
+ % Example:
1587
+ %
1588
+ % ```
1589
+ % ?- sat(A#B), weighted_maximum([1,2,1], [A,B,C], Maximum).
1590
+ % A = 0, B = 1, C = 1, Maximum = 3.
1591
+ % ```
1592
+
1593
+ weighted_maximum(Ws, Vars, Max) :-
1594
+ must_be(list(integer), Ws),
1595
+ must_be(list(var), Vars),
1596
+ single_bdd(Vars),
1597
+ Vars = [Var|_],
1598
+ var_index_root(Var, _, Root),
1599
+ root_get_formula_bdd(Root, _, BDD0),
1600
+ bdd_variables(BDD0, Vs),
1601
+ % existentially quantify variables that are not considered
1602
+ maplist(put_visited, Vars),
1603
+ exclude(is_visited, Vs, Unvisited),
1604
+ maplist(unvisit, Vars),
1605
+ foldl(existential, Unvisited, BDD0, BDD),
1606
+ maplist(var_with_index, Vars, IVs),
1607
+ pairs_keys_values(Pairs0, IVs, Ws),
1608
+ keysort(Pairs0, Pairs1),
1609
+ % sum linear combinations of repeated variables
1610
+ group_pairs_by_key(Pairs1, Groups),
1611
+ maplist(group_sumweights_pair, Groups, Pairs2),
1612
+ pairs_keys_values(Pairs2, IVs1, WeightsIndexOrder),
1613
+ pairs_values(IVs1, VarsIndexOrder),
1614
+ % Pairs is a list of Var-Weight terms, in index order of Vars
1615
+ pairs_keys_values(Pairs, VarsIndexOrder, WeightsIndexOrder),
1616
+ bdd_maximum(BDD, Pairs, Max),
1617
+ max_labeling(BDD, Pairs).
1618
+
1619
+ group_sumweights_pair((I-V)-Ws, (I-V)-W) :- sum_list(Ws, W).
1620
+
1621
+ max_labeling(1, Pairs) :- max_upto(Pairs, _, _).
1622
+ max_labeling(node(_,Var,Low,High,Aux), Pairs0) :-
1623
+ max_upto(Pairs0, Var, Pairs),
1624
+ get_attr(Aux, clpb_max, max(_,Dir)),
1625
+ direction_labeling(Dir, Var, Low, High, Pairs).
1626
+
1627
+ max_upto([], _, _).
1628
+ max_upto([Var0-Weight|VWs0], Var, VWs) :-
1629
+ ( Var == Var0 -> VWs = VWs0
1630
+ ; Weight =:= 0 ->
1631
+ ( Var0 = 0 ; Var0 = 1 ),
1632
+ max_upto(VWs0, Var, VWs)
1633
+ ; Weight < 0 -> Var0 = 0, max_upto(VWs0, Var, VWs)
1634
+ ; Var0 = 1, max_upto(VWs0, Var, VWs)
1635
+ ).
1636
+
1637
+ direction_labeling(low, 0, Low, _, Pairs) :- max_labeling(Low, Pairs).
1638
+ direction_labeling(high, 1, _, High, Pairs) :- max_labeling(High, Pairs).
1639
+
1640
+ bdd_maximum(1, Pairs, Max) :-
1641
+ pairs_values(Pairs, Weights0),
1642
+ include(<(0), Weights0, Weights),
1643
+ sum_list(Weights, Max).
1644
+ bdd_maximum(node(_,Var,Low,High,Aux), Pairs0, Max) :-
1645
+ ( get_attr(Aux, clpb_max, max(Max,_)) -> true
1646
+ ; ( skip_to_var(Var, Weight, Pairs0, Pairs),
1647
+ ( Low == 0 ->
1648
+ bdd_maximum_(High, Pairs, MaxHigh, MaxToHigh),
1649
+ Max is MaxToHigh + MaxHigh + Weight,
1650
+ Dir = high
1651
+ ; High == 0 ->
1652
+ bdd_maximum_(Low, Pairs, MaxLow, MaxToLow),
1653
+ Max is MaxToLow + MaxLow,
1654
+ Dir = low
1655
+ ; bdd_maximum_(Low, Pairs, MaxLow, MaxToLow),
1656
+ bdd_maximum_(High, Pairs, MaxHigh, MaxToHigh),
1657
+ Max0 is MaxToLow + MaxLow,
1658
+ Max1 is MaxToHigh + MaxHigh + Weight,
1659
+ Max is max(Max0,Max1),
1660
+ ( Max0 =:= Max1 -> Dir = _Any
1661
+ ; Max0 < Max1 -> Dir = high
1662
+ ; Dir = low
1663
+ )
1664
+ ),
1665
+ store_maximum(Aux, Max, Dir)
1666
+ )
1667
+ ).
1668
+
1669
+ bdd_maximum_(Node, Pairs, Max, MaxTo) :-
1670
+ bdd_maximum(Node, Pairs, Max),
1671
+ between_weights(Node, Pairs, MaxTo).
1672
+
1673
+ store_maximum(Aux, Max, Dir) :- put_attr(Aux, clpb_max, max(Max,Dir)).
1674
+
1675
+ between_weights(Node, Pairs0, MaxTo) :-
1676
+ ( Node == 1 -> MaxTo = 0
1677
+ ; node_var_low_high(Node, Var, _, _),
1678
+ phrase(skip_to_var_(Var, _, Pairs0, _), Weights0),
1679
+ include(<(0), Weights0, Weights),
1680
+ sum_list(Weights, MaxTo)
1681
+ ).
1682
+
1683
+ skip_to_var(Var, Weight, Pairs0, Pairs) :-
1684
+ phrase(skip_to_var_(Var, Weight, Pairs0, Pairs), _).
1685
+
1686
+ skip_to_var_(Var, Weight, [Var0-Weight0|VWs0], VWs) -->
1687
+ ( { Var == Var0 } ->
1688
+ { Weight = Weight0, VWs0 = VWs }
1689
+ ; ( { Weight0 =< 0 } -> []
1690
+ ; [Weight0]
1691
+ ),
1692
+ skip_to_var_(Var, Weight, VWs0, VWs)
1693
+ ).
1694
+
1695
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1696
+ Projection to residual goals.
1697
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1698
+
1699
+
1700
+ :- dynamic(clpb_residuals/1).
1701
+
1702
+ attribute_goals(Var) -->
1703
+ { var_index_root(Var, _, Root) },
1704
+ !,
1705
+ ( { root_get_formula_bdd(Root, Formula, BDD) } ->
1706
+ { del_bdd(Root) },
1707
+ ( { clpb_residuals(bdd) } ->
1708
+ { bdd_nodes(BDD, Nodes),
1709
+ phrase(nodes(Nodes), Ns) },
1710
+ [clpb:'$clpb_bdd'(Ns)]
1711
+ ; { phrase(sat_ands(Formula), Ands0),
1712
+ ands_fusion(Ands0, Ands),
1713
+ maplist(formula_anf, Ands, ANFs0),
1714
+ sort(ANFs0, ANFs1),
1715
+ exclude(eq_1, ANFs1, ANFs2),
1716
+ variables_separation(ANFs2, ANFs) },
1717
+ sats(ANFs)
1718
+ ),
1719
+ ( { get_attr(Var, clpb_atom, Atom) } ->
1720
+ [clpb:sat(Var=:=Atom)]
1721
+ ; []
1722
+ ),
1723
+ % formula variables not occurring in the BDD should be booleans
1724
+ { bdd_variables(BDD, Vs),
1725
+ maplist(del_clpb, Vs),
1726
+ term_variables(Formula, RestVs0),
1727
+ include(clpb_variable, RestVs0, RestVs) },
1728
+ booleans(RestVs)
1729
+ ; boolean(Var) % the variable may have occurred only in taut/2
1730
+ ).
1731
+ attribute_goals(Var) -->
1732
+ { get_atts(Var, clpb_max(_)),
1733
+ !,
1734
+ put_atts(Var, -clpb_max(_)) }.
1735
+ attribute_goals(Var) -->
1736
+ { get_atts(Var, clpb_bdd(BDD)),
1737
+ ground(BDD),
1738
+ put_atts(Var, -clpb_bdd(_)) }.
1739
+
1740
+ del_clpb(Var) :-
1741
+ del_attr(Var, clpb),
1742
+ del_attr(Var, clpb_hash),
1743
+ del_attr(Var, clpb_atom).
1744
+
1745
+ b_setval(K, T) :- bb_b_put(K, T).
1746
+ nb_setval(K, T) :- bb_put(K, T).
1747
+ b_getval(K, T) :- bb_get(K, T).
1748
+
1749
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1750
+ Fuse formulas that share the same variables into single conjunctions.
1751
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1752
+
1753
+ ands_fusion(Ands0, Ands) :-
1754
+ maplist(with_variables, Ands0, Pairs0),
1755
+ keysort(Pairs0, Pairs),
1756
+ group_pairs_by_key(Pairs, Groups),
1757
+ pairs_values(Groups, Andss),
1758
+ maplist(list_to_conjunction, Andss, Ands).
1759
+
1760
+ with_variables(F, Vs-F) :-
1761
+ term_variables(F, Vs0),
1762
+ variables_in_index_order(Vs0, Vs).
1763
+
1764
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1765
+ If possible, separate variables into different sat/1 goals.
1766
+ A formula F can be split in two if for two of its variables A and B,
1767
+ taut((A^F)*(B^F) =:= F, 1) holds. In the first conjunct, A does not
1768
+ occur, and in the second, B does not occur. We separate variables
1769
+ until that is no longer possible. There may be a better way to do this.
1770
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1771
+
1772
+ variables_separation(Fs0, Fs) :- separation_fixpoint(Fs0, [], Fs).
1773
+
1774
+ separation_fixpoint(Fs0, Ds0, Fs) :-
1775
+ phrase(variables_separation_(Fs0, Ds0, Rest), Fs1),
1776
+ partition(anf_done, Fs1, Ds1, Fs2),
1777
+ maplist(arg(1), Ds1, Ds2),
1778
+ maplist(arg(1), Fs2, Fs3),
1779
+ append(Ds0, Ds2, Ds3),
1780
+ append(Rest, Fs3, Fs4),
1781
+ sort(Fs4, Fs5),
1782
+ sort(Ds3, Ds4),
1783
+ ( Fs5 == [] -> Fs = Ds4
1784
+ ; separation_fixpoint(Fs5, Ds4, Fs)
1785
+ ).
1786
+
1787
+ anf_done(done(_)).
1788
+
1789
+ variables_separation_([], _, []) --> [].
1790
+ variables_separation_([F0|Fs0], Ds, Rest) -->
1791
+ ( { member(Done, Ds), F0 == Done } ->
1792
+ variables_separation_(Fs0, Ds, Rest)
1793
+ ; { sat_rewrite(F0, F),
1794
+ sat_bdd(F, BDD),
1795
+ bdd_variables(BDD, Vs0),
1796
+ exclude(universal_var, Vs0, Vs),
1797
+ maplist(existential_(BDD), Vs, Nodes),
1798
+ phrase(pairs(Nodes), Pairs),
1799
+ group_pairs_by_key(Pairs, Groups),
1800
+ phrase(groups_separation(Groups, BDD), ANFs) },
1801
+ ( { ANFs = [_|_] } ->
1802
+ list(ANFs),
1803
+ { Rest = Fs0 }
1804
+ ; [done(F0)],
1805
+ variables_separation_(Fs0, Ds, Rest)
1806
+ )
1807
+ ).
1808
+
1809
+
1810
+ existential_(BDD, V, Node) :- existential(V, BDD, Node).
1811
+
1812
+ groups_separation([], _) --> [].
1813
+ groups_separation([BDD1-BDDs|Groups], OrigBDD) -->
1814
+ { phrase(separate_pairs(BDDs, BDD1, OrigBDD), Nodes) },
1815
+ ( { Nodes = [_|_] } ->
1816
+ nodes_anfs([BDD1|Nodes])
1817
+ ; []
1818
+ ),
1819
+ groups_separation(Groups, OrigBDD).
1820
+
1821
+ separate_pairs([], _, _) --> [].
1822
+ separate_pairs([BDD2|Ps], BDD1, OrigBDD) -->
1823
+ ( { apply(*, BDD1, BDD2, And),
1824
+ And == OrigBDD } ->
1825
+ [BDD2]
1826
+ ; []
1827
+ ),
1828
+ separate_pairs(Ps, BDD1, OrigBDD).
1829
+
1830
+ nodes_anfs([]) --> [].
1831
+ nodes_anfs([N|Ns]) --> { node_anf(N, ANF) }, [anf(ANF)], nodes_anfs(Ns).
1832
+
1833
+ pairs([]) --> [].
1834
+ pairs([V|Vs]) --> pairs_(Vs, V), pairs(Vs).
1835
+
1836
+ pairs_([], _) --> [].
1837
+ pairs_([B|Bs], A) --> [A-B], pairs_(Bs, A).
1838
+
1839
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1840
+ Assert clpb:clpb_residuals(bdd) to obtain the BDD nodes as
1841
+ residuals. Note that they cannot be used as regular goals.
1842
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1843
+
1844
+ nodes([]) --> [].
1845
+ nodes([Node|Nodes]) -->
1846
+ { node_var_low_high(Node, Var0, Low, High),
1847
+ var_or_atom(Var0, Var),
1848
+ maplist(node_projection, [Node,High,Low], [ID,HID,LID]),
1849
+ var_index(Var0, VI) },
1850
+ [ID-(v(Var,VI) -> HID ; LID)],
1851
+ nodes(Nodes).
1852
+
1853
+
1854
+ node_projection(Node, Projection) :-
1855
+ node_id(Node, ID),
1856
+ ( integer(ID) -> Projection = node(ID)
1857
+ ; Projection = ID
1858
+ ).
1859
+
1860
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1861
+ By default, residual goals are sat/1 calls of the remaining formulas,
1862
+ using (mostly) algebraic normal form.
1863
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1864
+
1865
+ sats([]) --> [].
1866
+ sats([A|As]) --> [clpb:sat(A)], sats(As).
1867
+
1868
+ booleans([]) --> [].
1869
+ booleans([B|Bs]) --> boolean(B), booleans(Bs).
1870
+
1871
+ boolean(Var) -->
1872
+ { del_clpb(Var) },
1873
+ ( { get_attr(Var, clpb_omit_boolean, true) } ->
1874
+ { put_atts(Var, -clpb_omit_boolean(_)) }
1875
+ ; [clpb:sat(Var =:= Var)]
1876
+ ).
1877
+
1878
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1879
+ Relate a formula to its algebraic normal form (ANF).
1880
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1881
+
1882
+ formula_anf(Formula0, ANF) :-
1883
+ parse_sat(Formula0, Formula),
1884
+ sat_bdd(Formula, Node),
1885
+ node_anf(Node, ANF).
1886
+
1887
+ node_anf(Node, ANF) :-
1888
+ node_xors(Node, Xors0),
1889
+ maplist(maplist(monotonic_variable), Xors0, Xors),
1890
+ maplist(list_to_conjunction, Xors, Conjs),
1891
+ ( Conjs = [Var,C|Rest], clpb_var(Var) ->
1892
+ foldl(xor, Rest, C, RANF),
1893
+ ANF = (Var =\= RANF)
1894
+ ; Conjs = [One,Var,C|Rest], One == 1, clpb_var(Var) ->
1895
+ foldl(xor, Rest, C, RANF),
1896
+ ANF = (Var =:= RANF)
1897
+ ; Conjs = [C|Cs],
1898
+ foldl(xor, Cs, C, ANF)
1899
+ ).
1900
+
1901
+ monotonic_variable(Var0, Var) :-
1902
+ ( var(Var0), monotonic ->
1903
+ Var = v(Var0)
1904
+ ; Var = Var0
1905
+ ).
1906
+
1907
+ clpb_var(Var) :- var(Var), !.
1908
+ clpb_var(v(_)).
1909
+
1910
+ list_to_conjunction([], 1).
1911
+ list_to_conjunction([L|Ls], Conj) :- foldl(and, Ls, L, Conj).
1912
+
1913
+ xor(A, B, B # A).
1914
+
1915
+ eq_1(V) :- V == 1.
1916
+
1917
+ node_xors(Node, Xors) :-
1918
+ phrase(xors(Node), Xors0),
1919
+ % we remove elements that occur an even number of times (A#A --> 0)
1920
+ maplist(sort, Xors0, Xors1),
1921
+ pairs_keys_values(Pairs0, Xors1, _),
1922
+ keysort(Pairs0, Pairs),
1923
+ group_pairs_by_key(Pairs, Groups),
1924
+ exclude(even_occurrences, Groups, Odds),
1925
+ pairs_keys(Odds, Xors2),
1926
+ maplist(exclude(eq_1), Xors2, Xors).
1927
+
1928
+ even_occurrences(_-Ls) :- length(Ls, L), L mod 2 =:= 0.
1929
+
1930
+ xors(Node) -->
1931
+ ( { Node == 0 } -> []
1932
+ ; { Node == 1 } -> [[1]]
1933
+ ; { node_var_low_high(Node, Var0, Low, High),
1934
+ var_or_atom(Var0, Var),
1935
+ node_xors(Low, Ls0),
1936
+ node_xors(High, Hs0),
1937
+ maplist(with_var(Var), Ls0, Ls),
1938
+ maplist(with_var(Var), Hs0, Hs) },
1939
+ list(Ls0),
1940
+ list(Ls),
1941
+ list(Hs)
1942
+ ).
1943
+
1944
+ list([]) --> [].
1945
+ list([L|Ls]) --> [L], list(Ls).
1946
+
1947
+ with_var(Var, Ls, [Var|Ls]).
1948
+
1949
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1950
+ Global variables for unique node and variable IDs and atoms.
1951
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1952
+
1953
+ make_clpb_var('$clpb_next_var') :- nb_setval('$clpb_next_var', 0).
1954
+
1955
+ make_clpb_var('$clpb_next_node') :- nb_setval('$clpb_next_node', 0).
1956
+
1957
+ make_clpb_var('$clpb_atoms') :-
1958
+ empty_assoc(E),
1959
+ nb_setval('$clpb_atoms', E).
1960
+
1961
+ :- initialization((make_clpb_var(_),false;true)).
1962
+
1963
+ clpb_next_id(Var, ID) :-
1964
+ b_getval(Var, ID),
1965
+ Next is ID + 1,
1966
+ b_setval(Var, Next).
1967
+
1968
+ clpb_atom_var(Atom, Var) :-
1969
+ b_getval('$clpb_atoms', A0),
1970
+ ( get_assoc(Atom, A0, Var) -> true
1971
+ ; put_attr(Var, clpb_atom, Atom),
1972
+ put_attr(Var, clpb_omit_boolean, true),
1973
+ put_assoc(Atom, A0, Var, A),
1974
+ b_setval('$clpb_atoms', A)
1975
+ ).