-
Notifications
You must be signed in to change notification settings - Fork 9
/
functions.py
2252 lines (1904 loc) · 103 KB
/
functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import inspect
import math
import types
from collections import namedtuple
from pycsp3.classes.auxiliary.conditions import Condition, eq, le
from pycsp3.classes.auxiliary.enums import TypeOrderedOperator, TypeConditionOperator, TypeVar, TypeCtr, TypeCtrArg, TypeRank
from pycsp3.classes.auxiliary.diagrams import Automaton, MDD
from pycsp3.classes.entities import (
EVar, EVarArray, ECtr, EMetaCtr, ECtrs, EToGather, EToSatisfy, EBlock, ESlide, EAnd, EOr, ENot, EXor, EIfThen, EIfThenElse, EIff, EObjective, EAnnotation,
AnnEntities, CtrEntities, ObjEntities)
from pycsp3.classes.main.annotations import (
AnnotationDecision, AnnotationOutput, AnnotationVarHeuristic, AnnotationValHeuristic, AnnotationFiltering, AnnotationPrepro, AnnotationSearch,
AnnotationRestarts)
from pycsp3.classes.main.constraints import (
ConstraintIntension, ConstraintExtension, ConstraintRegular, ConstraintMdd, ConstraintAllDifferent,
ConstraintAllDifferentList, ConstraintAllDifferentMatrix, ConstraintAllEqual, ConstraintAllEqualList, ConstraintOrdered, ConstraintLex, ConstraintLexMatrix,
ConstraintPrecedence, ConstraintSum, ConstraintCount, ConstraintNValues, ConstraintCardinality, ConstraintMaximum,
ConstraintMinimum, ConstraintMaximumArg, ConstraintMinimumArg, ConstraintElement, ConstraintChannel, ConstraintNoOverlap, ConstraintCumulative,
ConstraintBinPacking, ConstraintKnapsack, ConstraintFlow, ConstraintCircuit, ConstraintClause, ConstraintAdhoc, ConstraintRefutation,
ConstraintDummyConstant, ConstraintSlide, PartialConstraint, ScalarProduct, auxiliary, manage_global_indirection)
from pycsp3.classes.main.objectives import ObjectiveExpression, ObjectivePartial
from pycsp3.classes.main.variables import Domain, Variable, VariableInteger, VariableSymbolic
from pycsp3.classes.nodes import TypeNode, Node
from pycsp3.dashboard import options
from pycsp3.tools.curser import queue_in, columns, OpOverrider, ListInt, ListVar, ListMultipleVar, ListCtr, cursing, convert_to_namedtuples
from pycsp3.tools.inspector import checkType, extract_declaration_for, comment_and_tags_of, comments_and_tags_of_parameters_of
from pycsp3.tools.utilities import (flatten, is_containing, is_1d_list, is_1d_tuple, is_matrix, ANY, ALL, warning, warning_if, error_if)
from pycsp3.classes.auxiliary.tables import to_starred_table_for_no_overlap1, to_starred_table_for_no_overlap2
''' Global Variables '''
absPython, maxPython, minPython = abs, max, min
EQ, NE, IN, NOTIN, SET = TypeNode.EQ, TypeNode.NE, TypeNode.IN, TypeNode.NOTIN, TypeNode.SET
started_modeling = False # It becomes true when the first variable or array of variables is defined (cursing is then activated)
def protect():
"""
Disables the redefined operators (==, >, >=, etc.), and returns the object OpOverrider.
On can then execute some code in protected mode by calling execute().
Once the code is executed, the redefined operators are reactivated.
The code typically looks like:
protect().execute(...)
:return: the object OpOverrider
"""
return OpOverrider.disable()
''' Checking Model Variants '''
def variant(name=None):
"""
Returns the name of the variant given on the command line (option -variant) if the specified argument is None.
Returns True iff the variant given on the command line is equal to the argument otherwise.
Note that the variant given on the command line is the substring until the symbol '-' (after this symbol,
the name of the sub-variant starts), or the end of the string
:param name: the name of a variant, or None
:return: the name of the variant specified by the user, or a Boolean
"""
assert options.variant is None or isinstance(options.variant, str)
pos = -1 if options.variant is None else options.variant.find("-") # position of dash in options.variant
option_variant = options.variant[0:pos] if pos != -1 else options.variant
return option_variant if name is None else option_variant == name
def subvariant(name=None):
"""
Returns the name of the sub-variant given on the command line (option -variant) if the specified argument is None.
Returns True iff the sub-variant given on the command line is equal to the argument otherwise.
Note that the sub-variant given on the command line is the substring starting after the symbol '-' (before this symbol,
this is the name of the variant).
:param name: the name of a sub-variant, or None
:return: the name of the sub-variant specified by the user, or a Boolean
"""
assert options.variant is None or isinstance(options.variant, str)
pos = -1 if options.variant is None else options.variant.find("-") # position of dash in options.variant
option_subvariant = options.variant[pos + 1:] if pos != -1 else None
return option_subvariant if name is None else option_subvariant == name
''' Declaring stand-alone variables and arrays '''
def _valid_identifier(s):
return isinstance(s, str) and all(c.isalnum() or c == '_' for c in s) # other characters to be allowed?
def Var(term=None, *others, dom=None, id=None):
"""
Builds a stand-alone variable with the specified domain.
The domain is either given by the named parameter dom, or given
by the sequence of terms passed as parameters. For example:
x = Var(0,1)
y = Var(range(10))
z = Var(v for v in range(100) if v%3 == 0)
:param term: the first term defining the domain, or None
:param others: the other terms defining the domain, or None
:param dom: the domain of the variable, or None
:param id: the id (name) of the variable, or None (usually, None)
:return: a stand-alone Variable with the specified domain
"""
global started_modeling
if not started_modeling and not options.uncurse:
cursing()
started_modeling = True
if term is None and dom is None:
dom = Domain(math.inf)
assert not (term and dom)
if term is not None:
dom = flatten(term, others)
if not isinstance(dom, Domain):
if isinstance(dom, (set, frozenset)):
dom = list(dom)
if isinstance(dom, (tuple, list)) and len(dom) > 1 and isinstance(dom[0], int):
dom = sorted(dom)
if dom[-1] - dom[0] + 1 == len(dom):
dom = range(dom[0], dom[-1] + 1)
dom = Domain(dom)
error_if(dom.type not in {TypeVar.INTEGER, TypeVar.SYMBOLIC},
"Currently, only integer and symbolic variables are supported. Problem with " + str(dom))
var_name = id if id else extract_declaration_for("Var") # the specified name, if present, has priority
# if var_name is None: # TODO: I do not remember the use of that piece of code
# if not hasattr(Var, "fly"):
# Var.fly = True
# warning("at least, one variable created on the fly")
# return dom
error_if(not _valid_identifier(var_name), "The variable identifier " + str(var_name) + " is not valid")
error_if(var_name in Variable.name2obj, "The identifier " + str(var_name) + " is used twice. This is not possible")
comment, tags = comment_and_tags_of(function_name="Var")
assert isinstance(comment, (str, type(None))), "A comment must be a string (or None). Usually, they are given on plain lines preceding the declaration"
var_object = VariableInteger(var_name, dom) if dom.type == TypeVar.INTEGER else VariableSymbolic(var_name, dom)
Variable.name2obj[var_name] = var_object
EVar(var_object, comment, tags) # object wrapping the variable x
return var_object
def VarArray(doms=None, *, size=None, dom=None, dom_border=None, id=None, comment=None, tags=None):
"""
Builds an array of variables.
The number of dimensions of the array is given by the number of values in size.
The size of the ith dimension is given by the ith value of size.
The domain is either the same for all variables, and then directly given by dom,
or specific to each variable, in which case dom must a function.
:param size: the size of each dimension of the array
:param dom: the domain of the variables
:param dom_border: the domain of the cells at the border of the (two-dimensional) array
:param id: the id (name) of the array, or None (usually, None)
:param comment: a string
:param tags a (possibly empty) list of tags
:return: an array of variables
"""
global started_modeling
if not started_modeling and not options.uncurse:
cursing()
started_modeling = True
if doms is not None:
assert isinstance(doms, list) and size is None and dom is None and dom_border is None and comment is None
assert all(isinstance(dom, Domain) or dom is None for dom in doms)
return VarArray(size=len(doms), dom=lambda i: doms[i])
if dom_border is not None:
assert len(size) == 2 and dom is not None
if isinstance(dom, type(lambda: 0)):
return VarArray(size=size, dom=lambda i, j: dom_border if i in (0, size[0] - 1) or j in (0, size[1] - 1) else dom(i, j))
return VarArray(size=size, dom=lambda i, j: dom_border if i in (0, size[0] - 1) or j in (0, size[1] - 1) else dom)
size = [size] if isinstance(size, int) else size
if len(size) > 1 and isinstance(size[-1], (tuple, list)): # it means that the last dimension is of variable length
if isinstance(dom, type(lambda: 0)):
return VarArray(size=size[:-1] + [max(size[-1])], dom=dom)
return VarArray(size=size[:-1] + [max(size[-1])], dom=lambda *ids: dom if ids[-1] < size[-1][ids[-2]] else None)
error_if(any(dimension == 0 for dimension in size), "No dimension must not be equal to 0")
checkType(size, [int])
# checkType(dom, (range, Domain, [int, range, str, Domain, type(None)], type(lambda: 0))) # TODO a problem with large sets
ext_name = extract_declaration_for("VarArray")
if isinstance(ext_name, list):
array_name = ext_name
error_if(id, "The parameter 'id' is not compatible with the specification of a list of individual names")
error_if(any(not _valid_identifier(v) for v in ext_name), "Some identifiers in " + str(ext_name) + " are not valid")
error_if(any(v in Variable.name2obj for v in ext_name), "Some identifiers in " + str(ext_name) + " are used twice.")
else:
array_name = id if id else ext_name # the specified name, if present, has priority
error_if(not _valid_identifier(array_name), "The variable identifier " + str(array_name) + " is not valid")
error_if(array_name in Variable.name2obj, "The identifier " + str(array_name) + " is used twice. This is not possible")
if comment is None and tags is None and not isinstance(array_name, list):
comment, tags = comment_and_tags_of(function_name="VarArray")
assert isinstance(comment, (str, type(None))), "A comment must be a string (or None). Usually, they are given on plain lines preceding the declaration"
if isinstance(dom, type(lambda: 0)):
r = len(inspect.signature(dom).parameters) # r=1 means that it must be a lambda *args:
assert len(size) == r or r == 1, "The number of arguments of the lambda must be equal to the number of dimensions of the multidimensional array "
assert isinstance(comment, (str, type(None))), "A comment must be a string (or None). Usually, they are given on plain lines preceding the declaration"
if isinstance(dom, (tuple, list, set, frozenset)):
vals = set(flatten(dom))
assert len(vals) > 0
min_value, max_value = min(vals), max(vals)
dom = range(min_value, max_value + 1) if isinstance(min_value, int) and 3 < len(vals) == (max_value - min_value + 1) else Domain(vals)
var_objects = Variable.build_variables_array(array_name, size, dom)
if isinstance(array_name, list):
assert (len(array_name) == len(var_objects))
for i in range(len(array_name)):
Variable.name2obj[array_name[i]] = var_objects[i]
EVar(var_objects[i], None, None) # object wrapping the variables
return tuple(var_objects)
else:
def _to_ListVar(t):
if t is None:
return None
if isinstance(t, Variable):
return t
assert isinstance(t, list)
return ListVar(_to_ListVar(x) for x in t)
Variable.name2obj[array_name] = var_objects
lv = _to_ListVar(var_objects)
EVarArray(lv, array_name, comment, tags) # object wrapping the array of variables
Variable.arrays.append(lv)
return lv
def VarArrayMultiple(*, size, fields):
assert isinstance(fields, dict) and all(isinstance(k, str) for k in fields)
size = [size] if isinstance(size, int) else size
checkType(size, [int])
comment, tags = comment_and_tags_of(function_name="VarArrayMultiple")
cname = extract_declaration_for("VarArrayMultiple")
arrays = [VarArray(size=size, dom=fields[k], id=cname + "_" + k,
comment="field " + str(k) + " of " + str(cname) + ("; " + comment if comment is not None else ""), tags=tags) for k in fields]
if not hasattr(VarArrayMultiple, "cnt"):
VarArrayMultiple.cnt = 0
NT = namedtuple("ant" + str(VarArrayMultiple.cnt), fields.keys())
VarArrayMultiple.cnt += 1
NT.__eq__ = ListVar.__eq__ # OpOverrider.__eq__lv
NT.__ne__ = ListVar.__ne__ # OpOverrider.__ne__lv
NT.__getitem__ = ListVar.__getitem__ # OpOverrider.__getitem__lv
def __rec(dims, subarrays):
if len(dims) == 0:
return NT(*[sub for sub in subarrays])
return ListMultipleVar([__rec(dims[1:], [sub[i] for sub in subarrays]) for i in range(dims[0])])
return __rec(size, arrays).add_fields(list(fields.keys()))
def var(name):
"""
Returns the variable or variable array whose name is specified
:param name: the name of the variable or variable array to be returned
"""
assert isinstance(name, str)
error_if(name not in Variable.name2obj,
"the variable, or variable array, specified when calling the function 'var()' with the name " + name + " has not been declared")
return Variable.name2obj[name]
''' Posting constraints (through satisfy()) '''
def _bool_interpretation_for_in(left_operand, right_operand, bool_value):
assert type(bool_value) is bool
if isinstance(left_operand, Variable):
if isinstance(right_operand, (tuple, list, set, frozenset, range)) and len(right_operand) == 0:
return None
if isinstance(right_operand, (tuple, list, set, frozenset)) and is_containing(right_operand, Variable):
if len(right_operand) < 4: # TODO hard coding (introducing an option to adjust that?)
st = Node.build(SET, right_operand)
return _Intension(Node.build(IN, left_operand, st) if bool_value else Node.build(NOTIN, left_operand, st))
if bool_value:
condition = Condition.build_condition((TypeConditionOperator.EQ, left_operand))
return ECtr(ConstraintElement(flatten(right_operand), index=None, condition=condition)) # member
else:
return [_Intension(Node.build(NE, left_operand, y)) for y in right_operand]
# condition = Condition.build_condition(TypeConditionOperator.NE, left_operand)
# return ECtr(ConstraintElement(flatten(right_operand), index=None, condition=condition)) # member
if isinstance(right_operand, range):
# return (right_operand.start <= left_operand) & (left_operand < right_operand.stop)
return _Extension(scope=[left_operand], table=list(right_operand), positive=bool_value)
if isinstance(left_operand, (Variable, int, str)) and isinstance(right_operand, (set, frozenset, range)):
# it is a unary constraint of the form x in/not in set/range
return _Intension(Node.build(IN, left_operand, right_operand) if bool_value else Node.build(NOTIN, left_operand, right_operand))
# elif isinstance(left_operand, Node) and isinstance(right_operand, range):
# if bool_value:
# ctr = Intension(conjunction(left_operand >= right_operand.start, left_operand <= right_operand.stop - 1))
# else:
# ctr = Intension(disjunction(left_operand < right_operand.start, left_operand > right_operand.stop - 1))
elif isinstance(left_operand, PartialConstraint): # it is a partial form of constraint (sum, count, maximum, ...)
ctr = ECtr(left_operand.constraint.set_condition(TypeConditionOperator.IN if bool_value else TypeConditionOperator.NOTIN, right_operand))
elif isinstance(right_operand, Automaton): # it is a regular constraint
ctr = Regular(scope=left_operand, automaton=right_operand)
elif isinstance(right_operand, MDD): # it is an MDD constraint
ctr = Mdd(scope=left_operand, mdd=right_operand)
elif isinstance(left_operand, int) and (is_1d_list(right_operand, Variable) or is_1d_tuple(right_operand, Variable)):
ctr = Count(right_operand, value=left_operand, condition=(TypeConditionOperator.GE, 1)) # atLeast1 TODO to be replaced by a member/element constraint ?
# elif isinstance(left_operand, Node):
#
else: # It is a table constraint
if not hasattr(left_operand, '__iter__'):
left_operand = [left_operand]
assert isinstance(right_operand, list)
if not bool_value and len(right_operand) == 0:
return None
# TODO what to do if the table is empty and bool_value is true? an error message ?
# if len(right_operand) == 0: # it means an empty table, and Python will generate True (not in [] => True)
if len(left_operand) == 1:
if not is_1d_list(right_operand, int) and not is_1d_list(right_operand, str):
assert all(isinstance(v, (tuple, list)) and len(v) == 1 for v in right_operand)
right_operand = [v[0] for v in right_operand]
ctr = _Extension(scope=flatten(left_operand), table=right_operand, positive=bool_value) # TODO ok for using flatten? (before it was list())
return ctr
def _complete_partial_forms_of_constraints(entities):
for i, c in enumerate(entities):
if isinstance(c, bool):
assert len(queue_in) > 0, "A boolean that does not represent a constraint is in the list of constraints in satisfy(): " + str(entities)
right_operand, left_operand = queue_in.popleft()
entities[i] = _bool_interpretation_for_in(left_operand, right_operand, c)
elif isinstance(c, ESlide):
for ent in c.entities:
_complete_partial_forms_of_constraints(ent.entities)
return entities
def _wrap_intension_constraints(entities):
for i, c in enumerate(entities):
if isinstance(c, Node):
entities[i] = _Intension(c) # the node is wrapped by a Constraint object (Intension)
return entities
def And(*args, meta=False):
"""
Builds a meta-constraint And from the specified arguments.
For example: And(Sum(x) > 10, AllDifferent(x))
When the parameter 'meta' is not true,
reification is employed.
:param args: a tuple of constraints
:param meta true if a meta-constraint form must be really posted
:return: a meta-constraint And, or its reified form
"""
if options.usemeta or meta:
return EAnd(_wrap_intension_constraints(_complete_partial_forms_of_constraints(flatten(*args))))
return conjunction(*args)
def Or(*args, meta=False):
"""
Builds a meta-constraint Or from the specified arguments.
For example: Or(Sum(x) > 10, AllDifferent(x))
When the parameter 'meta' is not true,
reification is employed.
:param args: a tuple of constraints
:param meta true if a meta-constraint form must be really posted
:return: a meta-constraint Or, or its reified form
"""
if options.usemeta or meta:
return EOr(_wrap_intension_constraints(_complete_partial_forms_of_constraints(flatten(*args))))
return disjunction(*args)
def Not(arg, meta=False):
"""
Builds a meta-constraint Not from the specified argument.
For example: Not(AllDifferent(x))
When the parameter 'meta' is not true,
reification is employed.
:param arg: a constraint
:param meta true if a meta-constraint form must be really posted
:return: a meta-constraint Not, or its reified form
"""
if options.usemeta or meta:
return ENot(_wrap_intension_constraints(_complete_partial_forms_of_constraints(arg)))
res = manage_global_indirection(arg)
if res is None:
return ENot(_wrap_intension_constraints(_complete_partial_forms_of_constraints(arg)))
return ~res # TODO to be checked
def Xor(*args, meta=False):
"""
Builds a meta-constraint Xor from the specified arguments.
For example: Xor(Sum(x) > 10, AllDifferent(x))
When the parameter 'meta' is not true,
reification is employed.
:param args: a tuple of constraints
:param meta true if a meta-constraint form must be really posted
:return: a meta-constraint Xor, or its reified form
"""
if options.usemeta or meta:
return EXor(_wrap_intension_constraints(_complete_partial_forms_of_constraints(flatten(*args))))
return xor(*args)
def If(test, *test_complement, Then, Else=None, meta=False):
"""
Builds a complex form of constraint(s), based on the general control structure 'if then else'
that can possibly be decomposed, at compilation time.
For example:
- If(Sum(x) > 10, Then=AllDifferent(x))
- If(Sum(x) > 10, Then=AllDifferent(x), Else=AllEqual(x))
- If(w > 0, y != z, Then=w == y + z)
- If(w > 0, y != z, Then=[w == y + z, v != 1])
- If(Sum(x) > 10, Then=y == z, Else=[AllEqual(x), y < 3])
When the parameter 'meta' is not true (the usual and default case),
reification may be employed.
:param test: the condition expression
:param test_complement: the other terms (if any) of the condition expression (assuming a conjunction)
:param Then the Then part
:param Else the Else part
:param meta true if a meta-constraint form must be really posted
:return: a complex form of constraint(s) based on the control structure 'if then else'
"""
# if len(testOthers) == 0 and isinstance(test, bool): # We don't allow that because otherwise 'in' no more usable as in If(x[0] in (2,3), Then=...
# return Then if test else Else
tests, thens = flatten(test, test_complement), [v for v in flatten(Then) if not (isinstance(v, ConstraintDummyConstant) and v.val == 1)]
assert isinstance(tests, list) and len(tests) > 0 and isinstance(thens, list) # after flatten, we have a list
if len(thens) == 0:
return None if Else is None else Or(tests, Else)
if options.usemeta or meta:
if Else is None:
return EIfThen(_wrap_intension_constraints(_complete_partial_forms_of_constraints(flatten(tests, thens))))
else:
return EIfThenElse(_wrap_intension_constraints(_complete_partial_forms_of_constraints(flatten(tests, thens, Else))))
tests, thens = manage_global_indirection(tests, also_pc=True), manage_global_indirection(thens, also_pc=True) # we get None or a list
assert tests is not None and thens is not None and len(tests) > 0 and len(thens) > 0
def __neg(term):
if isinstance(term, Variable):
assert term.dom.is_binary()
return var(term.id) if term.negation else Node.build(EQ, term, 0)
assert isinstance(term, Node) and term.type.is_predicate_operator()
sons = term.cnt
if term.type == TypeNode.NOT:
assert sons[0].type.is_predicate_operator()
return sons[0]
if term.type == TypeNode.AND:
return Node.build(TypeNode.OR, *[__neg(son) for son in sons])
if term.type == TypeNode.OR:
return Node.build(TypeNode.AND, *[__neg(son) for son in sons])
if term.type == TypeNode.IFF:
return Node.build(TypeNode.NOT, term)
if term.type == TypeNode.IMP:
assert len(sons) == 2 and sons[0].type.is_predicate_operator() and sons[1].type.is_predicate_operator()
return Node.build(TypeNode.AND, sons[0], Node.build(TypeNode.NOT, sons[1]))
if term.type == TypeNode.EQ and len(sons) == 2 and sons[1].type == TypeNode.INT and sons[1].cnt == 0 \
and sons[0].type == TypeNode.VAR and sons[0].cnt.dom.is_binary(): # x=0 => x
return sons[0].cnt
assert ~term.type is not None
return Node(~term.type, sons)
# if options.ev:
if Else is None and len(tests) == 1:
if isinstance(tests[0], Variable) and not tests[0].negation:
return [imply(tests, term) for term in flatten(thens)]
if len(thens) == 1:
if (not (isinstance(thens[0], Node) and thens[0].type == TypeNode.OR)
and not (isinstance(tests[0], Node) and tests[0].type == TypeNode.NOT)
and not (isinstance(tests[0], Variable) and tests[0].negation)):
return imply(tests, thens)
neg_test = __neg(tests[0]) if len(tests) == 1 else disjunction(__neg(term) for term in tests)
t = []
t.extend(disjunction(neg_test, term) for term in flatten(thens))
if Else is not None:
elses = [v for v in flatten(Else) if not (isinstance(v, ConstraintDummyConstant) and v.val == 1)]
elses = manage_global_indirection(elses, also_pc=True)
if len(elses) > 0:
test = conjunction(term for term in tests) if len(tests) > 1 else tests
t.extend(disjunction(test, v) for v in elses)
return t # [0] if len(t) == 1 else t
def Match(Expr, *, Cases):
assert isinstance(Cases, dict)
if isinstance(Expr, (tuple, list)):
r = len(Expr)
assert r > 1 and all(isinstance(v, (Variable, Node)) for v in Expr)
assert all(isinstance(k, (tuple, list)) and len(k) == r and all(isinstance(v, int) for v in k) for k in Cases.keys())
return [disjunction([Expr[i] != k[i] for i in range(r)] + [v]) for k, v in Cases.items()]
t = [(k, w) for k, v in Cases.items() for w in (v if isinstance(v, (tuple, list, set, frozenset)) else [v])]
if isinstance(Expr, (Variable, Node)):
return [expr(~k.operator, Expr, k.right_operand()) | v if isinstance(k, Condition)
else (Expr != k if not isinstance(k, (tuple, list, set, frozenset)) else not_belong(Expr, k)) | v for k, v in t]
else:
assert False, "Bad construction with Match: the expression must be a variable or an expression involving a variable"
# return [v for k, v in t if
# (not isinstance(k, (tuple, list, set, frozenset)) and Expr == k) or (isinstance(k, (tuple, list, set, frozenset)) and Expr in k)]
def Iff(*args, meta=True):
"""
Builds a meta-constraint Iff from the specified arguments.
For example: Iff(Sum(x) > 10, AllDifferent(x))
When the parameter 'meta' is not true,
reification is employed.
:param args: a tuple of constraints
:param meta true if a meta-constraint form must be really posted
:return: a meta-constraint Iff, or its reified form
"""
if meta:
return EIff(_wrap_intension_constraints(_complete_partial_forms_of_constraints(flatten(*args))))
return iff(*args)
def Slide(*args, expression=None, circular=None, offset=None, collect=None):
"""
Builds a meta-constraint Slide from the specified arguments.
Slide((x[i], x[i + 1]) in table for i in range(n - 1))
According to the specified constraints, the compiler may or may not succeed
in generating a slide meta-constraint.
:param args: a tuple of constraints
:return: a meta-constraint Slide
"""
if expression is not None: # the meta-constraint is defined directly by the user
return ECtr(ConstraintSlide(*args, expression, circular, offset, collect))
# we cannot directly complete partial forms (because it is executed before the analysis of the parameters of satisfy
entities = _wrap_intension_constraints(flatten(*args))
checkType(entities, [ECtr, bool])
return ESlide([EToGather(entities)])
def _group(*_args, block=False):
def _remove_dummy_constraints(tab):
if any(isinstance(v, ConstraintDummyConstant) for v in tab):
warning_if(any(isinstance(v, ConstraintDummyConstant) and v.val != 1 for v in tab), "It seems that there is a bad expression in the model")
return [v for v in tab if not isinstance(v, ConstraintDummyConstant)]
return tab
def _block_reorder(_entities):
reordered_entities = []
g = []
for c in _entities:
if isinstance(c, ECtr) and c.blank_basic_attributes():
g.append(c)
else:
if len(g) != 0:
reordered_entities.append(_group(g))
g.clear()
reordered_entities.append(c)
if len(g) != 0:
reordered_entities.append(_group(g))
return reordered_entities
tab = _remove_dummy_constraints(flatten(*_args))
if len(tab) == 0:
return None
entities = _wrap_intension_constraints(_complete_partial_forms_of_constraints(tab))
checkType(entities, [ECtr, ECtrs, EMetaCtr])
return EBlock(_block_reorder(entities)) if block else EToGather(entities)
def satisfy_from_auxiliary(t):
if t is None:
t = []
to_post = _group(pc == var for (pc, var) in auxiliary().get_collected_and_clear())
if to_post is not None:
t.append(to_post)
to_post = _group(auxiliary().get_collected_raw_and_clear())
if to_post is not None:
t.append(to_post)
to_post = _group((index, aux) in table for (index, aux, table) in auxiliary().get_collected_extension_and_clear())
if to_post is not None:
t.append(to_post)
return EToSatisfy(t)
def satisfy(*args, no_comment_tags_extraction=False):
"""
Posts all constraints that are specified as arguments
:param args: the different constraints to be posted
:return: an object wrapping the posted constraints
"""
def _reorder(l): # if constraints are given in (sub-)lists inside tuples; we flatten and reorder them to hopefully improve compactness
d = dict()
for tp in l:
if isinstance(tp, (tuple, list)):
for i, v in enumerate(tp):
d.setdefault(i, []).append(v)
else:
d.setdefault(0, []).append(tp)
return [v for vs in d.values() for v in vs]
comments1, comments2, tags1, tags2 = comments_and_tags_of_parameters_of(function_name="satisfy", args=args, no_extraction=no_comment_tags_extraction)
t = []
for i, arg in enumerate(args):
if arg is None:
continue
if isinstance(arg, ConstraintDummyConstant):
warning_if(arg.val != 1, "It seems that there is a bad expression in the model " + str(arg))
continue
if isinstance(arg, (tuple, set, frozenset, types.GeneratorType)):
arg = list(arg)
if isinstance(arg, list) and any(v is None for v in arg):
# TODO: what if there is a trailing comma?
if len(arg) == len(comments2[i]):
comments2[i] = [c for i, c in enumerate(comments2[i]) if arg[i] is not None]
if len(arg) == len(tags2[i]):
tags2[i] = [c for i, c in enumerate(tags2[i]) if arg[i] is not None]
arg = [v for v in arg if v is not None]
if isinstance(arg, list) and len(arg) > 0:
if isinstance(arg[0], tuple):
arg = _reorder(arg)
elif isinstance(arg[0], list): # do not work if the constraints involve the operator 'in'
# triple_list = all(isinstance(ar, list) and (len(ar) == 0 or isinstance(ar, (tuple, list))) for ar in arg)
# if triple_list:
# arg = _reorder(flatten(arg))
# else:
for j, l in enumerate(arg):
if isinstance(l, list) and len(l) > 0 and isinstance(l[0], tuple):
arg[j] = _reorder(l)
if isinstance(arg, Variable):
assert arg.dom.is_binary()
b = arg.negation
arg.negation = False
arg = (arg == (0 if b else 1)) # transformed into a basic logical equation
assert isinstance(arg, (ECtr, EMetaCtr, ESlide, Node, bool, list)), "non authorized type " + str(arg) + " " + str(type(arg))
comment_at_2 = any(comment != '' for comment in comments2[i])
tag_at_2 = any(tag != '' for tag in tags2[i])
if isinstance(arg, (ECtr, EMetaCtr, ESlide)): # case: simple constraint or slide
if isinstance(arg, ECtr) and isinstance(arg.constraint, ConstraintRefutation): # refutations must be transformed
to_post = _group(arg.constraint.to_list())
else:
to_post = _complete_partial_forms_of_constraints([arg])[0]
elif isinstance(arg, Node): # a predicate to be wrapped by a constraint (intension)
to_post = _Intension(arg)
elif isinstance(arg, bool): # a Boolean representing the case of a partial constraint or a node with operator in {IN, NOT IN}
assert queue_in, "An argument of satisfy() before position " + str(i) + " is badly formed"
other, partial = queue_in.popleft()
to_post = _bool_interpretation_for_in(partial, other, arg)
if isinstance(to_post, list):
to_post = _group(to_post)
else:
assert isinstance(arg, list)
if any(isinstance(ele, ESlide) for ele in arg): # Case: Slide
to_post = _group(arg, block=True)
elif comment_at_2 or tag_at_2: # Case: block
if len(arg) == len(comments2[i]) - 1 == len(tags2[i]) - 1 and comments2[i][-1] == "" and tags2[i][-1] == "":
# this avoids the annoying case where there is a comma at the end of the last line in a block
comments2[i] = comments2[i][:-1]
tags2[i] = tags2[i][:-1]
if len(arg) == len(comments2[i]) == len(tags2[i]): # if comments are not too wildly put
for j in range(len(arg)):
if isinstance(arg[j], (ECtr, ESlide)):
arg[j].note(comments2[i][j]).tag(tags2[i][j])
else: # if comments2[i][j] or tags2[i][j]: PB if we use this as indicated below
# BE CAREFUL: if bool present _group must be executed systematically (otherwise, confusion between false and True possible)
if isinstance(arg[j], list) and len(arg[j]) == 1:
arg[j] = arg[j][0]
if isinstance(arg[j], list) and len(arg[j]) > 0 and isinstance(arg[j][0], list):
for k in range(len(arg[j])):
arg[j][k] = _group(arg[j][k])
arg[j] = _group(arg[j], block=True).note(comments2[i][j]).tag(tags2[i][j])
else:
g = _group(arg[j]) # , block=True)
arg[j] = g.note(comments2[i][j]).tag(tags2[i][j]) if g is not None else None
to_post = _group(arg, block=True)
else: # Group
to_post = _group(arg)
if to_post is not None:
# to_post_aux = satisfy_from_auxiliary()
# if len(to_post_aux) > 0:
# to_post = EBlock(flatten(to_post, to_post_aux))
t.append(to_post.note(comments1[i]).tag(tags1[i]))
# if isinstance(to_post, ESlide) and len(to_post.entities) == 1:
# to_post.entities[0].note(comments1[i]).tag(tags1[i])
# return EToSatisfy(t)
return satisfy_from_auxiliary(t)
''' Generic Constraints (intension, extension) '''
def _Extension(*, scope, table, positive=True):
scope = flatten(scope)
assert len(scope) == len(set(scope))
checkType(scope, [Variable])
assert isinstance(table, list)
assert len(table) > 0, "A table must be a non-empty list of tuples or integers (or symbols)"
checkType(positive, bool)
if len(scope) == 1:
assert all(isinstance(v, int) if isinstance(scope[0], VariableInteger) else isinstance(v, str) for v in table)
else: # if all(isinstance(x, VariableInteger) for x in scope):
for i, t in enumerate(table):
if isinstance(t, (list, types.GeneratorType)):
table[i] = t = tuple(t)
else:
assert isinstance(t, tuple), str(t)
# we now manage shortcut expressions as in col(i) instead of eq(col(i)), and discard trivial ranges
if any(isinstance(v, (range, Node)) for v in t):
table[i] = tuple(eq(v) if isinstance(v, Node) else v.start if isinstance(v, range) and len(v) == 1 else v for v in t)
if len(t) != len(scope):
t = tuple(flatten(t))
assert len(t) == len(scope), (
"The length of each tuple must be the same as the arity (here, we have " + str(len(t)) + " vs " + str(len(scope)) + "). "
+ "Maybe a problem with slicing: you must for example write x[i:i+3,0] instead of x[i:i+3][0]")
table[i] = t
return ECtr(ConstraintExtension(scope, table, positive, options.keephybrid, options.restricttableswrtdomains))
def Table(*, scope, supports=None, conflicts=None):
"""
Builds and returns a constraint Table.
:param scope: the sequence of (distinct) involved variables
:param supports: the set/list of tuples, seen as supports (positive table)
:param conflicts: the set/list of tuples, seen as conflicts (negative table)
:return: a constraint Table (Extension)
"""
assert scope is not None and (supports is None) != (conflicts is None)
table = supports if supports is not None else conflicts
table = list(table) if isinstance(table, (set, frozenset)) else table
return _Extension(scope=scope, table=table, positive=supports is not None)
def _Intension(node):
checkType(node, Node)
ctr = ECtr(ConstraintIntension(node))
if ctr.blank_basic_attributes():
ctr.copy_basic_attributes_of(node)
node.mark_as_used()
return ctr
def col(*args):
assert len(args) == 1 and isinstance(args[0], int)
return Node(TypeNode.COL, args[0])
def abs(arg):
"""
If the specified argument is a node or a variable of the model, the function builds
and returns a node 'abs', root of a tree expression where the specified argument is a child.
Otherwise, the function returns, as usual, the absolute value of the specified argument
:return: either a node, root of a tree expression, or the absolute value of the specified argument
"""
if isinstance(arg, PartialConstraint):
arg = auxiliary().replace_partial_constraint(arg)
if isinstance(arg, Node) and arg.type == TypeNode.SUB:
return Node.build(TypeNode.DIST, arg.cnt)
return Node.build(TypeNode.ABS, arg) if isinstance(arg, (Node, Variable)) else absPython(arg)
def min(*args):
"""
When one of the specified arguments is a node or a variable of the model, the function builds
and returns a node 'min', root of a tree expression where specified arguments are children.
Otherwise, the function returns, as usual, the smallest item of the specified arguments
:return: either a node, root of a tree expression, or the smallest item of the specified arguments
"""
return args[0] if len(args) == 1 and isinstance(args[0], (int, str)) else Node.build(TypeNode.MIN, *args) if len(args) > 1 and any(
isinstance(a, (Node, Variable)) for a in args) else minPython(*args)
def max(*args):
"""
When one of the specified arguments is a node or a variable of the model, the function builds
and returns a node 'max', root of a tree expression where specified arguments are children.
Otherwise, the function returns, as usual, the largest item of the specified arguments
:return: either a node, root of a tree expression, or the largest item of the specified arguments
"""
return args[0] if len(args) == 1 and isinstance(args[0], (int, str)) else Node.build(TypeNode.MAX, *args) if len(args) > 1 and any(
isinstance(a, (Node, Variable)) for a in args) else maxPython(*args)
def xor(*args):
"""
If there is only one argument, returns it.
Otherwise, builds and returns a node 'xor', root of a tree expression where specified arguments are children.
Without any parent, it becomes a constraint.
:return: a node, root of a tree expression or the argument if there is only one
"""
if len(args) == 1 and isinstance(args[0], (tuple, list, set, frozenset, types.GeneratorType)):
args = tuple(args[0])
args = [v if not isinstance(v, (tuple, list)) else v[0] if len(v) == 1 else conjunction(v) for v in args]
return args[0] ^ args[1] if len(args) == 2 else Node.build(TypeNode.XOR, *args) if len(args) > 1 else args[0]
def iff(*args):
"""
Builds and returns a node 'iff', root of a tree expression where specified arguments are children.
Without any parent, it becomes a constraint.
:return: a node, root of a tree expression
"""
if len(args) == 1 and isinstance(args[0], (tuple, list, set, frozenset, types.GeneratorType)):
args = tuple(args[0])
assert len(args) >= 2
res = manage_global_indirection(*args)
if res is None:
return Iff(*args, meta=True)
res = [v if not isinstance(v, (tuple, list)) else v[0] if len(v) == 1 else conjunction(v) for v in res]
return res[0] == res[1] if len(res) == 2 else Node.build(TypeNode.IFF, *res)
def imply(*args):
"""
Builds and returns a node 'imply', root of a tree expression where specified arguments are children.
Without any parent, it becomes a constraint.
:param args: a tuple of two arguments
:return: a node, root of a tree expression
"""
assert len(args) == 2
cnd, tp = args # condition and then part
if isinstance(tp, (tuple, list, set, frozenset)):
tp = list(tp) # to transform sets into lists
assert len(tp) >= 1
return imply(cnd, tp[0]) if len(tp) == 1 else [imply(cnd, v) for v in tp]
if isinstance(tp, PartialConstraint):
tp = Node.build(TypeNode.EQ, auxiliary().replace_partial_constraint(tp), 1)
res = manage_global_indirection(cnd, tp)
if res is None:
return If(cnd, Then=tp)
# if len(res) == 2 and isinstance(res[1], (tuple, list, set, frozenset)):
# return [imply(res[0], v) for v in res[1]]
res = [v if not isinstance(v, (tuple, list)) else v[0] if len(v) == 1 else conjunction(v) for v in res]
return Node.build(TypeNode.IMP, *res)
def ift(test, Then, Else):
"""
Builds and returns a node 'ifthenelse', root of a tree expression where specified arguments are children.
Without any parent, it becomes a constraint.
:param test: the condition expression
:param Then the Then part
:param Else the Else part
:return: a node, root of a tree expression
"""
# assert len(args) == 3
# test, Then, Else = args # condition, then part and else part
if isinstance(test, ConstraintDummyConstant):
assert test.val in (0, 1)
return Then if test.val == 1 else Else
if Else is None:
return imply(test, Then)
if isinstance(test, (tuple, list)):
assert len(test) == 1, str(test)
test = test[0]
btp = isinstance(Then, (tuple, list, set, frozenset))
if btp:
Then = list(Then)
assert len(Then) >= 1
if len(Then) == 1:
return ift(test, Then[0], Else)
etp = isinstance(Else, (tuple, list, set, frozenset))
if etp:
Else = list(Else)
assert len(Else) >= 1
if len(Else) == 1:
return ift(test, Then, Else[0])
if btp or etp:
Then, Else = Then if isinstance(Then, list) else [Then], Else if isinstance(Else, list) else [Else]
# # we compute the negation of cnd
# if isinstance(cnd, Node) and ~cnd.type is not None:
# rcnd = Node(~cnd.type, cnd.cnt)
# elif isinstance(cnd, Variable):
# rcnd = var(cnd.id) if cnd.negation else ~cnd
# else:
# rcnd = ~cnd
return [imply(test, v) for v in Then] + [test | v for v in Else]
res = manage_global_indirection(test, Then, Else, also_pc=True)
if res is None:
return If(test, Then=Then, Else=Else, meta=True)
res = [v if not isinstance(v, (tuple, list)) else v[0] if len(v) == 1 else conjunction(v) for v in res]
assert len(res) == 3
if isinstance(res[0], int):
assert res[0] in (0, 1)
return res[1] if res[0] == 1 else res[2]
return Node.build(TypeNode.IF, *res)
def belong(x, values):
if isinstance(x, PartialConstraint):
x = auxiliary().replace_partial_constraint(x)
if isinstance(x, int):
assert is_1d_list(values, Variable)
return disjunction(y == x for y in values if y)
assert isinstance(x, Variable)
if isinstance(values, range):
if values.step != 1 or len(values) < 10:
values = list(values)
else:
return Node.in_range(x, values)
elif isinstance(values, int):
values = [values]
assert isinstance(values, (tuple, list, set, frozenset)) and all(isinstance(v, int) for v in values)
if len(values) == 1:
return Node.build(EQ, x, values[0])
return Node.build(IN, x, Node.build(SET, values))
def not_belong(x, values):
if isinstance(x, PartialConstraint):
x = auxiliary().replace_partial_constraint(x)
if isinstance(x, int):
assert is_1d_list(values, Variable)
return conjunction(y != x for y in values if y)
assert isinstance(x, Variable)
if isinstance(values, range):
if values.step != 1 or len(values) < 10:
values = list(values)
else:
return Node.not_in_range(x, values)
elif isinstance(values, int):
values = [values]
assert isinstance(values, (tuple, list, set, frozenset)) and all(isinstance(v, int) for v in values)
if len(values) == 1:
return Node.build(NE, x, values[0])
return Node.build(NOTIN, x, Node.build(SET, values))
def expr(operator, *args):
"""
Builds and returns a node, root of a tree expression where specified arguments are children.
The type of the new node is given by the specified operator.
When it is a string, it can be among {"<", "lt", "<=", "le", ">=", "ge", ">", "gt", "=", "==", "eq", "!=", "<>", "ne"}
Without any parent, it becomes a constraint.
:param operator: a string, or a constant from TypeNode or a constant from TypeConditionOperator or TypeOrderedOperator
:return: a node, root of a tree expression
"""
return Node.build(operator, *args)
def conjunction(*args):
"""
Builds and returns a node 'and', root of a tree expression where specified arguments are children.
Without any parent, it becomes a constraint.
:return: a node, root of a tree expression
"""
# return Count(manage_global_indirection(*args)) == len(args)
# t = flatten(args)
# if len(t) > 3:
# return Count(t) == len(t)
if len(args) == 1 and isinstance(args[0], (tuple, list, set, frozenset, types.GeneratorType)):
args = tuple(args[0])
if len(args) == 0:
return ConstraintDummyConstant(1)
return Node.conjunction(manage_global_indirection(*args))
def both(this, And):
"""
Builds and returns a node 'and', root of a tree expression where the two specified arguments are children.
Without any parent, it becomes a constraint.
:return: a node, root of a tree expression
"""
return conjunction(this, And)