agentic-mcp-solver 4.2.0__py3-none-any.whl
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.
- agentic_mcp_solver-4.2.0.dist-info/METADATA +318 -0
- agentic_mcp_solver-4.2.0.dist-info/RECORD +22 -0
- agentic_mcp_solver-4.2.0.dist-info/WHEEL +4 -0
- agentic_mcp_solver-4.2.0.dist-info/entry_points.txt +5 -0
- agentic_mcp_solver-4.2.0.dist-info/licenses/LICENSE +21 -0
- mcp_solver/__init__.py +20 -0
- mcp_solver/agent/__init__.py +1 -0
- mcp_solver/agent/cli.py +496 -0
- mcp_solver/agent/harness.py +258 -0
- mcp_solver/agent/mcp_server.py +508 -0
- mcp_solver/agent/runfolder.py +159 -0
- mcp_solver/helpers/__init__.py +7 -0
- mcp_solver/helpers/maxsat.py +79 -0
- mcp_solver/helpers/pysat.py +346 -0
- mcp_solver/helpers/z3.py +213 -0
- mcp_solver/templates/__init__.py +22 -0
- mcp_solver/templates/clingo.md +1305 -0
- mcp_solver/templates/cpmpy.md +124 -0
- mcp_solver/templates/didp.md +270 -0
- mcp_solver/templates/maxsat.md +192 -0
- mcp_solver/templates/pysat.md +186 -0
- mcp_solver/templates/z3.md +165 -0
|
@@ -0,0 +1,1305 @@
|
|
|
1
|
+
# Answer Set Programming (ASP) Task - v10
|
|
2
|
+
|
|
3
|
+
## Section 1: Mission Briefing & Core Requirements
|
|
4
|
+
|
|
5
|
+
### Primary Goal
|
|
6
|
+
Produce a solution using Answer Set Programming (ASP) that correctly models and solves the problem using the clingo Python API.
|
|
7
|
+
|
|
8
|
+
### Non-Negotiable Requirements
|
|
9
|
+
1. **Tool**: You MUST use the clingo Python API for modeling and solving
|
|
10
|
+
2. **Execution Time**: Your script must complete within 10 seconds
|
|
11
|
+
- **Optimization vs Bounds**: If the problem provides an expected optimal value or bound (e.g., "expected minimum cost: 50"), use that value as a CONSTRAINT rather than using `#minimize`/`#maximize`. Finding the absolute optimum can be extremely expensive. Instead, find any solution that satisfies the given bound.
|
|
12
|
+
- **Example**: Instead of `#minimize { Cost : total_cost(Cost) }`, use `:- total_cost(Cost), Cost > 50.`
|
|
13
|
+
3. **Output Format**: Print the final solution as a single JSON object to stdout
|
|
14
|
+
4. **Task Planning**: Structure your approach with clear steps:
|
|
15
|
+
- Mentally break down the problem into 5-8 logical tasks
|
|
16
|
+
- Follow the structured workflow defined below
|
|
17
|
+
- Use code comments to track your progress through tasks
|
|
18
|
+
5. **Error Documentation**: Create `feedback.md` for environment/specification issues
|
|
19
|
+
|
|
20
|
+
### Output Specifications
|
|
21
|
+
- Generate ONLY executable Python code using clingo
|
|
22
|
+
- Use clear, meaningful predicate names (e.g., `assigned(task1, worker2)` not `p(1,2)`)
|
|
23
|
+
- Extract solutions from answer sets and format as JSON
|
|
24
|
+
- Handle UNSAT cases gracefully with error JSON: `{"error": "No solution exists", "reason": "..."}`
|
|
25
|
+
|
|
26
|
+
### Final Checklist
|
|
27
|
+
Before completing your solution, verify:
|
|
28
|
+
☐ 1. **Uses clingo API** - Solution uses `clingo.Control()` and ASP rules
|
|
29
|
+
☐ 2. **Model solves correctly** - At least one answer set is found (or UNSAT handled)
|
|
30
|
+
☐ 3. **Optimization applied** - Use #minimize/#maximize ONLY when no explicit bound is given; when the problem states a bound, encode it as a hard constraint instead (see the requirement above)
|
|
31
|
+
☐ 4. **Solution extracted** - Answer set atoms properly extracted and formatted
|
|
32
|
+
☐ 4b. **No Model escapes on_model** - All solution data extracted to plain Python objects inside the callback (touching a Model after solve() returns segfaults)
|
|
33
|
+
☐ 5. **Output format correct** - JSON output with appropriate structure
|
|
34
|
+
☐ 6. **Predicates meaningful** - Clear names that reflect the problem domain
|
|
35
|
+
☐ 7. **Constraints verified independently** - All problem constraints are encoded AND re-checked by a plain-Python verify() whose expectations are re-derived from the problem text, not from your encoding's own interpretation
|
|
36
|
+
☐ 8. **Program submitted** - Call `submit_code` with the complete, verified,
|
|
37
|
+
self-contained program (all imports included, no reliance on session state)
|
|
38
|
+
|
|
39
|
+
## Section 2: Critical Rules of Engagement
|
|
40
|
+
|
|
41
|
+
### MANDATORY RULE: Core ASP Syntax
|
|
42
|
+
|
|
43
|
+
**FUNDAMENTAL RULE**: You must follow these basic syntax rules. Errors here are the most common cause of failures.
|
|
44
|
+
|
|
45
|
+
#### A. Constants vs. Variables
|
|
46
|
+
This is the single most important distinction in ASP syntax.
|
|
47
|
+
|
|
48
|
+
* **Constants (Symbols)**: Must start with a **lowercase letter**, be a **number**, or be enclosed in **double quotes `""`**.
|
|
49
|
+
* `item(apple).` (lowercase)
|
|
50
|
+
* `cost(100).` (number)
|
|
51
|
+
* `amino_acid(1, "H").` (quoted string - **use this for input data that is uppercase**)
|
|
52
|
+
|
|
53
|
+
* **Variables**: Must start with an **uppercase letter** or an **underscore `_`**.
|
|
54
|
+
* `has_color(Item, Color) :- ...`
|
|
55
|
+
* `cost(X, C) :- ...`
|
|
56
|
+
|
|
57
|
+
**Common Mistake and Correction:**
|
|
58
|
+
|
|
59
|
+
| Incorrect (produces "unsafe variable" error) | Correct |
|
|
60
|
+
|:----------------------------------------------|:--------|
|
|
61
|
+
| `amino_acid(1, H).` | `amino_acid(1, "H").` **(Best Practice)** or `amino_acid(1, h).` |
|
|
62
|
+
| `type(engine, V8).` | `type(engine, "V8").` or `type(engine, v8).` |
|
|
63
|
+
| `player(P1).` | `player(p1).` or `player("P1").` |
|
|
64
|
+
|
|
65
|
+
#### B. The Closed World Principle: Never Hallucinate Data
|
|
66
|
+
|
|
67
|
+
**FUNDAMENTAL RULE**: Your ASP program operates under a **Closed World Assumption**. This means anything not explicitly stated as a fact or derivable from a rule is considered **false**. You MUST NOT invent or assume data that isn't provided.
|
|
68
|
+
|
|
69
|
+
All data must come from two places only:
|
|
70
|
+
1. **Facts generated from the problem description.**
|
|
71
|
+
2. **New facts derived by your rules from existing facts.**
|
|
72
|
+
|
|
73
|
+
**Common Mistake and Correction:**
|
|
74
|
+
|
|
75
|
+
| Incorrect (Hallucinates data) | Correct |
|
|
76
|
+
|:----------------------------------------------|:--------|
|
|
77
|
+
| **Problem:** "The available parts are a `cpu` and a `gpu`." <br/><br/> `part(cpu; gpu; ram).` <br/><br/> **Error**: The program invented `part(ram)`, which was not in the problem description. | **Problem:** "The available parts are a `cpu` and a `gpu`." <br/><br/> `part(cpu). part(gpu).` <br/><br/> **Explanation**: Only facts directly corresponding to the input are created. |
|
|
78
|
+
| **Problem:** "Schedule tasks for workers `w1`, `w2`." <br/><br/> `worker(W) :- assigned(_, W).` <br/><br/> **Error**: This only defines workers *if* they get a task. If `w2` is a valid worker but gets no tasks, `worker(w2)` will not be true. | **Problem:** "Schedule tasks for workers `w1`, `w2`." <br/><br/> `worker(w1). worker(w2).` <br/><br/> **Explanation**: The set of all possible workers is explicitly defined as facts from the problem input. |
|
|
79
|
+
| **Problem:** "Costs are: R1→C1: 10, R1→C2: 12" <br/><br/> `cost("R1","C1",10). cost("R1","C2",12). cost("R2","C2",12).` <br/><br/> **Error**: Invented cost for R2→C2 not in problem. | **Problem:** "Costs are: R1→C1: 10, R1→C2: 12" <br/><br/> `cost("R1","C1",10). cost("R1","C2",12).` <br/><br/> **Explanation**: Only the explicitly stated costs are created as facts. |
|
|
80
|
+
|
|
81
|
+
#### Hierarchy of Truth: Data Tables vs. Example Outputs
|
|
82
|
+
|
|
83
|
+
**CRITICAL RULE**: When a problem specification contains both data tables/lists AND example outputs, the **data tables are the single, immutable source of truth**. Example outputs demonstrate the required **format** only - their **values** are illustrative.
|
|
84
|
+
|
|
85
|
+
**NEVER modify, invent, or transfer data to match an example output.** Your model must solve the problem defined by the data tables, even if the example's values appear inconsistent.
|
|
86
|
+
|
|
87
|
+
**Why This Matters:**
|
|
88
|
+
- Example outputs may contain typos or be slightly out of sync with primary data
|
|
89
|
+
- Example values are often from a different instance or simplified scenario
|
|
90
|
+
- Modifying data to match examples violates the Closed World Principle
|
|
91
|
+
|
|
92
|
+
**Common Mistake and Correction:**
|
|
93
|
+
|
|
94
|
+
| Incorrect (Modifies data to match example) | Correct (Uses only primary data) |
|
|
95
|
+
|:----------------------------------------------|:--------|
|
|
96
|
+
| **Data Table:** "Connection costs: A→B: 5, A→C: 10" <br/><br/> **Example Output:** Shows B connected to C <br/><br/> `cost("A","B",5). cost("A","C",10). cost("B","C",8).` <br/><br/> **Error**: Invented cost(B,C,8) to match example structure | **Data Table:** "Connection costs: A→B: 5, A→C: 10" <br/><br/> **Example Output:** Shows B connected to C <br/><br/> `cost("A","B",5). cost("A","C",10).` <br/><br/> **Explanation**: Use ONLY the provided costs. The solver finds the optimal solution using the true data. |
|
|
97
|
+
| **Data:** "Capacities: Server1: 100GB, Server2: 200GB" <br/><br/> **Example:** Shows Server3 in use <br/><br/> `capacity("Server1",100). capacity("Server2",200). capacity("Server3",150).` <br/><br/> **Error**: Added Server3 because example showed it | **Data:** "Capacities: Server1: 100GB, Server2: 200GB" <br/><br/> **Example:** Shows Server3 in use <br/><br/> `capacity("Server1",100). capacity("Server2",200).` <br/><br/> **Explanation**: Example is from a different instance. Use only the provided servers. |
|
|
98
|
+
|
|
99
|
+
**Priority Order:**
|
|
100
|
+
1. **Primary data tables/lists** (highest priority)
|
|
101
|
+
2. **Explicit problem constraints**
|
|
102
|
+
3. **Example output structure** (format guidance only)
|
|
103
|
+
4. **Example output values** (ignore if inconsistent)
|
|
104
|
+
|
|
105
|
+
#### C. Structure of Rules and Facts
|
|
106
|
+
* Every statement (fact or rule) **MUST** end with a period (`.`).
|
|
107
|
+
* In a rule body, a comma (`,`) means **AND**.
|
|
108
|
+
* Comments start with a percent sign (`%`).
|
|
109
|
+
|
|
110
|
+
```asp
|
|
111
|
+
% This is a FACT. It ends with a period.
|
|
112
|
+
city("paris").
|
|
113
|
+
|
|
114
|
+
% This is a RULE. Note the period at the end.
|
|
115
|
+
% "is_in_france(X) is true IF city(X) is true AND X is "paris"."
|
|
116
|
+
is_in_france(X) :- city(X), X == "paris".
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### MANDATORY RULE: Variable Safety
|
|
120
|
+
|
|
121
|
+
**FUNDAMENTAL RULE**: Every variable appearing in a rule MUST be grounded by appearing in at least one positive, non-aggregate, non-arithmetic literal in the rule's body.
|
|
122
|
+
|
|
123
|
+
**Why this matters**: ASP needs to know which values to check. Unsafe variables have no defined domain.
|
|
124
|
+
|
|
125
|
+
**Examples of UNSAFE vs SAFE rules**:
|
|
126
|
+
```asp
|
|
127
|
+
% UNSAFE - Variable S has no positive grounding
|
|
128
|
+
:- item(I), not on_shelf(I, S).
|
|
129
|
+
% Error: 'S' is unsafe - solver doesn't know which shelves to check
|
|
130
|
+
|
|
131
|
+
% SAFE - Variable S is grounded by shelf(S)
|
|
132
|
+
:- item(I), shelf(S), not on_shelf(I, S).
|
|
133
|
+
% Now solver checks all combinations of items and shelves
|
|
134
|
+
|
|
135
|
+
% UNSAFE - Variables X,Y only appear in negation
|
|
136
|
+
:- robot(R), not at(R,X,Y).
|
|
137
|
+
% Error: 'X' and 'Y' are unsafe
|
|
138
|
+
|
|
139
|
+
% SAFE - Variables X,Y grounded by location/2
|
|
140
|
+
:- robot(R), location(X,Y), not at(R,X,Y).
|
|
141
|
+
% Now solver knows to check all valid locations
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
#### Variable Safety with Negation as Failure (`not`)
|
|
145
|
+
|
|
146
|
+
A critical application of this rule is when using negation (`not`). Any variable used inside a `not` literal **must** be grounded by a positive literal elsewhere in the same rule body. The solver cannot find solutions by iterating through infinite possibilities of what is *not* true.
|
|
147
|
+
|
|
148
|
+
**Example: Finding unassigned tasks**
|
|
149
|
+
Imagine you have `task(1..10)` and `assigned(T, W)` facts for tasks that are already assigned. You want to write a rule to find unassigned tasks.
|
|
150
|
+
|
|
151
|
+
| Incorrect (produces "unsafe variable" error) | Correct |
|
|
152
|
+
|:----------------------------------------------|:--------|
|
|
153
|
+
| `unassigned(T) :- not assigned(T, W).` <br/><br/> **Error:** The variable `W` is unsafe. The solver doesn't know which set of workers (`W`) to check for non-assignment. | `unassigned(T) :- task(T), not assigned(T, _).` <br/><br/> **Explanation:** `task(T)` grounds the `T` variable. The underscore `_` in `not assigned(T, _)` checks for the existence of *any* assignment for that specific task `T`, correctly identifying tasks with no assignments. |
|
|
154
|
+
|
|
155
|
+
**Example: Circuit diagnosis - ordering matters!**
|
|
156
|
+
When a variable appears in multiple places, it must be grounded before being used in negation.
|
|
157
|
+
|
|
158
|
+
| Incorrect (unsafe variable error) | Correct |
|
|
159
|
+
|:----------------------------------------------|:--------|
|
|
160
|
+
| `wire_value(T, W, V) :- not faulty(G, _), gate_output(G, W), correct_output(T, G, V).` <br/><br/> **Error:** `G` is unsafe - it first appears in `not faulty(G, _)`. | `wire_value(T, W, V) :- gate_output(G, W), not faulty(G, _), correct_output(T, G, V).` <br/><br/> **Explanation:** `gate_output(G, W)` grounds `G` first. Now `not faulty(G, _)` checks if *that specific gate* is healthy. |
|
|
161
|
+
|
|
162
|
+
#### Choice Rule Variable Safety
|
|
163
|
+
|
|
164
|
+
**CRITICAL RULE**: Variables in choice rules must be grounded either:
|
|
165
|
+
1. **In the choice domain** (after the `:` inside `{...}`), OR
|
|
166
|
+
2. **In the rule body** (after the `:-`)
|
|
167
|
+
|
|
168
|
+
Variables appearing in the choice head but nowhere else are UNSAFE.
|
|
169
|
+
|
|
170
|
+
**General Pattern:**
|
|
171
|
+
```asp
|
|
172
|
+
% UNSAFE - Variables in choice head but not grounded
|
|
173
|
+
{chosen(X, Var1, Var2)} :- domain(X).
|
|
174
|
+
% Error: 'Var1' and 'Var2' have no defined domain
|
|
175
|
+
|
|
176
|
+
% SAFE - Option 1: Ground in choice domain
|
|
177
|
+
{chosen(X, Var1, Var2) : property1(Var1), property2(Var2)} :- domain(X).
|
|
178
|
+
|
|
179
|
+
% SAFE - Option 2: Ground in rule body
|
|
180
|
+
{chosen(X, Var1, Var2)} :- domain(X), property1(Var1), property2(Var2).
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
**Example: Assignment**
|
|
184
|
+
```asp
|
|
185
|
+
% UNSAFE
|
|
186
|
+
{assign(Task, Worker, Priority)} :- task(Task).
|
|
187
|
+
|
|
188
|
+
% SAFE - Ground in choice domain
|
|
189
|
+
{assign(Task, Worker, Priority) : worker(Worker), priority(Priority)} :- task(Task).
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
**Example: Pairing**
|
|
193
|
+
```asp
|
|
194
|
+
% UNSAFE
|
|
195
|
+
{pair(Group, P1, P2)} :- group(Group).
|
|
196
|
+
|
|
197
|
+
% SAFE
|
|
198
|
+
{pair(Group, P1, P2) : member(P1), member(P2)} :- group(Group), P1 != P2.
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### MANDATORY RULE: Aggregate Placement
|
|
202
|
+
|
|
203
|
+
**Aggregates (#count, #sum, #min, #max) can ONLY be used:**
|
|
204
|
+
- In the BODY of a rule (for conditions)
|
|
205
|
+
- In #minimize/#maximize statements
|
|
206
|
+
- NEVER in the HEAD of a regular rule
|
|
207
|
+
|
|
208
|
+
**Why**: Rule heads generate new facts, while aggregates compute over existing facts.
|
|
209
|
+
|
|
210
|
+
```asp
|
|
211
|
+
% CORRECT - Aggregate in constraint body
|
|
212
|
+
:- #count { X : selected(X) } > 5.
|
|
213
|
+
|
|
214
|
+
% CORRECT - Aggregate in optimization
|
|
215
|
+
#minimize { Cost,X : selected(X), cost(X,Cost) }.
|
|
216
|
+
|
|
217
|
+
% INCORRECT - Cannot use aggregate in rule head
|
|
218
|
+
% total(#sum{C,X : cost(X,C)}) :- ... % SYNTAX ERROR!
|
|
219
|
+
|
|
220
|
+
% CORRECT - Use auxiliary predicates instead
|
|
221
|
+
total(T) :- T = #sum{C,X : selected(X), cost(X,C)}.
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
### MANDATORY RULE: State Exclusivity (Fluents)
|
|
225
|
+
|
|
226
|
+
**FUNDAMENTAL PRINCIPLE**: A property that changes over time (a "fluent") can only have ONE value at any given time. You MUST enforce mutual exclusivity.
|
|
227
|
+
|
|
228
|
+
**Critical for temporal problems**: An entity cannot be in two states simultaneously.
|
|
229
|
+
|
|
230
|
+
```asp
|
|
231
|
+
% INCORRECT - Allows item to be in two places
|
|
232
|
+
item_at(I,X,Y,T+1) :- item_at(I,X,Y,T), not pickup(_,I,T).
|
|
233
|
+
carrying(R,I,T+1) :- pickup(R,I,T).
|
|
234
|
+
% BUG: Item can be both at location AND carried!
|
|
235
|
+
|
|
236
|
+
% CORRECT - Enforce mutual exclusivity
|
|
237
|
+
% Item cannot be in two different places
|
|
238
|
+
:- item_at(I,X1,Y1,T), item_at(I,X2,Y2,T), (X1,Y1) != (X2,Y2).
|
|
239
|
+
|
|
240
|
+
% Item cannot be both on grid AND carried
|
|
241
|
+
:- item_at(I,X,Y,T), carrying(_,I,T).
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
### Required 5-Step Workflow
|
|
245
|
+
|
|
246
|
+
#### Step 0: Plan Your Approach (MANDATORY - DO THIS FIRST!)
|
|
247
|
+
|
|
248
|
+
**Structure your solution with these logical tasks:**
|
|
249
|
+
```python
|
|
250
|
+
# Task Plan:
|
|
251
|
+
# 1. Analyze problem and identify constraints
|
|
252
|
+
# 2. Design ASP predicates and model structure
|
|
253
|
+
# 3. Implement facts and choice rules
|
|
254
|
+
# 4. Add constraints and optimization
|
|
255
|
+
# 5. Solve and extract solution
|
|
256
|
+
# 6. Format output as JSON
|
|
257
|
+
# 7. Test and verify solution
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
Use comments in your code to indicate which task you're working on:
|
|
261
|
+
```python
|
|
262
|
+
# Task 1: Analyze problem and identify constraints
|
|
263
|
+
# [Your analysis code here]
|
|
264
|
+
|
|
265
|
+
# Task 2: Design ASP predicates and model structure
|
|
266
|
+
# [Your design code here]
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
#### Step 1: Analyze & Model
|
|
270
|
+
- Identify objects/entities, relationships, constraints, optimization criteria
|
|
271
|
+
- Design appropriate predicates
|
|
272
|
+
- **Parse input data and generate ASP facts from problem description**
|
|
273
|
+
- **Identify fluents (changing properties) and enforce exclusivity**
|
|
274
|
+
|
|
275
|
+
#### Step 2: Implement with Clingo
|
|
276
|
+
- Create Control object
|
|
277
|
+
- Add ASP rules (facts, choice rules, constraints, optimization)
|
|
278
|
+
- Ground the program
|
|
279
|
+
- **Follow the Three-Step Action Pattern for temporal problems**
|
|
280
|
+
|
|
281
|
+
#### Step 3: Solve & Extract Solutions
|
|
282
|
+
- Configure solver parameters
|
|
283
|
+
- Extract atoms from answer sets
|
|
284
|
+
- Handle multiple solutions or optimization
|
|
285
|
+
|
|
286
|
+
#### Step 4: Format & Verify Output
|
|
287
|
+
- Convert to required JSON format
|
|
288
|
+
- Verify solution satisfies constraints
|
|
289
|
+
- Handle UNSAT cases gracefully. A justified UNSAT is a correct final
|
|
290
|
+
answer — verify only that every integrity constraint is warranted by the
|
|
291
|
+
problem text; do not try to prove *why* it is unsatisfiable. Likewise,
|
|
292
|
+
trust the solver's optimality; do not attempt to prove global optimality
|
|
293
|
+
yourself.
|
|
294
|
+
|
|
295
|
+
### When to Create feedback.md
|
|
296
|
+
|
|
297
|
+
Create `feedback.md` ONLY for:
|
|
298
|
+
- Missing packages or imports
|
|
299
|
+
- Inconsistencies or ambiguities in problem description
|
|
300
|
+
- Conflicting constraints that make problem unsolvable
|
|
301
|
+
- Environment setup problems
|
|
302
|
+
- API compatibility issues
|
|
303
|
+
|
|
304
|
+
NOT for your own logic errors or debugging.
|
|
305
|
+
|
|
306
|
+
### 2.5 How to Express Constraints - The Eliminative Mindset
|
|
307
|
+
|
|
308
|
+
**CRITICAL**: ASP constraints work by ELIMINATION, not assertion. You forbid what's invalid, not state what's valid.
|
|
309
|
+
|
|
310
|
+
**Common Constraint Patterns:**
|
|
311
|
+
|
|
312
|
+
```asp
|
|
313
|
+
% To enforce X >= Y, forbid X < Y
|
|
314
|
+
% WRONG: :- capacity >= 32. % This would forbid ALL solutions!
|
|
315
|
+
% CORRECT: Forbid capacity being less than 32
|
|
316
|
+
:- selected_ram(R), ram(R,_,Capacity,_,_), Capacity < 32.
|
|
317
|
+
|
|
318
|
+
% To enforce X > Y, forbid X <= Y
|
|
319
|
+
:- deadline(D), current_day(C), D <= C. % Deadline must be after today
|
|
320
|
+
|
|
321
|
+
% To enforce X != "bad_value", forbid X = "bad_value"
|
|
322
|
+
:- status(X, "invalid"). % No entity can have invalid status
|
|
323
|
+
|
|
324
|
+
% To enforce at least one selection, forbid having none
|
|
325
|
+
:- not selected(_). % At least one must be selected
|
|
326
|
+
|
|
327
|
+
% To enforce mutual exclusion, forbid both being true
|
|
328
|
+
:- has_property(X, hot), has_property(X, cold). % Can't be both
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
**Remember**: Think "what makes a solution invalid?" then write `:- invalid_condition.`
|
|
332
|
+
|
|
333
|
+
### 2.6 Hard vs Weak Constraints
|
|
334
|
+
|
|
335
|
+
**Use the right tool for the job:**
|
|
336
|
+
|
|
337
|
+
**Integrity Constraints (`:-`)**: Define what is IMPOSSIBLE
|
|
338
|
+
```asp
|
|
339
|
+
% These eliminate invalid answer sets entirely
|
|
340
|
+
:- overlapping_tasks(T1,T2). % No overlaps allowed
|
|
341
|
+
:- budget_exceeded. % Hard budget limit
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
**Weak Constraints (`:~`)**: Define what is UNDESIRABLE
|
|
345
|
+
```asp
|
|
346
|
+
% These guide optimization without eliminating solutions
|
|
347
|
+
:~ delayed(Task). [1@2] % Prefer on-time, priority 2
|
|
348
|
+
:~ cost(C). [C@1] % Minimize cost, priority 1
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
### 2.7 Multi-Objective Optimization
|
|
352
|
+
|
|
353
|
+
When using multiple `#minimize` or `#maximize` statements, clingo optimizes level-by-level in order:
|
|
354
|
+
|
|
355
|
+
```asp
|
|
356
|
+
% Optimized in this order:
|
|
357
|
+
#maximize { Score*3 : ai_performance(Score) }. % First priority
|
|
358
|
+
#maximize { Score*2 : gaming_score(Score) }. % Second priority
|
|
359
|
+
#maximize { Score : user_preference(Score) }. % Third priority
|
|
360
|
+
#minimize { Cost : total_cost(Cost) }. % Fourth priority
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
This allows sophisticated trade-off balancing without complex weight tuning.
|
|
364
|
+
|
|
365
|
+
## Section 3: Clingo API & Implementation Guide
|
|
366
|
+
|
|
367
|
+
### Basic API Flow
|
|
368
|
+
|
|
369
|
+
```python
|
|
370
|
+
import clingo
|
|
371
|
+
import json
|
|
372
|
+
|
|
373
|
+
# Create control object
|
|
374
|
+
ctl = clingo.Control()
|
|
375
|
+
|
|
376
|
+
# Add ASP program
|
|
377
|
+
program = """
|
|
378
|
+
% Facts from input
|
|
379
|
+
% ... generated facts ...
|
|
380
|
+
|
|
381
|
+
% Choice rules
|
|
382
|
+
{ choice(X) } :- domain(X).
|
|
383
|
+
|
|
384
|
+
% Constraints
|
|
385
|
+
:- invalid_condition.
|
|
386
|
+
|
|
387
|
+
% Optimization
|
|
388
|
+
#minimize { Cost,X : selected(X), cost(X,Cost) }.
|
|
389
|
+
"""
|
|
390
|
+
ctl.add("base", [], program)
|
|
391
|
+
|
|
392
|
+
# Ground the program
|
|
393
|
+
ctl.ground([("base", [])])
|
|
394
|
+
|
|
395
|
+
# Solve and extract
|
|
396
|
+
solution = None
|
|
397
|
+
def on_model(m):
|
|
398
|
+
global solution
|
|
399
|
+
atoms = m.symbols(atoms=True)
|
|
400
|
+
# Process atoms into solution
|
|
401
|
+
|
|
402
|
+
result = ctl.solve(on_model=on_model)
|
|
403
|
+
|
|
404
|
+
# Output
|
|
405
|
+
if result.satisfiable:
|
|
406
|
+
print(json.dumps(solution))
|
|
407
|
+
else:
|
|
408
|
+
print(json.dumps({"error": "No solution exists"}))
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
### CRITICAL: Finding One vs. All Solutions (Solver Configuration)
|
|
412
|
+
|
|
413
|
+
A frequent and critical error is misconfiguring the solver to search for all possible solutions when only one is required. This is a leading cause of timeouts on moderately complex problems. The number of models to find is controlled by the first argument to `clingo.Control()`.
|
|
414
|
+
|
|
415
|
+
> **Fundamental Rule:** If the problem asks for *a* feasible solution, you MUST limit the solver to find only one.
|
|
416
|
+
|
|
417
|
+
| Configuration | Behavior | Use Case | Consequence of Misuse |
|
|
418
|
+
| :----------------------------- | :------------------------------------------------------ | :------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------- |
|
|
419
|
+
| `ctl = clingo.Control(["1"])` | **Stops after the first solution (model) is found.** | **This should be your default for most tasks.** Use when the problem asks for *any* valid solution. | (Safe) |
|
|
420
|
+
| `ctl = clingo.Control()` or `ctl = clingo.Control(["0"])` | **Finds all possible solutions.** | Use **only** when the problem explicitly requires enumerating every single valid combination. | **Leads to timeouts.** The solver will continue working long after finding a valid solution, needlessly exploring the entire search space. |
|
|
421
|
+
|
|
422
|
+
**Example from a Failed Task (Bin Packing):**
|
|
423
|
+
- **The Goal:** Find one valid way to pack bins.
|
|
424
|
+
- **The Mistake:** `ctl = clingo.Control(["0"])` was used. The solver found a valid packing quickly but then continued searching for all other possible valid packings, eventually timing out.
|
|
425
|
+
- **The Fix:** Changing the call to `ctl = clingo.Control(["1"])` allows the program to terminate immediately after the first valid model is found, solving the problem well within the time limit.
|
|
426
|
+
|
|
427
|
+
### The Three-Step Action Modeling Pattern (CRITICAL for temporal problems)
|
|
428
|
+
|
|
429
|
+
For EVERY action in temporal/planning problems, you MUST model three aspects:
|
|
430
|
+
|
|
431
|
+
#### 1. Choice Rule (Generation)
|
|
432
|
+
Define when an action CAN possibly occur:
|
|
433
|
+
```asp
|
|
434
|
+
% Robot can try to pickup any item at any valid time
|
|
435
|
+
{ pickup(R,I,T) : item(I) } 1 :- robot(R), time(T), T < max_time.
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
#### 2. Precondition Constraints (Validation)
|
|
439
|
+
Define when an action is INVALID (prune invalid choices):
|
|
440
|
+
```asp
|
|
441
|
+
% Cannot pickup if robot and item at different locations
|
|
442
|
+
:- pickup(R,I,T), robot_at(R,RX,RY,T), item_at(I,IX,IY,T), (RX,RY) != (IX,IY).
|
|
443
|
+
|
|
444
|
+
% Cannot pickup if already carrying something
|
|
445
|
+
:- pickup(R,I,T), carrying(R,_,T).
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
#### 3. Effect Rules (State Change)
|
|
449
|
+
Define the NEW STATE resulting from a valid action:
|
|
450
|
+
```asp
|
|
451
|
+
% Pickup causes carrying at next timestep
|
|
452
|
+
carrying(R,I,T+1) :- pickup(R,I,T).
|
|
453
|
+
|
|
454
|
+
% Item no longer has location after pickup
|
|
455
|
+
% (Enforced by mutual exclusivity constraint)
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
### Passing Data to ASP
|
|
459
|
+
|
|
460
|
+
```python
|
|
461
|
+
def generate_facts(problem_data):
|
|
462
|
+
facts = []
|
|
463
|
+
for item in problem_data["items"]:
|
|
464
|
+
facts.append(f'item("{item}").')
|
|
465
|
+
return " ".join(facts)
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
### Extracting Solutions
|
|
469
|
+
|
|
470
|
+
```python
|
|
471
|
+
def extract_solution(model):
|
|
472
|
+
solution = {}
|
|
473
|
+
for atom in model.symbols(atoms=True):
|
|
474
|
+
if atom.match("assigned", 2):
|
|
475
|
+
task = str(atom.arguments[0])
|
|
476
|
+
worker = str(atom.arguments[1])
|
|
477
|
+
if worker not in solution:
|
|
478
|
+
solution[worker] = []
|
|
479
|
+
solution[worker].append(task)
|
|
480
|
+
return solution
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
### CRITICAL: The Model Object Is Only Valid Inside on_model (Segfault Risk)
|
|
484
|
+
|
|
485
|
+
The `clingo.Model` object passed to your `on_model` callback is only valid DURING
|
|
486
|
+
that callback. After `ctl.solve()` returns, clingo frees the underlying model —
|
|
487
|
+
touching it later is a use-after-free that crashes the Python process with a
|
|
488
|
+
segmentation fault (exit code 139) and NO Python traceback.
|
|
489
|
+
|
|
490
|
+
Extract everything you need into plain Python objects (ints, strings, lists, dicts)
|
|
491
|
+
INSIDE the callback. Never store the Model object itself for later use.
|
|
492
|
+
|
|
493
|
+
```python
|
|
494
|
+
# WRONG - segfaults after solve() returns:
|
|
495
|
+
saved = None
|
|
496
|
+
def on_model(m):
|
|
497
|
+
global saved
|
|
498
|
+
saved = m # Model outlives the callback
|
|
499
|
+
ctl.solve(on_model=on_model)
|
|
500
|
+
atoms = saved.symbols(atoms=True) # use-after-free -> SIGSEGV, no traceback
|
|
501
|
+
|
|
502
|
+
# CORRECT - extract inside the callback:
|
|
503
|
+
result = []
|
|
504
|
+
def on_model(m):
|
|
505
|
+
for a in m.symbols(atoms=True):
|
|
506
|
+
if a.match("assigned", 2):
|
|
507
|
+
result.append((str(a.arguments[0]), str(a.arguments[1])))
|
|
508
|
+
ctl.solve(on_model=on_model)
|
|
509
|
+
# work with the plain tuples in result
|
|
510
|
+
```
|
|
511
|
+
|
|
512
|
+
This also applies to verification: snapshot the atoms into plain Python inside
|
|
513
|
+
`on_model`, then run your checks on the snapshot after solving.
|
|
514
|
+
|
|
515
|
+
## Section 4: Problem-Solving Pattern Library
|
|
516
|
+
|
|
517
|
+
### 4.1 Modeling State and Change (NEW - CRITICAL)
|
|
518
|
+
|
|
519
|
+
#### A. Define Exclusive States (Fluents)
|
|
520
|
+
A fluent is a property that changes over time. It can only have ONE value at any time.
|
|
521
|
+
|
|
522
|
+
**Examples of fluents:**
|
|
523
|
+
- Location of an object
|
|
524
|
+
- Whether a resource is available
|
|
525
|
+
- State of a process (idle, running, complete)
|
|
526
|
+
|
|
527
|
+
**Enforce exclusivity:**
|
|
528
|
+
```asp
|
|
529
|
+
% Object cannot be in two places
|
|
530
|
+
:- at(Obj,Loc1,T), at(Obj,Loc2,T), Loc1 != Loc2.
|
|
531
|
+
|
|
532
|
+
% Resource cannot be both free and occupied
|
|
533
|
+
:- free(R,T), occupied(R,T).
|
|
534
|
+
|
|
535
|
+
% Process cannot be in multiple states
|
|
536
|
+
:- state(P,S1,T), state(P,S2,T), S1 != S2.
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
#### B. Frame Axioms: Persistence vs Change
|
|
540
|
+
Frame axioms define what persists. They must NOT fire when an action changes that state.
|
|
541
|
+
|
|
542
|
+
**Pattern:**
|
|
543
|
+
```asp
|
|
544
|
+
% State persists IF no action changes it
|
|
545
|
+
fluent(Args,T+1) :- fluent(Args,T), time(T+1),
|
|
546
|
+
not action_that_changes_fluent(Args,T).
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
**Example:**
|
|
550
|
+
```asp
|
|
551
|
+
% Item location persists if not picked up
|
|
552
|
+
item_at(I,X,Y,T+1) :- item_at(I,X,Y,T), time(T+1),
|
|
553
|
+
not pickup(_,I,T).
|
|
554
|
+
|
|
555
|
+
% Carrying persists if not put down
|
|
556
|
+
carrying(R,I,T+1) :- carrying(R,I,T), time(T+1),
|
|
557
|
+
not putdown(R,I,T).
|
|
558
|
+
```
|
|
559
|
+
|
|
560
|
+
#### C. Debugging Temporal Models
|
|
561
|
+
|
|
562
|
+
**Common issues and solutions:**
|
|
563
|
+
|
|
564
|
+
1. **Invalid state combinations**
|
|
565
|
+
- Check: Are mutually exclusive states enforced?
|
|
566
|
+
- Fix: Add exclusivity constraints
|
|
567
|
+
|
|
568
|
+
2. **Actions happening without preconditions**
|
|
569
|
+
- Check: Are all preconditions validated?
|
|
570
|
+
- Fix: Add precondition constraints
|
|
571
|
+
|
|
572
|
+
3. **States not changing after actions**
|
|
573
|
+
- Check: Are effect rules defined?
|
|
574
|
+
- Fix: Add effect rules for each action
|
|
575
|
+
|
|
576
|
+
4. **UNSAT when solution should exist**
|
|
577
|
+
- Debug: Comment out constraints one by one
|
|
578
|
+
- Test: Create minimal test case
|
|
579
|
+
- Isolate: Use "teleportation" test (bypass actions)
|
|
580
|
+
|
|
581
|
+
### 4.2 Assignment Problems
|
|
582
|
+
|
|
583
|
+
**Pattern: Worker-Task Assignment**
|
|
584
|
+
```asp
|
|
585
|
+
% Each task assigned to exactly one worker
|
|
586
|
+
1 { assigned(T,W) : worker(W) } 1 :- task(T).
|
|
587
|
+
|
|
588
|
+
% Worker capacity constraint
|
|
589
|
+
:- worker(W), #count { T : assigned(T,W) } > capacity(W).
|
|
590
|
+
```
|
|
591
|
+
|
|
592
|
+
### 4.3 Graph Problems
|
|
593
|
+
|
|
594
|
+
**Pattern: Graph Coloring**
|
|
595
|
+
```asp
|
|
596
|
+
% Each node gets exactly one color
|
|
597
|
+
1 { colored(N,C) : color(C) } 1 :- node(N).
|
|
598
|
+
|
|
599
|
+
% Adjacent nodes different colors
|
|
600
|
+
:- colored(N1,C), colored(N2,C), edge(N1,N2).
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
### 4.4 Scheduling Problems
|
|
604
|
+
|
|
605
|
+
**CRITICAL: Always Define a Finite Time Horizon**
|
|
606
|
+
|
|
607
|
+
For scheduling, planning, and any temporal problem, you MUST define a finite time domain. Without this, the solver may attempt to explore an infinite search space, leading to grounding errors (`#inf@0`) or extreme slowness.
|
|
608
|
+
|
|
609
|
+
```asp
|
|
610
|
+
% REQUIRED: Define finite time domain first
|
|
611
|
+
time(0..max_time). % Use the problem's latest deadline or a reasonable upper bound
|
|
612
|
+
```
|
|
613
|
+
|
|
614
|
+
**Pattern: Job Scheduling**
|
|
615
|
+
```asp
|
|
616
|
+
% STEP 1: Define time domain (CRITICAL!)
|
|
617
|
+
time(0..20). % Set based on problem constraints
|
|
618
|
+
|
|
619
|
+
% STEP 2: Each job starts at exactly one time
|
|
620
|
+
1 { start(J,T) : time(T) } 1 :- job(J).
|
|
621
|
+
|
|
622
|
+
% No time overflow
|
|
623
|
+
:- start(J,T), duration(J,D), T+D-1 > 20.
|
|
624
|
+
|
|
625
|
+
% No overlap
|
|
626
|
+
:- start(J1,T1), start(J2,T2), J1 != J2,
|
|
627
|
+
duration(J1,D1), T1 <= T2, T2 < T1+D1.
|
|
628
|
+
```
|
|
629
|
+
|
|
630
|
+
**Why This Matters:**
|
|
631
|
+
- Without `time(0..N)`, variables like `T` in `#minimize { T : makespan(T) }` have no bound
|
|
632
|
+
- The grounder will produce `#inf@0` errors or create enormous search spaces
|
|
633
|
+
- Always use the latest deadline or a reasonable upper bound as your time horizon
|
|
634
|
+
|
|
635
|
+
### 4.5 Temporal Reasoning with Frame Axioms
|
|
636
|
+
|
|
637
|
+
**Critical for**: Robot planning, logistics, action sequences
|
|
638
|
+
|
|
639
|
+
**Complete Pattern for Temporal Problems:**
|
|
640
|
+
|
|
641
|
+
```asp
|
|
642
|
+
% 1. ENTITIES AND TIME
|
|
643
|
+
robot(r1). item(i1). time(0..max_time).
|
|
644
|
+
location(1..5, 1..5).
|
|
645
|
+
|
|
646
|
+
% 2. INITIAL STATE
|
|
647
|
+
robot_at(r1,1,1,0).
|
|
648
|
+
item_at(i1,2,2,0).
|
|
649
|
+
|
|
650
|
+
% 3. ACTION GENERATION (Choice Rules)
|
|
651
|
+
{ move(R,Dir,T) : direction(Dir) } 1 :- robot(R), time(T), T < max_time.
|
|
652
|
+
{ pickup(R,I,T) : item(I) } 1 :- robot(R), time(T), T < max_time.
|
|
653
|
+
|
|
654
|
+
% 4. MUTUAL EXCLUSION (State Constraints)
|
|
655
|
+
% Robot cannot be in two places
|
|
656
|
+
:- robot_at(R,X1,Y1,T), robot_at(R,X2,Y2,T), (X1,Y1) != (X2,Y2).
|
|
657
|
+
|
|
658
|
+
% Item cannot be both at location and carried
|
|
659
|
+
:- item_at(I,X,Y,T), carrying(_,I,T).
|
|
660
|
+
|
|
661
|
+
% 5. ACTION PRECONDITIONS
|
|
662
|
+
% Cannot move outside grid
|
|
663
|
+
:- move(R,up,T), robot_at(R,X,Y,T), Y >= max_y.
|
|
664
|
+
|
|
665
|
+
% Cannot pickup from different location
|
|
666
|
+
:- pickup(R,I,T), robot_at(R,RX,RY,T), item_at(I,IX,IY,T), (RX,RY) != (IX,IY).
|
|
667
|
+
|
|
668
|
+
% 6. ACTION EFFECTS
|
|
669
|
+
% Movement changes robot position
|
|
670
|
+
robot_at(R,X,Y+1,T+1) :- move(R,up,T), robot_at(R,X,Y,T).
|
|
671
|
+
|
|
672
|
+
% Pickup creates carrying relationship
|
|
673
|
+
carrying(R,I,T+1) :- pickup(R,I,T).
|
|
674
|
+
|
|
675
|
+
% Putdown creates item location
|
|
676
|
+
item_at(I,X,Y,T+1) :- putdown(R,I,T), robot_at(R,X,Y,T).
|
|
677
|
+
|
|
678
|
+
% 7. FRAME AXIOMS (Persistence)
|
|
679
|
+
% Robot position persists if no movement
|
|
680
|
+
robot_at(R,X,Y,T+1) :- robot_at(R,X,Y,T), time(T+1),
|
|
681
|
+
not move(R,up,T), not move(R,down,T),
|
|
682
|
+
not move(R,left,T), not move(R,right,T).
|
|
683
|
+
|
|
684
|
+
% Item location persists if not picked up
|
|
685
|
+
item_at(I,X,Y,T+1) :- item_at(I,X,Y,T), time(T+1),
|
|
686
|
+
not pickup(_,I,T).
|
|
687
|
+
|
|
688
|
+
% Carrying persists if not put down
|
|
689
|
+
carrying(R,I,T+1) :- carrying(R,I,T), time(T+1),
|
|
690
|
+
not putdown(R,I,T).
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
### 4.6 Combinatorial Puzzles
|
|
694
|
+
|
|
695
|
+
**Pattern: N-Queens**
|
|
696
|
+
```asp
|
|
697
|
+
#const n=8.
|
|
698
|
+
1 { queen(R,C) : col(C) } 1 :- row(R).
|
|
699
|
+
:- queen(R1,C), queen(R2,C), R1 != R2.
|
|
700
|
+
:- queen(R1,C1), queen(R2,C2), R1 != R2, |R1-R2| == |C1-C2|.
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
### 4.7 Enforcing Dependent Properties (A implies B)
|
|
704
|
+
|
|
705
|
+
A common task is to enforce that if one property `P` exists, a corresponding property `Q` must also exist. A frequent mistake is to only forbid the case `P and not Q` using complex joins, which can be brittle. A more robust pattern is to state the implication directly as a constraint.
|
|
706
|
+
|
|
707
|
+
**Pattern: If a keyed path exists, a keyless return MUST exist.**
|
|
708
|
+
|
|
709
|
+
Let's say for a connection `conn(R1, R2, Key)`, we must ensure `conn(R2, R1, "null")` exists.
|
|
710
|
+
|
|
711
|
+
**Incorrect Attempt (Brittle):**
|
|
712
|
+
This attempts to join all possibilities and forbid the bad ones. It fails if multiple return paths exist or if the solver simply avoids creating a bidirectional link.
|
|
713
|
+
```asp
|
|
714
|
+
% Fails to enforce generation; only prunes specific bad combinations.
|
|
715
|
+
:- conn(R1, R2, Req1), conn(R2, R1, Req2), key(Req1), Req2 != "null".
|
|
716
|
+
```
|
|
717
|
+
|
|
718
|
+
**Correct Pattern (Robust Logic):**
|
|
719
|
+
This pattern forbids the state where the premise (`keyed path exists`) is true but the conclusion (`keyless return path exists`) is false. This forces the solver to generate the conclusion to satisfy the constraint.
|
|
720
|
+
|
|
721
|
+
```asp
|
|
722
|
+
% Define the premise: a keyed path exists from R1 to R2.
|
|
723
|
+
keyed_path(R1, R2) :- conn(R1, R2, Req), key(Req).
|
|
724
|
+
|
|
725
|
+
% Enforce the conclusion: if a keyed path exists, a keyless return MUST exist.
|
|
726
|
+
% This translates to: "It is an error if a keyed path from R1 to R2 exists
|
|
727
|
+
% AND a keyless path from R2 to R1 does NOT exist."
|
|
728
|
+
:- keyed_path(R1, R2), not conn(R2, R1, "null").
|
|
729
|
+
```
|
|
730
|
+
This approach correctly models the logical implication `keyed_path(R1, R2) -> conn(R2, R1, "null")` and is the standard way to express such dependencies in ASP.
|
|
731
|
+
|
|
732
|
+
### 4.8 Default Logic with Negation as Failure
|
|
733
|
+
|
|
734
|
+
**Pattern: Default Property with Exceptions**
|
|
735
|
+
|
|
736
|
+
This pattern implements defeasible reasoning where properties hold by default unless exceptions apply:
|
|
737
|
+
|
|
738
|
+
```asp
|
|
739
|
+
% General Pattern:
|
|
740
|
+
% A property holds by default...
|
|
741
|
+
has_property(X) :- entity(X), not lacks_property(X).
|
|
742
|
+
|
|
743
|
+
% ...unless a specific exception applies
|
|
744
|
+
lacks_property(X) :- exception_condition_1(X).
|
|
745
|
+
lacks_property(X) :- exception_condition_2(X).
|
|
746
|
+
|
|
747
|
+
% Example: Birds fly unless they're penguins or injured
|
|
748
|
+
flies(B) :- bird(B), not cannot_fly(B).
|
|
749
|
+
cannot_fly(B) :- penguin(B).
|
|
750
|
+
cannot_fly(B) :- injured(B).
|
|
751
|
+
|
|
752
|
+
% Example: Statements are true unless proven false
|
|
753
|
+
believed(Statement) :- statement(Statement), not disproven(Statement).
|
|
754
|
+
disproven(Statement) :- contradicts(Statement, Fact), proven(Fact).
|
|
755
|
+
```
|
|
756
|
+
|
|
757
|
+
**Key Insight**: The `not` operator implements Closed World Assumption - what cannot be proven true is assumed false.
|
|
758
|
+
|
|
759
|
+
### 4.9 Sequential Planning Problems (Tower of Hanoi, Blocks World)
|
|
760
|
+
|
|
761
|
+
**Critical for**: Multi-step sequential planning where exactly ONE action occurs per timestep.
|
|
762
|
+
|
|
763
|
+
**ANTI-PATTERN: Multiple Simultaneous Actions + Global Count**
|
|
764
|
+
|
|
765
|
+
This is the most common mistake in planning problems:
|
|
766
|
+
|
|
767
|
+
```asp
|
|
768
|
+
% WRONG: Allows multiple moves per timestep (one per disk!)
|
|
769
|
+
{ move(D, P1, P2, T) : peg(P1), peg(P2), P1 != P2 } 1 :- disk(D), time(T), T < max_time.
|
|
770
|
+
|
|
771
|
+
% Then uses slow global constraint to force total count
|
|
772
|
+
:- #count { D, P1, P2, T : move(D, P1, P2, T) } != 19.
|
|
773
|
+
```
|
|
774
|
+
|
|
775
|
+
**Why this is catastrophically slow:**
|
|
776
|
+
1. Generates moves for ALL disks from ANY peg to ANY peg (even illegal ones)
|
|
777
|
+
2. Allows up to N simultaneous moves per timestep (one per disk)
|
|
778
|
+
3. Uses expensive #count over entire plan to enforce sequence length
|
|
779
|
+
4. Creates massive search space that times out
|
|
780
|
+
|
|
781
|
+
**CORRECT PATTERN: Sequential Actions with Validity Checking**
|
|
782
|
+
|
|
783
|
+
The key principles:
|
|
784
|
+
1. **Define what CAN be moved** (e.g., top disk on a peg)
|
|
785
|
+
2. **Choose exactly ONE valid action per timestep**
|
|
786
|
+
3. **No global count needed** - sequence length emerges from timesteps
|
|
787
|
+
|
|
788
|
+
**Complete Tower of Hanoi Example:**
|
|
789
|
+
|
|
790
|
+
```asp
|
|
791
|
+
#const max_time = 19.
|
|
792
|
+
disk(1..4). peg(a;b;c;d).
|
|
793
|
+
time(0..max_time-1). % Action timesteps (0..18 for 19 moves)
|
|
794
|
+
|
|
795
|
+
% INITIAL STATE
|
|
796
|
+
on_peg(1,a,0). on_peg(2,a,0). on_peg(3,a,0). on_peg(4,a,0).
|
|
797
|
+
|
|
798
|
+
% --- 1. DEFINE WHAT CAN BE MOVED ---
|
|
799
|
+
% A disk is "top" if no smaller disk is on the same peg
|
|
800
|
+
top(D, P, T) :- on_peg(D, P, T), not on_peg(D2, P, T), D2 < D.
|
|
801
|
+
|
|
802
|
+
% --- 2. CHOOSE EXACTLY ONE VALID MOVE PER TIMESTEP ---
|
|
803
|
+
% At each time T, move exactly one top disk to a different peg
|
|
804
|
+
1 { move(D, P1, P2, T) : top(D, P1, T), peg(P2), P1 != P2 } 1 :- time(T).
|
|
805
|
+
|
|
806
|
+
% --- 3. PRECONDITIONS ---
|
|
807
|
+
% Cannot place larger disk on smaller disk
|
|
808
|
+
:- move(D, _, P2, T), top(D2, P2, T), D > D2.
|
|
809
|
+
|
|
810
|
+
% --- 4. EFFECTS ---
|
|
811
|
+
% Moved disk is on new peg at T+1
|
|
812
|
+
on_peg(D, P2, T+1) :- move(D, _, P2, T).
|
|
813
|
+
|
|
814
|
+
% --- 5. FRAME AXIOMS ---
|
|
815
|
+
% Disks not moved stay on their peg
|
|
816
|
+
on_peg(D, P, T+1) :- on_peg(D, P, T), time(T+1), not move(D, P, _, T).
|
|
817
|
+
|
|
818
|
+
% --- 6. STATE EXCLUSIVITY ---
|
|
819
|
+
% Disk cannot be on two pegs
|
|
820
|
+
:- on_peg(D, P1, T), on_peg(D, P2, T), P1 != P2.
|
|
821
|
+
|
|
822
|
+
% --- 7. DOMAIN-SPECIFIC CONSTRAINTS ---
|
|
823
|
+
% Pilgrim's journey: every disk must visit both B and C
|
|
824
|
+
visited(D, P) :- move(D, _, P, _).
|
|
825
|
+
:- disk(D), not visited(D, b).
|
|
826
|
+
:- disk(D), not visited(D, c).
|
|
827
|
+
|
|
828
|
+
% --- 8. GOAL ---
|
|
829
|
+
% All disks on peg D at final timestep
|
|
830
|
+
:- disk(D), not on_peg(D, d, max_time).
|
|
831
|
+
```
|
|
832
|
+
|
|
833
|
+
**Why this is fast:**
|
|
834
|
+
- Only generates valid moves (from top disks only)
|
|
835
|
+
- Exactly one move per timestep (correctly models sequential plan)
|
|
836
|
+
- No expensive global #count constraint
|
|
837
|
+
- Search space is minimal and focused
|
|
838
|
+
|
|
839
|
+
**Key Pattern Elements:**
|
|
840
|
+
|
|
841
|
+
1. **Define "Valid"**: Use auxiliary predicate (`top/3`) to identify what can be acted upon
|
|
842
|
+
2. **One Action Per Time**: `1 { action(...) : valid(...) } 1 :- time(T)`
|
|
843
|
+
3. **Constrain at Source**: Only generate moves from valid sources in choice rule
|
|
844
|
+
4. **No Global Counts**: Let sequence length emerge from timesteps naturally
|
|
845
|
+
|
|
846
|
+
**Blocks World Pattern:**
|
|
847
|
+
|
|
848
|
+
```asp
|
|
849
|
+
% Define what can be moved
|
|
850
|
+
clear(B,T) :- block(B), not on(_, B, T).
|
|
851
|
+
on_table_space(T) :- #count { B : on_table(B,T) } < max_table_slots.
|
|
852
|
+
|
|
853
|
+
% Exactly one move per timestep
|
|
854
|
+
1 { move_to_block(B1, B2, T) : clear(B1,T), clear(B2,T), B1 != B2 ;
|
|
855
|
+
move_to_table(B, T) : clear(B,T), on_table_space(T) } 1 :- time(T).
|
|
856
|
+
```
|
|
857
|
+
|
|
858
|
+
**General Takeaway:** For sequential planning, always:
|
|
859
|
+
- Define valid actions via auxiliary predicates
|
|
860
|
+
- Use `1 { ... } 1 :- time(T)` for exactly one action per timestep
|
|
861
|
+
- Avoid generate-and-filter patterns in choice rules
|
|
862
|
+
- Eliminate global #count constraints over entire plans
|
|
863
|
+
|
|
864
|
+
### 4.10 Sequence and Run-Based Constraints
|
|
865
|
+
|
|
866
|
+
**Critical for**: Puzzles with consecutive sequences (nonograms, nurse scheduling, delivery routes), problems requiring runs of items with specific properties.
|
|
867
|
+
|
|
868
|
+
Modeling sequences or "runs" of consecutive items is common in constraint problems. A critical distinction exists between problems where ALL items must justify themselves vs. problems where only certain items need to form runs.
|
|
869
|
+
|
|
870
|
+
#### Understanding "Runs" in Different Problem Types
|
|
871
|
+
|
|
872
|
+
**Run Definition**: A consecutive sequence of cells/slots with the same property (color, state, assignment).
|
|
873
|
+
|
|
874
|
+
**Two Fundamentally Different Patterns:**
|
|
875
|
+
|
|
876
|
+
1. **Simple Binary Problems** (e.g., black-and-white nonogram):
|
|
877
|
+
- Every "on" cell MUST belong to a defined run
|
|
878
|
+
- White cells are just separators
|
|
879
|
+
- Total coverage constraint is VALID
|
|
880
|
+
|
|
881
|
+
2. **Multi-State Problems** (e.g., colored nonogram, multi-skill nurse scheduling):
|
|
882
|
+
- Cells/slots of one state can act as separators for runs of another state
|
|
883
|
+
- Only run-forming cells need to justify themselves
|
|
884
|
+
- Total coverage constraint is INVALID
|
|
885
|
+
|
|
886
|
+
#### Anti-Pattern: Incorrect Total Coverage
|
|
887
|
+
|
|
888
|
+
A common error is applying simple binary logic to multi-state problems:
|
|
889
|
+
|
|
890
|
+
```asp
|
|
891
|
+
% ANTI-PATTERN for multi-color/multi-state problems
|
|
892
|
+
% This says: "Every non-empty cell MUST be part of a defined run"
|
|
893
|
+
% This is WRONG when cells of one color/state can separate runs of another
|
|
894
|
+
:- cell(R, C, Color), Color != empty, not is_in_a_run(R, C, Color).
|
|
895
|
+
|
|
896
|
+
% Example failure case:
|
|
897
|
+
% Row clue: [(red, 2), (red, 2)]
|
|
898
|
+
% Valid solution: [red, red, green, red, red]
|
|
899
|
+
% The green cell at index 2 is NOT in any green run, but it's REQUIRED
|
|
900
|
+
% to separate the two red runs. The constraint incorrectly forbids this!
|
|
901
|
+
```
|
|
902
|
+
|
|
903
|
+
**Why This Fails:**
|
|
904
|
+
- In multi-state problems, non-run items serve as separators
|
|
905
|
+
- Requiring every item to justify itself over-constrains the model
|
|
906
|
+
- Creates false UNSAT or forces invalid solutions
|
|
907
|
+
|
|
908
|
+
#### Correct Pattern: Constrain Runs, Not Gaps
|
|
909
|
+
|
|
910
|
+
The correct approach focuses ONLY on enforcing run properties, letting the solver determine separators naturally:
|
|
911
|
+
|
|
912
|
+
```asp
|
|
913
|
+
% CORRECT PATTERN: Only constrain the runs themselves
|
|
914
|
+
|
|
915
|
+
% 1. Define run positions (generate)
|
|
916
|
+
{ run_pos(Row, RunIdx, StartCol) : possible_start(StartCol) } 1
|
|
917
|
+
:- row_clue(Row, RunIdx, _, _).
|
|
918
|
+
|
|
919
|
+
% 2. Enforce run cells match the required color/state (constrain)
|
|
920
|
+
:- run_pos(Row, RunIdx, Start), row_clue(Row, RunIdx, RequiredColor, Len),
|
|
921
|
+
col(C), C >= Start, C < Start + Len,
|
|
922
|
+
cell(Row, C, ActualColor), ActualColor != RequiredColor.
|
|
923
|
+
|
|
924
|
+
% 3. Enforce ordering (runs appear in sequence)
|
|
925
|
+
:- run_pos(R, I1, C1), run_pos(R, I2, C2),
|
|
926
|
+
row_clue(R, I1, _, L1), I2 = I1 + 1, C2 < C1 + L1.
|
|
927
|
+
|
|
928
|
+
% 4. Enforce separation for same-color/state runs only
|
|
929
|
+
% (Different colors/states CAN be adjacent)
|
|
930
|
+
:- run_pos(R, I1, C1), run_pos(R, I2, C2),
|
|
931
|
+
row_clue(R, I1, Color, L1), row_clue(R, I2, Color, _),
|
|
932
|
+
I1 < I2, C2 < C1 + L1 + 1. % Same color needs gap
|
|
933
|
+
|
|
934
|
+
% NOTE: NO constraint on cells outside of runs!
|
|
935
|
+
% The solver determines their values to satisfy other constraints
|
|
936
|
+
```
|
|
937
|
+
|
|
938
|
+
#### Pattern Comparison Table
|
|
939
|
+
|
|
940
|
+
| Problem Type | Run Coverage | Separation Rules | Example Domains |
|
|
941
|
+
|:-------------|:-------------|:-----------------|:----------------|
|
|
942
|
+
| **Binary** | All "on" cells in runs | All runs need separation | B&W Nonogram, Simple scheduling |
|
|
943
|
+
| **Multi-State** | Only run-forming cells in runs | Same-state runs need separation<br/>Different-state runs can be adjacent | Colored Nonogram, Multi-skill scheduling, Delivery with vehicle types |
|
|
944
|
+
|
|
945
|
+
#### Complete Multi-Color Nonogram Pattern
|
|
946
|
+
|
|
947
|
+
```asp
|
|
948
|
+
% Facts
|
|
949
|
+
row(1..n). col(1..m).
|
|
950
|
+
color(0..k). % 0 = empty/white
|
|
951
|
+
row_clue(Row, RunIdx, Color, Length) :- ... % From problem data
|
|
952
|
+
col_clue(Col, RunIdx, Color, Length) :- ...
|
|
953
|
+
|
|
954
|
+
% Grid - each cell gets exactly one color
|
|
955
|
+
{ cell(R, C, Color) : color(Color) } 1 :- row(R), col(C).
|
|
956
|
+
|
|
957
|
+
% ROW CONSTRAINTS
|
|
958
|
+
% Define possible starting positions for runs
|
|
959
|
+
possible_col(C) :- col(C).
|
|
960
|
+
|
|
961
|
+
% Each run clue gets exactly one starting position
|
|
962
|
+
{ row_run_pos(R, RunIdx, StartCol) : possible_col(StartCol) } 1
|
|
963
|
+
:- row_clue(R, RunIdx, _, _).
|
|
964
|
+
|
|
965
|
+
% Cells within run must match run's color
|
|
966
|
+
:- row_run_pos(R, RunIdx, Start), row_clue(R, RunIdx, ReqColor, Len),
|
|
967
|
+
col(C), C >= Start, C < Start + Len,
|
|
968
|
+
cell(R, C, ActualColor), ActualColor != ReqColor.
|
|
969
|
+
|
|
970
|
+
% Runs must appear in order
|
|
971
|
+
:- row_run_pos(R, I1, C1), row_run_pos(R, I2, C2),
|
|
972
|
+
row_clue(R, I1, _, L1), I2 = I1 + 1, C2 < C1 + L1.
|
|
973
|
+
|
|
974
|
+
% Runs of SAME color must be separated (different colors can touch)
|
|
975
|
+
:- row_run_pos(R, I1, C1), row_run_pos(R, I2, C2),
|
|
976
|
+
row_clue(R, I1, SameColor, L1), row_clue(R, I2, SameColor, _),
|
|
977
|
+
I1 < I2, C2 < C1 + L1 + 1.
|
|
978
|
+
|
|
979
|
+
% Repeat for column constraints...
|
|
980
|
+
% (Same pattern with row/col swapped)
|
|
981
|
+
```
|
|
982
|
+
|
|
983
|
+
#### When to Use This Pattern
|
|
984
|
+
|
|
985
|
+
**Use Correct (Constrain Runs Only) Pattern When:**
|
|
986
|
+
- Multiple colors/states can coexist
|
|
987
|
+
- Different types can be adjacent
|
|
988
|
+
- Separators have meaningful values
|
|
989
|
+
- Problem has multi-dimensional constraints
|
|
990
|
+
|
|
991
|
+
**Examples:**
|
|
992
|
+
- Colored nonograms
|
|
993
|
+
- Multi-skill nurse scheduling
|
|
994
|
+
- Vehicle routing with different vehicle types
|
|
995
|
+
- Resource allocation with multiple resource types
|
|
996
|
+
|
|
997
|
+
#### Key Takeaways
|
|
998
|
+
|
|
999
|
+
1. **Never require total coverage** in multi-state sequence problems
|
|
1000
|
+
2. **Only constrain run properties**: position, length, internal consistency
|
|
1001
|
+
3. **Separate by sameness**: Only runs of identical color/state need gaps
|
|
1002
|
+
4. **Let solver determine gaps**: Don't over-constrain non-run cells
|
|
1003
|
+
5. **Different is adjacent**: Cells of different colors/states CAN touch
|
|
1004
|
+
|
|
1005
|
+
### 4.11 "Reachable Only After" / Ordered Reachability Constraints
|
|
1006
|
+
|
|
1007
|
+
When a problem requires that some target element become reachable only after all
|
|
1008
|
+
other elements (or only after specific ones) under an evolving reachability process,
|
|
1009
|
+
do NOT model it as an existential ordering — guessing a permutation with the target
|
|
1010
|
+
pinned last only proves that SOME order exists, which is weaker than what such
|
|
1011
|
+
problems ask. The intended reading is almost always about the actual reachability
|
|
1012
|
+
process: everything reachable gets reached as soon as it is reachable.
|
|
1013
|
+
|
|
1014
|
+
Model the process directly with a time-indexed fixpoint and constrain first-reach
|
|
1015
|
+
times:
|
|
1016
|
+
|
|
1017
|
+
```asp
|
|
1018
|
+
step(0..max_step).
|
|
1019
|
+
reached(S, 0) :- start(S).
|
|
1020
|
+
reached(Y, T+1) :- edge(X, Y), reached(X, T), step(T+1), unlocked(X, Y, T).
|
|
1021
|
+
reached(X, T+1) :- reached(X, T), step(T+1). % persistence
|
|
1022
|
+
first_reached(X, 0) :- reached(X, 0).
|
|
1023
|
+
first_reached(X, T) :- reached(X, T), not reached(X, T-1), T > 0, step(T).
|
|
1024
|
+
|
|
1025
|
+
% target must not become reachable before (or together with) any other element:
|
|
1026
|
+
:- first_reached(target, Tg), first_reached(X, Tx), X != target, Tx >= Tg.
|
|
1027
|
+
```
|
|
1028
|
+
|
|
1029
|
+
Adapt `unlocked/3` to whatever gates progression (collected items, satisfied
|
|
1030
|
+
prerequisites, ...). Verify with a plain-Python simulation of the same process:
|
|
1031
|
+
repeatedly add everything currently reachable, one step at a time, and check the
|
|
1032
|
+
required ordering of first-reach steps against the problem text — do not reuse
|
|
1033
|
+
your encoding's ordering predicates in the verifier.
|
|
1034
|
+
|
|
1035
|
+
## Section 5: Debugging & Advanced Techniques
|
|
1036
|
+
|
|
1037
|
+
### 5.1 Efficient Generation: Constrain Choices Early (Anti-Pattern: Generate-and-Filter)
|
|
1038
|
+
|
|
1039
|
+
A common performance pitfall is to generate a massive number of candidate solutions in a choice rule and then use separate integrity constraints to filter out the vast majority of invalid ones. This forces the grounder and solver to consider many useless options.
|
|
1040
|
+
|
|
1041
|
+
**The Principle: Constrain at the Source.** Build validity checks directly into the generating choice rule itself, so the solver only ever considers valid candidates.
|
|
1042
|
+
|
|
1043
|
+
**Anti-Pattern: Generate, then Filter**
|
|
1044
|
+
This approach generates all combinations and then prunes them.
|
|
1045
|
+
|
|
1046
|
+
```asp
|
|
1047
|
+
% DOMAIN: 100 items, 50 containers. compatible(I,C) defines valid pairs.
|
|
1048
|
+
item(1..100). container(1..50).
|
|
1049
|
+
compatible(1,c1). compatible(2,c1). %... many other compatibility facts
|
|
1050
|
+
|
|
1051
|
+
% ANTI-PATTERN: Generate all 100*50=5000 possible assignments
|
|
1052
|
+
{ placed(I,C) : container(C) } 1 :- item(I).
|
|
1053
|
+
|
|
1054
|
+
% Then, filter out the invalid ones
|
|
1055
|
+
:- placed(I,C), not compatible(I,C).
|
|
1056
|
+
```
|
|
1057
|
+
**Why it's slow:** The solver must first consider 5,000 potential `placed/2` atoms before eliminating most of them.
|
|
1058
|
+
|
|
1059
|
+
**Critical Note: Beyond Performance, This is a Correctness Issue**
|
|
1060
|
+
|
|
1061
|
+
The "Generate-and-Filter" anti-pattern is not just slow; it can lead to confusing `UNSATISFIABLE` results. If the choice rule generates a candidate for which the filtering data does not exist, the solver may be forced into an impossible state.
|
|
1062
|
+
|
|
1063
|
+
**Example: Assigning Features to Devices**
|
|
1064
|
+
Suppose you must assign a `feature(F)` to a `device(D)`, but only if a `driver(F, D)` fact exists.
|
|
1065
|
+
|
|
1066
|
+
**Anti-Pattern (Brittle and Confusing):**
|
|
1067
|
+
```asp
|
|
1068
|
+
% For each feature, choose a device to assign it to.
|
|
1069
|
+
1 { assign(F, D) : device(D) } 1 :- feature(F).
|
|
1070
|
+
|
|
1071
|
+
% Constraint: An assignment is only valid if a driver exists.
|
|
1072
|
+
:- assign(F,D), not driver(F,D).
|
|
1073
|
+
```
|
|
1074
|
+
**The Hidden Problem:** If you have a `feature(f_special)` for which **no** `driver(f_special, _)` facts exist, this model becomes UNSAT. The choice rule forces an assignment `assign(f_special, D)` for some device `D`. But the constraint then makes every possible choice invalid, leading to failure with no obvious reason why.
|
|
1075
|
+
|
|
1076
|
+
By constraining at the source, you avoid this problem entirely:
|
|
1077
|
+
```asp
|
|
1078
|
+
% CORRECT: Only generate assignments where a driver exists
|
|
1079
|
+
1 { assign(F, D) : device(D), driver(F, D) } 1 :- feature(F).
|
|
1080
|
+
% No separate constraint needed - only valid pairs are considered
|
|
1081
|
+
```
|
|
1082
|
+
|
|
1083
|
+
**Good Pattern: Constrain During Generation**
|
|
1084
|
+
This approach only generates combinations that are already known to be valid.
|
|
1085
|
+
|
|
1086
|
+
```asp
|
|
1087
|
+
% DOMAIN: Same as above.
|
|
1088
|
+
item(1..100). container(1..50).
|
|
1089
|
+
compatible(1,c1). compatible(2,c1). %...
|
|
1090
|
+
|
|
1091
|
+
% GOOD PATTERN: Only generate assignments (I,C) where compatible(I,C) is true.
|
|
1092
|
+
{ placed(I,C) : container(C), compatible(I,C) } 1 :- item(I).
|
|
1093
|
+
|
|
1094
|
+
% No filter rule is needed.
|
|
1095
|
+
```
|
|
1096
|
+
**Why it's fast:** The solver's search space is restricted from the very beginning to only valid pairs. If there are only 200 compatible pairs, it considers 200 options, not 5,000.
|
|
1097
|
+
|
|
1098
|
+
**General Takeaway:** Push filtering conditions from the body of separate constraints (`:- ...`) into the domain of the choice rule (`{... : conditions}`).
|
|
1099
|
+
|
|
1100
|
+
### 5.2 CRITICAL: Canonical Counting for Symmetric Relations
|
|
1101
|
+
|
|
1102
|
+
When counting relationships between pairs of entities (connections, edges, paths), you must ensure each pair is counted **exactly once**. A symmetric definition can lead to double-counting, making cardinality constraints impossible to satisfy.
|
|
1103
|
+
|
|
1104
|
+
**The Problem: Double-Counting**
|
|
1105
|
+
|
|
1106
|
+
A common mistake is to define a relationship symmetrically, which causes each instance to be counted multiple times:
|
|
1107
|
+
|
|
1108
|
+
```asp
|
|
1109
|
+
% INCORRECT: Double-counts one-way paths
|
|
1110
|
+
% If R3 -> R4 is one-way, this creates BOTH oneway("R3","R4") AND oneway("R4","R3")
|
|
1111
|
+
oneway(R1, R2) :- conn(R1, R2, _), not conn(R2, R1, _), R2 != "Goal".
|
|
1112
|
+
oneway(R1, R2) :- conn(R2, R1, _), not conn(R1, R2, _), R2 != "Goal".
|
|
1113
|
+
|
|
1114
|
+
% This constraint expects count=1, but gets count=2 for a single path!
|
|
1115
|
+
:- #count { R1, R2 : oneway(R1, R2) } != 1.
|
|
1116
|
+
```
|
|
1117
|
+
|
|
1118
|
+
**The Solution: Canonical Ordering**
|
|
1119
|
+
|
|
1120
|
+
Establish a canonical representation for each pair by enforcing an ordering constraint (typically using `<`). This ensures each pair is represented exactly once:
|
|
1121
|
+
|
|
1122
|
+
```asp
|
|
1123
|
+
% CORRECT: Canonical counting with ordering
|
|
1124
|
+
% A one-way path between R1 and R2 (where R1 < R2) creates exactly ONE atom
|
|
1125
|
+
oneway_pair(R1, R2) :- R1 < R2,
|
|
1126
|
+
( (conn(R1, R2, _), not conn(R2, R1, _)) ;
|
|
1127
|
+
(conn(R2, R1, _), not conn(R1, R2, _)) ).
|
|
1128
|
+
|
|
1129
|
+
% Now the constraint works correctly
|
|
1130
|
+
:- #count { R1, R2 : oneway_pair(R1, R2) } != 1.
|
|
1131
|
+
```
|
|
1132
|
+
|
|
1133
|
+
**Pattern Examples:**
|
|
1134
|
+
|
|
1135
|
+
```asp
|
|
1136
|
+
% Bidirectional connections (canonical form)
|
|
1137
|
+
bidirectional(R1, R2) :- R1 < R2, conn(R1, R2, _), conn(R2, R1, _).
|
|
1138
|
+
|
|
1139
|
+
% Counting edges in undirected graphs
|
|
1140
|
+
edge_count(N) :- N = #count { V1, V2 : V1 < V2, edge(V1, V2) }.
|
|
1141
|
+
|
|
1142
|
+
% Finding isolated pairs
|
|
1143
|
+
isolated_pair(A, B) :- A < B, entity(A), entity(B),
|
|
1144
|
+
not connected(A, B), not connected(B, A).
|
|
1145
|
+
```
|
|
1146
|
+
|
|
1147
|
+
**When to Use This Pattern:**
|
|
1148
|
+
|
|
1149
|
+
- Counting bidirectional or one-way connections
|
|
1150
|
+
- Measuring relationships in undirected graphs
|
|
1151
|
+
- Any symmetric or pair-based relationship requiring accurate counting
|
|
1152
|
+
- Whenever you need to distinguish between "relationship exists" and "count of relationships"
|
|
1153
|
+
|
|
1154
|
+
### 5.3 CRITICAL: Controlling Cardinality with Choice Rule Bounds
|
|
1155
|
+
|
|
1156
|
+
While Section 5.1 focuses on filtering the *domain* of a choice rule, it is equally critical to control the *number* of atoms chosen from that domain. An unbounded choice rule `{...}` allows the solver to select *any number* of atoms, which is often not the desired behavior and can lead to logical errors and massive search spaces.
|
|
1157
|
+
|
|
1158
|
+
> **Fundamental Rule:** Always specify bounds `L { ... } U` on your choice rules unless you explicitly intend to allow an arbitrary number of choices.
|
|
1159
|
+
|
|
1160
|
+
#### Anti-Pattern: Unbounded Choice for Relationships
|
|
1161
|
+
|
|
1162
|
+
This mistake was observed in a Metroidvania map generation task where the goal was to create at most one connection between any two rooms.
|
|
1163
|
+
|
|
1164
|
+
**The Code:**
|
|
1165
|
+
```asp
|
|
1166
|
+
% For each room pair, choose a requirement for a connection
|
|
1167
|
+
{ conn(R1, R2, Req) : requirement(Req) } :- room_pair(R1, R2).
|
|
1168
|
+
```
|
|
1169
|
+
|
|
1170
|
+
**The Problem:**
|
|
1171
|
+
This rule allows the solver to generate **multiple** connections between the same two rooms, e.g., `conn(r1,r2,"null")` and `conn(r1,r2,"RedKey")` simultaneously. This is logically incorrect for the problem and creates a combinatorial explosion in the search space, often leading to `grounding stopped` errors or timeouts.
|
|
1172
|
+
|
|
1173
|
+
#### Correct Pattern: Bounded Choice for Unique Relationships
|
|
1174
|
+
|
|
1175
|
+
By adding bounds, you enforce the intended logic directly and efficiently.
|
|
1176
|
+
|
|
1177
|
+
**The Code:**
|
|
1178
|
+
```asp
|
|
1179
|
+
% For each room pair, choose AT MOST ONE requirement for a connection
|
|
1180
|
+
0 { conn(R1, R2, Req) : requirement(Req) } 1 :- room_pair(R1, R2).
|
|
1181
|
+
```
|
|
1182
|
+
|
|
1183
|
+
**The Solution:**
|
|
1184
|
+
This rule correctly states: "For any pair of rooms (R1, R2), choose **zero or one** requirement for a connection." This enforces the intended unique relationship, drastically reduces the search space, and prevents logical errors.
|
|
1185
|
+
|
|
1186
|
+
#### General Patterns for Cardinality Control
|
|
1187
|
+
|
|
1188
|
+
| Goal | ASP Pattern | Explanation |
|
|
1189
|
+
| :------------------------------------- | :------------------------------------------------------------------ | :----------------------------------------------------- |
|
|
1190
|
+
| **Assign a unique property** | `1 { has_property(X, P) : property(P) } 1 :- entity(X).` | Each entity `X` must have **exactly one** property `P`.|
|
|
1191
|
+
| **Model an optional, unique connection** | `0 { connected(X, Y, Type) : conn_type(Type) } 1 :- pair(X, Y).` | There is **at most one** connection between `X` and `Y`.|
|
|
1192
|
+
| **Select a fixed number of items** | `k { selected(I) : item(I) } k :- ...` | **Exactly `k`** items must be selected from the domain. |
|
|
1193
|
+
| **Select a minimum number of items** | `k { selected(I) : item(I) } :- ...` | **At least `k`** items must be selected. |
|
|
1194
|
+
|
|
1195
|
+
### 5.3 Avoiding Grounding Explosion: Decompose Complex Arithmetic (Anti-Pattern: Monolithic Arithmetic)
|
|
1196
|
+
|
|
1197
|
+
Writing a single, large arithmetic constraint that involves many independent variables can cause a "grounding explosion." The grounder must instantiate the rule for every possible combination of values for those variables.
|
|
1198
|
+
|
|
1199
|
+
**The Principle: Aggregate, Don't Enumerate.** Use auxiliary predicates and aggregates (`#sum`, `#count`, etc.) to compute intermediate results. Then, write simpler constraints over those results.
|
|
1200
|
+
|
|
1201
|
+
**Anti-Pattern: Monolithic Arithmetic Constraint**
|
|
1202
|
+
This approach forces the grounder to iterate through all value combinations.
|
|
1203
|
+
|
|
1204
|
+
```asp
|
|
1205
|
+
% DOMAIN: Assign a value from 1..10 to four variables a,b,c,d.
|
|
1206
|
+
var(a;b;c;d). value(1..10).
|
|
1207
|
+
1 { assign(V, N) : value(N) } 1 :- var(V).
|
|
1208
|
+
|
|
1209
|
+
% ANTI-PATTERN: Compare sums directly.
|
|
1210
|
+
% This requires grounding for every combination of N1,N2,N3,N4 from 1..10.
|
|
1211
|
+
% That's 10 * 10 * 10 * 10 = 10,000 ground rules.
|
|
1212
|
+
:- assign(a, N1), assign(b, N2), assign(c, N3), assign(d, N4),
|
|
1213
|
+
N1 + N2 != N3 + N4.
|
|
1214
|
+
```
|
|
1215
|
+
**Why it's slow:** The grounder creates a massive number of rules that are computationally expensive to process, even if the logic is simple.
|
|
1216
|
+
|
|
1217
|
+
**Good Pattern: Decompose with Aggregates**
|
|
1218
|
+
This approach computes the sums first, then compares the two results.
|
|
1219
|
+
|
|
1220
|
+
```asp
|
|
1221
|
+
% DOMAIN: Same as above.
|
|
1222
|
+
var(a;b;c;d). value(1..10).
|
|
1223
|
+
1 { assign(V, N) : value(N) } 1 :- var(V).
|
|
1224
|
+
|
|
1225
|
+
% GOOD PATTERN: Use #sum to calculate intermediate values.
|
|
1226
|
+
sum_ab(S) :- S = #sum { N,V : assign(V,N), (V=a; V=b) }.
|
|
1227
|
+
sum_cd(S) :- S = #sum { N,V : assign(V,N), (V=c; V=d) }.
|
|
1228
|
+
|
|
1229
|
+
% Now, constrain the two resulting sums. This generates very few ground rules.
|
|
1230
|
+
:- sum_ab(S1), sum_cd(S2), S1 != S2.
|
|
1231
|
+
```
|
|
1232
|
+
**Why it's fast:** The `#sum` aggregate is highly optimized. The solver computes each sum just once. The final constraint only compares the two resulting sum values, avoiding the combinatorial explosion.
|
|
1233
|
+
|
|
1234
|
+
**General Takeaway:** Instead of writing complex arithmetic expressions with many variables in a single rule body, use aggregates to compute sub-expressions and constrain their results.
|
|
1235
|
+
|
|
1236
|
+
### Recursive Aggregates (#sum over a derived relation)
|
|
1237
|
+
|
|
1238
|
+
When a threshold depends on a relation you are still deriving, aggregate over
|
|
1239
|
+
that relation with a helper predicate to keep the rule stratified and readable
|
|
1240
|
+
(classic example: transitive company control via ownership percentages):
|
|
1241
|
+
|
|
1242
|
+
```asp
|
|
1243
|
+
controls(X,X) :- company(X).
|
|
1244
|
+
contrib(A,B,A,P) :- owns(A,B,P).
|
|
1245
|
+
contrib(A,B,C,P) :- controls(A,C), owns(C,B,P), A != C.
|
|
1246
|
+
sum(A,B,S) :- company(A), company(B), S = #sum { P,C : contrib(A,B,C,P) }.
|
|
1247
|
+
controls(A,B) :- sum(A,B,S), S > 50, A != B.
|
|
1248
|
+
```
|
|
1249
|
+
|
|
1250
|
+
Use a helper (`contrib/4`) so the aggregate ranges over ground tuples; do not
|
|
1251
|
+
inline a `#sum` that recurses on the predicate it defines.
|
|
1252
|
+
|
|
1253
|
+
### Debugging Temporal Models (CRITICAL)
|
|
1254
|
+
|
|
1255
|
+
1. **Test state exclusivity first**
|
|
1256
|
+
```asp
|
|
1257
|
+
% Add test constraints to verify exclusivity
|
|
1258
|
+
:- item_at(test_item,_,_,5), carrying(_,test_item,5).
|
|
1259
|
+
```
|
|
1260
|
+
|
|
1261
|
+
2. **Isolate action logic**
|
|
1262
|
+
```asp
|
|
1263
|
+
% Test if goals are achievable without actions
|
|
1264
|
+
item_at(I,X,Y,max_time) :- item_destination(I,X,Y).
|
|
1265
|
+
```
|
|
1266
|
+
|
|
1267
|
+
3. **Trace single actions**
|
|
1268
|
+
```asp
|
|
1269
|
+
% Force specific action to test effects
|
|
1270
|
+
move(r1,up,0).
|
|
1271
|
+
```
|
|
1272
|
+
|
|
1273
|
+
4. **Use clingo's debugging features**
|
|
1274
|
+
```python
|
|
1275
|
+
# Show grounded rules
|
|
1276
|
+
ctl.ground([("base", [])])
|
|
1277
|
+
for atom in ctl.symbolic_atoms:
|
|
1278
|
+
if "item_at" in str(atom):
|
|
1279
|
+
print(atom)
|
|
1280
|
+
```
|
|
1281
|
+
|
|
1282
|
+
### Common Errors and Solutions
|
|
1283
|
+
|
|
1284
|
+
1. **"Unsafe variable" errors**:
|
|
1285
|
+
- Add positive predicate defining variable's domain
|
|
1286
|
+
|
|
1287
|
+
2. **"Syntax error, unexpected #sum"**:
|
|
1288
|
+
- Move aggregate to body or optimization
|
|
1289
|
+
|
|
1290
|
+
3. **No answer sets (UNSAT)**:
|
|
1291
|
+
- Check mutual exclusivity constraints
|
|
1292
|
+
- Verify action preconditions aren't too restrictive
|
|
1293
|
+
- Test minimal cases
|
|
1294
|
+
|
|
1295
|
+
4. **Invalid plans/solutions**:
|
|
1296
|
+
- Check state exclusivity enforcement
|
|
1297
|
+
- Verify frame axioms and action effects
|
|
1298
|
+
|
|
1299
|
+
### Best Practices
|
|
1300
|
+
|
|
1301
|
+
1. **Start with state model**: Define fluents and exclusivity first
|
|
1302
|
+
2. **Test incrementally**: Add one action type at a time
|
|
1303
|
+
3. **Use meaningful names**: `robot_at(r1,3,4,5)` not `p(1,3,4,5)`
|
|
1304
|
+
4. **Document assumptions**: Comment complex constraints
|
|
1305
|
+
5. **Verify exclusivity**: Always enforce mutual exclusion for fluents
|