[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -1,90 +1,310 @@
---
id: wiki-2026-0508-constraint-satisfaction-problems
id: wiki-2026-0508-csp
title: Constraint Satisfaction Problems (CSP)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-CSP]
aliases: [CSP, 제약 충족 문제, AC-3, backtracking, MIP, OR-Tools, scheduling]
duplicate_of: none
source_trust_level: A
confidence_score: 0.93
tags: [Algorithm, AI, Optimization, CSP]
verification_status: applied
tags: [csp, constraint-programming, optimization, scheduling, sat, smt, ortools, backtracking]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: Python / C++
framework: OR-Tools / Z3 / MiniZinc / Choco
---
# [[Constraint Satisfaction Problems (CSP)|Constraint Satisfaction Problems (CSP)]] (제약 충족 문제)
# Constraint Satisfaction Problems (CSP)
## 📌 한 줄 통찰 (The Karpathy Summary)
> "규칙을 깨지 않고 빈칸을 채우는 지적인 퍼즐 풀이." 변수, 도메인, 제약 조건 세 가지 요소로 정의되며, 모든 제약을 동시에 만족하는 해를 찾는 탐색 기반의 고전적 AI 핵심 분야다.
## 한 줄
> **"매 rule 의 break X + 매 fill"**. 매 (Variables, Domains, Constraints) 의 triple. 매 backtracking + 매 propagation. 매 modern: OR-Tools, Z3 SMT, MiniZinc. 매 scheduling, 매 routing, 매 puzzle 의 NP-hard 의 practical 접근.
## 📖 구조화된 지식 (Synthesized Content)
- **Three Components**:
- **Variables ($X$)**: 값을 할당받아야 하는 대상 (예: 스케줄링의 시간표 칸).
- **Domains ($D$)**: 각 변수가 가질 수 있는 가능한 값들의 집합.
- **Constraints ($C$)**: 변수들 사이의 규칙 (예: 같은 시간에는 한 강의실만 사용 가능).
- **Core Algorithms**:
- **Backtracking [[Search|Search]]**: 값을 하나씩 할당해보고 규칙에 어긋나면 돌아가는 방식.
- **Constraint Propagation (AC-3)**: 값을 할당하기 전에 불가능한 값들을 미리 제거하여 탐색 공간을 줄임.
- **Applications**: 스케줄링(공장 공정, 학교 시간표), 지도 색칠하기, 수도쿠(Sudoku), 논리 회로 설계 등.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- CSP는 NP-완전(NP-Complete) 문제인 경우가 많아 변수가 많아지면 기하급수적으로 어려워진다. 최신 AI 시스템에서는 고전적인 CSP 알고리즘에 강화학습을 결합하여, 다음에 시도할 변수를 선택하는 전략([[Heuristics|Heuristics]])을 최적화하는 시도가 이루어지고 있다.
### 매 components
- **Variables** (X): 매 assignable.
- **Domains** (D): 매 possible values.
- **Constraints** (C): 매 relations.
## 🔗 지식 연결 (Graph)
- Related: [[Graph-Theory|Graph-Theory]] , [[Combinatorial-Optimization|Combinatorial-Optimization]]
- Comparison: [[Operations-Research|Operations-Research]]
### 매 type
- **Boolean**: SAT.
- **Integer / discrete**: pure CSP.
- **Continuous**: linear / convex / nonlinear programming.
- **Mixed Integer**: MIP.
- **SMT**: 매 first-order theory.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 algorithm
**언제 이 지식을 쓰는가:**
- *(TODO)*
#### Backtracking
- 매 DFS + 매 backtrack on constraint violation.
- 매 baseline.
**언제 쓰면 안 되는가:**
- *(TODO)*
#### Constraint Propagation
- **AC-3** (Arc Consistency): 매 inconsistent value 의 prune.
- **Forward Checking**: 매 variable assignment 시 의 future variable 의 prune.
## 🧪 검증 상태 (Validation)
#### Heuristic
- **MRV** (Minimum Remaining Values): 매 가장 constrained variable first.
- **Degree heuristic**: 매 매 connected variable.
- **LCV** (Least Constraining Value): 매 future flexibility maximize.
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
#### Local search
- **Min-conflicts**: 매 random init + 매 conflict reduce.
- **Simulated annealing**.
- **Tabu search**.
## 🧬 중복 검사 (Duplicate Check)
### 매 SAT (special case)
- 매 boolean only.
- 매 CNF form.
- 매 modern solver: Glucose, MiniSat, Kissat.
- 매 reduction: 매 다른 NP-complete 의 SAT.
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### SMT (extended)
- 매 first-order theory + decision procedure.
- 매 theory: arithmetic, arrays, bitvectors, strings.
- 매 Z3, CVC5, Yices.
## 🕓 변경 이력 (Changelog)
### 매 MIP (Mixed Integer Programming)
- 매 LP relaxation + branch & bound.
- 매 Gurobi, CPLEX, OR-Tools.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### CP-SAT (modern)
- 매 OR-Tools 의 hybrid.
- 매 CP + SAT.
- 매 매 fastest 의 industrial scheduling.
## 💻 코드 패턴 (Code Patterns)
### 매 응용
1. **Scheduling**: 매 work, 매 sport, 매 exam.
2. **Routing** (VRP).
3. **Resource allocation**.
4. **Configuration** (car options).
5. **Puzzle** (Sudoku, N-Queens, Zebra).
6. **Verification** (SMT).
7. **Compiler** (register allocation).
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
## 💻 패턴
```text
# TODO
### N-Queens (backtracking)
```python
def solve_n_queens(n):
queens = [-1] * n
def backtrack(row):
if row == n: return [queens[:]]
solutions = []
for col in range(n):
if all(queens[r] != col and abs(queens[r] - col) != row - r
for r in range(row)):
queens[row] = col
solutions.extend(backtrack(row + 1))
return solutions
return backtrack(0)
print(len(solve_n_queens(8))) # 92
```
## 🤔 의사결정 기준 (Decision Criteria)
### AC-3 (constraint propagation)
```python
def ac3(domains, constraints):
"""매 arc consistency."""
queue = [(x, y) for (x, y) in constraints]
while queue:
(x, y) = queue.pop(0)
if revise(domains, x, y, constraints):
if not domains[x]: return False
for z in neighbors(x):
if z != y: queue.append((z, x))
return True
**선택 A를 써야 할 때:**
- *(TODO)*
def revise(domains, x, y, constraints):
revised = False
for vx in list(domains[x]):
if not any(constraint_holds(x, vx, y, vy, constraints) for vy in domains[y]):
domains[x].remove(vx)
revised = True
return revised
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Sudoku (OR-Tools CP-SAT)
```python
from ortools.sat.python import cp_model
**기본값:**
> *(TODO)*
def solve_sudoku(grid):
model = cp_model.CpModel()
# 매 9×9 variable
cells = [[model.NewIntVar(1, 9, f'c{r}{c}') for c in range(9)] for r in range(9)]
# 매 given clues
for r in range(9):
for c in range(9):
if grid[r][c] != 0:
model.Add(cells[r][c] == grid[r][c])
# 매 row / col / box uniqueness
for r in range(9):
model.AddAllDifferent(cells[r])
for c in range(9):
model.AddAllDifferent([cells[r][c] for r in range(9)])
for br in range(3):
for bc in range(3):
model.AddAllDifferent([cells[3*br + i][3*bc + j] for i in range(3) for j in range(3)])
solver = cp_model.CpSolver()
if solver.Solve(model) == cp_model.OPTIMAL:
return [[solver.Value(cells[r][c]) for c in range(9)] for r in range(9)]
return None
```
## ❌ 안티패턴 (Anti-Patterns)
### Job Shop Scheduling (OR-Tools)
```python
from ortools.sat.python import cp_model
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
def schedule_jobs(jobs):
model = cp_model.CpModel()
horizon = sum(t for job in jobs for _, t in job)
all_tasks = {}
machine_to_intervals = collections.defaultdict(list)
for j_id, job in enumerate(jobs):
for t_id, (machine, duration) in enumerate(job):
start = model.NewIntVar(0, horizon, f'start_{j_id}_{t_id}')
end = model.NewIntVar(0, horizon, f'end_{j_id}_{t_id}')
interval = model.NewIntervalVar(start, duration, end, f'interval_{j_id}_{t_id}')
all_tasks[(j_id, t_id)] = (start, end, interval)
machine_to_intervals[machine].append(interval)
# 매 매 machine 의 1 task 만 의 동시.
for intervals in machine_to_intervals.values():
model.AddNoOverlap(intervals)
# 매 매 job 의 sequence (precedence).
for j_id, job in enumerate(jobs):
for t_id in range(len(job) - 1):
model.Add(all_tasks[(j_id, t_id+1)][0] >= all_tasks[(j_id, t_id)][1])
# 매 minimize makespan
makespan = model.NewIntVar(0, horizon, 'makespan')
model.AddMaxEquality(makespan, [all_tasks[(j_id, len(job)-1)][1] for j_id, job in enumerate(jobs)])
model.Minimize(makespan)
solver = cp_model.CpSolver()
solver.Solve(model)
return solver.ObjectiveValue()
```
### Z3 SMT
```python
from z3 import *
# 매 example: 매 8-puzzle solvability check
s = Solver()
x = [Int(f'x_{i}') for i in range(9)]
s.add([0 <= xi for xi in x])
s.add([xi <= 8 for xi in x])
s.add(Distinct(x))
s.add(x[0] == 1)
s.add(x[1] == 2)
# ...
if s.check() == sat:
print(s.model())
```
### Vehicle Routing (VRP)
```python
from ortools.constraint_solver import routing_enums_pb2, pywrapcp
manager = pywrapcp.RoutingIndexManager(num_nodes, num_vehicles, depot)
routing = pywrapcp.RoutingModel(manager)
def distance_callback(from_index, to_index):
return distance_matrix[manager.IndexToNode(from_index)][manager.IndexToNode(to_index)]
transit_idx = routing.RegisterTransitCallback(distance_callback)
routing.SetArcCostEvaluatorOfAllVehicles(transit_idx)
params = pywrapcp.DefaultRoutingSearchParameters()
params.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
solution = routing.SolveWithParameters(params)
```
### MiniZinc (declarative)
```minizinc
% n-queens.mzn
int: n = 8;
array[1..n] of var 1..n: q;
constraint forall(i, j in 1..n where i < j) (
q[i] != q[j] /\
q[i] - q[j] != i - j /\
q[i] - q[j] != j - i
);
solve satisfy;
```
### ML-aided heuristic (RL for branching)
```python
# 매 modern: RL 의 branching variable selection
class LearnedHeuristic:
def __init__(self, model):
self.model = model
def select_variable(self, state):
"""매 state 의 features → 매 best variable to branch."""
features = encode_state(state)
return self.model.predict(features)
```
## 🤔 결정 기준
| 문제 | Tool |
|---|---|
| Boolean SAT | Glucose, Kissat |
| SMT (math) | Z3, CVC5 |
| Discrete CSP | OR-Tools CP-SAT |
| MIP (large) | Gurobi, CPLEX |
| Scheduling | OR-Tools CP-SAT |
| Routing | OR-Tools |
| Continuous | scipy.optimize |
| Declarative | MiniZinc |
**기본값**: OR-Tools CP-SAT 의 baseline (free + fast).
## 🔗 Graph
- 부모: [[Combinatorial-Optimization]] · [[AI-Search]] · [[Graph-Theory]]
- 변형: [[SAT]] · [[SMT]] · [[MIP]] · [[CP]]
- 응용: [[Scheduling]] · [[Routing]] · [[Verification]]
- Tool: [[OR-Tools]] · [[Z3]] · [[Gurobi]] · [[MiniZinc]]
- Adjacent: [[Black-Box-Optimization]] · [[Automated-Theorem-Proving]] · [[Bayesian-Statistics]]
## 🤖 LLM 활용
**언제**: 매 scheduling, 매 routing, 매 configuration. 매 verification. 매 puzzle.
**언제 X**: 매 differentiable problem (gradient descent). 매 black-box (BO).
## ❌ 안티패턴
- **No propagation**: 매 backtracking 만.
- **MRV / LCV 무시**: 매 inefficient.
- **Wrong solver for problem class**: 매 SAT for continuous.
- **No problem decomposition**: 매 huge instance 의 fail.
- **Constraint 의 redundant 의 add**: 매 solver 의 hint.
- **Single solution mode**: 매 enumerate 의 expensive.
## 🧪 검증 / 중복
- Verified (Russell-Norvig AI book, OR-Tools docs, Handbook of CP).
- 신뢰도 A.
- Related: [[Black-Box-Optimization]] · [[Automated-Theorem-Proving]] · [[Bayesian-Statistics]] · [[Causal-Inference]].
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — type + algorithm + 매 N-Queens / AC-3 / Sudoku / JSP / VRP code |