-
Notifications
You must be signed in to change notification settings - Fork 0
/
program_functions_csp.py
912 lines (735 loc) · 28.2 KB
/
program_functions_csp.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
# This file is loaded with two different global scopes.
# The first scope is the one when this file is imported by another file. This will provide a list of available functions to be added to the LLM prompts.
# The second scope is created when this file is loaded and run by the exec() function. This will provide a valid scope to run the program generated by LLM.
# We can't have only one scope, because some predefined functions use global variables that are statically (lexically) binded.
from abc import abstractmethod
from typing import Callable
import numpy as np
import csp_func_control as cfc
from csp_solver import CSPConstraint, CSPSolver, CSPVar, Solution, reset_var_counter
from misc_utils import (
check,
check_list_of_type,
check_set_of_type,
is_list_of_type,
is_set_of_type,
lookat_matrix,
)
from scannet_utils import ObjInstance
from scope_env import GlobalState, register_handler
from score_funcs import SCORE_FUNCTIONS
CSP_SOLVER: CSPSolver | None = None
TARGET_VARIABLE: CSPVar | None = None
# set far_distance to 0 and others to 20 to get the evaluation results in paper
class Configs:
near_distance = 2
far_distance = 0
between_distance = 1
center_distance = 1
above_below_horizontal_distance = 1
def reset_target():
global TARGET_VARIABLE
TARGET_VARIABLE = None
def check_target() -> bool:
return TARGET_VARIABLE is not None
def reset_csp_solver():
"""
reset the csp solver. always call this before executing the generated program.
no need to call it for type checking.
"""
global CSP_SOLVER
CSP_SOLVER = CSPSolver()
reset_var_counter()
def run_csp_solver(
query: str,
solver_type: str = "default",
select_solution: str = "min_dist",
):
"""
solve the csp problem. call this after executing the generated program to get solutions.
"""
if solver_type == "naive":
CSP_SOLVER.solve_naive()
elif solver_type == "non_csp":
CSP_SOLVER.solve_non_csp()
elif solver_type == "default":
CSP_SOLVER.solve(query=query, select_solution=select_solution)
else:
raise SystemError(f"invalid csp solver type: {solver_type}.")
def get_var_identifier(csp_var: CSPVar | list[CSPVar] | set[CSPVar] | None) -> str:
if csp_var is None:
return "(none)"
if isinstance(csp_var, CSPVar):
return csp_var.get_identifier()
if is_list_of_type(csp_var, CSPVar):
return f"[{', '.join(var.get_identifier() for var in csp_var)}]"
raise SystemError(f"invalid variable: {csp_var}")
@register_handler()
class DefineVariable:
FUNC_NAME = "DEFINE_VARIABLE"
SIG_STR = "(labels: list[str]) -> CSPVar"
def call_type_check(self, labels: list[str]) -> CSPVar:
check(
isinstance(labels, list),
f"parameter @labels has wrong type: {type(labels)}.",
)
check(
all(isinstance(x, str) for x in labels),
"parameter @labels must only contain str!",
)
check(len(labels) > 0, "parameter @labels must not be empty!")
for label in labels:
check(
label in GlobalState.relevant_obj_set,
f"label ({label}) not in the given list of object labels.",
)
return CSPVar()
def call(self, labels: list[str]) -> CSPVar:
global CSP_SOLVER
check(all(x in GlobalState.relevant_obj_instances for x in labels))
return CSP_SOLVER.create_var(labels=labels)
@register_handler(cfc.DISABLE_NEGATION)
class DefineNegativeVariable:
FUNC_NAME = "DEFINE_NEGATIVE_VARIABLE"
SIG_STR = "(labels: list[str]) -> CSPVar"
def call_type_check(self, labels: list[str]) -> CSPVar:
check(
isinstance(labels, list),
f"parameter @labels has wrong type: {type(labels)}.",
)
check(
all(isinstance(x, str) for x in labels),
"parameter @labels must only contain str!",
)
check(len(labels) > 0, "parameter @labels must not be empty!")
for label in labels:
check(
label in GlobalState.relevant_obj_set,
f"label ({label}) not in the given list of object labels.",
)
csp_var = CSPVar()
csp_var.negative = True
return csp_var
def call(self, labels: list[str]) -> CSPVar:
global CSP_SOLVER
check(all(x in GlobalState.relevant_obj_instances for x in labels))
return CSP_SOLVER.create_var(labels=labels, negative=True)
@register_handler()
class SetTarget:
FUNC_NAME = "SET_TARGET"
SIG_STR = "(obj: CSPVar) -> None"
def call_type_check(self, obj: CSPVar) -> None:
global TARGET_VARIABLE
check(not obj.negative, "negative variables cannot be set as target.")
check(isinstance(obj, CSPVar), f"parameter @obj has wrong type: {type(obj)}.")
check(
TARGET_VARIABLE is None,
"there is only one target and you can only call SetTarget once!",
)
TARGET_VARIABLE = obj
def call(self, obj: CSPVar) -> None:
obj.set_as_target()
def build_check_func(
target: CSPVar,
anchor: CSPVar,
check_func_1_1: Callable[[ObjInstance, ObjInstance], bool],
) -> Callable[[Solution], bool]:
check(isinstance(target, CSPVar))
check(isinstance(anchor, CSPVar))
check(target != anchor)
def check_func(
solution_dict: Solution,
) -> bool:
inst_a = solution_dict[target]
inst_b = solution_dict[anchor]
if inst_a == inst_b:
return False
return check_func_1_1(inst_a, inst_b)
return check_func
class ConstraintSimple(CSPConstraint):
SIG_STR = "(target: CSPVar, anchor: CSPVar) -> CSPConstraint"
def get_desc_str(self) -> str:
return f"[target: {get_var_identifier(self.target)}] [anchor: {get_var_identifier(self.anchor)}]"
def call_type_check(self, target: CSPVar, anchor: CSPVar) -> CSPConstraint:
check(
isinstance(target, CSPVar),
f"parameter @target has wrong type: {type(target)}.",
)
check(
isinstance(anchor, CSPVar),
f"parameter @anchor has wrong type: {type(target)}.",
)
check(target != anchor, "parameter @target and @anchor should not be the same.")
check(
not target.negative or not anchor.negative,
"at least one of @target and @anchor must be non-negative.",
)
con = self.__class__()
con.target = target
return con
def call(self, target: CSPVar, anchor: CSPVar) -> CSPConstraint:
con = self.__class__(target=target, anchor=anchor)
CSP_SOLVER.add_constraint(constraint=con)
return con
@staticmethod
@abstractmethod
def check_func_1_1(inst_0: ObjInstance, inst_1: ObjInstance) -> bool:
"""implement this method to check the relation between two single instances"""
def __init__(
self,
target: CSPVar | None = None,
anchor: CSPVar | None = None,
):
if target is None or anchor is None:
return
super().__init__()
self.target = target
self.anchor = anchor
self.check_func: Callable | None = None
# this is a dependency if the target is a CSPSetVar
self.check_func = build_check_func(
target=self.target,
anchor=self.anchor,
check_func_1_1=self.check_func_1_1,
)
def get_target_var(self) -> CSPVar:
return self.target
def get_vars(self) -> set[CSPVar]:
return {self.target, self.anchor}
def check_solution(self, solution_dict: Solution) -> bool:
check(self.target in solution_dict)
check(self.anchor in solution_dict)
return self.check_func(solution_dict)
@register_handler()
class ConstraintLeft(ConstraintSimple):
FUNC_NAME = "CONSTRAINT_LEFT"
@staticmethod
def check_func_1_1(inst_0: ObjInstance, inst_1: ObjInstance) -> bool:
if inst_1.label == "room center":
return True
# when looking at inst_1, inst_0 is on the left
world_to_local = lookat_matrix(
eye=inst_1.bbox.center, target=GlobalState.room_center
)
center_0_local = world_to_local @ np.hstack([inst_0.bbox.center, 1])
center_0_local = center_0_local[:3]
# return center_0_local[0] < 0 and ConstraintNear.check_func_1_1(inst_0, inst_1)
return center_0_local[0] < 0
@register_handler()
class ConstraintRight(ConstraintSimple):
FUNC_NAME = "CONSTRAINT_RIGHT"
@staticmethod
def check_func_1_1(inst_0: ObjInstance, inst_1: ObjInstance) -> bool:
if inst_1.label == "room center":
return True
# when looking at inst_1, inst_0 is on the right
world_to_local = lookat_matrix(
eye=inst_1.bbox.center, target=GlobalState.room_center
)
center_0_local = world_to_local @ np.hstack([inst_0.bbox.center, 1])
center_0_local = center_0_local[:3]
# return center_0_local[0] > 0 and ConstraintNear.check_func_1_1(inst_0, inst_1)
return center_0_local[0] > 0
@register_handler()
class ConstraintNear(ConstraintSimple):
FUNC_NAME = [
"CONSTRAINT_NEAR",
"CONSTRAINT_FRONT",
"CONSTRAINT_BEHIND",
"CONSTRAINT_CLOSE",
"CONSTRAINT_BESIDE",
]
@staticmethod
def check_func_1_1(inst_0: ObjInstance, inst_1: ObjInstance) -> bool:
# # max_extent = inst_1.bbox.max_extent
# max_extent = max(inst_0.bbox.max_extent, inst_1.bbox.max_extent)
# threshold = get_config("near_distance_ratio") * max_extent
threshold = Configs.near_distance
return np.linalg.norm(inst_0.bbox.center - inst_1.bbox.center) < threshold
@register_handler()
class ConstraintFar(ConstraintSimple):
FUNC_NAME = [
"CONSTRAINT_FAR",
"CONSTRAINT_AWAY",
"CONSTRAINT_ACROSS",
"CONSTRAINT_OPPOSITE",
]
@staticmethod
def check_func_1_1(inst_0: ObjInstance, inst_1: ObjInstance) -> bool:
# max_extent = inst_1.bbox.max_extent
# # max_extent = max(inst_0.bbox.max_extent, inst_1.bbox.max_extent)
# threshold = get_config("far_distance_ratio") * max_extent
threshold = Configs.far_distance
return np.linalg.norm(inst_0.bbox.center - inst_1.bbox.center) > threshold
@register_handler()
class ConstraintAbove(ConstraintSimple):
FUNC_NAME = [
"CONSTRAINT_ABOVE",
"CONSTRAINT_ON",
]
@staticmethod
def check_func_1_1(inst_0: ObjInstance, inst_1: ObjInstance) -> bool:
is_above = inst_0.bbox.center[2] > inst_1.bbox.center[2] + 1e-3
dist_h = np.linalg.norm(inst_0.bbox.center[:2] - inst_1.bbox.center[:2])
# max_extent = min(
# max(inst_0.bbox.extents["x"], inst_0.bbox.extents["y"]),
# max(inst_1.bbox.extents["x"], inst_1.bbox.extents["y"]),
# )
# threshold = get_config("above_below_horizontal_distance_ratio") * max_extent
threshold = Configs.above_below_horizontal_distance
return is_above and dist_h < threshold
@register_handler()
class ConstraintBelow(ConstraintSimple):
FUNC_NAME = [
"CONSTRAINT_BELOW",
"CONSTRAINT_UNDER",
]
@staticmethod
def check_func_1_1(inst_0: ObjInstance, inst_1: ObjInstance) -> bool:
is_below = inst_0.bbox.center[2] < inst_1.bbox.center[2] - 1e-3
dist_h = np.linalg.norm(inst_0.bbox.center[:2] - inst_1.bbox.center[:2])
# max_extent = min(
# max(inst_0.bbox.extents["x"], inst_0.bbox.extents["y"]),
# max(inst_1.bbox.extents["x"], inst_1.bbox.extents["y"]),
# )
# threshold = get_config("above_below_horizontal_distance_ratio") * max_extent
threshold = Configs.above_below_horizontal_distance
return is_below and dist_h < threshold
@register_handler()
class ConstraintInside(ConstraintSimple):
FUNC_NAME = [
"CONSTRAINT_INSIDE",
"CONSTRAINT_IN",
]
SIG_STR = "(target: CSPVar, anchor: CSPVar) -> CSPConstraint"
def call_type_check(self, target: CSPVar, anchor: CSPVar) -> CSPConstraint:
check(
isinstance(target, CSPVar),
f"parameter @target has wrong type: {type(target)}.",
)
check(
isinstance(anchor, CSPVar),
f"parameter @anchor has wrong type: {type(anchor)}.",
)
check(target != anchor, "parameter @target and @anchor should not be the same.")
con = self.__class__()
con.target = target
return con
def call(self, target: CSPVar, anchor: CSPVar) -> CSPConstraint:
check(isinstance(target, CSPVar))
check(isinstance(anchor, CSPVar))
con = self.__class__(target=target, anchor=anchor)
CSP_SOLVER.add_constraint(constraint=con)
return con
@staticmethod
def check_func_1_1(inst_0: ObjInstance, inst_1: ObjInstance) -> bool:
return inst_1.bbox.contains(inst_0.bbox.center)
@register_handler()
class ConstraintCenter(ConstraintSimple):
FUNC_NAME = [
"CONSTRAINT_CENTER",
"CONSTRAINT_MIDDLE",
]
@staticmethod
def check_func_1_1(inst_0: ObjInstance, inst_1: ObjInstance) -> bool:
return inst_1.bbox.contains(inst_0.bbox.center)
@staticmethod
def check_func_1_n(inst_0: ObjInstance, inst_1: list[ObjInstance]) -> bool:
if len(inst_1) == 0:
return False
centers = [inst.bbox.center for inst in inst_1]
group_center = np.mean(centers, axis=0)
if inst_0 in inst_1:
# if the target is one of the anchors, it must be the instance in the middle
min_idx = np.argmin([np.linalg.norm(c - group_center) for c in centers])
return inst_0 == inst_1[min_idx]
else:
# otherwise, the target must be close enough to the center of the anchors
# max_extent = np.mean([inst.bbox.max_extent for inst in inst_1])
# threshold = get_config("center_distance_ratio") * max_extent
threshold = Configs.center_distance
return np.linalg.norm(inst_0.bbox.center - group_center) < threshold
def build_check_func_between(
target: CSPVar,
anchors: set[CSPVar],
check_func_between: Callable[[ObjInstance, list[ObjInstance]], bool],
) -> Callable[[Solution], bool]:
check(
isinstance(target, CSPVar),
f"invalid argument type: {type(target)}; {type(anchors)}",
)
check_set_of_type(
anchors,
CSPVar,
f"invalid argument type: {type(target)}; {type(anchors)}",
)
def check_func(
solution_dict: Solution,
) -> bool:
inst_a = solution_dict[target]
sol_b = [solution_dict[anchor] for anchor in anchors]
# ignore the target instance in the set of anchor instances
if inst_a in sol_b:
sol_b.remove(inst_a)
if len(sol_b) >= 2:
return check_func_between(inst_a, sol_b)
else:
return False
return check_func
@register_handler()
class ConstraintBetween(CSPConstraint):
FUNC_NAME = ["CONSTRAINT_BETWEEN"]
SIG_STR = "(target: CSPVar, anchors: set[CSPVar]) -> CSPConstraint"
def call_type_check(self, target: CSPVar, anchors: set[CSPVar]) -> CSPConstraint:
check(
isinstance(target, CSPVar),
f"parameter @target has wrong type: {type(target)}.",
)
check_set_of_type(
anchors,
CSPVar,
f"parameter @anchors has wrong type: {type(target)}.",
)
if isinstance(anchors, set):
check(
(len(anchors) >= 2),
"parameter @anchors must include at least two variables.",
)
check(
all(isinstance(x, CSPVar) for x in anchors),
"parameter @anchors contains invalid element.",
)
check(target not in anchors, "@anchors must not include the @target!")
check(not target.negative, "@target cannot be negative.")
check(
all(not anchor.negative for anchor in anchors),
"@anchors cannot contain negative variables.",
)
con = self.__class__()
con.target = target
return con
def call(self, target: CSPVar, anchors: set[CSPVar]) -> CSPConstraint:
check(isinstance(target, CSPVar))
check_set_of_type(anchors, CSPVar)
con = self.__class__(target=target, anchors=anchors)
CSP_SOLVER.add_constraint(constraint=con)
return con
@staticmethod
def check_func_between(
inst_0: ObjInstance,
inst_1_arr: list[ObjInstance],
) -> bool:
if len(inst_1_arr) == 2:
c0 = inst_0.bbox.center
c1 = inst_1_arr[0].bbox.center
c2 = inst_1_arr[1].bbox.center
diff = c2 - c1
diff_norm = np.linalg.norm(diff) + 1e-5
diff /= diff_norm
# the projected length should be between 0 and diff_norm
t = (c0 - c1).dot(diff)
if t <= 1e-3 or t >= diff_norm - 1e-3:
return False
d = np.linalg.norm(np.cross(c2 - c1, c1 - c0)) / (
np.linalg.norm(c2 - c1) + 1e-5
)
# max_extent = max(
# inst_0.bbox.max_extent,
# inst_1_arr[0].bbox.max_extent,
# inst_1_arr[1].bbox.max_extent,
# )
# threshold = get_config("between_distance_ratio") * max_extent
threshold = Configs.between_distance
return d < threshold
elif len(inst_1_arr) > 2:
c0 = inst_0.bbox.center
c1_arr = [inst_1.bbox.center for inst_1 in inst_1_arr]
c1 = np.mean(c1_arr, axis=0)
d = np.linalg.norm(c0 - c1)
# or better: decide with barycentric coordinates on the horizontal plane
# return d < inst_0.bbox.max_extent * get_config("between_distance_ratio")
return d < Configs.between_distance
raise SystemError(
"not enough anchors: at least two required, "
f"but only {len(inst_1_arr)} were given."
)
def get_desc_str(self) -> str:
check_set_of_type(self.anchors, CSPVar)
return (
f"[target: {get_var_identifier(self.target)}]"
f" [anchors: {' '.join(anchor.get_identifier() for anchor in self.anchors)}]"
)
def __init__(
self,
target: CSPVar | None = None,
anchors: set[CSPVar] | None = None,
):
if target is None or anchors is None:
return
super().__init__()
self.target = target
self.anchors = anchors
self.check_func: Callable | None = None
self.check_func = build_check_func_between(
target=self.target,
anchors=self.anchors,
check_func_between=self.check_func_between,
)
# collect variables used in this constraint
self.variables = {self.target, *self.anchors}
def get_target_var(self) -> CSPVar:
return self.target
def get_vars(self) -> set[CSPVar]:
return self.variables
def check_solution(self, solution_dict: Solution) -> bool:
check(self.target in solution_dict)
check(
isinstance(self.anchors, set)
and all(anchor in solution_dict for anchor in self.anchors)
)
return self.check_func(solution_dict)
@register_handler(cfc.DISABLE_MINMAX)
class ConstraintMin(CSPConstraint):
FUNC_NAME = "CONSTRAINT_MIN_OF"
SIG_STR = "(target: CSPVar, score_func: str, anchor: CSPVar | None = None) -> CSPConstraint"
SELECT_FUNC = min
def call_type_check(
self,
target: CSPVar,
score_func: str,
anchor: CSPVar | None = None,
) -> CSPConstraint:
check(
isinstance(target, CSPVar),
f"parameter @target has wrong type: {type(target)}.",
)
check(
anchor is None or isinstance(anchor, CSPVar),
f"parameter @anchor has wrong type: {type(anchor)}.",
)
check(
isinstance(score_func, str),
f"parameter @score_func has wrong type: {type(score_func)}.",
)
check(
(anchor is None or target != anchor),
"parameter @target and @anchor should not be the same.",
)
check(
(score_func in SCORE_FUNCTIONS),
f"score function [{score_func}] is not defined!",
)
if anchor is None:
check(
SCORE_FUNCTIONS[score_func].NEED_ANCHOR is False,
(
"you did not specify the @anchor parameter, "
f"but the score function you used ({score_func}) require an anchor."
),
)
else:
check(
SCORE_FUNCTIONS[score_func].NEED_ANCHOR is True,
(
"you specified the @anchor parameter, but the score function you "
f"used ({score_func}) does not require an anchor."
),
)
check(not target.negative, "@target cannot be negative.")
check(anchor is None or not anchor.negative, "@anchor cannot be negative.")
con = self.__class__()
con.target = target
return con
def call(
self,
target: CSPVar,
score_func: str,
anchor: CSPVar | None = None,
) -> CSPConstraint:
con = self.__class__(target=target, anchor=anchor, score_func=score_func)
CSP_SOLVER.add_constraint(constraint=con)
return con
def get_desc_str(self) -> str:
return (
f"[target: {get_var_identifier(self.target)}]"
f" [anchor: {get_var_identifier(self.anchor)}]"
)
def __init__(
self,
target: CSPVar | None = None,
anchor: CSPVar | None = None,
score_func: str | None = None,
):
# anchor can be none
if target is None or score_func is None:
return
super().__init__()
self.target = target
self.anchor = anchor
self.score_func = SCORE_FUNCTIONS[score_func]
if self.anchor is not None:
self.variables = {self.target, self.anchor}
else:
self.variables = {self.target}
def get_target_var(self) -> CSPVar:
return self.target
def get_vars(self) -> set[CSPVar]:
return self.variables
def check_solution(self, solution_dict: Solution) -> bool:
raise NotImplementedError()
def filter_solutions(self, solutions: list[Solution]) -> list[Solution]:
if not solutions:
return []
check(all(self.target in sol for sol in solutions))
anchor_inst = None
if self.anchor is not None:
check(all(self.anchor in sol for sol in solutions))
# check(len(set(sol[self.anchor] for sol in solutions)) == 1)
anchor_inst = solutions[0][self.anchor]
cand_insts = [sol[self.target] for sol in solutions]
check(len(cand_insts) > 0)
select_func = self.SELECT_FUNC
scores = self.score_func.get_scores(cand_insts, anchor_inst)
# print()
# print(scores)
# if self.anchor is not None:
# print("has anchor!")
# for inst in cand_insts:
# print(inst.inst_id, inst.label)
# if anchor_inst is not None:
# print("anchor:", anchor_inst.inst_id, anchor_inst.label)
# print()
check(len(scores) == len(solutions))
return [select_func(zip(solutions, scores), key=lambda x: x[1])[0]]
@register_handler(cfc.DISABLE_MINMAX)
class ConstraintMax(ConstraintMin):
FUNC_NAME = "CONSTRAINT_MAX_OF"
SELECT_FUNC = max
@register_handler()
class ConstraintMore(CSPConstraint):
FUNC_NAME = "CONSTRAINT_MORE"
SIG_STR = "(target: CSPVar, reference: CSPVar, score_func: str, anchor: CSPVar | None = None) -> CSPConstraint"
@staticmethod
def COMPARE_FUNC(a, b):
return a > b
def call_type_check(
self,
target: CSPVar,
reference: CSPVar,
score_func: str,
anchor: CSPVar | None = None,
) -> CSPConstraint:
# TODO: allow @target to be CSPSetVar (maybe also reference and anchor?)
check(
isinstance(reference, CSPVar),
f"parameter @reference has wrong type: {type(reference)}.",
)
check(
isinstance(target, CSPVar),
f"parameter @target has wrong type: {type(target)}.",
)
check(
anchor is None or isinstance(anchor, CSPVar),
f"parameter @anchor has wrong type: {type(anchor)}.",
)
check(
isinstance(score_func, str),
f"parameter @score_func has wrong type: {type(score_func)}.",
)
check(
(score_func in SCORE_FUNCTIONS),
f"score function [{score_func}] is not defined!",
)
check(
(anchor is None or target != anchor),
"parameter @target and @anchor should not be the same.",
)
check(
(target != reference),
"parameter @target and @reference should not be the same.",
)
if anchor is None:
check(
SCORE_FUNCTIONS[score_func].NEED_ANCHOR is False,
(
"you did not specify the @anchor parameter, "
f"but the score function you used ({score_func}) require an anchor."
),
)
else:
check(
SCORE_FUNCTIONS[score_func].NEED_ANCHOR is True,
(
"you specified the @anchor parameter, but the score function you "
f"used ({score_func}) does not require an anchor."
),
)
check(not target.negative, "@target cannot be negative.")
check(not reference.negative, "@reference cannot be negative.")
check(anchor is None or not anchor.negative, "@anchor cannot be negative.")
con = self.__class__()
con.target = target
return con
def call(
self,
target: CSPVar,
reference: CSPVar,
score_func: str,
anchor: CSPVar | None = None,
) -> CSPConstraint:
con = self.__class__(
target=target, reference=reference, anchor=anchor, score_func=score_func
)
CSP_SOLVER.add_constraint(constraint=con)
return con
def get_desc_str(self) -> str:
return (
f"[target: {get_var_identifier(self.target)}]"
f" [reference: {get_var_identifier(self.reference)}]"
f" [anchor: {get_var_identifier(self.anchor)}]"
)
def __init__(
self,
target: CSPVar | None = None,
reference: CSPVar | None = None,
anchor: CSPVar | None = None,
score_func: str | None = None,
):
# anchor can be none
if target is None or reference is None or score_func is None:
return
super().__init__()
self.target = target
self.reference = reference
self.anchor = anchor
self.score_func = SCORE_FUNCTIONS[score_func]
if self.anchor is not None:
self.variables = {self.target, self.reference, self.anchor}
else:
self.variables = {self.target, self.reference}
def get_target_var(self) -> CSPVar:
return self.target
def get_dependent_var(self) -> CSPVar | None:
return self.target
def get_vars(self) -> set[CSPVar]:
return self.variables
def check_solution(self, solution_dict: Solution) -> bool:
check(isinstance(self.target, CSPVar))
check(self.target in solution_dict)
check(self.reference in solution_dict)
check(self.anchor is None or self.anchor in solution_dict)
inst_target = solution_dict[self.target]
inst_ref = solution_dict[self.reference]
if self.anchor is None:
scores = self.score_func.get_scores([inst_target, inst_ref])
else:
scores = self.score_func.get_scores(
[inst_target, inst_ref], solution_dict[self.anchor]
)
return self.COMPARE_FUNC(scores[0], scores[1])
@register_handler()
class ConstraintLess(ConstraintMore):
FUNC_NAME = "CONSTRAINT_LESS"
@staticmethod
def COMPARE_FUNC(a, b):
return a < b