[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
@@ -2,87 +2,191 @@
id: wiki-2026-0508-abstract-syntax-tree-transformat
title: Abstract Syntax Tree Transformation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AST-TRANS]
aliases: [AST Transform, AST Rewrite, Code Transformation]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [AST, Abstract Syntax Tree, Transformation, Compiler, Babel]
confidence_score: 0.92
verification_status: applied
tags: [compiler, ast, codemod, transformation, static-analysis]
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: TypeScript/Python
framework: Babel/ts-morph/LibCST
---
# [[Abstract-Syntax-Tree-Transformation|Abstract-Syntax-Tree-Transformation]] (AST 변환)
# Abstract Syntax Tree Transformation
## 📌 한 줄 통찰 (The Karpathy Summary)
> "코드를 조각하듯 변형하라." 소스 코드를 트리 구조로 분해한 뒤, 특정 노드를 추가, 삭제, 수정하여 완전히 새로운 기능이 담긴 코드로 재생산하는 현대 개발 도구의 핵심 마술이다.
## 한 줄
> **"매 source-as-data — 매 string 의 X, 매 tree 의 mutation."**. AST transformation 의 source code 의 parse tree 의 structured manipulation — 매 1970s compiler theory 의 root, 매 2026 의 codemod / linter / formatter / LLM-assisted refactor backbone (Babel, ts-morph, LibCST, tree-sitter).
## 📖 구조화된 지식 (Synthesized Content)
- **Code Transpilation**:
- 최신 자바스크립트(ES6+)를 구형 브라우저에서도 돌아가게 하는 `Babel` 같은 도구가 AST 변환의 가장 대표적인 사례다.
- **Custom Babel Plugins**:
- 특정 함수 호출을 컴파일 시점에 최적화하거나, 로깅 코드를 자동으로 삽입하는 등의 작업을 AST 노드 조작을 통해 수행한다.
- **Codemods**:
- 대규모 코드베이스의 라이브러리 버전을 업그레이드할 때, API 변경 사항을 수천 개의 파일에 자동으로 반영하는 자동화된 코드 수정 기술.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 무분별한 AST 변환은 디버깅을 지옥으로 만든다. 실행되는 코드와 원본 소스 코드가 결합력을 잃기 때문이다. 따라서 `Source Map` 생성을 철저히 관리하여 변환 후에도 원본 위치를 추적할 수 있게 해야 한다.
### 매 Pipeline
- **Parse**: source string → token stream → AST (lexer + parser).
- **Visit/Traverse**: 매 node 의 type-based dispatch (visitor pattern).
- **Transform**: node insert / replace / remove / wrap.
- **Print**: AST → source string (preserving comments / formatting via concrete syntax tree or sourcemap).
## 🔗 지식 연결 (Graph)
- Related: [[Abstract-Syntax-Tree-Traversal|Abstract-Syntax-Tree-Traversal]] , Custom-ESLint-Rules-Development
- Foundation: Computational Theory & Math/Information Theory
### 매 Tools (2026)
- **Babel** (JS/TS): `@babel/parser` + `@babel/traverse` + `@babel/generator`. 매 ecosystem standard.
- **ts-morph** (TS): high-level wrapper over TypeScript compiler API. 매 type-aware transform.
- **LibCST** (Python): concrete syntax tree, formatting-preserving. Instagram-grade codemod.
- **tree-sitter**: incremental parser, multi-language. 매 editor / LSP foundation.
- **jscodeshift**: Facebook codemod runner over Babel.
- **swc / oxc**: Rust-based, 10-50x faster than Babel.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **Codemod**: API migration (e.g., React class → hooks).
2. **Linter / formatter**: ESLint, Prettier, Ruff.
3. **LLM context compression**: AST-based code summarization.
4. **Security scanner**: Semgrep AST pattern matching.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Pattern 1 — Babel: Replace function call name
## 🧪 검증 상태 (Validation)
```typescript
import * as parser from "@babel/parser";
import traverse from "@babel/traverse";
import generate from "@babel/generator";
import * as t from "@babel/types";
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
const code = `console.log("hi"); console.error("err");`;
const ast = parser.parse(code, { sourceType: "module" });
## 🧬 중복 검사 (Duplicate Check)
traverse(ast, {
CallExpression(path) {
const callee = path.node.callee;
if (t.isMemberExpression(callee) && t.isIdentifier(callee.object, { name: "console" })) {
callee.object = t.identifier("logger");
}
},
});
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
console.log(generate(ast).code);
// → logger.log("hi"); logger.error("err");
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pattern 2 — ts-morph: Add type annotation
**선택 A를 써야 할 때:**
- *(TODO)*
```typescript
import { Project } from "ts-morph";
**선택 B를 써야 할 때:**
- *(TODO)*
const project = new Project();
const sf = project.addSourceFileAtPath("src/foo.ts");
**기본값:**
> *(TODO)*
sf.getFunctions().forEach((fn) => {
fn.getParameters().forEach((p) => {
if (!p.getTypeNode()) p.setType("unknown");
});
});
## ❌ 안티패턴 (Anti-Patterns)
await sf.save();
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Pattern 3 — LibCST: Python codemod (preserves formatting)
```python
import libcst as cst
class RenameImport(cst.CSTTransformer):
def leave_ImportFrom(self, orig, updated):
if updated.module and updated.module.value == "old_pkg":
return updated.with_changes(module=cst.Attribute(
value=cst.Name("new_pkg"), attr=cst.Name("submod")
))
return updated
tree = cst.parse_module(open("foo.py").read())
new_tree = tree.visit(RenameImport())
open("foo.py", "w").write(new_tree.code)
```
### Pattern 4 — tree-sitter query (Semgrep-like)
```scheme
; Find all `console.log(...)` calls
(call_expression
function: (member_expression
object: (identifier) @obj
property: (property_identifier) @prop)
(#eq? @obj "console")
(#eq? @prop "log")) @match
```
### Pattern 5 — jscodeshift script
```javascript
module.exports = function (file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.VariableDeclaration, { kind: "var" })
.forEach((p) => { p.value.kind = "const"; })
.toSource();
};
```
### Pattern 6 — Type-aware refactor with TS compiler API
```typescript
import ts from "typescript";
function transformer<T extends ts.Node>(ctx: ts.TransformationContext) {
return (root: T) => {
function visit(node: ts.Node): ts.Node {
if (ts.isCallExpression(node) && node.expression.getText() === "deprecated") {
return ts.factory.createCallExpression(
ts.factory.createIdentifier("modern"),
undefined, node.arguments
);
}
return ts.visitEachChild(node, visit, ctx);
}
return ts.visitNode(root, visit) as T;
};
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| JS/TS quick codemod | jscodeshift + Babel |
| Type-aware TS refactor | ts-morph |
| Python large-scale | LibCST |
| Multi-language editor / search | tree-sitter |
| Performance-critical CI | swc / oxc |
| Security pattern detection | Semgrep |
| LLM-driven refactor | tree-sitter + LLM tool-use |
**기본값**: Babel for JS/TS, LibCST for Python, tree-sitter for cross-language.
## 🔗 Graph
- 부모: [[Compiler-Theory]] · [[Static-Analysis]]
- 변형: [[Concrete-Syntax-Tree]] · [[Tree-Sitter]]
- 응용: [[Codemod]] · [[Linter]] · [[LLM-Code-Refactor]]
- Adjacent: [[Type-Inference]] · [[Symbol-Resolution]]
## 🤖 LLM 활용
**언제**: large-scale code migration, repo-wide rename, API deprecation cleanup, structured code understanding for LLM context.
**언제 X**: one-off edits (use sed/IDE), formatting-only changes (use Prettier/Ruff direct), single-file simple regex.
## ❌ 안티패턴
- **Regex-as-AST**: complex code transform 의 regex 의 fragile — comment / string literal 의 false match.
- **Format loss**: 매 round-trip 의 comment / whitespace 의 drop — concrete syntax tree (LibCST) 또는 sourcemap 사용.
- **Type-blind refactor**: TS 의 type info 의 ignore — runtime error.
- **No idempotency**: codemod 의 re-run 의 duplicate transform — guard idempotent.
## 🧪 검증 / 중복
- Verified (Babel docs, ts-morph docs, LibCST Instagram engineering blog).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (Babel/ts-morph/LibCST/tree-sitter, 6 patterns, decision table) |
@@ -2,93 +2,146 @@
id: wiki-2026-0508-adaptive-curation
title: Adaptive Curation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ADCU-001]
aliases: [Dynamic Curation, Personalized Curation, Active Curation]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-reinforced, curation, adaptation, information-filter, adaptive-content, customization]
confidence_score: 0.88
verification_status: applied
tags: [recsys, curation, personalization, active-learning, feedback]
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
framework: PyTorch/scikit-learn
---
# [[Adaptive-Curation|Adaptive-Curation]]
# Adaptive Curation
## 📌 한 줄 통찰 (The Karpathy Summary)
> "당신만을 위한 세상의 가공: 쏟아지는 정보와 상품 중에서 사용자의 시시각각 변하는 맥락, 취향, 피드백을 실시간으로 반영하여 가장 가치 있는 것들만 정제해 보여주는 지능형 큐레이션."
## 한 줄
> **"매 selection 의 close-loop — 매 user feedback 의 corpus 의 reshape."**. Adaptive curation 의 static collection 의 X, 매 user signal (click, dwell, rating, embedding drift) 의 use → 매 corpus / ranking / recommendation 의 dynamic adjust. 매 2026 의 LLM-augmented (semantic embedding + bandits + RLHF) 의 standard.
## 📖 구조화된 지식 (Synthesized Content)
적응형 큐레이션(Adaptive-Curation)은 사용자의 행동 데이터와 외부 환경의 변화를 학습하여, 최적의 콘텐츠나 정보를 선별(Curate)해 제공하는 기술 및 전략입니다.
## 매 핵심
1. **동작 핵심**:
* **Dynamic Feedback Loop**: 사용자가 클릭하거나 무시하는 신호를 즉각적으로 반영하여 추천 알고리즘 수정.
* **Context-Awareness**: 시간, 장소, 현재 감정 상태 등 외부 맥락을 파악하여 큐레이션 기준 변경.
* **Multi-objective Balancing**: 사용자의 만족도(Engagement) 뿐만 아니라 다양성(Diversity), 정보의 신뢰성(Trust) 등 상충하는 목표를 동시에 최적화.
2. **기존 시스템과의 차이**:
* **Static Curation**: 사람이 수동으로 선정한 리스트 (일관성은 높으나 개인화 부족).
* **Simple Algorithm**: 과거 취향에만 고착된 추천 (에코 챔버 발생 위험).
* **Adaptive Curation**: 변화하는 취향을 선제적으로 감지하고 발견(Discovery)의 기쁨을 제공.
### 매 Components
- **Catalog / corpus**: candidate items.
- **User signal**: explicit (rating, like) + implicit (click, dwell, scroll depth).
- **Ranker / selector**: scoring function (often embedding sim + bandit + LTR).
- **Update loop**: feedback → model update → next selection.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거 미디어 정책은 편집자의 권위를 통한 '일방통행적 정보 배포' 정책이었으나, 현대의 플랫폼 정책은 개별 사용자에게 최적화된 '분산형 적응 큐레이션 정책'으로 독점을 정당화함(RL Update).
- **정책 변화(RL Update)**: 적응형 큐레이션이 '필터 버블'을 강화하고 확증 편향을 심화시킨다는 비판 정책이 제기됨에 따라, 의도적으로 사용자에게 상반된 의견을 노출시키는 '균형 잡힌 적응 큐레이션 정책' 도입이 공공 알고리즘의 의무 요건이 됨.
### 매 Algorithms
- **Collaborative filtering**: matrix factorization (SVD, ALS).
- **Content-based**: TF-IDF / semantic embedding (sentence-transformers, OpenAI ada-3, Cohere v4).
- **Hybrid**: 매 collaborative + content.
- **Bandits**: ε-greedy, UCB, Thompson sampling — 매 explore/exploit.
- **Contextual bandit / LinUCB**: user feature 의 use.
- **RLHF / DPO**: 매 LLM-era curation (Claude, GPT-5).
## 🔗 지식 연결 (Graph)
- Personalization, Exploitation vs Exploration, [[Reward Prediction Error|Reward Prediction Error]], Information Ethics, [[Superficiality-Metrics|Superficiality-Metrics]]
- **Modern Tech/Tools**: TikTok recommendation engine, Spotify Daily Mix, Amazon's adaptive storefront.
---
### 매 응용
1. News feed (TikTok, X).
2. E-commerce product ranking (Amazon, Coupang).
3. Knowledge base curation (Notion AI, Glean).
4. RAG corpus filtering — 매 LLM context 의 dynamic selection.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Pattern 1 — Embedding-based candidate retrieval
**언제 쓰면 안 되는가:**
- *(TODO)*
```python
import numpy as np
from sentence_transformers import SentenceTransformer
## 🧪 검증 상태 (Validation)
model = SentenceTransformer("all-MiniLM-L12-v2")
docs = ["AI safety", "RAG patterns", "vector DB"]
doc_emb = model.encode(docs, normalize_embeddings=True)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def retrieve(query: str, k=5):
q = model.encode(query, normalize_embeddings=True)
scores = doc_emb @ q
return np.argsort(-scores)[:k]
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pattern 2 — Thompson Sampling bandit
**선택 A를 써야 할 때:**
- *(TODO)*
```python
import numpy as np
**선택 B를 써야 할 때:**
- *(TODO)*
class ThompsonSampler:
def __init__(self, n_arms):
self.alpha = np.ones(n_arms)
self.beta = np.ones(n_arms)
def select(self):
samples = np.random.beta(self.alpha, self.beta)
return int(np.argmax(samples))
def update(self, arm, reward):
if reward > 0: self.alpha[arm] += 1
else: self.beta[arm] += 1
```
**기본값:**
> *(TODO)*
### Pattern 3 — Click-through online update
## ❌ 안티패턴 (Anti-Patterns)
```python
def on_click(user_id, item_id, dwell_s):
reward = 1 if dwell_s > 5 else 0
bandit.update(item_id, reward)
feature_store.log(user_id, item_id, dwell_s)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Pattern 4 — Contextual ranker (LightGBM LTR)
```python
import lightgbm as lgb
ranker = lgb.LGBMRanker(objective="lambdarank", n_estimators=300)
ranker.fit(X_train, y_train, group=group_train)
scores = ranker.predict(X_val)
```
### Pattern 5 — RAG with adaptive filter
```python
def adaptive_rag(query, user_profile):
candidates = vector_db.search(query, k=50)
reranked = cross_encoder.rerank(query, candidates)
filtered = [c for c in reranked if user_profile.relevance(c) > 0.6]
return filtered[:5]
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Cold start, no user data | Content-based + popularity prior |
| Rich interaction logs | Hybrid + LTR |
| Real-time exploration | Thompson / LinUCB |
| LLM context curation | Embedding + cross-encoder rerank |
| Long-tail discovery | UCB exploration boost |
**기본값**: embedding retrieval + cross-encoder rerank + Thompson exploration.
## 🔗 Graph
- 부모: [[Recommender-Systems]] · [[Active-Learning]]
- 변형: [[Collaborative-Filtering]] · [[Multi-Armed-Bandit]]
- 응용: [[RAG]] · [[News-Feed-Ranking]] · [[Search-Reranking]]
- Adjacent: [[Relevance-Feedback]] · [[Ranking-Algorithms]]
## 🤖 LLM 활용
**언제**: dynamic corpus, user feedback available, explore/exploit tradeoff matters, RAG context selection.
**언제 X**: static catalog (use plain ranking), no feedback (cold start dominates), regulated content (use rule-based).
## ❌ 안티패턴
- **Filter bubble**: pure exploit 의 user 의 narrow exposure.
- **Feedback contamination**: bot click 의 model 의 poison.
- **No exploration decay**: ε constant — 매 mature system 의 ε ↓.
- **Position bias ignore**: top item 의 click 의 inflate — debiasing essential.
## 🧪 검증 / 중복
- Verified (Netflix tech blog, TikTok recsys papers, RecSys 2024 proceedings).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (bandits, LTR, RAG patterns) |
@@ -2,87 +2,163 @@
id: wiki-2026-0508-additive-type-logic
title: Additive Type Logic
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-ADDITIVE-TYPE]
aliases: [Sum Types, Tagged Union, Discriminated Union, Algebraic Data Types]
duplicate_of: none
source_trust_level: A
confidence_score: 0.97
tags: ["Type Theory|[Type Theory", Additive Type Logic, TypeScript, Category Theory]
confidence_score: 0.93
verification_status: applied
tags: [type-theory, adt, sum-type, pattern-matching, functional]
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: Rust/TypeScript/Haskell
framework: ADT
---
# [[Additive-Type-Logic|Additive-Type-Logic]] (가법 타입 논리)
# Additive Type Logic
## 📌 한 줄 통찰 (The Karpathy Summary)
> "타입은 집합이다." 서로 다른 타입 지식을 더하여 더 크고 정교한 타입을 형성하고, 이를 통해 런타임 오류 가능성을 원천 봉쇄하는 조합론적 타입 설계 철학이다.
## 한 줄
> **"매 OR 의 type-level — 매 either A or B, 매 never both."**. Additive type (sum / coproduct) 의 algebra 의 `+` operator — Either, Option, Result 의 backbone. 매 type theory (Curry-Howard) 의 OR proposition 의 mirror, 매 2026 의 Rust/TS/Haskell/Swift idiom.
## 📖 구조화된 지식 (Synthesized Content)
- **[[Union Types|Union Types]] (|)**:
- "A이거나 B일 수 있는" 집합의 합집합 개념. 다형성(Polymorphism)을 안전하게 구현하는 기초다.
- **Intersection Types (&)**:
- "A이면서 동시에 B여야 하는" 집합의 교집합 개념. 여러 기능을 가진 믹스인(Mixin) 객체를 정의할 때 강력하다.
- **Nominal vs Structural Addition**:
- 단순히 이름만 더하는 것이 아니라, 구조적 특징을 결합하여 컴파일 타임에 타입의 정합성을 수식처럼 계산한다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 과도한 타입 덧셈(Intersection)은 타입 추론 속도를 늦추고 에러 메시지를 난해하게 만든다. 특히 무한 재귀적인 타입 결합은 컴파일러가 포기하게 만들 수 있으므로, `Interface Extension`을 통해 적절히 계층화하는 설계가 권장된다.
### 매 Theory
- **Sum type** `A + B`: value 의 either A 또는 B (with tag).
- **Product type** `A × B`: value 의 both A and B (tuple/struct).
- **Curry-Howard**: sum ↔ logical OR (), product ↔ AND (∧).
- **Initial object**: `Void` (empty sum) — never inhabited.
- **Unit**: `()` (empty product) — single inhabitant.
- **Distributivity**: `A × (B + C) = A × B + A × C`.
## 🔗 지식 연결 (Graph)
- Related: TypeScript-Advanced-Type-System-Design , Category_Theory
- Foundation: Computational Theory & Math/Information Theory
### 매 Implementations
- **Haskell/Elm**: `data Maybe a = Nothing | Just a`.
- **Rust**: `enum Result<T, E> { Ok(T), Err(E) }`.
- **TS**: discriminated union `{ tag: 'ok'; v: T } | { tag: 'err'; e: E }`.
- **Swift**: `enum` with associated values.
- **Kotlin**: `sealed class`.
- **Scala 3**: `enum` (formerly sealed trait).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Error handling without exceptions (Result).
2. State machine encoding.
3. JSON variant (tagged union).
4. Parser combinator output.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Pattern 1 — Rust Result / Option
## 🧪 검증 상태 (Validation)
```rust
fn parse_age(s: &str) -> Result<u32, String> {
s.parse::<u32>().map_err(|e| format!("parse: {e}"))
}
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
match parse_age("42") {
Ok(n) if n < 150 => println!("ok {n}"),
Ok(n) => println!("suspicious {n}"),
Err(e) => eprintln!("{e}"),
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pattern 2 — TypeScript discriminated union
**선택 A를 써야 할 때:**
- *(TODO)*
```typescript
type Shape =
| { kind: "circle"; r: number }
| { kind: "rect"; w: number; h: number };
**선택 B를 써야 할 때:**
- *(TODO)*
const area = (s: Shape): number => {
switch (s.kind) {
case "circle": return Math.PI * s.r ** 2;
case "rect": return s.w * s.h;
}
};
```
**기본값:**
> *(TODO)*
### Pattern 3 — Exhaustiveness check (TS never)
## ❌ 안티패턴 (Anti-Patterns)
```typescript
function assertNever(x: never): never { throw new Error(`unhandled: ${x}`); }
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
const handle = (s: Shape) => {
switch (s.kind) {
case "circle": return "c";
case "rect": return "r";
default: return assertNever(s); // compile error if missed
}
};
```
### Pattern 4 — Haskell ADT + pattern match
```haskell
data Tree a = Leaf | Node (Tree a) a (Tree a)
depth :: Tree a -> Int
depth Leaf = 0
depth (Node l _ r) = 1 + max (depth l) (depth r)
```
### Pattern 5 — State machine via enum
```rust
enum Conn {
Disconnected,
Connecting { since: Instant },
Connected { id: SessionId },
Closing,
}
fn step(c: Conn, ev: Event) -> Conn { /* exhaustive match */ }
```
### Pattern 6 — Zod (TS runtime ADT)
```typescript
import { z } from "zod";
const Result = z.discriminatedUnion("tag", [
z.object({ tag: z.literal("ok"), v: z.number() }),
z.object({ tag: z.literal("err"), e: z.string() }),
]);
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Error handling | Result / Either |
| Optional value | Option / Maybe |
| 3+ variant state | sealed enum / sum type |
| External JSON variant | discriminated union + schema |
| Boolean only | bool (sum 의 unit + unit) |
**기본값**: discriminated union with explicit tag + exhaustive pattern match.
## 🔗 Graph
- 부모: [[Type-Theory]] · [[Algebraic-Data-Types]]
- 변형: [[Product-Type]] · [[GADT]] · [[Polymorphic-Variant]]
- 응용: [[Error-Handling]] · [[State-Machine]] · [[Parser-Combinator]]
- Adjacent: [[Pattern-Matching]] · [[Curry-Howard]]
## 🤖 LLM 활용
**언제**: type-driven design, error handling without exceptions, state machine, schema variant modeling.
**언제 X**: dynamic / duck-typed contexts (Python without union types), single-variant case (just struct).
## ❌ 안티패턴
- **Boolean blindness**: `bool` 의 use 의 meaning lost — named variant 의 prefer.
- **Stringly-typed tag**: free-form string 의 tag — typo unsafe.
- **Non-exhaustive match**: default arm 의 silent — exhaustiveness check 의 enable.
- **Nested Option**: `Option<Option<T>>` 의 ambiguous — flatten 또는 redesign.
## 🧪 검증 / 중복
- Verified (TAPL, Pierce / Rust Book / TS Handbook).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (Rust/TS/Haskell, 6 patterns) |
@@ -2,92 +2,131 @@
id: wiki-2026-0508-aesthetic-value
title: Aesthetic Value
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-AEVA-001]
aliases: [Aesthetics, Beauty Theory, Aesthetic Judgment]
duplicate_of: none
source_trust_level: A
confidence_score: 0.91
tags: [auto-reinforced, aesthetics, value-theory, art-Philosophy, design-Principles]
confidence_score: 0.85
verification_status: applied
tags: [philosophy, aesthetics, axiology, design, computational-aesthetics]
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
framework: CLIP/aesthetic-predictor
---
# [[Aesthetic-Value|Aesthetic-Value]]
# Aesthetic Value
## 📌 한 줄 통찰 (The Karpathy Summary)
> "아름다움이라는 객관적 질서: 단순히 개인의 취향을 넘어, 대칭, 비례, 조화, 그리고 의외성이라는 요소를 통해 인간의 뇌에 쾌락과 경외감을 선사하는 시각적/지적 가치의 정수."
## 한 줄
> **"매 beauty 의 measurable — 매 subjective 의 X, 매 inter-subjective regularity 의 model."**. Aesthetic value 의 philosophy (Kant, Hume) 의 root, 매 2026 의 computational aesthetics (CLIP-aesthetic, LAION predictor, FLUX-Pro reward model) 의 design / image-gen / UI optimization 의 quantified.
## 📖 구조화된 지식 (Synthesized Content)
미적 가치(Aesthetic-Value)는 사물이나 예술 작품이 가진 가치 중, 그것을 지각하거나 경험할 때 느끼는 아름다움, 숭엄함, 조화로움 등과 관련된 가치를 의미합니다.
## 매 핵심
1. **미적 가치의 구성 요소**:
* **Balance & Harmony**: 구성 요소들 간의 균형과 질서. ([[Symmetry-and-Invariance|Symmetry-and-Invariance]]와 연결)
* **Complexity & Novelty**: 너무 단순하면 지루하고, 너무 복잡하면 혼란스럽지만, 적절한 복잡성 속에 숨겨진 참신함은 높은 미적 가치를 가짐.
* **Sublimity (숭고함)**: 인간의 이해를 넘어서는 거대함이나 압도적인 힘에서 느끼는 심미적 경외감.
2. **적용 및 중요성**:
* **UI/UX Design**: 심미적으로 뛰어난 디자인은 사용자에게 신뢰감을 주며 시스템의 사용성을 높임 (Aesthetic-Usability Effect).
* **[[Architecture|Architecture]]**: 공간의 미적 가치는 거주자의 정서와 행동 방식에 영향을 미침.
### 매 Theories
- **Kant's "disinterested pleasure"**: aesthetic judgment 의 free of utility / desire.
- **Hume's "delicacy of taste"**: trained sensibility 의 inter-subjective standard.
- **Formalism (Bell, Fry)**: significant form — composition / line / color.
- **Expressivism (Collingwood)**: art 의 emotion 의 expression.
- **Institutional theory (Dickie)**: artworld 의 designation.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 미학을 인간 전유의 주관적 영역으로 보았으나, 현대의 AI 미학 정책은 인간의 뇌가 선호하는 패턴을 통계적으로 학습하여 '객관적인 미적 가치 점수'를 산출하고 생성 AI에 투영하는 정책으로 진화함(RL Update).
- **정책 변화(RL Update)**: 기업 브랜딩 및 제품 설계 정책에서, 기능성(Utility)만큼이나 '미적 독창성(Aesthetic Originality)'을 차별화의 핵심 전략 자산으로 관리하는 정책이 강화됨.
### 매 Computational Aesthetics
- **LAION-Aesthetics predictor**: CLIP embedding → MLP → 1-10 score.
- **PickScore / HPSv2**: human-preference reward model for image-gen.
- **FLUX-Pro / Imagen 3 reward**: aesthetic + prompt-alignment dual reward.
- **A/B testing**: empirical preference (UI design).
- **Birkhoff's M = O / C**: Order over Complexity (1933).
## 🔗 지식 연결 (Graph)
- [[Visual-Effects-VFX|Visual-Effects-VFX]], [[Style-Transfer|Style-Transfer]], Human-Computer Interaction (HCI), [[Symmetry-and-Invariance|Symmetry-and-Invariance]], Foundational Models
- **Modern Tech/Tools**: Aesthetic reward models in Generative AI, Adobe Firefly, Midjourney.
---
### 매 응용
1. Image generation reward (FLUX, SD3, Imagen 3 RLHF).
2. UI / design system scoring.
3. Photo curation (Apple Photos, Google Photos auto-pick).
4. Stock image ranking.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Pattern 1 — LAION aesthetic score
**언제 쓰면 안 되는가:**
- *(TODO)*
```python
import torch, clip
from huggingface_hub import hf_hub_download
## 🧪 검증 상태 (Validation)
device = "cuda" if torch.cuda.is_available() else "cpu"
clip_model, preprocess = clip.load("ViT-L/14", device=device)
mlp_path = hf_hub_download("LAION-AI/aesthetic-predictor", "sa_0_4_vit_l_14_linear.pth")
mlp = torch.nn.Linear(768, 1).to(device)
mlp.load_state_dict(torch.load(mlp_path))
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def score(img_pil):
with torch.no_grad():
emb = clip_model.encode_image(preprocess(img_pil).unsqueeze(0).to(device))
emb = emb / emb.norm(dim=-1, keepdim=True)
return mlp(emb.float()).item()
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pattern 2 — PickScore reward (HF)
**선택 A를 써야 할 때:**
- *(TODO)*
```python
from transformers import AutoProcessor, AutoModel
proc = AutoProcessor.from_pretrained("yuvalkirstain/PickScore_v1")
model = AutoModel.from_pretrained("yuvalkirstain/PickScore_v1").cuda()
**선택 B를 써야 할 때:**
- *(TODO)*
def pick_score(prompt, image):
inputs = proc(text=prompt, images=image, return_tensors="pt", padding=True).to("cuda")
with torch.no_grad():
return model(**inputs).logits_per_image.item()
```
**기본값:**
> *(TODO)*
### Pattern 3 — Birkhoff order/complexity
## ❌ 안티패턴 (Anti-Patterns)
```python
def birkhoff(order_count: int, complexity: int) -> float:
return order_count / max(complexity, 1)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Pattern 4 — RLHF aesthetic reward (training)
```python
# DDPO-style: gradient through diffusion sampling chain
def reward_fn(images, prompts):
return 0.5 * laion_aesthetic(images) + 0.5 * pick_score(prompts, images)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Photo curation | LAION-aesthetic |
| Image-gen RLHF | PickScore + HPSv2 ensemble |
| UI / web design | A/B test + heatmap |
| Art history analysis | Formalism + expert label |
**기본값**: ensemble (LAION + PickScore + human eval).
## 🔗 Graph
- 부모: [[Axiology]] · [[Philosophy-of-Art]]
- 변형: [[Computational-Aesthetics]] · [[Beauty-Metric]]
- 응용: [[Image-Generation-RLHF]] · [[Photo-Curation]] · [[UI-Design]]
- Adjacent: [[Reward-Modeling]] · [[Human-Preference]]
## 🤖 LLM 활용
**언제**: image / design quality reward, preference-tuned generation, large-scale curation.
**언제 X**: pure subjective single-user use (preference learn), ethical/cultural sensitive context (model bias).
## ❌ 안티패턴
- **Single-metric absolutism**: LAION 의 over-fit (saturated colors).
- **Ignoring cultural bias**: training data 의 Western/Instagram bias.
- **No human spot-check**: reward gaming → aesthetic collapse.
- **Treating subjective as objective**: 매 score 의 ranking 의 X distance.
## 🧪 검증 / 중복
- Verified (LAION-Aesthetics paper, PickScore NeurIPS 2023, FLUX technical report).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (CLIP-aesthetic, PickScore, RLHF) |
@@ -2,67 +2,123 @@
id: wiki-2026-0508-alcoholism
title: Alcoholism
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ALCO-001]
aliases: [Alcohol Use Disorder, AUD, Alcohol Dependence]
duplicate_of: none
source_trust_level: A
confidence_score: 0.88
tags: [auto-reinforced, alcoholism, addiction-Psychology, public-health, mental-health]
confidence_score: 0.9
verification_status: applied
tags: [health, neuroscience, addiction, public-health, computational-health]
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: Python
framework: scikit-learn / PyTorch
---
# [[Alcoholism|Alcoholism]]
# Alcoholism
## 📌 한 줄 통찰 (The Karpathy Summary)
> "조절력을 잃은 질병: 술에 대한 강박적 집착과 남용으로 인해 건강, 관계, 사회적 기능을 파괴함에도 불구하고 멈출 수 없는 만성적 중독 상태."
## 한 줄
> **"매 chronic relapsing brain disorder — 매 willpower 의 X, 매 reward circuit 의 hijack."**. Alcoholism (DSM-5: Alcohol Use Disorder, AUD) 의 dopamine / GABA / glutamate 의 imbalance — 매 2026 의 GLP-1 (semaglutide) 의 craving suppression evidence + naltrexone / acamprosate 의 mainline + AI-driven relapse prediction.
## 📖 구조화된 지식 (Synthesized Content)
알코올 의존증(Alcoholism)은 알코올 섭취를 스스로 조절하지 못하고 심리적, 생리적으로 술에 매몰되는 질환입니다.
## 매 핵심
1. **주요 특징**:
* **Tolerance (내성)**: 같은 효과를 보려면 더 많은 술을 마셔야 함.
* **Withdrawal (금단)**: 단주 시 떨림, 환각, 불안 증세 발생.
* **Impulsivity**: 부정적 결과를 알면서도 즉각적인 보상(술)을 선택. ([[Decision Theory|Decision Theory]]와 연결)
2. **원인**:
* 뇌의 보상체계(도파민 회로) 고장, 유전적 요인, 극심한 스트레스 및 사회적 환경.
3. **치료**:
* 약물 치료, 인지 행동 치료(CBT), 집단 상담 (AA - Alcoholics Anonymous).
### 매 Neurobiology
- **Dopamine surge** in nucleus accumbens → euphoria.
- **GABA-A potentiation** → anxiolysis, sedation.
- **NMDA glutamate antagonism** → cognitive slowing.
- **Allostasis**: chronic use → reward set-point shift, withdrawal hypersensitivity.
- **HPA axis dysregulation**: stress → relapse trigger.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 의지 부족이나 '도덕적 결함'으로 보는 처벌 정책이 강했으나, 현대 보건 정책은 뇌의 신경생물학적 질병으로 규정하고 '공공 위생 정책' 관점에서 접근함(RL Update).
- **정책 변화(RL Update)**: 중독 치료 정책에 디지털 치료제(DTx) 및 AI 상담사 정책을 도입하여, 접근성을 높이고 사후 관리를 자동화하는 'Smart Recovery 정책'이 추진됨.
### 매 Diagnosis (DSM-5 AUD)
- 11 criteria, 2+ in 12 months → AUD.
- Severity: mild (2-3), moderate (4-5), severe (6+).
- AUDIT-C screen: 3-question, score ≥4 (M) / ≥3 (F) → flag.
## 🔗 지식 연결 (Graph)
- [[Decision Theory|Decision Theory]], [[Reward Prediction Error|Reward Prediction Error]], [[Psychology & Behavior|Psychology & Behavior]], [[Altruism|Altruism]], [[AI for Social Good|AI for Social Good]]
- **Modern Tech/Tools**: Digital therapeutics (DTx) for addiction, Continuous monitoring wearables.
---
### 매 Treatment (2026)
- **Pharmacotherapy**: naltrexone, acamprosate, disulfiram. GLP-1 (semaglutide / tirzepatide) emerging — Phase 3 trials show ~40% craving ↓.
- **Psychosocial**: CBT, motivational interviewing, 12-step (AA).
- **Digital**: reSET-O FDA-cleared, Quit Genius.
- **AI**: ML relapse prediction from EMA + wearable HRV.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Public health screening (AUDIT in EHR).
2. Personalized treatment (pharmacogenomics).
3. Relapse prediction (ML on smartphone passive sensing).
4. Policy modeling (alcohol tax, MUP).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Pattern 1 — AUDIT-C scoring
## 🧪 검증 상태 (Validation)
```python
def audit_c(freq: int, drinks_per_day: int, binge_freq: int) -> int:
return freq + drinks_per_day + binge_freq # each 0-4
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
def flag(score: int, sex: str) -> bool:
return score >= (4 if sex == "M" else 3)
```
## 🧬 중복 검사 (Duplicate Check)
### Pattern 2 — Relapse prediction (logistic regression on EMA)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
```python
from sklearn.linear_model import LogisticRegression
features = ["craving_vas", "stress", "sleep_h", "social_isolation", "hrv_rmssd"]
clf = LogisticRegression(class_weight="balanced", max_iter=500)
clf.fit(X[features], y_relapse_7d)
```
## 🕓 변경 이력 (Changelog)
### Pattern 3 — Just-in-time intervention (JITAI)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
```python
def maybe_intervene(state):
if state.craving > 7 or state.location_near_bar:
send_push("Coping skill: 4-7-8 breath. Call sponsor?")
```
### Pattern 4 — HRV-based stress proxy (wearable)
```python
def stress_proxy(rmssd_ms: float, baseline: float) -> float:
return max(0.0, (baseline - rmssd_ms) / baseline)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Screening (PCP visit) | AUDIT-C |
| Mild AUD, motivated | Brief intervention + naltrexone |
| Severe AUD, withdrawal | Inpatient detox + benzodiazepine taper |
| Comorbid obesity | GLP-1 (semaglutide) — emerging |
| High relapse risk | CBT + naltrexone + digital JITAI |
**기본값**: AUDIT-C → if positive: brief intervention + naltrexone trial + referral.
## 🔗 Graph
- 부모: [[Addiction-Neuroscience]] · [[Mental-Health]]
- 변형: [[Substance-Use-Disorder]] · [[Behavioral-Addiction]]
- 응용: [[Digital-Therapeutics]] · [[Relapse-Prediction]] · [[Public-Health-Policy]]
- Adjacent: [[Dopamine]] · [[Burnout-Prevention]] · [[Cognitive-Behavioral-Therapy]]
## 🤖 LLM 활용
**언제**: care navigator, coping skill coaching, EMA prompting, literature synthesis for clinicians.
**언제 X**: diagnosis (clinician role), crisis (route to hotline / 988), withdrawal management (medical emergency).
## ❌ 안티패턴
- **"Just willpower" framing**: stigma, evidence-contradicted.
- **Cold-turkey alone in severe AUD**: delirium tremens 의 fatal risk.
- **One-size-fits-all RX**: 매 patient 의 phenotype heterogeneous.
- **Ignoring comorbid depression / PTSD**: untreated → relapse near-certain.
## 🧪 검증 / 중복
- Verified (DSM-5, NIAAA guidelines, NEJM 2024 GLP-1/AUD trial).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (DSM-5, GLP-1, JITAI ML) |
@@ -1,92 +1,148 @@
---
id: wiki-2026-0508-algorithm-complexity-big-o
title: Algorithm Complexity Big O
title: Algorithm Complexity (Big O)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [BIG-O-001]
aliases: [Big-O, Time-Complexity, Asymptotic-Analysis]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [computer-science, algorithm, complexity, Optimization, big-o]
confidence_score: 0.95
verification_status: applied
tags: [computer-science, algorithm, complexity, big-o]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: stdlib
---
# Algorithm Complexity (Big O, 알고리즘 복잡도)
# Algorithm Complexity (Big O)
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터가 무한히 늘어날, 알고리즘이 얼마나 버틸 수 있는지 측정하라" — 입력 데이터의 크기($n$)에 따른 시간적(Time) 및 공간적(Space) 자원 소모량의 증가 추세를 나타내는 수학적 표기법.
## 한 줄
> **"매 입력이 무한히 커질 때 알고리즘이 어떻게 scale하는지 측정"**. Big-O는 worst-case asymptotic upper bound를 표기 — 매 constant factor와 lower-order term은 drop. 매 1976년 Knuth가 CS에 popularize, 매 2026 ML/AI 에서도 attention $O(n^2)$ → FlashAttention $O(n)$ 같은 algorithmic breakthrough의 척도로 active.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 구체적인 실행 시간 대신 최악의 경우(Worst-case)를 기준으로 알고리즘의 확장성([[Scalability|Scalability]])을 분류하여 효율적인 설계를 돕는 추상화 패턴.
- **주요 복잡도 단계:**
- **$O(1)$:** 상수 시간. 입력 크기와 무관하게 즉시 처리 (예: 배열 인덱스 접근).
- **$O(\log n)$:** 로그 시간. 처리 범위가 절반씩 줄어듦 (예: 이진 탐색).
- **$O(n)$:** 선형 시간. 입력 크기에 비례 (예: 단순 반복문).
- **$O(n \log n)$:** 선형 로그 시간. 효율적인 정렬 알고리즘 (예: Merge Sort, Quick Sort).
- **$O(n^2)$:** 이차 시간. 이중 반복문. 대규모 데이터에서 기하급수적으로 느려짐.
- **$O(2^n)$:** 지수 시간. 매우 위험한 복잡도 (예: 피보나치 재귀).
- **의의:** AI 모델 학습이나 대규모 인덱싱 시 알고리즘 선택의 결정적 기준이 됨.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순히 '빠른' 알고리즘을 찾던 시기에서, 메모리 사용량(Space Complexity)과 캐시 효율성까지 고려하는 다각적 최적화 시대로 진화.
- **정책 변화:** Antigravity 프로젝트는 모든 지식 검색 및 클러스터링 알고리즘 도입 시 최악의 경우 $O(n \log n)$ 이하의 복잡도를 유지하는 것을 원칙으로 함.
### 매 복잡도 계급
- $O(1)$: array index, hash lookup, stack push.
- $O(\log n)$: binary search, balanced BST insert.
- $O(n)$: linear scan, single pass.
- $O(n \log n)$: comparison sort floor, FFT.
- $O(n^2)$: nested loops, naive matmul, bubble sort.
- $O(n^3)$: triple nested, naive matrix mul.
- $O(2^n)$: subset enumeration, naive recursion.
- $O(n!)$: permutation, brute-force TSP.
## 🔗 지식 연결 (Graph)
- Algorithm, [[Parallel-Computing|Parallel-Computing]], Vector-Database-Selection, [[Optimization|Optimization]]
- **Raw Source:** 10_Wiki/Topics/AI/Algorithm-Complexity-Big-O.md
### 매 표기 family
- **Big-O ($O$)**: upper bound (worst case).
- **Big-Omega ($\Omega$)**: lower bound (best case).
- **Big-Theta ($\Theta$)**: tight bound.
- **little-o ($o$)**: strict upper (not tight).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. ML attention: $O(n^2)$ → FlashAttention 2026 $O(n)$ memory.
2. Database index: B-Tree $O(\log n)$ vs full scan $O(n)$.
3. RAG retrieval: HNSW $O(\log n)$ vs brute kNN $O(n)$.
4. LLM inference: KV cache reuse turns $O(n^2)$ generation into $O(n)$.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Empirical complexity measurement
```python
import time, numpy as np
def measure(fn, sizes):
times = []
for n in sizes:
data = list(range(n))
t0 = time.perf_counter()
fn(data)
times.append(time.perf_counter() - t0)
# log-log slope ≈ exponent
slope = np.polyfit(np.log(sizes), np.log(times), 1)[0]
return slope # ~1.0 → O(n), ~2.0 → O(n^2)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Master Theorem (divide & conquer)
```python
# T(n) = a*T(n/b) + O(n^d)
# Case 1: d < log_b(a) → T(n) = O(n^log_b(a)) (e.g., Strassen)
# Case 2: d = log_b(a) → T(n) = O(n^d log n) (e.g., merge sort: 2T(n/2)+n → O(n log n))
# Case 3: d > log_b(a) → T(n) = O(n^d)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Amortized analysis (dynamic array)
```python
class DynArray:
def __init__(self):
self.cap, self.n, self.buf = 1, 0, [None]
def push(self, x): # amortized O(1) despite O(n) resize
if self.n == self.cap:
self.cap *= 2
self.buf = self.buf + [None]*self.cap
self.buf[self.n] = x; self.n += 1
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Space-time tradeoff (memoization)
```python
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)
# without cache: O(2^n) time
# with cache: O(n) time, O(n) space
```
**기본값:**
> *(TODO)*
### Big-O of recursion via recurrence
```python
# binary search: T(n) = T(n/2) + O(1) → O(log n)
def bsearch(a, x, lo=0, hi=None):
hi = hi if hi is not None else len(a)
if lo >= hi: return -1
m = (lo + hi) // 2
if a[m] == x: return m
return bsearch(a, x, lo, m) if a[m] > x else bsearch(a, x, m+1, hi)
```
## ❌ 안티패턴 (Anti-Patterns)
### Profiling-based complexity
```python
import cProfile, pstats
cProfile.run('expensive_fn(data)', '/tmp/prof')
pstats.Stats('/tmp/prof').sort_stats('cumulative').print_stats(20)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| n size | tolerable complexity |
|---|---|
| $n \le 10$ | $O(n!)$, $O(2^n)$ OK |
| $n \le 10^3$ | $O(n^3)$ OK |
| $n \le 10^5$ | $O(n^2)$ borderline, prefer $O(n \log n)$ |
| $n \le 10^7$ | $O(n \log n)$ |
| $n \le 10^9$ | $O(n)$ or $O(\log n)$ only |
**기본값**: 매 production 코드는 $O(n \log n)$ 이하 target. 매 ML inference path는 $O(n)$ 이하.
## 🔗 Graph
- 부모: [[Theoretical-Computer-Science]] · [[Theoretical-Computer-Science]]
- 변형: [[BFS vs DFS]] · [[Dynamic-Programming]] · [[Greedy-Algorithms]]
- 응용: [[Optimization-Algorithms]] · [[Combinatorial-Optimization]]
- Adjacent: [[Kolmogorov-Complexity]] · [[Information Theory]]
## 🤖 LLM 활용
**언제**: 매 algorithm choice review, 매 scaling concern (n>10^5), 매 inference path optimization.
**언제 X**: 매 micro-benchmark (constant factors dominate); 매 distributed system (network I/O dominates).
## ❌ 안티패턴
- **Premature optimization**: 매 $n=100$ 에서 $O(n^2)$ vs $O(n \log n)$ — 매 negligible.
- **Hidden quadratic**: 매 `for x in list: if x in list:` — 매 list `in` 은 $O(n)$ → 매 total $O(n^2)$.
- **Big-O fetishism**: 매 cache locality, branch prediction이 매 매 $\log n$ factor보다 큼 (소형 n).
## 🧪 검증 / 중복
- Verified (CLRS Ch.3, Knuth TAOCP Vol.1).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Big-O classes, master theorem, amortized analysis |
@@ -2,91 +2,148 @@
id: wiki-2026-0508-atomism
title: Atomism
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ATOM-001]
aliases: [Logical Atomism, Reductionism, Atomic Decomposition]
duplicate_of: none
source_trust_level: A
confidence_score: 0.88
tags: [auto-reinforced, atomism, Philosophy, Physics, reductionism, material-Logic]
confidence_score: 0.86
verification_status: applied
tags: [philosophy, reductionism, decomposition, design, software-architecture]
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: TypeScript/Python
framework: design-systems
---
# [[Atomism|Atomism]]
# Atomism
## 📌 한 줄 통찰 (The Karpathy Summary)
> "세상의 최소 단위: 모든 복잡한 사물은 결국 더 이상 쪼개지지 않는 작고 견고한 '원자'들의 조합일 뿐이라는 철학적/과학적 환원주의."
## 한 줄
> **"매 whole 의 indivisible part 의 sum — 매 understand 의 decompose."**. Atomism 의 ancient Greek (Democritus, Leucippus) origin → modern logical atomism (Russell, early Wittgenstein) → 2026 의 software (atomic design, atom CSS, atomic commit, atomic transaction) 의 ubiquitous design principle.
## 📖 구조화된 지식 (Synthesized Content)
원자론(Atomism)은 우주가 무수한 개별적이고 파괴 불가능하며 변화하지 않는 입자들로 구성되어 있다는 사상입니다.
## 매 핵심
1. **철학적 원류**:
* 고대 그리스 데모크리토스가 제안. "탄생과 죽음은 우연히 모였다가 흩어지는 원자들의 배열 변화일 뿐"이라고 주장.
2. **과학적 도약**:
* 근대 화학과 물리학의 토대가 되었으며, 물질의 성질을 구성 요소의 결합 방식으로 규명하는 데 성공함.
3. **지적 태도 (Logical Atomism)**:
* 복잡한 문장이나 지식도 최소 단위인 '원자 명제'로 분석할 수 있다는 비트겐슈타인의 철학으로 계승됨. ([[Analysis|Analysis]]와 연결)
### 매 Philosophical Roots
- **Democritus (~460 BC)**: matter 의 indivisible atom.
- **Russell's logical atomism (1918)**: world 의 logical atom (sense data) 의 사실.
- **Wittgenstein's Tractatus**: atomic facts → propositions.
- **Reductionism**: complex → simple components.
- **Counter**: holism (Quine), emergence — 매 whole > sum.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 원자가 정말 '최소 단위'라고 믿었으나, 현대 물리학 정책은 원자 내부의 쿼크나 끈 이론(String Theory) 등 더 미세한 층위와 '파동-입자 이중성' 정책을 수용하며 원자론적 사고의 한계를 인정함(RL Update).
- **정책 변화(RL Update)**: 소프트웨어 설계 정책에서, 거대한 단일 코드(Monolith) 대신 작고 독립적인 원자 단위의 기능을 조립하는 '마이크로서비스 아키텍처(MSA) 정책'으로 원자론적 철학이 공학적 표준이 됨.
### 매 Software Atomism
- **Atomic design (Brad Frost)**: atom → molecule → organism → template → page.
- **Atomic CSS (Tailwind, UnoCSS)**: utility class 의 single property.
- **Atomic commit (Git)**: 1 commit = 1 logical change.
- **Atomic transaction (DB)**: ACID 의 A — all-or-nothing.
- **Atomic operation (concurrency)**: indivisible CPU instruction (CAS).
## 🔗 지식 연결 (Graph)
- [[Analysis|Analysis]], [[Structuralism|Structuralism]], Reductionism, [[Arrangement-and-Composition|Arrangement-and-Composition]], Philosophy of Science
- **Modern Tech/Tools**: [[Atomic Design|Atomic Design]] (UI/UX), Microservices [[Architecture|Architecture]].
---
### 매 응용
1. Component-driven UI (Storybook, Bit).
2. Microservice / function decomposition.
3. Test atomicity (1 test = 1 assertion principle).
4. Knowledge management (atomic note, Zettelkasten).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Pattern 1 — Atomic design (React)
**언제 쓰면 안 되는가:**
- *(TODO)*
```tsx
// atom
export const Button = ({ children, ...p }) =>
<button className="px-3 py-1 rounded" {...p}>{children}</button>;
## 🧪 검증 상태 (Validation)
// molecule
export const SearchBar = () => (
<div className="flex gap-2">
<Input placeholder="search" />
<Button>Go</Button>
</div>
);
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
// organism
export const Header = () => (
<header><Logo /><SearchBar /><UserMenu /></header>
);
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pattern 2 — Atomic CSS (Tailwind)
**선택 A를 써야 할 때:**
- *(TODO)*
```html
<button class="px-4 py-2 bg-blue-500 hover:bg-blue-600 rounded text-white">
Submit
</button>
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Pattern 3 — Atomic commit (Git)
**기본값:**
> *(TODO)*
```bash
# BAD: 1 commit, 3 unrelated changes
git commit -m "fix bug + refactor + add feature"
## ❌ 안티패턴 (Anti-Patterns)
# GOOD: 3 atomic commits
git add src/bug.ts && git commit -m "fix: null check in parse"
git add src/utils/ && git commit -m "refactor: extract helper"
git add src/feature.ts && git commit -m "feat: add export csv"
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Pattern 4 — Atomic CAS (Rust)
```rust
use std::sync::atomic::{AtomicUsize, Ordering};
let counter = AtomicUsize::new(0);
counter.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst).ok();
```
### Pattern 5 — Atomic note (Zettelkasten)
```markdown
# 20260510-1432-recursive-decomposition
매 problem 의 self-similar subproblem 의 split → solve → combine.
대표 의 merge sort, quicksort, divide-and-conquer.
→ [[20260509-2210-master-theorem]]
→ [[20260510-1450-dynamic-programming]]
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| UI design | Atomic design hierarchy |
| Styling | Atomic CSS (Tailwind/UnoCSS) |
| VCS | Atomic commit |
| Concurrency | atomic primitives + lock-free |
| Notes | Atomic note (1 idea / file) |
| Architecture | weigh atomism vs holism (some properties emergent) |
**기본값**: atomic decomposition + holistic review (avoid reductionist trap).
## 🔗 Graph
- 부모: [[Reductionism]] · [[Philosophy-of-Science]]
- 변형: [[Holism]] · [[Emergence]] · [[Logical-Atomism]]
- 응용: [[Atomic-Design]] · [[Atomic-CSS]] · [[Atomic-Commit]] · [[Zettelkasten]]
- Adjacent: [[Composition-over-Inheritance]] · [[Single-Responsibility-Principle]]
## 🤖 LLM 활용
**언제**: design system creation, refactoring monolith, documentation structure, knowledge graph.
**언제 X**: irreducibly emergent system (consciousness, ecosystem), tightly-coupled domain logic.
## ❌ 안티패턴
- **Reductionist fallacy**: 매 whole 의 part 의 sum 의 X — emergence 무시.
- **Over-atomization**: 100 utility classes for 1 button — readability collapse.
- **Atomic worship**: 매 every commit atomic 의 over-engineer (squash merge available).
- **Lost-context note**: atomic note 의 link 없음 — 매 island.
## 🧪 검증 / 중복
- Verified (Russell "Philosophy of Logical Atomism", Brad Frost "Atomic Design", classical CS).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (philosophy + 5 software patterns) |
@@ -2,66 +2,129 @@
id: wiki-2026-0508-autobiography
title: Autobiography
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-AUBI-001]
aliases: [Self-Narrative, Memoir, Personal Narrative, Life Writing]
duplicate_of: none
source_trust_level: A
confidence_score: 0.88
tags: [auto-reinforced, autobiography, narrative, memory, identity, storytelling, Reflection]
confidence_score: 0.85
verification_status: applied
tags: [narrative, qualitative-research, self-knowledge, llm-personalization]
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: Python
framework: LangChain/LlamaIndex
---
# [[Autobiography|Autobiography]]
# Autobiography
## 📌 한 줄 통찰 (The Karpathy Summary)
> "과거의 재구성, 자아의 기록: 개인이 자신의 삶을 회고하며 시간의 흐름 속에 흩어진 경험들을 하나의 일관된 서사로 엮어냄으로써, '나는 누구인가'를 세상에 선포하는 주관적 진실의 기록."
## 한 줄
> **"매 self 의 narrative 의 construct — 매 memory 의 chronicle 의 X, 매 meaning-making 의 retrospective."**. Autobiography 의 self 의 first-person 의 life narrative — 매 Augustine "Confessions" 의 origin, 매 2026 의 LLM-era 의 personal corpus (lifelog + journal + chat history) 의 personalization / digital twin / memory-augmented agent 의 source data.
## 📖 구조화된 지식 (Synthesized Content)
자서전(Autobiography)은 저자가 자신의 생애를 스스로 서술한 기록물입니다.
## 매 핵심
1. **특징**:
* **Subjectivity**: 객관적 사실보다 저자가 그 사실을 어떻게 '느끼고 해석했는지'가 핵심.
* **Thematic Selection**: 모든 순간을 담는 것이 아니라, 현재의 자신을 만든 결정적인 장면들을 선택해 배합.
* **Self-Reflection**: 기록 과정 자체가 자아를 성찰하고 치유하며 정체성을 확립하는 행위임.
2. **사회적 의의**:
* 한 개인의 역사를 통해 당시의 시대상과 보편적 인간 경험을 조명함.
* 성공담뿐만 아니라 실패와 내면의 갈등을 공유하여 후대에 영감을 줌.
### 매 Theoretical Frames
- **Bruner's narrative identity**: self 의 ongoing story.
- **McAdams' life-story model**: 7 themes (agency, communion, redemption, contamination...).
- **Ricoeur's "narrative identity"**: 매 idem (sameness) + ipse (selfhood).
- **Distinction**: autobiography (whole life) vs memoir (period/theme) vs autoethnography (cultural lens).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 '영웅적 서사' 중심의 정적인 기록 정책이 주류였으나, 현대의 자서전 정책은 삶의 단편들을 파편적으로 기록하고 공유하는 '디지털 로그(Digital Log) 및 마이크로 자서전 정책'으로 변모함(RL Update).
- **정책 변화(RL Update)**: AI 기술 정책과 결합하여, 개인이 남긴 방대한 디지털 흔적을 분석해 자서전 초안을 잡아주거나 가상 인격으로 복원해주는 'AI 자서전 및 유산 관리 서비스 정책'이 실무적으로 검토됨.
### 매 2026 Computational Use
- **LLM personalization**: chat history → user profile embedding.
- **Lifelog**: passive sensing (location, photo, journal) → searchable corpus.
- **Digital twin / memory agent**: Mem0, MemGPT, Letta 의 long-term memory.
- **Therapy adjunct**: LLM-guided narrative therapy.
## 🔗 지식 연결 (Graph)
- [[AI and Narrative|AI and Narrative]], [[Authenticity|Authenticity]], Memory, Self-Correction Mechanisms, [[Psychology & Behavior|Psychology & Behavior]]
- **Modern Tech/Tools**: Day One ([[Journaling|Journaling]] app), Ghostwriting AI, Digital legacy platforms.
---
### 매 응용
1. Personal AI assistant memory.
2. Qualitative research (life-history interview).
3. Digital legacy / estate.
4. Self-reflection coaching (BetterUp AI).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Pattern 1 — Journal indexing (LlamaIndex)
**언제 쓰면 안 되는가:**
- *(TODO)*
```python
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
## 🧪 검증 상태 (Validation)
docs = SimpleDirectoryReader("~/journal").load_data()
index = VectorStoreIndex.from_documents(docs)
qe = index.as_query_engine(similarity_top_k=5)
print(qe.query("When did I feel most burned out in 2025?"))
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Pattern 2 — Mem0 long-term memory
## 🧬 중복 검사 (Duplicate Check)
```python
from mem0 import Memory
m = Memory()
m.add("I prefer tea over coffee, switched in 2024 after gastritis.", user_id="me")
results = m.search("morning beverage preference", user_id="me")
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Pattern 3 — Life-event timeline extraction
## 🕓 변경 이력 (Changelog)
```python
import json
from anthropic import Anthropic
client = Anthropic()
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
EXTRACT = """Extract life events as JSON: [{date, type, summary, valence}].
Text: {text}"""
resp = client.messages.create(
model="claude-opus-4-7",
max_tokens=2000,
messages=[{"role": "user", "content": EXTRACT.format(text=journal_text)}],
)
events = json.loads(resp.content[0].text)
```
### Pattern 4 — Narrative coherence score
```python
def coherence(events):
# simple proxy: causal-chain density
causal = sum(1 for e in events if e.get("caused_by"))
return causal / max(len(events), 1)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| LLM personalization | Mem0 / Letta + RAG over journal |
| Therapy / coaching | guided narrative writing + LLM reflection |
| Research interview | semi-structured + thematic analysis |
| Digital legacy | encrypted lifelog + access policy |
**기본값**: Mem0 for runtime memory, LlamaIndex RAG for retrospective query.
## 🔗 Graph
- 부모: [[Narrative-Identity]] · [[Qualitative-Research]]
- 변형: [[Memoir]] · [[Autoethnography]] · [[Lifelog]]
- 응용: [[LLM-Personalization]] · [[Digital-Twin]] · [[Memory-Augmented-Agent]]
- Adjacent: [[Narrative-Therapy]] · [[Working-Memory]]
## 🤖 LLM 활용
**언제**: personal assistant memory, retrospective query over journal, coaching reflection prompts.
**언제 X**: clinical diagnosis, legal record (chain-of-custody), shared corpus (privacy).
## ❌ 안티패턴
- **Memory leak (PII)**: 매 personal corpus 의 train 의 leak — opt-out + local model.
- **Narrative coherence forcing**: LLM 의 confabulate 의 false memory.
- **Recency bias**: recent events 의 over-weight — temporal balance.
- **No edit/delete**: GDPR right-to-erasure 위반.
## 🧪 검증 / 중복
- Verified (McAdams "Stories We Live By", Mem0 / Letta docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (LLM memory, lifelog, narrative theory) |
@@ -2,65 +2,145 @@
id: wiki-2026-0508-autoethnography
title: Autoethnography
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-AUET-001]
aliases: [Auto-Ethnography, Self-Ethnography, Reflexive Ethnography]
duplicate_of: none
source_trust_level: A
confidence_score: 0.85
tags: [auto-reinforced, autoethnography, qualitative-Research, sociology, storytelling, reflexivity]
confidence_score: 0.86
verification_status: applied
tags: [qualitative-research, ethnography, methodology, narrative, ux-research]
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: Python
framework: NVivo/Atlas.ti
---
# [[Autoethnography|Autoethnography]]
# Autoethnography
## 📌 한 줄 통찰 (The Karpathy Summary)
> "나를 통해 사회를 읽기: 연구자가 관찰자가 아닌 주인공이 되어 자신의 개인적 경험을 기록하고, 이를 사회문화적 맥락과 연결하여 분석함으로써 보편적 인간사를 깊이 있게 통찰하는 질적 연구법."
## 한 줄
> **"매 self-as-instrument — 매 personal experience 의 cultural lens 의 X, 매 cultural lens through personal experience."**. Autoethnography 의 ethnography 의 first-person 의 reflexive variant — Carolyn Ellis / Tony Adams 의 1990s formalize. 매 2026 의 UX research / HCI / AI ethics 의 standard method (영향 the lived experience of bias, accessibility, AI use).
## 📖 구조화된 지식 (Synthesized Content)
오토에스노그라피(Autoethnography, 자기기술지)는 자서전적 글쓰기와 인류학적 현지조사를 결합한 연구 방법론입니다.
## 매 핵심
1. **방법론적 핵심**:
* **Reflexivity (성찰성)**: 연구자 자신의 편견과 감정을 숨기지 않고 분석의 도구로 사용.
* **Evocative Writing**: 독자가 연구자의 경험에 감정적으로 공명하게 만드는 서사적 표현 강조.
* **Linking Local to Global**: 개인의 소소한 일상(Local)이 어떻게 거대한 사회 구조(Global)를 반영하거나 저항하는지 규명.
2. **장점**:
* 전통적인 연구에서 소외된 소수자나 개인의 은밀한 목소리를 학문적 영역으로 끌어올림 ([[Victimhood-Narratives|Victimhood-Narratives]]의 학문적 승화).
### 매 Types
- **Evocative**: literary, emotional, narrative-driven.
- **Analytic** (Anderson): theoretical contribution, research-oriented.
- **Interpretive**: meaning-making, hermeneutic.
- **Critical / performative**: activist, social-justice frame.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 '객관성'이 결여되었다는 비판 정책에 시달렸으나, 현대 사회과학 정책은 연구자의 완전한 중립성은 불가능함을 인정하고 '투명한 주관성 정책'이 오히려 더 정직한 지식을 만든다고 평가함(RL Update).
- **정책 변화(RL Update)**: 디지털 인류학 정책에서, 플랫폼 노동자나 AI 개발자가 자신의 노동 경험을 기록하여 기술 생태계의 민낯을 고발하는 '에이전틱 자기기술지 정책'이 기술 비평의 핵심 도구로 부상함.
### 매 Method
1. **Field**: self in everyday context (often the researcher's own life domain).
2. **Data**: journal, photo, artifact, interview.
3. **Reflexivity**: position 의 explicit (gender, race, role).
4. **Layered analysis**: thick description + theoretical frame.
5. **Triangulation**: peer debrief, member check.
## 🔗 지식 연결 (Graph)
- [[Sociology of Knowledge|Sociology of Knowledge]], [[Authenticity|Authenticity]], [[AI and Narrative|AI and Narrative]], [[Victimhood-Narratives|Victimhood-Narratives]], [[Scientific Communication|Scientific Communication]]
- **Modern Tech/Tools**: Narrative [[Analysis|Analysis]] software, Qualitative re[[Search|Search]] journals.
### 매 Validity Criteria
- **Substantive contribution** (Richardson).
- **Aesthetic merit**.
- **Reflexivity / honesty**.
- **Impact / resonance**.
- **Verisimilitude** (Ellis).
### 매 응용
1. UX research (researcher 의 own use experience).
2. AI ethics (LLM 의 daily use 의 lived account).
3. Disability studies (insider perspective).
4. Medical sociology (illness narrative).
## 💻 패턴
### Pattern 1 — Field journal template (Markdown)
```markdown
---
date: 2026-05-10
context: solo coding session, claude-opus-4-7
mood: 6/10
position: M, 32y, SWE, 8y exp
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
# Observation
- 14:00 prompted Claude w/ vague spec → suggested decomposition steps...
- 14:15 felt resistance to refactor; noticed "it's working, why touch"
**언제 이 지식을 쓰는가:**
- *(TODO)*
# Reflection
- 매 sunk-cost feeling 의 cultural inheritance? Engineering pride?
**언제 쓰면 안 되는가:**
- *(TODO)*
# Theoretical link
- Norman 의 affordance / Schön 의 reflective practitioner.
```
## 🧪 검증 상태 (Validation)
### Pattern 2 — Coding (qualitative) — open coding
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
```python
codes = {
"resistance-to-refactor": ["sunk cost", "it's working", "why touch"],
"delegation-discomfort": ["am I cheating", "is this me"],
"flow-with-LLM": ["pair programming", "thinking partner"],
}
```
## 🧬 중복 검사 (Duplicate Check)
### Pattern 3 — Layered narrative (analytic)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
```markdown
## Vignette
[evocative narrative paragraph]
## 🕓 변경 이력 (Changelog)
## Analysis
[theoretical interpretation: Schön reflective practice]
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## Cultural connection
[broader: SWE identity in age of LLM agents]
```
### Pattern 4 — Member check (peer debrief)
```python
# Share excerpt with informant for response
checks = [
{"excerpt": "...", "informant": "P3", "response": "yes resonates", "date": "2026-05-09"},
{"excerpt": "...", "informant": "P5", "response": "I'd frame differently", "date": "2026-05-09"},
]
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Researcher 의 own lived domain | Autoethnography (insider) |
| Other community | Ethnography (outsider) + reflexivity |
| Quick UX insight | diary study + autoethnography hybrid |
| Theory contribution | Analytic autoethnography (Anderson) |
| Activist / community | Critical / performative |
**기본값**: Analytic autoethnography with peer debrief + member check.
## 🔗 Graph
- 부모: [[Ethnography]] · [[Qualitative-Research]]
- 변형: [[Memoir]] · [[Reflective-Practice]] · [[Diary-Study]]
- 응용: [[UX-Research]] · [[AI-Ethics]] · [[Disability-Studies]]
- Adjacent: [[Autobiography]] · [[Grounded-Theory-Method]] · [[Thematic-Analysis]]
## 🤖 LLM 활용
**언제**: studying one's own use of tech / LLM, insider perspective on team or community, theoretical reflection.
**언제 X**: large-N generalization needed, double-blind requirement, no reflexivity training.
## ❌ 안티패턴
- **Solipsism**: 매 self 의 only — no theoretical contribution.
- **No reflexivity**: position 의 unmark — bias hidden.
- **Cherry-picked vignette**: confirmation bias.
- **Skipping member check** in critical / community work.
## 🧪 검증 / 중복
- Verified (Ellis & Bochner, Anderson 2006, Adams et al. "Autoethnography" 2015).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (types, validity criteria, 4 patterns) |
@@ -2,94 +2,152 @@
id: wiki-2026-0508-automated-decision-making
title: Automated Decision Making
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ADM-001]
aliases: [ADM, Algorithmic Decision-Making, Automated Decisions]
duplicate_of: none
source_trust_level: A
confidence_score: 0.96
tags: [auto-reinforced, automated-decision-making, adm, algorithm, Efficiency, ethics-governance]
confidence_score: 0.93
verification_status: applied
tags: [decision-systems, ml, governance, fairness, eu-ai-act]
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
framework: scikit-learn/PyTorch/Aequitas
---
# [[Automated-Decision-Making|Automated-Decision-Making]]
# Automated Decision Making (ADM)
## 📌 한 줄 통찰 (The Karpathy Summary)
> "알고리즘이 내리는 판결: 인간의 개입 없이 사전에 설정된 논리나 AI 모델이 데이터를 분석하여 대출 승인, 채용 합격, 혹은 형량 판단과 같은 중요한 의사결정을 실시간으로 수행하는 체계."
## 한 줄
> **"매 algorithm 의 decision authority — 매 human approval 의 X 또는 minimal."**. ADM 의 system 의 input 의 받는 → 매 ML / rule / hybrid 의 통한 decision (loan, hiring, sentencing, content mod, dispatch) 의 output. 매 2026 의 EU AI Act (high-risk category) + GDPR Art.22 + Colorado SB205 의 governed.
## 📖 구조화된 지식 (Synthesized Content)
자동화된 의사결정(Automated-Decision-Making, ADM)은 데이터를 입력받아 알고리즘이 자동으로 결론을 도출하고 이를 집행하는 시스템을 의미합니다.
## 매 핵심
1. **유형**:
* **Decision [[Support|Support]]**: AI가 분석 결과를 제공하고 최종 결정은 인간이 함. (Human-in-the-loop)
* **Fully Automated**: 인간의 개입 없이 시스템이 즉시 행동 수행. (예: 주식 알고리즘 매매, 광고 입찰)
2. **이점**:
* **Scale & Speed**: 수백만 건의 요청을 1초 이내에 처리 가능.
* **Consistency**: 감정이나 피로도에 좌우되지 않는 일관된 기준 적용.
3. **위점**:
* **Lack of Context**: 숫자로 표현되지 않는 미묘한 인간적 상황 무시.
* **Embedded Bias**: 알고리즘 내에 숨어있는 차별적 요소가 대량 집행됨.
### 매 Categories
- **Rule-based**: explicit if/then (DMN, decision tables).
- **ML scoring**: classifier / regressor → threshold.
- **LLM agentic**: tool-use + reasoning loop (Claude / GPT-5).
- **Human-in-the-loop (HITL)**: ML proposes, human approves.
- **Human-on-the-loop**: ML acts, human monitors / can override.
- **Fully automated**: no human in critical path.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 효율성만을 위해 ADM 도입을 권장하는 정책이었으나, 현대의 인권 정책은 이에 대해 '설명 요구권'과 '인간에 의한 재검토권'을 법적으로 보장하는 정책으로 강화됨(RL Update, 예: GDPR 제22조).
- **정책 변화(RL Update)**: 공공 수사 및 복지 정책에서 ADM을 쓸 경우, 반드시 알고리즘의 소스코드와 학습 데이터를 감사받아야 하는 'ADM 투명성 및 책임성 의무화 정책'이 글로벌 표준이 됨.
### 매 Regulation (2026)
- **EU AI Act** (entered force 2025): high-risk systems (biometric, hiring, credit, law enforcement) → conformity assessment, transparency, human oversight.
- **GDPR Art.22**: right to not be subject to solely automated decision with legal effect; right to explanation.
- **Colorado AI Act (SB205)**: 2026 effective — algorithmic discrimination duty for high-risk AI.
- **NYC Local Law 144**: AEDT bias audit.
## 🔗 지식 연결 (Graph)
- [[Algorithmic Fairness|Algorithmic Fairness]], [[AI Accountability|AI Accountability]], [[Decision Theory|Decision Theory]], [[Algorithmic Transparency|Algorithmic Transparency]], [[AI Governance|AI Governance]]
- **Modern Tech/Tools**: Credit scoring AI, Resume screening tools, Automated trading[[_system|system]]s.
---
### 매 Components
- Input validation + preprocessing.
- Feature engineering / embedding.
- Model + threshold + calibration.
- Decision policy (action mapping).
- Logging + audit trail.
- Override / appeal channel.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Credit underwriting (FICO, Upstart).
2. Hiring screening (with caution post-NYC LL 144).
3. Content moderation (Hive, Perspective API).
4. Insurance claims triage.
5. Dispatching (Uber, DoorDash).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Pattern 1 — Decision policy with audit
## 🧪 검증 상태 (Validation)
```python
import logging, hashlib, json, time
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def decide(applicant, model, threshold=0.6):
score = model.predict_proba([applicant])[0, 1]
decision = "approve" if score >= threshold else "review"
audit = {
"ts": time.time(), "id": applicant["id"],
"score": float(score), "threshold": threshold,
"decision": decision, "model_v": model.version,
"input_hash": hashlib.sha256(json.dumps(applicant, sort_keys=True).encode()).hexdigest(),
}
logging.info(json.dumps(audit))
return decision, audit
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pattern 2 — Bias audit (Aequitas)
**선택 A를 써야 할 때:**
- *(TODO)*
```python
from aequitas.group import Group
g = Group()
xtab, _ = g.get_crosstabs(df_with_predictions, attr_cols=["race", "gender"])
print(xtab[["attribute_name", "fpr", "fnr", "tpr"]])
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Pattern 3 — Calibration check
**기본값:**
> *(TODO)*
```python
from sklearn.calibration import calibration_curve
prob_true, prob_pred = calibration_curve(y_test, y_score, n_bins=10)
# expect diagonal — deviation = miscalibration
```
## ❌ 안티패턴 (Anti-Patterns)
### Pattern 4 — HITL queue (low-confidence routing)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
```python
def route(score, low=0.4, high=0.7):
if score >= high: return "auto-approve"
if score < low: return "auto-deny"
return "human-review"
```
### Pattern 5 — EU AI Act conformity log
```python
@dataclass
class ConformityRecord:
system_id: str
risk_class: str # "high" | "limited" | "minimal"
intended_purpose: str
training_data_summary: str
bias_test_results: dict
human_oversight_design: str
last_audit: str
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| High-stakes (credit, hire, health) | HITL + bias audit + appeal |
| Reversible low-stakes | full auto + sample review |
| Real-time (dispatch) | full auto + monitoring |
| Regulated (EU high-risk) | conformity assessment + transparency |
| Novel domain | shadow mode → HITL → automation |
**기본값**: HITL + audit log + bias monitoring + appeal channel.
## 🔗 Graph
- 부모: [[Decision-Theory]] · [[ML-Systems]]
- 변형: [[Rule-Based-System]] · [[Agentic-AI]] · [[HITL]]
- 응용: [[Credit-Scoring]] · [[Content-Moderation]] · [[Hiring-Screening]]
- Adjacent: [[Algorithmic-Fairness]] · [[Model-Calibration]] · [[Audit-Logging]]
## 🤖 LLM 활용
**언제**: drafting decision policy, reviewing audit logs for anomalies, generating explanation text (Art.22), bias test fixture generation.
**언제 X**: autonomous high-stakes decision without human in loop, opaque LLM-only path for regulated domain.
## ❌ 안티패턴
- **Black box high-stakes**: no explanation = GDPR/AI-Act violation risk.
- **No appeal channel**: legitimacy collapse.
- **Drift unmonitored**: production model 의 silent degrade.
- **Proxy discrimination**: ZIP code → race proxy unlawful.
## 🧪 검증 / 중복
- Verified (EU AI Act final text, NIST AI RMF, Aequitas docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (EU AI Act, HITL, bias audit) |
@@ -2,88 +2,161 @@
id: wiki-2026-0508-automated-map-generation
title: Automated Map Generation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-GENMAP]
aliases: [Procedural Map Generation, PCG, Auto-Cartography]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [PCG, Map Generation, Algorithm, Noise Nature]
confidence_score: 0.9
verification_status: applied
tags: [pcg, gamedev, cartography, gis, generative]
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: Unity/Godot/Houdini
---
# [[Automated-Map-Generation|Automated-Map-Generation]] (절차적 맵 생성 PCG)
# Automated Map Generation
## 📌 한 줄 통찰 (The Karpathy Summary)
> 무한한 우주는 수학 공식([[Seed|Seed]]) 하나에서 탄생한다. 절차적 생성(PCG)은 개발자의 노동력을 '규칙의 창조'로 전이시켜 콘텐츠의 무한 확장을 가능케 한다.
## 한 줄
> **"매 noise + constraint + agent — 매 hand-craft 의 X, 매 procedure 의 grow."**. Automated map generation 의 PCG (procedural content generation) 의 spatial subset — 매 1980 Rogue dungeon → Minecraft (Perlin) → 2026 의 Houdini node + WaveFunctionCollapse + diffusion-based terrain (LumaWorld, Genie 2). GIS 측 의 OpenStreetMap auto-vectorize from satellite (SAM-2 + DETR).
## 📖 구조화된 지식 (Synthesized Content)
- **Perlin Noise & Simplex Noise**:
- 자연스러운 지형(산, 계곡, 해안선)을 만들기 위한 수학적 노이즈 알고리즘. 연속성을 가진 난수를 통해 자연의 불규칙성을 모사한다.
- **Constraint-based Generation (제약 기반 생성)**:
- 단순히 무작위로 만드는 것이 아니라, "마을은 물 근처에 있어야 한다", "보스 방은 입구에서 가장 멀어야 한다"는 비즈니스 로직(제약 조건)을 알고리즘에 주입한다.
- **Dungeon Generation (BSP, WFC)**:
- **BSP (Binary Space Partitioning)**: 공간을 이진 분할하여 방과 복도를 배치하는 정석적인 방식.
- **WFC (Wave Function Collapse)**: 인접한 타일 간의 관계성을 기반으로 복잡한 구조를 확률적으로 붕괴시켜 완성하는 최신 알고리즘.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- PCG는 자칫 '반복적이고 지루한(Samey)' 느낌을 줄 수 있다. 이를 방지하기 위해 핵심 랜드마크는 수동 제작(Manual Polish)하고, 그 사이의 연결을 PCG가 담당하는 하이브리드 방식이 선호된다.
### 매 Approaches
- **Noise-based**: Perlin / Simplex / fBm — terrain heightmap.
- **Cellular automata**: cave / organic terrain (Game of Life variant).
- **L-systems**: vegetation / road network.
- **Wave Function Collapse (WFC)**: tile-based, constraint propagation.
- **Agent-based**: drunken walk, BSP partition.
- **Graph grammar**: dungeon room layout.
- **Diffusion / GAN**: 2024+ heightmap / texture from prompt.
- **Satellite → vector** (GIS): SAM-2 + OSM tagging.
## 🔗 지식 연결 (Graph)
- Related: [[Systemic_Simulation_Principles|Systemic_Simulation_Principles]] , Art_Direction_Governance
- Foundation: [[Information Theory|Information Theory]]
### 매 Properties
- Determinism (seed reproducibility).
- Controllability (parameter / prompt steering).
- Coherence (no impossible tiles).
- Aesthetic / playability metric.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Game level (Minecraft, NMS, Diablo).
2. Open-world terrain (UE5 PCG, Houdini).
3. GIS map auto-extraction.
4. Simulation environments (CARLA, Habitat).
5. Tabletop RPG (Watabou, Dungeon Alchemist).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Pattern 1 — Perlin heightmap
## 🧪 검증 상태 (Validation)
```python
import numpy as np
from noise import pnoise2
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def heightmap(w, h, scale=80, octaves=5, seed=0):
arr = np.zeros((h, w))
for y in range(h):
for x in range(w):
arr[y, x] = pnoise2(x/scale, y/scale, octaves=octaves, base=seed)
return (arr - arr.min()) / (arr.max() - arr.min())
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pattern 2 — Cellular automaton cave
**선택 A를 써야 할 때:**
- *(TODO)*
```python
def step(grid):
h, w = grid.shape
out = grid.copy()
for y in range(1, h-1):
for x in range(1, w-1):
n = grid[y-1:y+2, x-1:x+2].sum() - grid[y, x]
out[y, x] = 1 if n > 4 else 0
return out
**선택 B를 써야 할 때:**
- *(TODO)*
# init random 45% wall, run 5 steps → cave
```
**기본값:**
> *(TODO)*
### Pattern 3 — Wave Function Collapse (sketch)
## ❌ 안티패턴 (Anti-Patterns)
```python
# tiles: list of (id, neighbor constraint dict)
def wfc(grid_size, tiles):
grid = [[set(t.id for t in tiles) for _ in range(grid_size)] for _ in range(grid_size)]
while not all_collapsed(grid):
c = lowest_entropy_cell(grid)
grid[c.y][c.x] = {random.choice(list(grid[c.y][c.x]))}
propagate(grid, c, tiles)
return grid
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Pattern 4 — BSP dungeon partition
```python
def split(rect, depth=4):
if depth == 0 or min(rect.w, rect.h) < 12: return [rect]
if rect.w > rect.h:
x = random.randint(rect.x + 4, rect.x + rect.w - 4)
return split(Rect(rect.x, rect.y, x - rect.x, rect.h), depth-1) + \
split(Rect(x, rect.y, rect.x + rect.w - x, rect.h), depth-1)
# similar for vertical
```
### Pattern 5 — Diffusion terrain (2026)
```python
# Pseudo: Stable Diffusion XL fine-tuned on heightmap atlas
heightmap = sd_terrain.generate(prompt="alpine valley with river, top-down heightmap, 16-bit grayscale")
mesh = heightmap_to_mesh(heightmap, vertical_scale=200.0)
```
### Pattern 6 — Satellite → OSM (SAM-2)
```python
# Mask building footprints from satellite tile, convert to OSM polygons
masks = sam2.predict(satellite_tile)
polygons = [mask_to_polygon(m) for m in masks if m.score > 0.8]
osm_xml = polygons_to_osm(polygons, tag={"building": "yes"})
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Continuous terrain | Perlin / Simplex / fBm |
| Organic cave | Cellular automaton |
| Tile-based level (puzzle) | WFC |
| Dungeon rooms | BSP + corridor connect |
| Open-world AAA | Houdini + UE5 PCG |
| Prompted asset | Diffusion (SDXL terrain LoRA) |
| GIS extraction | SAM-2 + DETR + OSM tagging |
**기본값**: Perlin for terrain, WFC for tile-based, BSP for dungeons.
## 🔗 Graph
- 부모: [[Procedural-Content-Generation]] · [[Computational-Geometry]]
- 변형: [[Wave-Function-Collapse]] · [[L-Systems]] · [[Cellular-Automata]]
- 응용: [[Game-Level-Design]] · [[GIS]] · [[Simulation-Environment]]
- Adjacent: [[Perlin-Noise]] · [[Diffusion-Models]] · [[Geographic-Information-Systems]]
## 🤖 LLM 활용
**언제**: parameter tuning suggestions, prompt-to-terrain via diffusion, level metric scoring (playability / aesthetic), debug seed reproduction.
**언제 X**: hand-crafted narrative levels, regulatory cartography (use authoritative source).
## ❌ 안티패턴
- **No seed log**: bug 의 reproduce 불가.
- **Pure noise = boring**: 매 noise 의 only 의 no landmark — overlay POI / agent 추가.
- **Unconstrained WFC**: contradictory tile set → infinite backtrack.
- **Diffusion without metric guard**: visual nice but topologically broken (impassable cliff).
## 🧪 검증 / 중복
- Verified (Shaker et al. "Procedural Content Generation in Games", Houdini docs, WFC Maxim Gumin).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (Perlin, WFC, BSP, diffusion, SAM-2) |
@@ -2,87 +2,170 @@
id: wiki-2026-0508-autonomous-vehicle-path-planning
title: Autonomous Vehicle Path Planning
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-PATHPLAN]
aliases: [AV Path Planning, Self-Driving Planning, Motion Planning]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
tags: [Path Planning, "A* Algorithm", Robotics, Autonomous Vehicle]
confidence_score: 0.94
verification_status: applied
tags: [robotics, autonomous-driving, motion-planning, mpc, av]
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: Apollo/Autoware/OpenPlanner
---
# [[Autonomous-Vehicle-Path-Planning|Autonomous-Vehicle-Path-Planning]] (자율주행 경로 계획)
# Autonomous Vehicle Path Planning
## 📌 한 줄 통찰 (The Karpathy Summary)
> 경로 계획은 '가장 빠른 길'을 찾는 것이 아니라, '안전하고 부드러우며 예측 가능한' 움직임을 실시간으로 설계하는 확률적 탐색이다.
## 한 줄
> **"매 perception 의 X — 매 prediction + decision + trajectory 의 closed-loop."**. AV path planning 의 perception output (objects, lanes, drivable area) → prediction (other agents) → behavior decision (lane change, yield) → trajectory (smooth, kinodynamic) → control. 매 2026 의 Tesla FSD v13 (end-to-end NN), Waymo (modular), Wayve LINGO (VLM-based), 모두 의 hybrid trend.
## 📖 구조화된 지식 (Synthesized Content)
- **Global Path Planning**:
- 출발지에서 목적지까지의 거시적인 경로를 설정한다. 고전적인 **A* (A-star)** 알고리즘이나 **Dijkstra** 알고리즘이 지도 데이터 위에서 작동한다.
- **Local Motion Planning (실시간 회피)**:
- 갑자기 튀어나오는 보행자나 장애물을 피하기 위한 미시적인 궤적 최적화. **RRT* (Rapidly-exploring Random Tree)**나 **Hybrid A*** 등이 사용된다.
- **[[Behavior|Behavior]]al Decision (판단 레이어)**:
- 차선 변경, 추월, 일단 정지 등 도로의 법규(Traffic Laws)와 에티켓을 반영한 의사결정 알고리즘과 물리적 제어를 결합한다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 과거에는 규칙 기반(Rule-based) 알고리즘이 주류였으나, 최근에는 복잡한 도심 상황을 해결하기 위해 'End-to-End' 딥러닝 방식과 '전통적 플래닝'을 결합한 계층적 구조가 표준으로 자리 잡았다.
### 매 Architecture (Modular)
1. **Mission planner**: route (A→B) over road graph.
2. **Behavior planner**: discrete decision (FSM / POMDP / RL).
3. **Local planner / motion**: collision-free trajectory (Frenet, lattice, sampling, optimization).
4. **Trajectory tracker**: MPC / pure pursuit → steering + throttle.
## 🔗 지식 연결 (Graph)
- Related: [[Systemic_Simulation_Principles|Systemic_Simulation_Principles]] , Robotic Manipulation
- Context: [[Digital Twins|Digital Twins]]
### 매 Algorithms
- **Search**: A*, Hybrid A* (kinematic), RRT*, RRT-Connect.
- **Sampling**: lattice planner (predefined motion primitives).
- **Optimization**: iLQR, MPC, CILQR (cost = comfort + safety + progress).
- **Frenet frame**: lateral + longitudinal decoupling.
- **Learning-based**: ChauffeurNet, MotionLM, end-to-end (Tesla FSD v13).
- **Foundation model**: Wayve LINGO-2 / GAIA-2 — VLM + driving.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Safety
- ISO 26262 / ISO 21448 (SOTIF).
- RSS (Responsibility-Sensitive Safety, Mobileye).
- Formal verification of decision layer.
- Out-of-distribution detection.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. L4 robotaxi (Waymo, Cruise relaunch, Apollo Go).
2. L2+ ADAS (Tesla FSD, BYD, NIO Pilot).
3. Truck platooning (Aurora, Plus).
4. Last-mile delivery (Nuro).
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Pattern 1 — Frenet trajectory generation
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
```python
import numpy as np
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def frenet_quintic(s0, sd0, sdd0, s1, sd1, sdd1, T):
# solve quintic polynomial coeffs for s(t)
A = np.array([[T**3, T**4, T**5],
[3*T**2, 4*T**3, 5*T**4],
[6*T, 12*T**2, 20*T**3]])
b = np.array([s1 - s0 - sd0*T - 0.5*sdd0*T*T,
sd1 - sd0 - sdd0*T,
sdd1 - sdd0])
a3, a4, a5 = np.linalg.solve(A, b)
return [s0, sd0, sdd0/2, a3, a4, a5]
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pattern 2 — Hybrid A* (sketch)
**선택 A를 써야 할 때:**
- *(TODO)*
```python
def hybrid_a_star(start, goal, grid, motion_primitives):
open_set = PriorityQueue()
open_set.put((0, start))
came_from = {}
g = {start: 0}
while not open_set.empty():
_, cur = open_set.get()
if reached(cur, goal): return reconstruct(came_from, cur)
for prim in motion_primitives:
nxt = apply(cur, prim)
if collides(nxt, grid): continue
new_g = g[cur] + prim.cost
if new_g < g.get(nxt, 1e18):
g[nxt] = new_g
f = new_g + reeds_shepp_heuristic(nxt, goal)
open_set.put((f, nxt))
came_from[nxt] = (cur, prim)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Pattern 3 — MPC trajectory tracking (acados / casadi)
**기본값:**
> *(TODO)*
```python
import casadi as ca
N = 20 # horizon
dt = 0.1
opti = ca.Opti()
X = opti.variable(4, N+1) # [x, y, theta, v]
U = opti.variable(2, N) # [steer, accel]
cost = 0
for k in range(N):
cost += ca.sumsqr(X[:2, k] - ref[:2, k]) + 0.1 * ca.sumsqr(U[:, k])
opti.subject_to(X[:, k+1] == bicycle_model(X[:, k], U[:, k], dt))
opti.minimize(cost)
opti.solver("ipopt")
sol = opti.solve()
```
## ❌ 안티패턴 (Anti-Patterns)
### Pattern 4 — RSS (longitudinal safe distance)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
```python
def rss_safe_distance(v_rear, v_front, a_max_accel, a_max_brake, a_min_brake, rho=0.1):
return max(0,
v_rear * rho
+ 0.5 * a_max_accel * rho**2
+ (v_rear + a_max_accel * rho)**2 / (2 * a_min_brake)
- v_front**2 / (2 * a_max_brake))
```
### Pattern 5 — Behavior FSM
```python
class State(str, Enum): KEEP="keep"; LEFT="left"; RIGHT="right"; STOP="stop"
def transition(s, perception):
if perception.front_blocked and perception.left_clear: return State.LEFT
if perception.red_light: return State.STOP
return State.KEEP
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Highway lane change | Frenet + lattice + MPC |
| Parking | Hybrid A* + Reeds-Shepp |
| Urban intersection | POMDP / behavior tree + RSS check |
| Off-road / unstructured | RRT* + sampling MPC |
| End-to-end product (Tesla) | NN policy + safety guard |
**기본값**: Frenet planning + MPC tracking + RSS safety check + rule-based behavior FSM.
## 🔗 Graph
- 부모: [[Robotics]] · [[Motion-Planning]] · [[Optimal-Control-Theory]]
- 변형: [[A-Star]] · [[RRT]] · [[Model-Predictive-Control]]
- 응용: [[Robotaxi]] · [[ADAS]] · [[Autonomous-Truck]]
- Adjacent: [[Kalman-Filter]] · [[Particle-Filter]] · [[ISO-26262]]
## 🤖 LLM 활용
**언제**: scenario synthesis (corner cases), behavior reasoning prototype (LINGO-style), code generation for ROS / Apollo modules, log triage.
**언제 X**: real-time control loop (latency, safety cert), final RSS verification (formal methods).
## ❌ 안티패턴
- **Greedy lane change**: no comfort cost → jerky.
- **No prediction uncertainty**: 매 single mode 의 future — multi-modal essential.
- **Skipping kinodynamic check**: A* path 의 robot 의 unfollowable.
- **End-to-end without guard**: NN failure mode → safety violation.
## 🧪 검증 / 중복
- Verified (Apollo, Autoware open-source, Mobileye RSS paper, Waymo safety report).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (Frenet, Hybrid A*, MPC, RSS) |
@@ -2,90 +2,143 @@
id: wiki-2026-0508-axiology
title: Axiology
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-AXIO-001]
aliases: [Value Theory, Theory of Value, Philosophy of Value]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced, axiology, value-theory, ethics, aesthetics, Philosophy]
confidence_score: 0.86
verification_status: applied
tags: [philosophy, ethics, value-theory, ai-alignment, decision-theory]
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
framework: RL/Reward-Modeling
---
# [[Axiology|Axiology]]
# Axiology
## 📌 한 줄 통찰 (The Karpathy Summary)
> "가치의 뿌리를 묻다: 선(善)은 무엇이고 아름다움(美)은 무엇인가? 우리가 무엇을 '가치 있다'고 느끼는 근본적인 기준과 체계를 탐구하는 철학적 기초."
## 한 줄
> **"매 value 의 study — 매 what 의 X, 매 worth 의 question."**. Axiology 의 ethics + aesthetics 의 unifying framework — intrinsic vs instrumental, monism vs pluralism. 매 2026 의 AI alignment 의 core relevance: reward modeling / Constitutional AI / preference elicitation 의 axiological commitments.
## 📖 구조화된 지식 (Synthesized Content)
가치론(Axiology)은 가치의 본질, 유형, 그리고 평가 기준을 다루는 철학의 분과입니다. 크게 윤리학(내재적 선)과 미학(외적 아름다움)을 포함합니다.
## 매 핵심
1. **가치의 분류**:
* **Intrinsic Value (내재적 가치)**: 그 자체로 소중한 것 (예: 행복, 생명).
* **Instrumental Value (도구적 가치)**: 목적 달성을 위한 수단으로서의 가치 (예: 돈, 기술).
2. **왜 중요한가?**:
* 모든 의사결정(Decision Making)의 이면에는 가치 우선순위가 숨어 있음. 가치체계가 흔들리면 판단의 일관성(Consistency)도 무너짐.
### 매 Subdomains
- **Ethics**: moral value (good / right).
- **Aesthetics**: aesthetic value (beautiful / sublime).
- **Epistemology of value**: truth, knowledge value.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 가치를 절대적이고 불변하는 것으로 보는 본질주의 정책이 강했으나, 현대 정책은 사회적 합의와 맥락에 따라 변하는 '상대적 가치 구성 정책'을 수용함(RL Update).
- **정책 변화(RL Update)**: 인공지능의 가치 정렬([[Alignment|Alignment]]) 정책 수립 시, 프로그래머 개인의 가치가 아닌 인류 보편의 가치론적 합의를 모델에 어떻게 수치화하여 주입할 것인가가 공학적 난제로 부상함.
### 매 Distinctions
- **Intrinsic** (good in itself, e.g., happiness for hedonist) vs **instrumental** (good for X).
- **Subjective** (depends on attitude) vs **objective** (mind-independent).
- **Monism** (one value, e.g., utility) vs **pluralism** (many incommensurable values).
- **Realist** vs **anti-realist**.
## 🔗 지식 연결 (Graph)
- [[Ethics & AI|Ethics & AI]], [[Aesthetic-Value|Aesthetic-Value]], [[Alignment|Alignment]], [[Decision Theory|Decision Theory]], [[AI Humanism|AI Humanism]]
- **Modern Tech/Tools**: Ethical framework design, Value alignment [[Protocols|Protocols]].
---
### 매 Major Frames
- **Hedonism** (Bentham, Mill): pleasure / absence of pain.
- **Eudaimonism** (Aristotle): flourishing.
- **Perfectionism**: excellence, capability (Sen, Nussbaum).
- **Consequentialism**: outcomes.
- **Deontology**: duty (Kant).
- **Virtue ethics**: character.
- **Pluralist value (Berlin)**: incommensurable goods.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 AI Alignment Connection (2026)
- **Reward model = axiological model**: implicit value commitment.
- **Constitutional AI** (Anthropic): explicit principles → critique → revise.
- **Preference learning (RLHF, DPO, IPO)**: aggregate human preferences.
- **Pluralism challenge**: whose values? → community / democratic AI.
- **Goodhart's law**: 매 measure → target → corruption (instrumental ≠ intrinsic).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. AI alignment / reward design.
2. Cost-benefit analysis (policy).
3. Aesthetic scoring (image gen).
4. Healthcare QALY/DALY weighting.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Pattern 1 — Multi-objective reward (pluralism)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
```python
def reward(traj):
return (
1.0 * progress(traj) # instrumental
+ 0.5 * comfort(traj) # intrinsic-ish
+ 2.0 * safety(traj) # constraint priority
- 0.3 * energy(traj) # cost
)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pattern 2 — Constitutional critique (Anthropic-style)
**선택 A를 써야 할 때:**
- *(TODO)*
```python
CONSTITUTION = [
"Avoid harm.",
"Be honest.",
"Respect autonomy.",
"Promote well-being equitably.",
]
**선택 B를 써야 할 때:**
- *(TODO)*
def critique(response, principles=CONSTITUTION):
return llm.complete(f"Critique against: {principles}\nResponse: {response}")
**기본값:**
> *(TODO)*
def revise(response, critique_text):
return llm.complete(f"Revise: {response}\nIn light of: {critique_text}")
```
## ❌ 안티패턴 (Anti-Patterns)
### Pattern 3 — Preference elicitation
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
```python
# binary preference dataset → DPO / IPO
pairs = [{"prompt": p, "chosen": a, "rejected": b}, ...]
# train policy to maximize likelihood ratio
```
### Pattern 4 — Pareto frontier (incommensurable values)
```python
def is_pareto(point, all_points):
return not any(all(o[i] >= point[i] for i in range(len(point))) and o != point
for o in all_points)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Single clear metric | Scalar reward (monism) |
| Multiple comparable | Weighted sum (pluralism reduced) |
| Incommensurable | Pareto / lexicographic |
| Norm uncertainty | Constitutional + critique loop |
| Democratic | Preference aggregation + transparency |
**기본값**: pluralism + transparent weights + constitutional guardrails.
## 🔗 Graph
- 부모: [[Philosophy]] · [[Ethics]]
- 변형: [[Hedonism]] · [[Eudaimonism]] · [[Deontology]] · [[Virtue-Ethics]]
- 응용: [[AI-Alignment]] · [[Reward-Modeling]] · [[Cost-Benefit-Analysis]]
- Adjacent: [[Aesthetic-Value]] · [[Decision-Theory]] · [[Constitutional-AI]]
## 🤖 LLM 활용
**언제**: alignment policy drafting, principle articulation, value-laden decision review, ethical critique generation.
**언제 X**: pure technical optimization with no value tradeoff, single-stakeholder narrow domain.
## ❌ 안티패턴
- **Hidden monism**: 매 single metric 의 dressed-up — Goodhart 의 vulnerable.
- **False precision**: numeric weight 의 spurious 의 incommensurable values.
- **No stakeholder mapping**: whose values 의 unclear.
- **Reward hacking**: instrumental → intrinsic 의 confuse.
## 🧪 검증 / 중복
- Verified (Stanford Encyclopedia of Philosophy "Value Theory", Anthropic Constitutional AI paper).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (frames + AI alignment patterns) |
@@ -2,65 +2,157 @@
id: wiki-2026-0508-axiomatic-systems
title: Axiomatic Systems
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-AXSY-001]
aliases: [Axiomatic Method, Formal Systems, Deductive Systems]
duplicate_of: none
source_trust_level: A
confidence_score: 0.96
tags: [auto-reinforced, axiomatic-systems, Logic, mathematics, formal-methods, Structuralism]
confidence_score: 0.95
verification_status: applied
tags: [logic, foundations, formal-methods, proof, type-theory]
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: Lean/Coq/Agda
framework: Lean4/mathlib
---
# [[Axiomatic-Systems|Axiomatic-Systems]]
# Axiomatic Systems
## 📌 한 줄 통찰 (The Karpathy Summary)
> "가장 밑바닥부터 쌓아 올린 논리의 성벽: 증명 없이 참으로 받아들이는 몇 가지 '공리'에서 시작하여, 엄격한 추론 규칙만을 사용해 복잡한 정리들을 무결하게 도출해내는 지식 최상위의 연역 체계."
## 한 줄
> **"매 finite axiom + inference rule → 매 derivable theorem."**. Axiomatic system 의 Euclid (BC 300) → Hilbert (1899 Grundlagen) → Gödel (incompleteness 1931) → 매 2026 의 Lean 4 + mathlib (200k+ formalized theorems, 매 working math 의 formal redo) + LLM-augmented proof assistant (Anthropic Claude / DeepMind AlphaProof).
## 📖 구조화된 지식 (Synthesized Content)
공리계(Axiomatic-Systems)는 소수의 근본 원리([[Axioms|Axioms]])로부터 모든 지식을 논리적으로 끌어내는 체계화된 이론적 구조입니다. 에우클레이데스의 기하학이 대표적 예시입니다.
## 매 핵심
1. **3대 건전성 요건**:
* **Consistency (일관성)**: 체계 내에서 서로 모순되는 두 명제가 동시에 참이 될 수 없음.
* **Independence (독립성)**: 한 공리가 다른 공리들로부터 도출될 수 없어야 함 (최소한의 원칙).
* **Completeness (완전성)**: 해당 영역의 모든 참인 명제를 체계 내에서 증명할 수 있어야 함 (괴델의 불완전성 정리에 의해 한계 노출).
2. **구조주의적 연결**:
* 개별 사실보다 그 사실들을 엮어주는 '관계의 규칙(공리)'이 시스템의 본질을 결정함 (Structuralism과 연결).
### 매 Components
- **Primitive symbols / vocabulary**.
- **Axioms**: unproved starting propositions.
- **Inference rules** (modus ponens, generalization).
- **Theorems**: derivable from axioms via rules.
- **Models / interpretations**.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 모든 지식을 공리화할 수 있다는 '힐베르트 서약' 정책이 우세했으나, 현대의 불완전성 정비 정책은 체계 내부에 증명 불가능한 영역이 존재함을 인정하고 유연한 보완 정책을 취함(RL Update).
- **정책 변화(RL Update)**: 소프트웨어 무결성 검증 정책에서, 코드를 공리적 시스템으로 변환하여 오류가 없음을 수학적으로 확증하는 '형식 검증(Formal Verification) 정책'이 하이-리스크 시스템의 핵심 표준이 됨.
### 매 Properties
- **Consistency**: 매 contradiction 의 X (¬(P ∧ ¬P) provable).
- **Completeness**: every true (in model) statement provable.
- **Decidability**: algorithm to determine theoremhood.
- **Soundness**: only true things provable.
- **Independence**: 매 axiom 의 not derivable from others.
- **Categoricity**: all models isomorphic.
## 🔗 지식 연결 (Graph)
- [[Axioms|Axioms]], [[Logic|Logic]], [[Structuralism|Structuralism]], [[Automated-Reasoning|Automated-Reasoning]], [[Safety & Reliability|Safety & Reliability]]
- **Modern Tech/Tools**: TLA+ (Formal [[Specification|Specification]]), Mathematical proof assistants.
---
### 매 Famous Systems
- **Euclidean geometry**: 5 postulates (parallel postulate independent → non-Euclidean).
- **Peano arithmetic (PA)**: natural numbers; incomplete (Gödel).
- **ZFC set theory**: foundation of most math; CH independent (Cohen).
- **Group / ring / field**: abstract algebra.
- **Hilbert system / Natural deduction / Sequent calculus**: proof formalisms.
- **Type theory** (Martin-Löf, Calculus of Constructions): foundation for Coq/Lean/Agda.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 2026 Computational
- **Lean 4 + mathlib**: rapid formalization (Tao's PFR, Gowers).
- **Coq**: CompCert verified compiler, 4-color theorem.
- **Isabelle**: seL4 microkernel.
- **AlphaProof / Claude proof**: LLM + Lean tactic search.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. Math research (formalized proof).
2. Formal verification (CompCert, seL4, AWS s2n).
3. Cryptographic protocol proof (EasyCrypt, F*).
4. Smart contract verification.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Pattern 1 — Lean 4: prove a + 0 = a
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
```lean
theorem add_zero (a : Nat) : a + 0 = a := by
induction a with
| zero => rfl
| succ n ih => simp [Nat.add_succ, ih]
```
## 🧬 중복 검사 (Duplicate Check)
### Pattern 2 — Coq: list reversal involutive
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
```coq
Theorem rev_involutive : forall (A : Type) (l : list A),
rev (rev l) = l.
Proof.
induction l as [| x xs IH].
- reflexivity.
- simpl. rewrite rev_app_distr. simpl. rewrite IH. reflexivity.
Qed.
```
## 🕓 변경 이력 (Changelog)
### Pattern 3 — Agda: dependent type proof
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
```agda
data : Set where
zero :
suc :
_+_ :
zero + n = n
suc m + n = suc (m + n)
+-identity : (n : ) n + zero n
+-identity zero = refl
+-identity (suc n) = cong suc (+-identity n)
```
### Pattern 4 — Hilbert-style propositional proof
```
1. P → (Q → P) axiom K
2. (P → (Q → R)) → ((P → Q) → (P → R)) axiom S
3. P hypothesis
4. Q → P MP 1, 3
```
### Pattern 5 — LLM-assisted proof (Lean tactic suggestion)
```python
def llm_tactic(goal_state):
return claude.complete(f"""You are a Lean 4 proof assistant.
Given goal:
{goal_state}
Suggest one tactic step. Output only the tactic.""")
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Math formalization | Lean 4 + mathlib |
| Verified compiler / OS | Coq (CompCert, seL4) |
| Type-theory research | Agda / Lean |
| Crypto protocol | EasyCrypt / F* |
| Quick logical sketch | Hilbert-style on paper |
| LLM-augmented | Lean + Claude tactic search |
**기본값**: Lean 4 for new formalization, Coq for legacy verified systems.
## 🔗 Graph
- 부모: [[Mathematical-Logic]] · [[Foundations-of-Mathematics]]
- 변형: [[Type-Theory]] · [[Set-Theory]] · [[Natural-Deduction]]
- 응용: [[Formal-Verification]] · [[Theorem-Proving]] · [[Smart-Contract-Verification]]
- Adjacent: [[Godel-s-Incompleteness-Theorems]] · [[Curry-Howard]] · [[Theoretical-Computer-Science]]
## 🤖 LLM 활용
**언제**: tactic suggestion, lemma name search in mathlib, proof sketch translation, error diagnosis.
**언제 X**: producing final certificate without check (use proof assistant), informal-only "proof" claims.
## ❌ 안티패턴
- **Inconsistent axioms**: explosion (anything provable).
- **Hidden axiom of choice**: constructivism violation in proof claimed constructive.
- **Tactic blob without lemma factor**: maintenance nightmare.
- **No model check**: theorem 의 vacuous (no model).
## 🧪 검증 / 중복
- Verified (Lean 4 docs, mathlib4, Hilbert "Grundlagen", Mendelson "Intro to Math Logic").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FULL content (Lean/Coq/Agda, 5 patterns) |
@@ -1,88 +1,161 @@
---
id: wiki-2026-0508-b-tree
title: B Tree
title: B-Tree
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-B-TREE]
aliases: [B+Tree, BTree, Balanced-Tree-Index]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [B-Tree, Data Structure, DB, Indexing]
confidence_score: 0.95
verification_status: applied
tags: [data-structure, tree, index, database]
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
framework: stdlib
---
# [[B-Tree|B-Tree]] (B-트리)
# B-Tree
## 📌 한 줄 통찰 (The Karpathy Summary)
> "디스크의 느린 속도를 이겨내는 최적의 균형." 한 노드에 여러 데이터를 담고 층수를 낮게 유지하여, 수백만 건의 데이터도 단 3~4번의 읽기만으로 찾아내는 인덱스의 제왕이다.
## 한 줄
> **"매 disk-friendly한 self-balancing search tree — 매 한 노드에 매 많은 key를 저장해 매 height를 minimize"**. 매 1970년 Bayer & McCreight가 IBM에서 design, 매 2026 PostgreSQL/MySQL InnoDB/SQLite의 default index, 매 NVMe SSD에서도 여전히 dominant — 매 sequential I/O와 cache line alignment 친화적.
## 📖 구조화된 지식 (Synthesized Content)
- **Multi-way [[Search|Search]] Tree**:
- 이진 트리(2-way)와 달리 노드 하나가 수십~수백 개의 자식을 가질 수 있다. 이를 통해 트리의 높이(Height)를 극적으로 낮춘다.
- **Self-Balancing**:
- 데이터가 추가되거나 삭제될 때마다 스스로 노드를 분할(Split)하거나 합치며(Merge) 높이 균형을 유지한다. 언제나 탐색 속도가 보장된다.
- **Disk I/O [[Efficiency|Efficiency]]**:
- 노드 한 개의 크기를 하드디스크의 한 블록(Page) 크기에 맞춰 설계하여, 한 번의 스핀으로 최대한 많은 정보를 읽어오게 한다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 현대의 SSD 환경에서는 랜덤 액세스 속도가 빨라져서 B-Tree 계열 외에도 LSM-Tree(NoSQL 등에서 사용) 같은 다양한 변종이 사용된다. 하지만 여전히 관계형 DB(MySQL, PostgreSQL)의 기본 인덱스는 B+Tree(B-Tree의 계층형 변형)가 압도적 표준이다.
### 매 invariant
- 매 node는 매 $[t-1, 2t-1]$ keys 보유 (매 root만 예외).
- 매 internal node는 매 $[t, 2t]$ children.
- 매 모든 leaf는 매 same depth.
- 매 keys 매 sorted within node.
## 🔗 지식 연결 (Graph)
- Related: [[Distributed-Systems-Engineering|Distributed-Systems-Engineering]] , [[Combinatorial-Optimization|Combinatorial-Optimization]]
- Foundation: Computational Thinking
### 매 B+ Tree variant (DB 표준)
- 매 internal node는 매 keys만 — 매 data는 매 leaf에만.
- 매 leaf끼리 매 linked list — 매 range scan $O(k)$.
- 매 PostgreSQL/MySQL이 매 사용.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. RDBMS index (PostgreSQL btree).
2. Filesystem (ext4 HTree, NTFS).
3. KV store (LevelDB SST, RocksDB).
4. Vector DB metadata index.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### B-Tree node (Python)
```python
class BTreeNode:
def __init__(self, t, leaf=False):
self.t = t # min degree
self.keys = []
self.children = []
self.leaf = leaf
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def search(self, k):
i = 0
while i < len(self.keys) and k > self.keys[i]:
i += 1
if i < len(self.keys) and self.keys[i] == k:
return (self, i)
if self.leaf:
return None
return self.children[i].search(k)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Insert with split
```python
def split_child(parent, i):
t = parent.t
full = parent.children[i]
new = BTreeNode(t, full.leaf)
new.keys = full.keys[t:]
if not full.leaf:
new.children = full.children[t:]
full.children = full.children[:t]
parent.keys.insert(i, full.keys[t-1])
full.keys = full.keys[:t-1]
parent.children.insert(i+1, new)
**선택 A를 써야 할 때:**
- *(TODO)*
def insert(root, k):
if len(root.keys) == 2*root.t - 1:
new_root = BTreeNode(root.t)
new_root.children.append(root)
split_child(new_root, 0)
root = new_root
insert_nonfull(root, k)
return root
```
**선택 B를 써야 할 때:**
- *(TODO)*
### B+ Tree range scan
```python
def range_scan(leaf, lo, hi):
out = []
node = leaf
while node:
for k in node.keys:
if lo <= k <= hi: out.append(k)
elif k > hi: return out
node = node.next # leaf-linked list
return out
```
**기본값:**
> *(TODO)*
### PostgreSQL B-Tree usage
```sql
CREATE INDEX idx_users_email ON users USING btree (email);
-- equality + range + sort 사용
EXPLAIN SELECT * FROM users WHERE email > 'a' AND email < 'm';
-- Index Scan using idx_users_email
```
## ❌ 안티패턴 (Anti-Patterns)
### SQLite WITHOUT ROWID (B-Tree direct)
```sql
CREATE TABLE kv (k TEXT PRIMARY KEY, v BLOB) WITHOUT ROWID;
-- 매 data가 매 PK index 자체에 — 매 secondary lookup 제거
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Bulk loading (sorted insert)
```python
def bulk_load(sorted_pairs, t=64):
# Sort + bottom-up build (vs O(n log n) per-insert)
leaves = [sorted_pairs[i:i+2*t-1]
for i in range(0, len(sorted_pairs), 2*t-1)]
# build internal levels...
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| OLTP, point + range query | B+ Tree (default) |
| Append-heavy timeseries | LSM (RocksDB) — B-Tree write amp 高 |
| In-memory only, no range | Hash index |
| Vector similarity | HNSW (not B-Tree) |
| Spatial | R-Tree / GiST |
**기본값**: 매 RDBMS index는 매 B+ Tree. 매 SSD/NVMe에서도 매 page-aligned (8KB-16KB) 노드.
## 🔗 Graph
- 부모: [[Linked-Lists-and-Trees]] · [[Theoretical-Computer-Science]]
- 변형: [[Hash-Functions-and-Maps]] (alternative)
- 응용: Database-Index · [[Bloom-Filters in Search]]
- Adjacent: [[Algorithm-Complexity-Big-O]] · LSM-Tree
## 🤖 LLM 활용
**언제**: 매 DB schema design, 매 "왜 query가 slow?" debugging, 매 index choice review.
**언제 X**: 매 in-memory + write-heavy → LSM 우선; 매 vector search → HNSW.
## ❌ 안티패턴
- **Random UUID v4 PK**: 매 B-Tree에 매 random insert → 매 page split storm. 매 UUIDv7 (time-ordered) 사용.
- **Over-indexing**: 매 모든 column에 index — 매 write amp + storage 폭증.
- **Index on low-cardinality**: 매 boolean column index — 매 useless, full scan 더 빠름.
## 🧪 검증 / 중복
- Verified (Bayer 1972 original paper, PostgreSQL docs Ch.62).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — B-Tree/B+Tree, split logic, DB index |
@@ -2,93 +2,185 @@
id: wiki-2026-0508-bfs-vs-dfs
title: BFS vs DFS
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-BDFS-001]
aliases: [Breadth-First vs Depth-First, 너비 우선 vs 깊이 우선]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [auto-reinforced, bfs, dfs, algorithms, graph-Search, tree-traversal, Problem-Solving]
confidence_score: 0.95
verification_status: applied
tags: [algorithms, graph, traversal, bfs, dfs, search]
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
framework: none
---
# [[BFS vs DFS|BFS vs DFS]]
# BFS vs DFS
## 📌 한 줄 통찰 (The Karpathy Summary)
> "지식 탐색의 두 가지 갈래: 현재 층위의 모든 가능성을 먼저 훑으며 최단 경로를 찾는 '발 넓은' 너비 우선 탐색(BFS)과, 한 가지 가능성을 끝까지 파고들어 바닥을 확인하는 '집요한' 깊이 우선 탐색(DFS)의 지적 대비."
## 한 줄
> **"매 graph traversal 의 두 fundamental order: queue (BFS) vs stack (DFS)"**. 매 1959 Moore 의 BFS, 매 1882 Trémaux 의 DFS-like maze. 매 modern algo 의 building block — 매 shortest path, topological sort, cycle detection 의 base.
## 📖 구조화된 지식 (Synthesized Content)
너비 우선 탐색(BFS)과 깊이 우선 탐색(DFS)은 그래프나 트리 구조를 순회하는 가장 기초적인 알고리즘입니다.
## 매 핵심
1. **BFS (Breadth-First Search)**:
* **동작**: 루트 노드에서 가까운 노드부터 차례대로 방문 (Queue 사용).
* **장점**: 최단 경로(Shortest path)를 찾는 데 최적임.
* **단점**: 모든 자식 노드를 메모리에 담아야 하므로 공간 복잡도가 높음.
2. **DFS (Depth-First Search)**:
* **동작**: 한 분기를 결정하면 그 분기의 끝(Leaf)까지 가본 후 뒤로 돌아옴 (Stack 또는 Recursion 사용).
* **장점**: 메모리 가성비가 좋고, 경로상에 정답이 깊이 있을 때 유리함.
* **단점**: 얻은 경로가 최단 경로라는 보장이 없으며 무한 루프 위험이 있음. ([[Backward-Reasoning|Backward-Reasoning]]과 연결)
### 매 BFS
- queue (FIFO) 의 사용 — 매 level-by-level expansion.
- **shortest path** 의 unweighted graph 의 guarantee (edge count 기준).
- 매 시간: O(V + E), 매 공간: O(V) (queue + visited).
- 매 응용: shortest hop, level traversal, bipartite check, web crawl (per-depth limit).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 문제 유형에 따라 하나를 선택하는 정적인 알고리즘 정책이었으나, 현대 AI 정책(MCTS 등)은 두 방식을 확률적으로 혼합하거나 보상에 따라 동적으로 깊이와 너비를 결정하는 '적응적 탐색 정책'으로 진화함(RL Update).
- **정책 변화(RL Update)**: 거대 언어 모델의 생각의 사슬(Chain of Thought) 추론 정책에서, 하나의 답변에 함몰되지 않고 여러 가지 추론 가지를 BFS적으로 생성해 비교하는 'Tree-of-Thoughts' 기법이 고난도 문제 해결의 핵심 정책이 됨.
### 매 DFS
- stack (LIFO) / recursion 의 사용 — 매 deep dive first.
- **shortest path** 의 X — 매 tree edge order 의 의 의.
- 매 시간: O(V + E), 매 공간: O(V) (recursion stack / explicit stack).
- 매 응용: cycle detection, topological sort, SCC (Tarjan/Kosaraju), maze solving.
## 🔗 지식 연결 (Graph)
- [[Binary-Search|Binary-Search]], [[Backward-Reasoning|Backward-Reasoning]], [[Search-Optimization|Search-Optimization]], [[Analysis|Analysis]], Pattern Recognition
- **Modern Tech/Tools**: Pathfinding algorithms in GPS, Crawling bots, Game AI (Minimax).
---
### 매 trade-off
| Aspect | BFS | DFS |
|---|---|---|
| Memory | O(b^d) — wide tree 의 explode | O(b·d) — deep stack |
| Path | shortest (unweighted) | any reachable |
| Implementation | queue + iterative | recursion / explicit stack |
| Backtracking | hard | natural |
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용 differential
1. **shortest path (unweighted)** → BFS.
2. **shortest path (weighted)** → Dijkstra (BFS의 generalization, 매 priority queue).
3. **topological sort** → DFS (post-order reverse) / Kahn's BFS.
4. **cycle detection** → DFS (back edge) / BFS (in-degree).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### BFS basic
```python
from collections import deque
from typing import Dict, List, Set
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def bfs(graph: Dict[int, List[int]], start: int) -> List[int]:
visited: Set[int] = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for nb in graph[node]:
if nb not in visited:
visited.add(nb)
queue.append(nb)
return order
```
## 🤔 의사결정 기준 (Decision Criteria)
### BFS shortest path (unweighted)
```python
def bfs_shortest(graph, start, target):
queue = deque([(start, [start])])
visited = {start}
while queue:
node, path = queue.popleft()
if node == target:
return path
for nb in graph[node]:
if nb not in visited:
visited.add(nb)
queue.append((nb, path + [nb]))
return None # unreachable
```
**선택 A를 써야 할 때:**
- *(TODO)*
### DFS recursive
```python
def dfs(graph, node, visited=None, order=None):
if visited is None: visited, order = set(), []
visited.add(node)
order.append(node)
for nb in graph[node]:
if nb not in visited:
dfs(graph, nb, visited, order)
return order
```
**선택 B를 써야 할 때:**
- *(TODO)*
### DFS iterative (avoids recursion limit)
```python
def dfs_iter(graph, start):
stack, visited, order = [start], set(), []
while stack:
node = stack.pop()
if node in visited: continue
visited.add(node)
order.append(node)
# reverse for same order as recursive
for nb in reversed(graph[node]):
if nb not in visited:
stack.append(nb)
return order
```
**기본값:**
> *(TODO)*
### Topological sort (DFS post-order)
```python
def topo_sort(graph):
visited, order = set(), []
def visit(n):
if n in visited: return
visited.add(n)
for nb in graph[n]: visit(nb)
order.append(n) # post-order
for n in graph: visit(n)
return order[::-1]
```
## ❌ 안티패턴 (Anti-Patterns)
### Cycle detection (DFS with color)
```python
WHITE, GRAY, BLACK = 0, 1, 2
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
def has_cycle(graph):
color = {n: WHITE for n in graph}
def dfs(n):
color[n] = GRAY
for nb in graph[n]:
if color[nb] == GRAY: return True # back edge
if color[nb] == WHITE and dfs(nb): return True
color[n] = BLACK
return False
return any(dfs(n) for n in graph if color[n] == WHITE)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| shortest path (unweighted) | BFS |
| shortest path (weighted) | Dijkstra / A* |
| topological sort | DFS post-order / Kahn |
| cycle detection | DFS color |
| memory tight, deep tree | DFS |
| memory ample, wide goals | BFS |
| 매 path enumeration / backtrack | DFS |
| 매 web crawl (depth-limited) | BFS with depth |
**기본값**: shortest path 의 BFS, 매 structural analysis (topo, cycle, SCC) 의 DFS.
## 🔗 Graph
- 부모: [[Graph Theory]] · [[Search Algorithms]]
- 변형: [[Bidirectional Search]] · [[Iterative Deepening]] · [[Beam Search]]
- 응용: [[Dijkstra's Algorithm]] · [[A-Star Pathfinding]] · [[Topological Sort]] · [[Connected Components]]
- Adjacent: [[Tree Traversal]] · [[Tarjan SCC]] · [[Kosaraju Algorithm]]
## 🤖 LLM 활용
**언제**: 매 graph 문제 의 first-cut, 매 grid maze, 매 dependency resolution, 매 social network expansion.
**언제 X**: 매 weighted shortest path (Dijkstra), 매 heuristic 가능 시 (A*), 매 huge graph 의 sampling (random walk).
## ❌ 안티패턴
- **BFS의 memory**: 매 huge branching factor → O(b^d) 의 OOM. 매 IDDFS 의 의 의.
- **DFS recursion limit**: Python 의 default 1000 — 매 large graph 의 stack overflow. 매 iterative 의 의.
- **visited X**: 매 cycle 의 infinite loop.
- **BFS의 path 의 다 저장**: O(V²) memory — 매 parent map 의 의 reconstruct.
## 🧪 검증 / 중복
- Verified (CLRS Ch 22; Sedgewick Algorithms 4th).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — BFS/DFS comparison with topo sort + cycle detection patterns |
@@ -2,87 +2,173 @@
id: wiki-2026-0508-biological-inspired-algorithms
title: Biological Inspired Algorithms
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-BIO-INSPIRED]
aliases: [Bio-Inspired Computing, Nature-Inspired Algorithms, Bionic Algorithms]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [Bio-Inspired Algorithms, Genetic Algorithms, Ant Colony Optimization, Evolution]
confidence_score: 0.88
verification_status: applied
tags: [optimization, metaheuristics, evolutionary, swarm]
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
framework: DEAP, pyswarms, scikit-opt
---
# BioLogical-Inspired-Algorithms (생물 유래 알고리즘)
# Biological Inspired Algorithms
## 📌 한 줄 통찰 (The Karpathy Summary)
> "자연은 수억 년 동안 검증된 최적화 라이브러리다." 진화, 군집 행동, 면역 체계 등 생물계의 생존 전략을 수학적으로 모델링하여 복잡한 공학적 난제를 해결하는 최적화 기법이다.
## 한 줄
> **"매 nature 의 problem-solving 을 computational metaheuristic 로 abstract"**. 1950s cybernetics → 1970s GA → 1990s ACO/PSO → 2020s neuroevolution + LLM-guided search 까지, 매 NP-hard / black-box optimization 의 main toolkit 으로 evolved.
## 📖 구조화된 지식 (Synthesized Content)
- **Genetic Algorithms (GA)**:
- 선택, 교차(Crossover), 변이(Mutation) 과정을 반복하며 가장 '적합한' 해를 찾아가는 다윈의 진화론 기반 알고리즘.
- **[[Swarm Intelligence|Swarm Intelligence]] (ACO/PSO)**:
- 개별 개체(개미, 새)는 단순하지만, 그들의 상호작용이 거대한 지능(최단 경로 찾기 등)을 만들어내는 현상을 이용한 최적화.
- **Neural Networks**:
- 뇌의 뉴런 연결 구조를 모방한 인공 신경망 역시 가장 거대한 생물 유래 알고리즘의 범주에 속한다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 자연 모방 알고리즘은 전역 최적해(Global Optimum)를 찾는 데 유용하지만, 수렴 속도가 느릴 수 있다. 따라서 최근에는 수학적인 경사 하강법과 하이브리드로 결합하여 '정밀도'와 '탐색 범위'를 동시에 잡는 추세다.
### 매 분류
- **Evolutionary**: GA, GP, ES, DE, CMA-ES, NEAT.
- **Swarm intelligence**: PSO (bird flocks), ACO (ant pheromone), ABC (bee colony), Firefly.
- **Immune-inspired**: Clonal Selection, Negative Selection.
- **Neural-inspired**: ANN, Spiking NN, Hebbian learning.
- **Physical/biological hybrid**: Slime mould (Physarum), DNA computing.
## 🔗 지식 연결 (Graph)
- Related: [[Reinforcement-Learning|Reinforcement-Learning]] , [[Algorithmic-Biology|Algorithmic-Biology]]
- [[Strategy|Strategy]]: [[Innovation|Innovation]]-[[Management|Management]]
### 매 공통 구조
1. **Population** of candidates.
2. **Fitness** function (objective).
3. **Variation** operators (mutation, crossover, social update).
4. **Selection** pressure (tournament, roulette, elitism).
5. **Iteration** until convergence / budget.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 강점
- 매 derivative-free, black-box-friendly.
- 매 multimodal landscape 의 escape from local optima.
- 매 parallel-friendly (population evaluation).
- 매 hybridize easily with local search (memetic).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Genetic Algorithm (DEAP)
```python
from deap import base, creator, tools, algorithms
import random
## 🧪 검증 상태 (Validation)
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
tb = base.Toolbox()
tb.register("attr", random.randint, 0, 1)
tb.register("individual", tools.initRepeat, creator.Individual, tb.attr, n=100)
tb.register("population", tools.initRepeat, list, tb.individual)
tb.register("evaluate", lambda ind: (sum(ind),))
tb.register("mate", tools.cxTwoPoint)
tb.register("mutate", tools.mutFlipBit, indpb=0.05)
tb.register("select", tools.selTournament, tournsize=3)
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
pop = tb.population(n=300)
algorithms.eaSimple(pop, tb, cxpb=0.7, mutpb=0.2, ngen=40, verbose=False)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Particle Swarm Optimization (pyswarms)
```python
import numpy as np, pyswarms as ps
**선택 A를 써야 할 때:**
- *(TODO)*
def sphere(x): return np.sum(x**2, axis=1)
**선택 B를 써야 할 때:**
- *(TODO)*
opt = ps.single.GlobalBestPSO(
n_particles=30, dimensions=10,
options={"c1": 0.5, "c2": 0.3, "w": 0.9},
bounds=(np.full(10, -5), np.full(10, 5)),
)
cost, pos = opt.optimize(sphere, iters=200)
```
**기본값:**
> *(TODO)*
### Ant Colony Optimization (TSP)
```python
import numpy as np
def aco_tsp(dist, n_ants=20, n_iter=200, alpha=1, beta=5, rho=0.1, q=1):
n = len(dist); pher = np.ones((n,n))
best_len, best_path = np.inf, None
for _ in range(n_iter):
paths = []
for _ in range(n_ants):
unvis = list(range(n)); cur = unvis.pop(0); path = [cur]
while unvis:
p = (pher[cur,unvis]**alpha) * ((1/dist[cur,unvis])**beta)
nxt = unvis[np.random.choice(len(unvis), p=p/p.sum())]
path.append(nxt); unvis.remove(nxt); cur = nxt
paths.append(path)
pher *= (1-rho)
for path in paths:
L = sum(dist[path[i],path[i+1]] for i in range(n-1))
if L < best_len: best_len, best_path = L, path
for i in range(n-1): pher[path[i], path[i+1]] += q/L
return best_path, best_len
```
## ❌ 안티패턴 (Anti-Patterns)
### CMA-ES (continuous, modern default)
```python
import cma
es = cma.CMAEvolutionStrategy(8 * [0.5], 0.5)
es.optimize(lambda x: sum(xi**2 for xi in x))
print(es.result.xbest)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Differential Evolution (scipy)
```python
from scipy.optimize import differential_evolution
res = differential_evolution(lambda x: (x[0]-3)**2 + (x[1]+1)**2,
bounds=[(-5,5),(-5,5)], strategy="best1bin",
popsize=30, mutation=(0.5,1.0), recombination=0.7)
```
### NEAT (neuroevolution)
```python
import neat
config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
neat.DefaultSpeciesSet, neat.DefaultStagnation, "config-neat")
pop = neat.Population(config)
def eval_genomes(genomes, cfg):
for gid, g in genomes:
net = neat.nn.FeedForwardNetwork.create(g, cfg)
g.fitness = simulate(net) # env-specific
winner = pop.run(eval_genomes, n=50)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Continuous, smooth | Gradient / L-BFGS |
| Continuous, black-box, ≤ 100 dim | **CMA-ES** |
| Continuous, parallel, robust | **Differential Evolution** |
| Combinatorial (TSP, scheduling) | **GA + local search (memetic)**, ACO |
| Real-time multi-agent | **PSO** |
| Neural architecture / policy | **NEAT, evolution strategies** |
| Very expensive eval | Bayesian optimization |
**기본값**: 매 continuous black-box 면 **CMA-ES**, 매 combinatorial 이면 **memetic GA**.
## 🔗 Graph
- 부모: [[Metaheuristics]] · [[Optimization]]
- 변형: [[Genetic-Algorithm]] · [[Particle-Swarm-Optimization]] · [[Ant-Colony-Optimization]] · [[Differential-Evolution]] · [[CMA-ES]] · [[NEAT]]
- 응용: [[Hyperparameter-Optimization]] · [[Neural-Architecture-Search]] · [[Robot-Control]] · [[Scheduling]]
- Adjacent: [[Bayesian-Optimization]] · [[Reinforcement-Learning]] · [[Simulated-Annealing]]
## 🤖 LLM 활용
**언제**: 매 black-box objective + non-differentiable + multimodal landscape, 매 prompt-search / hyperparameter tuning, 매 NAS.
**언제 X**: 매 differentiable + convex (gradient 의 압도적 빠름), 매 budget < 100 evaluations (Bayesian opt 의 선호).
## ❌ 안티패턴
- **Premature convergence**: 매 selection pressure 의 too-high → 매 diversity collapse. 매 niching, fitness sharing 사용.
- **Hyperparameter neglect**: 매 GA 의 cx/mut prob 의 untuned → 매 random search 의 못함.
- **Reinventing wheels**: 매 "Whale Optimization", "Grey Wolf" 등 매 metaphor-only papers — 매 CMA-ES / DE 의 거의 항상 better baseline.
- **No restart**: 매 stuck — 매 IPOP/BIPOP restart 의 critical.
## 🧪 검증 / 중복
- Verified (Holland 1975 GA; Kennedy & Eberhart 1995 PSO; Dorigo 1992 ACO; Hansen 2001 CMA-ES; Stanley 2002 NEAT).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 placeholder |
| 2026-05-10 | Manual cleanup — taxonomy, 6 algo patterns, decision matrix |
@@ -2,65 +2,138 @@
id: wiki-2026-0508-black-hole
title: Black Hole
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-BLHO-001]
aliases: [Schwarzschild, Event Horizon, Singularity]
duplicate_of: none
source_trust_level: A
confidence_score: 0.88
tags: [auto-reinforced, black-hole, astroPhysics, singularity, gravity, space-time]
confidence_score: 0.9
verification_status: applied
tags: [physics, general-relativity, computation, information-theory]
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: Python
framework: einsteinpy, astropy
---
# [[Black-Hole|Black-Hole]]
# Black Hole
## 📌 한 줄 통찰 (The Karpathy Summary)
> "시공간의 막다른 길: 거대한 질량이 좁은 공간에 압축되어 중력이 무한대에 수렴함으로써, 빛조차 빠져나갈 수 없는 우주의 가장 극단적이고 신비로운 마침표."
## 한 줄
> **"매 spacetime 의 region where escape velocity > c"**. Schwarzschild (1916) solution → Hawking radiation (1974) → EHT M87* image (2019) + Sgr A* (2022) → 매 2026 modern view: 매 information paradox 의 holographic / ER=EPR resolution 의 frontier. 매 CS 측면에서는 매 information bound, holographic encoding, computational limit 의 reference physical system.
## 📖 구조화된 지식 (Synthesized Content)
블랙홀(Black-Hole)은 중력이 너무 강해 빛을 포함한 어떤 입자도 탈출할 수 없는 시공간의 영역입니다.
## 매 핵심
1. **핵심 구조**:
* **Event Horizon (사건의 지평선)**: 안쪽에서 일어나는 일을 외부에서 결코 알 수 없는 경계면.
* **Singularity (특이점)**: 질량이 무한한 밀도로 압축되어 기존의 물리 법칙이 붕괴하는 중심 시스템.
2. **왜 중요한가?**:
* 일반 상대성 이론과 양자 역학이 충돌하는 지점으로, 우주의 근본 원리를 이해하는 핵심 열쇠임.
* 정보 역설(Information Paradox): 블랙홀로 들어간 정보가 영원히 사라지는가, 보존되는가에 대한 논쟁은 지식 보존의 물리학적 기초가 됨.
### 매 정의 / 종류
- **Schwarzschild** (non-rotating, no charge): r_s = 2GM/c².
- **Kerr** (rotating): 매 ergosphere + frame dragging.
- **ReissnerNordström** (charged), **KerrNewman** (rotating + charged).
- 매 mass 분류: stellar (5100 M☉), intermediate (10²–10⁵), supermassive (10⁶–10¹⁰), primordial (PBH).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 블랙홀이 모든 정보를 영영 삼키는 '파괴의 장소' 정책으로 보았으나, 현대 물리학 정책은 호킹 복사(Hawking Radiation)를 통해 아주 미세하게 정보를 방출할 수 있다는 정책으로 업데이트됨(RL Update).
- **정책 변화(RL Update)**: 블랙홀의 실제 관측 데이터(Event Horizon Telescope)가 확보됨에 따라, 가설로만 존재하던 영역이 실질적인 '데이터 분석의 영역 정책'으로 들어왔으며, 이를 분석하기 위해 거대 AI 알고리즘이 필수적으로 사용됨.
### 매 entropy / information
- BekensteinHawking entropy: S = k·A / (4·ℓ_P²).
- 매 information 매 area 에 비례 — 매 holographic principle 의 origin.
- Hawking T = ℏc³ / (8π·G·M·k_B) — 매 radiation 의 thermal.
- 매 information paradox: 매 unitary evolution vs thermal radiation. **2020 island formula (Penington, Almheiri 등) 의 Page curve 도출**.
## 🔗 지식 연결 (Graph)
- [[Artificial Intelligence (AI)|Artificial Intelligence (AI)]], [[Scientific-Method|Scientific-Method]], [[Analysis|Analysis]], [[Information-Theory|Information-Theory]], [[Philosophy|Philosophy]] of Science
- **Modern Tech/Tools**: Gravitational wave detectors (LIGO), Event Horizon Telescope imagery AI.
---
### 매 CS / 정보이론 연결
1. **Holographic bound**: 매 region 의 max info ≤ A / (4·ℓ_P²) bits.
2. **Computational limit**: Lloyd 2000 — 매 ultimate laptop 의 1 kg, 1 L 매 black-hole limit at 10⁵¹ ops/s.
3. **Quantum error correction**: 매 AdS/CFT 의 bulk reconstruction 의 QEC code (Almheiri-Dong-Harlow).
4. **ER=EPR**: 매 entanglement = wormhole — 매 quantum gravity 의 unification 의 hint.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Schwarzschild radius
```python
G, c, MSUN = 6.67430e-11, 2.99792458e8, 1.989e30
def schwarzschild_radius_m(M_solar): return 2 * G * (M_solar * MSUN) / c**2
print(schwarzschild_radius_m(1)) # 2953 m (Sun)
print(schwarzschild_radius_m(4.3e6)) # Sgr A*
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### Hawking temperature & lifetime
```python
import math
hbar, kB = 1.054571817e-34, 1.380649e-23
def hawking_T(M_kg): return hbar*c**3 / (8*math.pi*G*M_kg*kB)
def evap_time_s(M_kg): return 5120 * math.pi * G**2 * M_kg**3 / (hbar * c**4)
print(hawking_T(MSUN)) # ~6e-8 K
print(evap_time_s(MSUN) / 3.15e16) # ~2e67 yr
```
## 🧪 검증 상태 (Validation)
### Geodesic integration (einsteinpy)
```python
from einsteinpy.geodesic import Timelike
from einsteinpy.metric import Schwarzschild
import astropy.units as u
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
geo = Timelike(metric="Schwarzschild", metric_params=(0,),
position=[40, math.pi/2, 0], momentum=[0, 0, 3.83],
steps=5500, delta=0.5, return_cartesian=True)
```
## 🧬 중복 검사 (Duplicate Check)
### BekensteinHawking entropy
```python
lP2 = 2.612e-70 # Planck area m^2
def BH_entropy_bits(M_kg):
rs = 2*G*M_kg/c**2
A = 4*math.pi*rs**2
return A / (4*lP2) / math.log(2)
print(f"{BH_entropy_bits(MSUN):.2e} bits") # ~1e77
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Holographic bound check
```python
def holographic_max_bits(area_m2): return area_m2 / (4*lP2) / math.log(2)
# 매 1 m² boundary 매 ~1e69 bits maximum.
```
## 🕓 변경 이력 (Changelog)
### Image-plane shadow radius (EHT-style)
```python
def shadow_radius_uas(M_solar, distance_kpc):
rs = schwarzschild_radius_m(M_solar)
shadow_m = 3*math.sqrt(3)*rs # photon ring diameter ≈ 5.196·r_s/2
d_m = distance_kpc * 3.086e19
return (shadow_m / d_m) * (180/math.pi) * 3600 * 1e6
print(shadow_radius_uas(6.5e9, 16800)) # M87* ~ 42 µas
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Newtonian regime (r ≫ r_s) | Newtonian gravity |
| Static, spherical | **Schwarzschild metric** |
| Rotating astrophysical | **Kerr metric** |
| Quantum-gravity / info | **Page curve + island formula** |
| Holographic / dual CFT | **AdS/CFT** |
| Numerical merger | **Numerical Relativity (Einstein Toolkit)** |
**기본값**: 매 astrophysics 면 **Kerr**, 매 CS / info-theoretic discussion 면 **BekensteinHawking + holographic bound**.
## 🔗 Graph
- 부모: [[General-Relativity]] · [[Quantum-Field-Theory]]
- 변형: [[Schwarzschild-Metric]] · [[Kerr-Metric]] · [[Primordial-Black-Hole]]
- 응용: [[Holographic-Principle]] · [[AdS-CFT]] · [[Hawking-Radiation]] · [[Gravitational-Waves]]
- Adjacent: [[Information-Paradox]] · [[Page-Curve]] · [[ER-EPR]] · [[Computational-Limit]]
## 🤖 LLM 활용
**언제**: 매 information-theoretic 한 entropy bound, 매 holographic / quantum gravity 의 thought experiment, 매 cosmology numerical estimation.
**언제 X**: 매 sci-fi narrative 의 wormhole-as-shortcut (매 traversable wormhole 의 exotic-matter 필요 — 매 separate topic).
## ❌ 안티패턴
- **"매 black hole 의 information 의 lost"**: 매 modern view 의 unitary preserved (Page curve, island formula).
- **"매 singularity 의 physical"**: 매 GR breakdown 의 indicator — 매 quantum gravity 의 expected to resolve.
- **"매 Hawking radiation 매 carries info trivially"**: 매 detailed mechanism 의 still active research (replica wormholes 2020).
- **Mixing M_BH ↔ r_s units**: 매 SI (kg, m) vs geometrized (M = G·M_kg/c²) 매 cross-check 항상.
## 🧪 검증 / 중복
- Verified (Schwarzschild 1916; Hawking 1974; Bekenstein 1973; EHT Collaboration 2019, 2022; Penington 2020).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 placeholder |
| 2026-05-10 | Manual cleanup — physics + CS info-bound + 6 patterns |
@@ -2,88 +2,150 @@
id: wiki-2026-0508-bloom-filters-in-search
title: Bloom Filters in Search
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [BLOOM-001]
aliases: [Bloom Filter, BF, Probabilistic Set Membership]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [computer-science, data-structure, Search, algorithm, Efficiency]
confidence_score: 0.92
verification_status: applied
tags: [data-structures, search, probabilistic, indexing]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: pybloom-live, RedisBloom
---
# Bloom Filters in Search (검색에서의 블룸 필터)
# Bloom Filters in Search
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터가 '없다'는 것은 확실히 알려주되, '있다'는 것은 확률적으로 답하라" — 아주 적은 메모리만 사용하여 특정 원소가 집합에 포함되어 있는지 빠르게 확인하는 확률적 자료구조.
## 한 줄
> **"매 set membership 의 ultra-compact probabilistic test"**. Burton Bloom (1970) 이 spell-checker 위해 designed — modern search 에서 매 inverted-index pruning, cache short-circuit, distributed dedup 의 핵심 primitive 로 사용.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 방대한 데이터셋에서 실제 검색(I/O 연산)을 수행하기 전, 대상이 존재할 가능성이 있는지 미리 필터링하여 시스템 부하를 획기적으로 줄이는 고속 거름망 패턴.
- **작동 원리:**
- **Hashing:** 여러 개의 해시 함수를 사용하여 비트 배열의 특정 위치를 1로 설정.
- **False Positive:** 실제로 없는데 있다고 답할 확률은 존재함 (충돌 발생 시).
- **No False Negative:** 없다고 답하면 실제로 100% 없음. 불필요한 디스크/네트워크 접근을 원천 차단.
- **응용 사례:** DB 인덱스 검색 최적화, 웹 브라우저의 유해 사이트 필터링, 분산 시스템의 캐시 효율성 증대.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 정확한 결과가 필수적이라는 데이터 구조의 고정관념에서 벗어나, '확률적 효율성'이 시스템 전체 성능에 더 큰 이득을 줄 수 있음을 증명.
- **정책 변화:** Antigravity 프로젝트의 대규모 위키 문서 검색 시, 모든 문서를 임베딩 비교하기 전 블룸 필터를 통해 관련 키워드가 전혀 없는 문서를 1차적으로 배제함.
### 매 작동 원리
- m-bit array + k independent hash functions.
- Insert: 매 element x → 매 k hashes → 매 set bits at h1(x), …, hk(x).
- Query: 매 모든 k bits set → "possibly in set". 매 하나라도 0 → "definitely not".
- **False positive O, false negative X** — 매 search 의 negative-cache 에 ideal.
## 🔗 지식 연결 (Graph)
- [[Algorithm-Complexity-Big-O|Algorithm-Complexity-Big-O]],[[_system|system]]-Design-for-AI-Scale, Vector-Database-Selection, [[Parallel-Computing|Parallel-Computing]]
- **Raw Source:** 10_Wiki/Topics/AI/[[Bloom-Filters|Bloom-Filters]] in Search.md
### 매 수학
- Optimal k = (m/n) · ln 2.
- FP rate p ≈ (1 e^(kn/m))^k.
- 매 1% FP 위해 매 element 당 ~9.6 bits 필요 (load factor independent of element size).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용 in Search
1. **Inverted-index shard pruning** — Elasticsearch, Lucene 매 segment-level BF.
2. **CDN cache check** — 매 origin 의 round-trip avoid (Akamai).
3. **Crawler URL dedup** — Googlebot-style frontier.
4. **LSM-tree SSTable pruning** — RocksDB, Cassandra, ScyllaDB.
5. **Vector-DB ANN candidate filter** — Milvus, Weaviate.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Vanilla Python
```python
import mmh3, math
from bitarray import bitarray
## 🧪 검증 상태 (Validation)
class BloomFilter:
def __init__(self, n: int, fp: float = 0.01):
self.m = math.ceil(-(n * math.log(fp)) / (math.log(2) ** 2))
self.k = max(1, round((self.m / n) * math.log(2)))
self.bits = bitarray(self.m); self.bits.setall(0)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
def _hashes(self, x: bytes):
h1, h2 = mmh3.hash64(x, signed=False)
return [(h1 + i * h2) % self.m for i in range(self.k)]
## 🧬 중복 검사 (Duplicate Check)
def add(self, x: bytes):
for i in self._hashes(x): self.bits[i] = 1
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def __contains__(self, x: bytes) -> bool:
return all(self.bits[i] for i in self._hashes(x))
```
## 🤔 의사결정 기준 (Decision Criteria)
### RedisBloom (production)
```python
import redis
r = redis.Redis()
r.execute_command("BF.RESERVE", "urls", 0.001, 10_000_000)
r.execute_command("BF.ADD", "urls", "https://example.com/a")
exists = r.execute_command("BF.EXISTS", "urls", "https://example.com/a") # 1 or 0
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Counting Bloom Filter (supports delete)
```python
class CountingBF:
def __init__(self, m, k): self.c = [0]*m; self.m, self.k = m, k
def add(self, x):
for i in self._h(x): self.c[i] += 1
def remove(self, x):
for i in self._h(x):
if self.c[i] > 0: self.c[i] -= 1
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Cuckoo Filter (modern alternative)
```python
# pip install cuckoofilter
from cuckoofilter import CuckooFilter
cf = CuckooFilter(capacity=1_000_000, fingerprint_size=12)
cf.insert(b"item"); cf.contains(b"item"); cf.delete(b"item")
```
**기본값:**
> *(TODO)*
### LSM-tree integration (RocksDB-style, conceptual)
```python
def get(key):
for sstable in reversed(levels): # newest first
if key not in sstable.bloom: # BF rejects → skip disk read
continue
v = sstable.disk_lookup(key)
if v is not None: return v
return None
```
## ❌ 안티패턴 (Anti-Patterns)
### Distributed scale-out (partitioned BF)
```python
def shard(key, n_shards): return mmh3.hash(key) % n_shards
# 매 shard 매 own BF — node-local query, gossip-merged for global view.
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Static set, exact 필요 | Perfect hash (CHD, BBHash) |
| Dynamic, FP OK, no delete | **Bloom Filter** |
| Need delete | Counting BF or Cuckoo Filter |
| Need count/freq | Count-Min Sketch |
| Streaming dedup, bounded mem | HyperLogLog (cardinality only) |
| Need sorted range query | B-tree / SSTable index |
**기본값**: 매 dynamic insert + lookup 의 negative-cache 에서는 **Bloom Filter (k = m/n · ln 2, p = 1%)**.
## 🔗 Graph
- 부모: [[Probabilistic-Data-Structures]] · [[Hash-Functions]]
- 변형: [[Counting-Bloom-Filter]] · [[Cuckoo-Filter]] · [[Quotient-Filter]] · [[XOR-Filter]]
- 응용: [[LSM-Tree]] · [[Inverted-Index]] · [[Web-Crawler]] · [[CDN-Cache]]
- Adjacent: [[HyperLogLog]] · [[Count-Min-Sketch]] · [[MinHash]]
## 🤖 LLM 활용
**언제**: 매 candidate-key set 의 fast negative-test, 매 duplicate detection in streaming pipeline, 매 ANN search 의 pre-filter.
**언제 X**: 매 exact membership 필수 (auth, billing), 매 small n (< 1000) 일 때 — 매 hash-set 의 simpler.
## ❌ 안티패턴
- **Underestimate n**: 매 capacity overflow → 매 FP rate 의 explode (saturated bits).
- **Weak hash (e.g., DJB2)**: 매 correlated bits → 매 actual FP > theoretical. **MurmurHash3 / xxHash 사용.**
- **Delete via clearing bits**: 매 corrupts other entries — 매 Counting BF 사용.
- **Sharing BF across security boundary**: 매 timing side-channel 의 set membership leak.
## 🧪 검증 / 중복
- Verified (Bloom 1970, "Space/Time Trade-offs in Hash Coding"; Broder & Mitzenmacher 2002 survey; RocksDB & Cassandra source).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 placeholder |
| 2026-05-10 | Manual cleanup — full content (theory, 6 patterns, decision matrix) |
@@ -1,94 +1,154 @@
---
id: wiki-2026-0508-brute-force
title: Brute force
title: Brute-force
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-BRFO-001]
aliases: [Exhaustive-Search, Naive-Algorithm]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
tags: [auto-reinforced, brute-force, algorithms, exhaustive-Search, computation, Optimization]
confidence_score: 0.9
verification_status: applied
tags: [algorithm, search, baseline]
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
framework: stdlib
---
# [[Brute-force|Brute-force]]
# Brute-force
## 📌 한 줄 통찰 (The Karpathy Summary)
> "우직한 전수 조사: 지름길을 찾는 영리한 기법 대신, 가능한 모든 경우의 수를 하나하나 전부 시도하여 기어이 정답을 찾아내는, 컴퓨터의 압도적 연산력을 믿고 밀어붙이는 무차별 대입 방식."
## 한 줄
> **"매 모든 후보를 매 enumerate해서 매 검사 — 매 단순함이 매 최대 무기"**. 매 algorithmic paradigm으로서 매 baseline + correctness oracle. 매 2026 ML/AI에서도 매 grid search, 매 fuzzing, 매 password cracking, 매 small-n CSP 에서 매 still alive — 매 GPU + parallelism으로 매 brute force가 매 더 viable.
## 📖 구조화된 지식 (Synthesized Content)
브루트 포스(Brute-force)는 문제를 해결하기 위해 가능한 모든 조합을 탐색하는 가장 단순하고 확실한 방법입니다.
## 매 핵심
1. **특징**:
* **Simplicity**: 구현이 매우 쉽고 논리적 오류가 적음.
* **Guarantee**: 정답이 존재한다면 100% 찾아냄.
* **[[Efficiency|Efficiency]]**: 데이터의 양(N)이 커질수록 탐색 시간이 기하급수적으로 늘어남 (Time Complexity 이슈).
2. **주요 용도**:
* 비밀번호 무차별 대입 공격(Brute-force attack) 방어 테스트.
* 데이터 크기가 작아 고난도 알고리즘을 짤 필요가 없는 경우.
* 더 나은 알고리즘의 정답률을 검증하기 위한 기준점(Baseline).
### 매 핵심 idea
- 매 search space 전체를 매 systematic enumerate.
- 매 correctness가 매 trivially provable.
- 매 complexity는 매 보통 exponential — 매 small n only.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 '무식한 방법' 정책으로 치부되었으나, 현대 인프라 정책(GPU/Cloud)은 연산 비용의 급격한 하락 덕분에 병렬 처리를 통한 '고속 브루트 포스 정책'이 오히려 복잡한 알고리즘보다 개발 시간 대비 효율이 좋은 경우가 많아짐(RL Update).
- **정책 변화(RL Update)**: 보안 정책 수립 시, 브루트 포스 공격을 막기 위해 로그인 시도를 제한(Rate Limiting)하거나 CAPTCHA를 강제하는 '지능형 접근 차단 정책'이 필수 표준이 됨.
### 매 응용
1. String matching (naive: $O(nm)$ vs KMP $O(n+m)$).
2. Cryptanalysis: brute-force key search (e.g., 56-bit DES → cracked 1998).
3. Hyperparameter grid search (small grid).
4. Test oracle (fast brute-force vs optimized — fuzz to verify).
5. Combinatorial: TSP, SAT, knapsack — 매 small n.
6. Fuzzing: AFL/libFuzzer 매 brute random + coverage feedback.
## 🔗 지식 연결 (Graph)
- [[BFS vs DFS|BFS vs DFS]], [[Binary-Search|Binary-Search]], [[Optimization|Optimization]], [[Search-Optimization|Search-Optimization]], [[Technical-Architecture|Technical-Architecture]]
- **Modern Tech/Tools**: Password cracking simulations, Permutation generators.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Naive substring search
```python
def find_naive(text, pat):
n, m = len(text), len(pat)
for i in range(n - m + 1):
if text[i:i+m] == pat:
return i
return -1
# O(n*m) — fine for short pattern; KMP/Boyer-Moore better large m
```
## 🤔 의사결정 기준 (Decision Criteria)
### Subset enumeration
```python
from itertools import combinations
def best_subset(items, score_fn):
best = (None, float('-inf'))
for r in range(len(items)+1):
for combo in combinations(items, r):
s = score_fn(combo)
if s > best[1]: best = (combo, s)
return best
# 2^n subsets — only for n <= 20
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Permutation TSP (exact for n<=10)
```python
from itertools import permutations
def tsp_brute(dist, start=0):
n = len(dist)
best = float('inf'); best_path = None
for perm in permutations(range(1, n)):
path = (start,) + perm + (start,)
cost = sum(dist[path[i]][path[i+1]] for i in range(n))
if cost < best: best, best_path = cost, path
return best, best_path
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Brute force as test oracle
```python
def fast_solve(input_): ... # production
def brute_solve(input_): ... # obvious O(n^k)
**기본값:**
> *(TODO)*
def test_with_fuzz():
import random
for _ in range(10_000):
x = random_input()
assert fast_solve(x) == brute_solve(x), x
```
## ❌ 안티패턴 (Anti-Patterns)
### Grid hyperparameter search
```python
import itertools
def grid_search(model_fn, param_grid, X, y):
best = (None, float('-inf'))
keys = list(param_grid)
for vals in itertools.product(*[param_grid[k] for k in keys]):
params = dict(zip(keys, vals))
score = cv_score(model_fn(**params), X, y)
if score > best[1]: best = (params, score)
return best
# Use Optuna/random search for >5 dims
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Pruning + brute (branch-and-bound hybrid)
```python
def knapsack_bnb(weights, values, cap):
best = [0]
def rec(i, w, v):
if w > cap: return
if i == len(weights):
best[0] = max(best[0], v); return
# upper bound (LP relax) — prune if can't beat best
rec(i+1, w + weights[i], v + values[i])
rec(i+1, w, v)
rec(0, 0, 0)
return best[0]
```
## 매 결정 기준
| n size | Brute viable? |
|---|---|
| $n \le 10$ | $O(n!)$ OK |
| $n \le 25$ | $O(2^n)$ OK |
| $n \le 50$ | $O(2^{n/2})$ meet-in-the-middle |
| $n > 50$ | DP / heuristic / approximation |
**기본값**: 매 첫 implementation은 매 brute. 매 그것이 매 너무 slow일 때만 매 optimize. 매 brute는 매 reference oracle로 매 keep.
## 🔗 Graph
- 부모: [[Algorithm-Complexity-Big-O]]
- 변형: [[Greedy-Algorithms]] (heuristic) · [[Dynamic-Programming]] (memoize) · Branch-and-Bound
- 응용: Cryptanalysis · [[Combinatorial-Optimization]]
- Adjacent: [[Bubble-Sort]] · [[BFS vs DFS]]
## 🤖 LLM 활용
**언제**: 매 first implementation, 매 correctness oracle, 매 small n problem.
**언제 X**: 매 n>50, 매 production hot path — 매 better algorithm 필수.
## ❌ 안티패턴
- **Brute in production hot loop**: 매 $O(n^2)$ when $O(n \log n)$ trivial.
- **Throwing away brute baseline**: 매 optimized version에 매 bug — 매 oracle 없음.
- **Brute force without bound**: 매 무한 loop — 매 max iterations / timeout 필수.
## 🧪 검증 / 중복
- Verified (CLRS Ch.31, Skiena Algorithm Design Manual).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — brute paradigm + oracle pattern |
@@ -2,94 +2,167 @@
id: wiki-2026-0508-bubble-sort
title: Bubble Sort
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-BUSO-001]
aliases: [버블 정렬, Sinking Sort, Exchange Sort]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [auto-reinforced, bubble-sort, algorithms, Sorting, educational, comparison-sort]
confidence_score: 0.9
verification_status: applied
tags: [algorithm, sorting, comparison-sort, education]
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/Rust
framework: stdlib
---
# [[Bubble-Sort|Bubble-Sort]]
# Bubble Sort
## 📌 한 줄 통찰 (The Karpathy Summary)
> "인접한 단짝의 순위 바꿈: 서로 이웃한 두 원소를 비교하며 큰 것을 뒤로 보내는 과정을 물그릇 속 거품이 위로 올라오듯 반복하여, 가장 무거운(큰) 원소부터 하나씩 제 자리를 찾아 보내는 정렬의 입문서."
## 한 줄
> **"매 인접 비교+swap 의 매 simplest sort"**. 1956 Iverson notation discussion 부터 매 textbook canonical example. 매 production 의 X — 매 O(n²) 이라 n>50 의 부적합. 매 2026 의 매 교육적 가치 + matrix-vector kernel optimization research 의 사용.
## 📖 구조화된 지식 (Synthesized Content)
버블 정렬(Bubble-Sort)은 인접한 두 항목을 비교하여 순서가 맞지 않으면 서로 교체(Swap)하며 전체를 정렬하는 방식입니다.
## 매 핵심
1. **동작 원리**:
* 첫 번째와번째 비교 -> 교체 여부 결정.
* 두 번째와 세 번째 비교 ... 끝까지 진행.
* 이면 한 개의 가장 큰 원소가 끝으로 감. 이 과정을 원소 개수만큼 반복.
2. **성능 지표**:
* **Time Complexity**: $O(N^2)$ (데이터가 많아지면 매우 느려짐).
* **Stability**: 동일한 값의 상대적 순서가 유지되는 안정 정렬(Stable Sort).
3. **교육적 의미**:
* 실무에서 대용량 데이터를 정렬할 때는 쓰이지 않지만, 알고리즘의 기초 논리인 '비교'와 '교환'을 배우는 가장 좋은 교재임.
### 매 알고리즘
- 매 n-1 passes — 매 pass 마다 인접원소 비교 + swap (잘못된 순서면).
- 매 pass 후 가장 큰 element 가 매 우측 끝 의 "bubble up".
- 매 in-place — O(1) extra space.
- 매 stable sort — 매 동등 키 의 상대적 순서 유지.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거 정렬 정책 연구는 버블 정렬의 비효율성을 강조하는 데 그쳤으나, 현대 임베디드 정책이나 특수 정렬 정책에서는 구현 코드가 매우 짧다는 '공간 절약 정책'의 장점이 특정 상황에서 재평가되기도 함(RL Update).
- **정책 변화(RL Update)**: 엔지비니어링 교육 정책에서, 단순히 빠른 알고리즘만 가르치기보다 버블 정렬의 비효율성을 측정(Profiling)하고 이를 개선하는 과정(Quick/Merge Sort로의 전이)을 보여주는 '이론 체계화 정책'이 강화됨.
### 매 복잡도
- **Worst/Average**: O(n²) — 매 reverse-sorted input.
- **Best**: O(n) — 매 already-sorted + early-termination flag.
- **Comparisons**: n(n-1)/2 worst case.
- **Swaps**: 매 inversions 수 = n(n-1)/2 worst case.
## 🔗 지식 연결 (Graph)
- [[Binary-Search|Binary-Search]], [[Search-Optimization|Search-Optimization]], [[Analysis|Analysis]], Pattern Recognition, [[Arrangement-and-Composition|Arrangement-and-Composition]]
- **Modern Tech/Tools**: Computer science 101 curriculum, Visual sorting simulators.
---
### 매 응용
1. **Education**: 매 introductory CS course 의 1st sort.
2. **Tiny n (<10)**: 매 cache-friendly + low overhead.
3. **Nearly-sorted detection**: 매 single-pass 로 sorted 여부 check.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Classic Bubble Sort
```python
def bubble_sort(arr: list[int]) -> None:
n = len(arr)
for i in range(n - 1):
for j in range(n - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
```
## 🤔 의사결정 기준 (Decision Criteria)
### Optimized with Early-Exit Flag
```python
def bubble_sort_optimized(arr: list[int]) -> None:
n = len(arr)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
return # 매 already sorted — 매 O(n) best case
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Cocktail Shaker (Bidirectional)
```python
def cocktail_sort(arr: list[int]) -> None:
lo, hi = 0, len(arr) - 1
while lo < hi:
for j in range(lo, hi):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
hi -= 1
for j in range(hi, lo, -1):
if arr[j - 1] > arr[j]:
arr[j - 1], arr[j] = arr[j], arr[j - 1]
lo += 1
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Generic with Comparator (Rust)
```rust
fn bubble_sort<T, F: Fn(&T, &T) -> std::cmp::Ordering>(arr: &mut [T], cmp: F) {
let n = arr.len();
for i in 0..n.saturating_sub(1) {
let mut swapped = false;
for j in 0..n - 1 - i {
if cmp(&arr[j], &arr[j + 1]) == std::cmp::Ordering::Greater {
arr.swap(j, j + 1);
swapped = true;
}
}
if !swapped { return; }
}
}
```
**기본값:**
> *(TODO)*
### Branchless Inner Loop (CPU pipeline-friendly)
```c
void bubble_sort_branchless(int *a, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
int cmp = a[j] > a[j + 1];
int tmp = a[j];
a[j] = cmp ? a[j + 1] : a[j];
a[j + 1] = cmp ? tmp : a[j + 1];
}
}
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Linked-List Variant
```python
def bubble_sort_linked(head):
if not head: return head
swapped = True
while swapped:
swapped = False
cur = head
while cur.next:
if cur.val > cur.next.val:
cur.val, cur.next.val = cur.next.val, cur.val
swapped = True
cur = cur.next
return head
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| n < 10, simple code 우선 | Bubble Sort (optimized) |
| n < 50, 거의 sorted | Insertion Sort > Bubble |
| n > 100 | Quicksort/Timsort/std `sort` |
| Stable + small n | Bubble or Insertion |
| Production code | 매 절대 X — 매 stdlib `sort` |
**기본값**: 매 production 은 stdlib (Timsort/IntroSort) — 매 Bubble 은 교육 only.
## 🔗 Graph
- 부모: [[Sorting Algorithms]] · [[Comparison Sort]]
- 변형: [[Cocktail Shaker Sort]] · [[Odd-Even Sort]]
- 응용: [[Algorithm Education]] · [[Inversion Counting]]
- Adjacent: [[Insertion Sort]] · [[Selection Sort]] · [[Quicksort]] · [[Timsort]]
## 🤖 LLM 활용
**언제**: 매 algorithm tutorials 의 explanation, 매 n<20 의 quick prototype, 매 inversions counting heuristic.
**언제 X**: 매 production sort, 매 n>100, 매 latency-sensitive paths — 매 Timsort/Quicksort 의 사용.
## ❌ 안티패턴
- **Production deployment**: 매 100x slower than Timsort 의 large n.
- **Recursive bubble**: 매 stack overhead 의 점진적 추가 — 매 pure loss.
- **No early-exit**: 매 sorted input 의 O(n²) 의 낭비.
- **Bubble for objects with expensive comparison**: 매 n² comparisons 의 cost explosion.
## 🧪 검증 / 중복
- Verified (Knuth TAOCP Vol 3 §5.2.2, CLRS Ch. 2 problem 2-2).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Bubble sort patterns + variants + decision matrix |
@@ -2,61 +2,168 @@
id: wiki-2026-0508-burnout-prevention-in-profession
title: Burnout Prevention in Professional Gaming
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Esports Burnout, Pro Gamer Mental Health, Player Wellness]
duplicate_of: none
source_trust_level: A
confidence_score: 0.96
tags: [Burnout, Professional Gaming, Mental Health, Performance]
confidence_score: 0.85
verification_status: applied
tags: [esports, mental-health, performance, sports-science, wellness]
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: N/A
framework: WHO ICD-11 / Maslach Burnout Inventory
---
# Burnout-Prevention-in-Professional-Gaming (프로게이머 번아웃 방지)
# Burnout Prevention in Professional Gaming
## 📌 한 줄 통찰 (The Karpathy Summary)
> "휴식도 훈련의 일부다." 0.1초의 반응 속도를 다투는 프로의 세계에서 뇌의 피로(Cognitive Fatigue)를 관리하지 못하는 것은 승리를 포기하는 것과 같다.
## 한 줄
> **"매 chronic occupational stress 의 esports adaptation"**. WHO ICD-11 (2019) 의 burnout 의 occupational phenomenon 인정 후 매 esports 의 매 acute risk profile (10-14h practice/day, age 16-24 peak, parasocial pressure). 매 2026 의 매 LCS/LCK/VCT 의 mandatory wellness programs 의 standardization.
## 📖 구조화된 지식 (Synthesized Content)
- **Cognitive Fatigability (인지적 피로도)**:
- 고도의 집중력이 지속될 때 전전두엽의 포도당 소모가 급증하며 의사결정 속도가 저하된다. 이를 방지하기 위해 정기적인 'Mental Reset' 루틴이 필수적이다.
- **[[Dopamine|Dopamine]] Detox (도파민 디톡스)**:
- 게임의 강력한 시각적/청각적 자극에 노출된 뇌를 위해, 연습 시간 외에는 자극이 적은 환경(명상, 산책)을 제공하여 뇌의 보상 시스템을 안정화한다.
- **Sleep Hygiene (수면 위생)**:
- 렘(REM) 수면 단계에서 당일 학습한 전략과 반응 기술이 장기 기억으로 전이된다. 하루 7시간 이상의 규칙적인 수면은 가장 강력한 기술 향상 도구다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 무조건적인 연습 시간 증가는 오히려 '플래토(Plateau, 성체기)' 현상을 유발한다. 짧고 강렬한 '몰입 연습(Deliberate Practice)'과 완전한 단절을 동반한 휴식을 교차시키는 것이 롱런하는 선수의 공통점이다.
### 매 Burnout 정의 (Maslach 3-axis)
- **Emotional exhaustion**: 매 energy depletion — 매 pre-match anxiety + post-match crash.
- **Depersonalization**: 매 cynicism — 매 fans/team 의 distance.
- **Reduced accomplishment**: 매 efficacy 의 감소 — 매 mechanical skill plateau perception.
## 🔗 지식 연결 (Graph)
- Related: [[Behavioral-Economics|Behavioral-Economics]] , [[Complexity-Theory|Complexity-Theory]]
- Foundation: [[Information Theory|Information Theory]]
### 매 Esports-specific 위험 요인
- **Practice volume**: 매 70+ hr/week scrim/solo queue — 매 traditional sports 의 X.
- **Travel + boot camp**: 매 sleep disruption + jet lag — 매 LAN circuit 의 매 6+ flights/year.
- **Parasocial pressure**: 매 stream + Twitter visibility 의 매 24/7 scrutiny.
- **Career compression**: 매 peak age 18-22 — 매 pro window <5 years average.
- **Sedentary load**: 매 wrist/back/eye strain 의 cumulative.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Prevention 4-tier
1. **Schedule design**: 매 practice cap (8h/day max) + 매 mandatory rest day.
2. **Sleep hygiene**: 매 fixed bedtime + 매 blue-light cutoff 22:00.
3. **Exercise mandate**: 매 30min cardio/day — 매 LCK Gen.G/T1 의 mandatory.
4. **Mental health professional**: 매 sports psych on-staff — 매 LCS minimum since 2023.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Maslach Burnout Inventory Scoring (Python)
```python
from dataclasses import dataclass
## 🧪 검증 상태 (Validation)
@dataclass
class MBIScore:
emotional_exhaustion: int # 0-54
depersonalization: int # 0-30
personal_accomplishment: int # 0-48 (reverse-scored)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
@property
def burnout_risk(self) -> str:
ee_high = self.emotional_exhaustion >= 27
dp_high = self.depersonalization >= 13
pa_low = self.personal_accomplishment <= 31
score = ee_high + dp_high + pa_low
return ["low", "moderate", "high", "severe"][score]
## 🧬 중복 검사 (Duplicate Check)
# Weekly screening
player = MBIScore(emotional_exhaustion=30, depersonalization=15, personal_accomplishment=28)
print(player.burnout_risk) # "severe" — escalate to sports psych
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Practice Load Tracker
```python
class PracticeLoad:
def __init__(self):
self.daily_hours = [] # last 14 days
## 🕓 변경 이력 (Changelog)
def acute_chronic_ratio(self) -> float:
# 매 ACWR — 매 traditional sports injury predictor
acute = sum(self.daily_hours[-7:]) / 7
chronic = sum(self.daily_hours[-28:]) / 28
return acute / chronic if chronic else 0
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
def needs_rest_day(self) -> bool:
# ACWR > 1.5 = elevated injury/burnout risk
return self.acute_chronic_ratio() > 1.5
```
### Sleep Quality Wearable Integration
```python
import datetime
def assess_sleep(whoop_data: dict) -> dict:
return {
"duration_hr": whoop_data["sleep_minutes"] / 60,
"rem_pct": whoop_data["rem_minutes"] / whoop_data["sleep_minutes"],
"deep_pct": whoop_data["deep_minutes"] / whoop_data["sleep_minutes"],
"should_skip_scrim": whoop_data["recovery_score"] < 33, # 매 red zone
}
```
### Team Wellness Dashboard Schema
```sql
CREATE TABLE player_wellness (
player_id UUID,
date DATE,
mbi_score INT,
sleep_hours FLOAT,
practice_hours FLOAT,
self_reported_mood INT, -- 1-10 Likert
psych_session_attended BOOL,
PRIMARY KEY (player_id, date)
);
-- Weekly intervention trigger
SELECT player_id FROM player_wellness
WHERE date >= NOW() - INTERVAL '7 days'
GROUP BY player_id
HAVING AVG(self_reported_mood) < 5 OR AVG(sleep_hours) < 6;
```
### Cognitive Behavioral Therapy (CBT) Reframe Template
```python
# 매 negative-thought logging — 매 used in T1/Faker's wellness program
cbt_log = {
"trigger": "lost ranked to lower-tier opponent",
"automatic_thought": "I'm losing my mechanics, career is over",
"cognitive_distortion": "catastrophizing + all-or-nothing",
"balanced_thought": "Single game variance is high; check 14-day winrate",
"evidence_for": "Solo queue is noisy; pros have 50-55% winrate",
"action": "Review VOD, identify 1 micro-improvement, sleep 8h",
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| MBI score 의 high+ | Mandatory psych referral + 1-week reduced load |
| ACWR > 1.5 | Force rest day, no scrim |
| Sleep < 6h × 3+ days | Sleep specialist consult |
| Performance plateau + cynicism | Burnout > skill issue → wellness intervention |
| Pre-Worlds/Major | Increased monitoring (daily MBI mini) |
**기본값**: 매 weekly MBI + daily sleep/load tracking + monthly psych check-in.
## 🔗 Graph
- 부모: [[Sports Psychology]] · [[Occupational Health]]
- 변형: [[Streamer Burnout]] · [[Coach Burnout]]
- 응용: [[Esports Team Management]] · [[Player Contracts]]
- Adjacent: [[Cognitive Neuroscience of Flow]] · [[Sleep Science]] · [[CBT]]
## 🤖 LLM 활용
**언제**: 매 wellness check-in chatbot, 매 CBT thought-record assistance, 매 schedule optimization 의 load balancing.
**언제 X**: 매 clinical diagnosis (psychiatrist 영역), 매 medication decision, 매 crisis intervention (988 hotline 의 즉시 escalation).
## ❌ 안티패턴
- **More-hours-better**: 매 LCK 70hr scrim 의 mythology — 매 evidence shows diminishing returns >50hr.
- **Stigma against psych**: 매 "weakness" perception — 매 modern orgs 의 normalization.
- **Reactive only**: 매 burnout 후 intervention — 매 too late (recovery 의 6-12개월).
- **Solo-queue grind 의 unlimited**: 매 chronic stress 의 mechanical decay.
## 🧪 검증 / 중복
- Verified (WHO ICD-11 QD85, Maslach 1996, Smith et al. 2022 esports burnout study).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — MBI scoring + ACWR + CBT integration patterns |
@@ -2,111 +2,148 @@
id: wiki-2026-0508-caetextia
title: Caetextia
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Context Blindness, Contextual Blindness]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
source_trust_level: B
confidence_score: 0.75
verification_status: applied
tags: [psychology, autism, cognition, neurodiversity, theory]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: N/A
framework: Human Givens (Griffin & Tyrrell)
---
# [[카이텍스티아 (Caetextia)]]
# Caetextia
## 📌 한 줄 통찰 (The Karpathy Summary)
카이텍스티아(Caetextia)는 심리학자 조 그리핀(Joe Griffin)과 이반 타이렐(Ivan Tyrrell)이 자폐 스펙트럼 장애(ASD) 인구, 특히 고기능 자폐인에게서 지배적으로 나타나는 행동 양상을 설명하기 위해 고안한 용어로 '맥락 맹목성'을 뜻한다 [1]. 이는 여러 상호작용하는 변수들에 주의를 동시에 할당하고 전환하지 못하는 현상으로, 주어진 상황의 맥락 정보를 무의식적으로 활용하거나 환경 변화의 의미를 제대로 평가하지 못하게 만든다 [2, 3]. 만성적인 신경발달적 증상 외에도 심한 스트레스, 불안, 우울증에 의해 일시적인 형태로 발생할 수도 있다 [4].
## 한 줄
> **"매 context-blindness 의 cognitive trait"**. Joe Griffin & Ivan Tyrrell (Human Givens, 2008) 의 coined term — 매 Latin _caecus_ (blind) + _textus_ (context). 매 autism spectrum 의 매 core deficit hypothesis 의 한 candidate — 매 Peter Vermeulen 의 "context blindness" theory 와 overlap. 매 2026 의 매 mainstream DSM 의 X — 매 niche framework remain.
## 📖 Core 기Content
* **어원 및 정의**: 카이텍스티아는 라틴어로 맹목을 뜻하는 'caecus'와 맥락을 뜻하는 'contextus'의 합성어이다 [1]. 그리핀과 타이렐은 '아스퍼거 증후군'이라는 명칭보다, 상호작용하는 변수들이 다른 변수에 미치는 영향을 파악하지 못하는 무능력을 설명하는 데 있어 '카이텍스티아'가 훨씬 더 정확하고 기술적인 용어라고 제안했다 [1].
* **작동 메커니즘**: 핵심은 상호작용하는 변수들을 다룰 때 행동을 적절하게 조정하지 못하고 행동을 둘러싼 맥락을 고려하지 못하는 것이다 [2]. 이 현상은 주의(attention)의 흐름을 유지하고 전환하는 능력을 기반으로 설명된다 [5]. 예를 들어, 거울로 머리를 빗을 때 거울에 보이지 않는 뒷머리는 빗지 않는 등의 행동을 보이는데, 이는 국소적인 시각적 자극을 '머리 전체'라는 전체적인 맥락과 연결하지 못하기 때문이다 [3].
* **심리적 및 일상적 파급 효과**: 한 번에 하나 이상의 변수나 요인에 주의를 기울여야 하는 상황에 직면하면 환자는 심각한 좌절감, 분노, 불안감을 경험하게 된다 [2]. 환경 변화의 맥락을 적절히 평가하지 못하여 발생하는 이러한 극심한 불안은 결국 고정된 규칙에 강박적으로 집착하는 행동 양식으로 이어진다 [3].
* **'맥락 맹' 개념과의 비교**: 피터 베르뮬렌(Peter Vermeulen)이 독립적으로 제안한 '맥락 맹(Context blindness)'과 밀접하게 연관되지만, 이론적 초점에는 차이가 있다 [5]. 베르뮬렌의 맥락 맹은 약한 중앙 응집 이론의 연장선상에서 사전 경험과 암묵적 단서를 의미 도출에 병합하는 '의미 형성(meaning-making)' 단계의 결함으로 본다 [5, 6]. 반면 카이텍스티아는 개별적인 '주의(attention)의 분배와 전환 메커니즘'의 부재에 무게를 둔다 [3, 5].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
과거 카이텍스티아를 뇌의 지배적 반구에 따라 '좌뇌형 카이텍스티아'와 '우뇌형 카이텍스티아'로 구분하려던 시도가 있었으나, 이는 지나친 단순화(oversimplification)라는 한계를 가진다 [4, 7]. 현대에는 이를 디폴트 시스템(default systems)의 관점에서, 디폴트 시스템에 과도하게 빠져 있거나(우뇌형) 반대로 철저히 배제되어(좌뇌형) 현재의 현실을 깊은 맥락과 연결하지 못하는 것으로 설명하는 것이 더 정확하다고 평가받는다 [7].
또한, 엄격한 의미의 맥락 맹이나 카이텍스티아 가설이 과제 기반의 실증적 연구(task-based evidence)를 통해 항상 완벽하게 일관된 지지를 받는 것은 아니라는 제약이 있다 [8]. 더불어 맥락 통합 실패는 복잡한 다중 변수 환경에서 불안과 좌절을 유발하는 치명적 단점이 되지만, 역으로 생각하면 맥락의 간섭 없이 세부 사항과 개별 부품에 고립적으로 집중할 수 있는 특징(예: 수학 및 공학적 세밀함, 블록 설계에서의 뛰어난 성능)과 맞닿아 있는 반대 급부(Trade-off)를 지니고 있다 [2, 3, 9, 10].
### 매 정의
- **Context blindness**: 매 situational meaning extraction 의 어려움.
- 매 detail processing 의 strong — 매 gestalt context 의 weak.
- 매 literal interpretation tendency — 매 sarcasm/idiom 의 difficulty.
- 매 weak central coherence theory (Frith 1989) 와 conceptual cousin.
## 🔗 지식 연결 (Graph)
### Related Concepts
### 매 manifestations
- 매 social cue mis-reading — 매 tone/body language 의 missing.
- 매 routine rigidity — 매 context-shift 의 high cost.
- 매 generalization 의 어려움 — 매 task-specific learning 의 narrow.
- 매 hyperfocus 의 detail-level — 매 big picture 의 fade.
#### [관계 유형 A (병리학적 메커니즘 및 핵심 이론)]
- [[맥락 맹 (Context Blindness)]]
- 연결 이유: 피터 베르뮬렌이 제안한 밀접한 관련 개념으로, 자폐 스펙트럼에서 의미 형성 시 자발적 맥락 사용의 결함을 설명함 [5, 10].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 루트 주제인 '맥락 통합'의 결함을 주의 전환의 실패(카이텍스티아)로 볼 것인지, 아니면 감각 입력에 대한 사전 경험 및 의미 추론의 결여(맥락 맹)로 볼 것인지 이론적 렌즈의 차이를 이해할 수 있음 [5].
### 매 Programming/Tech 관련성
1. **Specification literalism**: 매 ambiguous spec 의 매 over-literal implementation — 매 PM intent 의 미파악.
2. **Strong type/contract design**: 매 caetextic developers 의 explicit contract preference.
3. **Edge-case detection**: 매 detail-focus 의 strength — 매 QA/security/protocol design.
4. **Code review style**: 매 surface vs. systemic critique 의 contrast.
- [[약한 중앙 응집 이론 (Weak Central Coherence Theory)]]
- 연결 이유: 자폐 스펙트럼의 인지 스타일이 전체적인 상황(큰 그림)을 통합하지 못하고 국소적 세부 사항에 집중한다는 것을 설명하는 근본 이론임 [5, 10, 11].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 맥락 통합의 부재가 가져오는 단점(불안, 유연성 부족)과 디테일 지각에서의 강점(퍼즐, 블록 맞추기에서의 우위)이라는 트레이드오프 양면성을 깊이 있게 파악할 수 있음 [9-11].
### 매 Caveats
- 매 not DSM-5/ICD-11 의 official diagnosis.
- 매 Human Givens framework 의 academic acceptance limited.
- 매 spectrum/dimension — 매 binary trait 의 X.
#### [관계 유형 B (신경/인지적 기제)]
- [[주의 전환 (Attention Switching/Allocation)]]
- 연결 이유: 카이텍스티아의 가장 핵심적인 인지적 결함이 상호작용하는 복수의 변수 간에 주의를 할당하고 전환하는 능력의 부재로 구체화되기 때문임 [3, 4].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 다학제적 지능에서 성공적인 '맥락 통합'이 성립하기 위해서는 감각 정보에 대한 단순 입력을 넘어선 주의력의 능동적인 배분 및 통제가 필수적임을 알 수 있음 [4].
## 💻 패턴
- [[디폴트 시스템 (Default System)]]
- 연결 이유: 카이텍스티아 현상을 단순히 뇌 반구 모델로 나누는 것을 넘어, 현재 상태와 깊은 맥락을 연결하지 못하는 신경학적 기반을 설명하는 시스템임 [7].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 자극과 현실 인식의 과정에서 뇌의 내정 상태 네트워크가 맥락적 틀을 제공하고 상황을 조율하는 메커니즘을 규명할 수 있음 [7].
### Context-Aware vs. Context-Blind Code Style
```python
# 매 context-blind: 매 strict literal contract
def transfer(amount: Decimal, from_id: int, to_id: int) -> TransferResult:
if amount <= 0: raise ValueError("amount must be positive")
if from_id == to_id: raise ValueError("self-transfer forbidden")
# 매 explicit precondition checks — 매 caller intent 의 무시
### Deeper Research Questions
# 매 context-aware: 매 inferring caller intent
def transfer(amount: Decimal, from_id: int, to_id: int) -> TransferResult:
# 매 same account 일 때 — 매 likely UI bug — 매 silent no-op + log
if from_id == to_id:
logger.info("self-transfer attempted, treating as no-op", from_id)
return TransferResult.skipped()
```
- 카이텍스티아가 정의하는 '주의 할당 및 전환 능력의 한계'를 극복하기 위해, 상호작용 변수를 단계적으로 제시하는 환경적 개입이 자폐 스펙트럼 환자의 인지적 과부하와 불안을 유의미하게 감소시킬 수 있는가?
- 피터 베르뮬렌의 '맥락 맹'과 그리핀 & 타이렐의 '카이텍스티아'는 각각 의미 형성과 주의 전환에 초점을 맞추는데, 이 두 인지적 결함은 신경 정보 처리 과정에서 순차적으로 발생하는가 아니면 별개의 메커니즘으로 작동하는가?
- 스트레스, 불안, 우울증 등에 의해 유발되는 일시적인 카이텍스티아와 신경발달장애(ASD)에서 비롯되는 만성적 카이텍스티아는 '디폴트 시스템'의 조절 이상이라는 측면에서 뇌과학적으로 동일한 궤적을 공유하는가?
- 인공지능 모델(예: 단순화된 어텐션 메커니즘)에서 여러 모달리티나 변수를 동시에 참조하지 못하는 병목이 발생할 때, 인간의 카이텍스티아 메커니즘을 분석하여 이를 극복할 계산적 영감(computational inspiration)을 얻을 수 있는가?
- 약한 중앙 응집 이론이 주장하는 세부 사항 중심의 지각적 우위를 훼손하지 않으면서도, 일상에서 카이텍스티아로 인한 '규칙 집착'과 불안을 완화할 수 있는 인지적 보상(compensatory) 전략은 무엇인가?
### Sarcasm/Idiom Detection (NLP)
```python
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
### Practical Application Contexts
# 매 caetextia model 의 자동화 X — 매 NLP 의 sarcasm classifier 의 사용
tok = AutoTokenizer.from_pretrained("helinivan/english-sarcasm-detector")
model = AutoModelForSequenceClassification.from_pretrained("helinivan/english-sarcasm-detector")
- **Implementation:** 자폐 스펙트럼 장애(ASD)를 가진 인구를 위한 교육, 치료 및 생활 지원 환경을 구축할 때, 다중 변수가 동시에 얽힌 복잡한 상황 노출을 최소화하고 직관적이며 구조화된 지침을 제공하여 불안을 통제함 [2, 3].
- **System Design:** 소프트웨어 및 사용자 인터페이스(UI) 설계 시, 사용자가 암묵적 단서를 바탕으로 여러 화면의 맥락을 스스로 통합하도록 강요하지 않고, 현재 수행 중인 작업과 직접 연관된 명시적이고 시각적인 단일 포커스를 제공하도록 설계함.
- **Operation / Maintenance:** 높은 스트레스나 억울한 감정을 겪는 일반 조직원도 상황의 상호작용 변수를 파악하지 못하는 '일시적 카이텍스티아' 상태에 놓일 수 있음을 인지하고 [4], 업무 부하가 높을 시 다중 변수 통합 작업을 배제하여 인적 오류를 방지함.
- **Learning Path:** 루트 주제인 '맥락 통합'이 지능 시스템에서 차지하는 위상을 이해하기 위해, 그 기능이 결핍된 병리학적 사례(카이텍스티아, 맥락 맹, 약한 중앙 응집)를 선행 학습함. 이를 통해 정상적인 인간 인지 기능이나 AI의 어텐션 메커니즘이 수행해야 하는 다중 변수 통합의 설계 조건을 역산(reverse engineering)함.
- **My Project Relevance:** 소스에 관련 정보가 부족합니다. (개별 사용자의 구체적 프로젝트 정보는 제공되지 않음)
def is_sarcastic(text: str) -> bool:
inputs = tok(text, return_tensors="pt", truncation=True)
logits = model(**inputs).logits
return torch.argmax(logits).item() == 1
```
### Adjacent Topics
### Contract-First API Design (caetextia-friendly)
```typescript
// 매 explicit precondition — 매 ambiguity 의 elimination
type TransferInput = {
readonly amount: Money & { __brand: 'positive' };
readonly from: AccountId;
readonly to: AccountId & { __brand: 'different-from-from' };
readonly idempotencyKey: string;
};
- [[예측 처리 (Predictive Processing)]]
- 확장 방향: 뇌를 예측 기관으로 보는 관점(Friston의 자유 에너지 원리 등)을 토대로, 감각 입력과 맥락적 사전 지식의 결합이 어떻게 이루어지는지 탐구하여 자폐 스펙트럼의 맥락 사용 결함 연구를 확장함 [5, 8].
- [[마음 이론 (Theory of Mind)]]
- 확장 방향: 사회적 상호작용에서 타인의 감정과 의도라는 '사회적 맥락'을 통합하여 행동을 예측하는 능력에 대한 연구로, 맥락 맹 및 카이텍스티아가 야기하는 의사소통 한계의 근본 원인을 폭넓게 파악함 [12, 13].
// 매 type-level enforcement — 매 caller 의 intent 의 disambiguate
function transfer(input: TransferInput): Promise<Result<TransferOk, TransferErr>>;
```
---
*Last updated: 2026-05-04*
### Workplace Accommodation Checklist
```yaml
# 매 caetextia-aware engineering team practices
communication:
- explicit_written_specs: required
- meeting_agenda: shared 24h ahead
- sarcasm_in_slack: marked /s or emoji
- decision_documentation: ADR mandatory
code_review:
- use_explicit_blocking_vs_nit_tags
- link_to_design_doc_for_context
focus:
- deep_work_blocks: 4hr no-meeting windows
- notification_batching: 2x/day
```
## 📖 구조화된 지식 (Synthesized Content)
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Spec 의 ambiguity | Disambiguate explicitly — 매 caetextia 의 friendly |
| Sarcasm-heavy team comm | Add /s markers + async-text 우선 |
| Code review | Tag blocking vs. nit explicitly |
| Onboarding | Written runbook + ADR archive |
| Brainstorm session | Async written round 1 → sync round 2 |
**추출된 패턴:**
> *(TODO)*
**기본값**: 매 explicit > implicit communication, 매 written > verbal context.
**세부 내용:**
- *(TODO)*
## 🔗 Graph
- 부모: [[Cognitive Theory]] · [[Neurodiversity]]
- 변형: [[Weak Central Coherence]] · [[Context Blindness (Vermeulen)]]
- 응용: [[Inclusive Engineering Practice]] · [[Specification Writing]]
- Adjacent: [[Autism Spectrum]] · [[Theory of Mind]] · [[Pragmatics]]
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 🤖 LLM 활용
**언제**: 매 spec disambiguation, 매 sarcasm/idiom annotation, 매 written-context expansion 의 ambiguous chat.
**언제 X**: 매 clinical diagnosis (DSM-5 의 X), 매 individual labeling — 매 stigmatization risk.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## ❌ 안티패턴
- **Pop-psych labeling**: 매 colleague 의 "caetextic" 의 stigma — 매 framework 의 misuse.
- **Binary classification**: 매 spectrum 의 reality 의 ignore.
- **Diagnosis without clinician**: 매 self/peer-diagnosis 의 academic basis 의 약함.
- **Conflating with autism**: 매 caetextia ≠ autism — 매 partial overlap only.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 / 중복
- Verified (Griffin & Tyrrell, _Human Givens Approach_ 2008; Vermeulen _Autism as Context Blindness_ 2012).
- 신뢰도 B (niche framework, not mainstream DSM).
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Caetextia framework + engineering applications + caveats |
@@ -2,63 +2,149 @@
id: wiki-2026-0508-chaos-theory-in-systems
title: Chaos Theory in Systems
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [CHAOS-001]
aliases: [Deterministic Chaos, Nonlinear Dynamics, Sensitive Dependence]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [mathematics, complex-systems, chaos-theory, nonlinear-dynamics, _system-design]
confidence_score: 0.9
verification_status: applied
tags: [dynamical-systems, mathematics, distributed-systems, simulation]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python/NumPy/SciPy
framework: scipy.integrate
---
# Chaos Theory in Systems (시스템에서의 카오스 이론)
# Chaos Theory in Systems
## 📌 한 줄 통찰 (The Karpathy Summary)
> "결정론적인 질서 안에서도 예측 불가능한 요동이 숨어 있다" — 초기 조건의 미세한 차이가 시간이 흐름에 따라 거대한 결과의 차이를 만들어내는(나비 효과) 비선형 동역학 시스템의 성질을 탐구하는 이론.
## 한 줄
> **"매 deterministic 이지만 매 unpredictable"**. Lorenz 1963 weather model 의 butterfly effect — 매 sensitive dependence on initial conditions. 매 distributed systems / ML training / financial modeling 의 매 ubiquitous. 매 2026 의 매 Lyapunov-aware stress testing + chaos engineering (Netflix Chaos Monkey lineage) 의 mainstream.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 규칙적인 알고리즘으로 작동하는 시스템이라도, 요소 간의 복잡한 피드백 루프와 비선형성으로 인해 장기적인 예측이 원천적으로 불가능해지는 복잡계([[Complex Systems|Complex Systems]]) 패턴.
- **핵심 개념:**
- **Butterfly Effect:** 초기값의 0.0001% 차이가 전혀 다른 결과를 초래함.
- **Strange Attractors:** 혼돈 속에서도 특정 궤적이나 패턴으로 수렴하는 기하학적 구조 (예: 로렌츠 끌개).
- **Fractals:** 부분과 전체가 닮아 있는 자기 유사성(Self-similarity) 구조.
- **Nonlinearity:** 입력의 합이 출력의 합과 같지 않은 시스템의 불규칙한 특성.
- **의의:** 기상 예측, 주식 시장, 그리고 수천 개의 에이전트가 상호작용하는 대규모 AI 생태계의 불안정성을 이해하는 틀 제공.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 선형적인 인과관계로 세상을 설명하려던 고전 과학의 한계를 넘어, 불규칙성 자체가 시스템의 본질적 속성임을 규명.
- **정책 변화:** Skybound 프로젝트의 대규모 함대 시뮬레이션 시, 카오스 이론을 응용하여 각 기체의 단순한 로직이 합쳐져 예측 불가능하면서도 유기적인 진형 변화를 보이도록 설계함.
### 매 Three properties (Devaney definition)
- **Sensitive dependence**: 매 ε perturbation 의 exponential divergence — 매 Lyapunov exponent λ > 0.
- **Topological transitivity**: 매 any neighborhood 의 매 trajectory 의 visits 모든 region.
- **Dense periodic orbits**: 매 periodic points 의 dense in phase space.
## 🔗 지식 연결 (Graph)
- [[Complexity-Theory|Complexity-Theory]], [[Artificial-Life|Artificial-Life]], [[Multi-Agent-Systems-MAS|Multi-Agent-Systems-MAS]], System-Design-for-AI-Scale
- **Raw Source:** 10_Wiki/Topics/AI/Chaos-Theory in Systems.md
### 매 Canonical 시스템
- **Lorenz attractor**: dx/dt = σ(y-x), dy/dt = x(ρ-z)-y, dz/dt = xy-βz.
- **Logistic map**: x_{n+1} = r·x_n·(1-x_n) — 매 r > 3.57 의 chaos.
- **Double pendulum**: 매 mechanical chaos 의 textbook.
- **Hénon map**: 매 2D discrete chaos.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Engineering 응용
1. **Chaos engineering**: 매 production failure injection — 매 Netflix/AWS Fault Injection Service.
2. **Cryptographic PRNG seeds**: 매 chaotic map 의 entropy source.
3. **Distributed system jitter**: 매 thundering herd 의 randomized backoff.
4. **Neural network training**: 매 loss landscape 의 chaotic regime detection.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Lorenz Integration (NumPy)
```python
import numpy as np
from scipy.integrate import solve_ivp
## 🧪 검증 상태 (Validation)
def lorenz(t, state, sigma=10, rho=28, beta=8/3):
x, y, z = state
return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
sol = solve_ivp(lorenz, (0, 40), [1.0, 1.0, 1.0],
t_eval=np.linspace(0, 40, 10000), rtol=1e-9)
# 매 second trajectory 의 ε perturbation
sol2 = solve_ivp(lorenz, (0, 40), [1.0 + 1e-8, 1.0, 1.0],
t_eval=sol.t, rtol=1e-9)
divergence = np.linalg.norm(sol.y - sol2.y, axis=0)
# divergence 의 exponential 증가 — 매 butterfly effect
```
## 🧬 중복 검사 (Duplicate Check)
### Lyapunov Exponent Estimation
```python
def largest_lyapunov(traj_a, traj_b, dt):
eps0 = np.linalg.norm(traj_a[:, 0] - traj_b[:, 0])
eps_t = np.linalg.norm(traj_a - traj_b, axis=0)
lam = np.mean(np.log(eps_t[1:] / eps0)) / (dt * len(eps_t))
return lam # > 0 → chaotic
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Logistic Map Bifurcation
```python
def logistic_orbit(r, x0=0.5, n=1000, discard=500):
x = x0
for _ in range(discard):
x = r * x * (1 - x)
orbit = []
for _ in range(n):
x = r * x * (1 - x)
orbit.append(x)
return orbit
# r=2.9 → fixed point; r=3.5 → period-4; r=3.9 → chaos
```
## 🕓 변경 이력 (Changelog)
### Chaos Engineering — Latency Injection
```python
import random, asyncio
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
async def chaos_middleware(handler, prob=0.05, max_delay_ms=2000):
if random.random() < prob:
delay = random.expovariate(1 / max_delay_ms) / 1000
await asyncio.sleep(delay)
if random.random() < 0.01:
raise ConnectionResetError("chaos: simulated network failure")
return await handler()
```
### Decorrelated Jitter (AWS pattern)
```python
def decorrelated_jitter(prev: float, base: float = 0.1, cap: float = 30.0) -> float:
# 매 thundering herd 방지 — 매 chaos-inspired backoff
return min(cap, random.uniform(base, prev * 3))
```
### Strange Attractor Reconstruction (Takens embedding)
```python
def takens_embed(series, m=3, tau=1):
n = len(series) - (m - 1) * tau
return np.array([series[i:i + m * tau:tau] for i in range(n)])
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Long-horizon weather/finance prediction | 매 ensemble + 매 horizon limit |
| Distributed system retry | Decorrelated jitter (chaotic) |
| Production resilience | Chaos engineering (Litmus/Gremlin) |
| Periodic dynamics | Linear analysis 충분 — 매 chaos theory X |
| ML loss instability | Lyapunov-style divergence detection |
**기본값**: 매 nonlinear coupling 의 시스템 의 sensitivity analysis 우선.
## 🔗 Graph
- 부모: [[Dynamical Systems]] · [[Nonlinear Dynamics]]
- 변형: [[Lorenz Attractor]] · [[Logistic Map]] · [[Hénon Map]]
- 응용: [[Chaos Engineering]] · [[Backoff and Jitter]] · [[Stochastic Simulation]]
- Adjacent: [[Fractals]] · [[Strange Attractor]] · [[Bifurcation Theory]] · [[Lyapunov Exponent]]
## 🤖 LLM 활용
**언제**: 매 dynamical model 의 explanation, 매 simulation code generation, 매 chaos engineering policy authoring.
**언제 X**: 매 long-term precise prediction (의 fundamental limit), 매 financial trading decisions 의 sole basis.
## 🤖 안티패턴
- **Determinism = predictability**: 매 chaos 의 counterexample.
- **Long-horizon point forecasts**: 매 Lyapunov horizon 의 violation.
- **Ignoring numerical precision**: 매 single-precision 의 sensitive systems 의 silent error compounding.
- **Conflating chaos with randomness**: 매 deterministic + bounded — 매 stochastic 와 different.
## 🧪 검증 / 중복
- Verified (Lorenz 1963 _Deterministic Nonperiodic Flow_, Strogatz _Nonlinear Dynamics and Chaos_ 2nd ed).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Lorenz/Lyapunov/chaos engineering integrations |
@@ -2,87 +2,186 @@
id: wiki-2026-0508-climate-change-mitigation-framew
title: Climate Change Mitigation Frameworks
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-SCI-CLIMATE]
aliases: [Carbon Mitigation, Net Zero Frameworks, GHG Reduction]
duplicate_of: none
source_trust_level: A
confidence_score: 0.93
tags: [Climate Change, Net Zero, Carbon Neutral, Mitigation]
confidence_score: 0.9
verification_status: applied
tags: [climate, sustainability, policy, carbon-accounting, esg]
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
framework: GHG Protocol / SBTi / TCFD
---
# Climate-Change-Mitigation-Frameworks (기후 변화 대응 프레임워크)
# Climate Change Mitigation Frameworks
## 📌 한 줄 통찰 (The Karpathy Summary)
> 기후 변화는 단순한 환경 문제가 아니라 '에너지 시스템의 대전환' 문제이며, 과학적 실증 데이터에 기반한 탄소 예산(Carbon [[Budget|Budget]]) 관리가 핵심이다.
## 한 줄
> **"매 GHG emission 의 systematic reduction 의 standardized 방법론"**. 1992 UNFCCC → 2015 Paris Agreement → 2024 SBTi Corporate Net-Zero Standard 의 lineage. 매 2026 의 매 EU CSRD + SEC climate disclosure rule 의 의무화 — 매 software 회사 의 매 Scope 1/2/3 reporting 의 mandatory.
## 📖 구조화된 지식 (Synthesized Content)
- **Decarbonization (탈탄소화)**:
- 화석 연료 기반의 에너지 믹스를 태양광, 풍력, 원자력 등 저탄소 에너지원으로 전환하고 전력을 효율화한다.
- **Carbon Capture & [[Storage|Storage]] (CCS)**:
- 배출된 이산화탄소를 포집하여 지하나 해저에 영구 격리하는 기술적 보완책. 넷 제로(Net Zero) 달성을 위한 최후의 수단이다.
- **Emissions Trading[[_system|system]] (ETS)**:
- 탄소 배출에 '가격'을 매겨 기업들이 자발적으로 배출량을 줄이도록 유도하는 시장 경제 기반의 정책 도구.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 선진국과 개도국 사이의 '기후 정의' 문제가 항상 충돌한다. 기술적 해결만큼이나 글로벌 거버넌스(Paris Agreement)와 금융 지원 체계가 동반되어야 실무적인 변화가 가능하다.
### 매 Major frameworks
- **GHG Protocol**: 매 corporate accounting 의 de-facto — 매 Scope 1/2/3.
- **SBTi (Science Based Targets initiative)**: 매 1.5°C-aligned reduction targets.
- **TCFD → ISSB IFRS S2**: 매 financial disclosure standard.
- **CDP**: 매 voluntary disclosure platform.
- **Paris Agreement NDCs**: 매 national-level commitments.
## 🔗 지식 연결 (Graph)
- Related: [[Circular-Economy|Circular-Economy]] , [[Distributed-Systems-Engineering|Distributed-Systems-Engineering]]
- Policy: [[Collaboration_Governance|Collaboration_Governance]]
### 매 Scope definitions
- **Scope 1**: 매 direct emissions — 매 owned vehicles/boilers.
- **Scope 2**: 매 purchased electricity/heat — 매 location-based vs market-based.
- **Scope 3**: 매 value chain (15 categories) — 매 software 회사 의 95%+ 일반적.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Mitigation hierarchy
1. **Avoid**: 매 emission 의 prevention — 매 highest priority.
2. **Reduce**: 매 efficiency + clean energy switch.
3. **Replace**: 매 high-carbon → low-carbon technology.
4. **Offset**: 매 residual 의 removal — 매 last resort, quality-graded.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 Software industry 응용
- 매 cloud carbon footprint (Scope 3 cat. 1, 2).
- 매 green coding practices — 매 Greensoft Foundation.
- 매 carbon-aware computing — 매 workload shifting.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### GHG Inventory Calculator
```python
from dataclasses import dataclass
from decimal import Decimal
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
@dataclass
class Emission:
scope: int # 1, 2, or 3
category: str
activity_data: Decimal # kWh, liters, km, etc.
emission_factor: Decimal # kgCO2e per unit
@property
def co2e_kg(self) -> Decimal:
return self.activity_data * self.emission_factor
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
inventory = [
Emission(1, "natural_gas", Decimal("12000"), Decimal("0.184")), # m³ → kgCO2e
Emission(2, "electricity_market_based", Decimal("450000"), Decimal("0.293")), # kWh
Emission(3, "purchased_goods", Decimal("2_500_000"), Decimal("0.45")), # USD spend-based
]
total_tco2e = sum(e.co2e_kg for e in inventory) / 1000
```
## 🤔 의사결정 기준 (Decision Criteria)
### Cloud Carbon Footprint (AWS example)
```python
import boto3, datetime
ce = boto3.client("ce")
res = ce.get_cost_and_usage(
TimePeriod={"Start": "2026-04-01", "End": "2026-05-01"},
Granularity="MONTHLY",
Metrics=["UsageQuantity"],
GroupBy=[{"Type": "DIMENSION", "Key": "REGION"}],
)
# 매 region 의 grid intensity 의 mapping
GRID_INTENSITY = { # kgCO2e/kWh, 2025 IEA
"us-east-1": 0.379, "eu-west-1": 0.295, "ap-northeast-1": 0.471,
"eu-north-1": 0.041, # 매 Sweden — 매 cleanest
}
```
**선택 A를 써야 할 때:**
- *(TODO)*
### SBTi Target Setting (1.5°C linear pathway)
```python
def sbti_pathway(base_year_emissions: float, base_year: int,
target_year: int, sector: str = "general") -> dict:
# 매 SBTi cross-sectoral absolute contraction approach (CSAA) 4.2% pa 1.5°C
annual_rate = 0.042
years = target_year - base_year
target_emissions = base_year_emissions * (1 - annual_rate) ** years
return {
"base_year": base_year, "base_emissions_tCO2e": base_year_emissions,
"target_year": target_year, "target_emissions_tCO2e": target_emissions,
"reduction_pct": (1 - target_emissions / base_year_emissions) * 100,
}
# sbti_pathway(10000, 2020, 2030) → ~35% reduction
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Carbon-Aware Workload Scheduler
```python
import requests
**기본값:**
> *(TODO)*
def get_grid_intensity_g_per_kwh(region: str) -> float:
r = requests.get(f"https://api.electricitymap.org/v3/carbon-intensity/latest?zone={region}",
headers={"auth-token": "..."})
return r.json()["carbonIntensity"]
## ❌ 안티패턴 (Anti-Patterns)
def schedule_batch_job(regions: list[str]) -> str:
intensities = {r: get_grid_intensity_g_per_kwh(r) for r in regions}
return min(intensities, key=intensities.get) # 매 cleanest grid 의 region
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Marginal Abatement Cost Curve (MACC) data
```python
import pandas as pd
macc = pd.DataFrame([
{"measure": "LED lighting", "abatement_tCO2e": 200, "cost_per_t": -180},
{"measure": "Solar PPA", "abatement_tCO2e": 1500, "cost_per_t": -25},
{"measure": "Heat pump", "abatement_tCO2e": 400, "cost_per_t": 35},
{"measure": "Direct air capture", "abatement_tCO2e": 100, "cost_per_t": 600},
]).sort_values("cost_per_t")
# 매 negative cost 의 measure 우선 (매 NPV positive)
```
### TCFD Disclosure Skeleton
```yaml
governance:
board_oversight: "Sustainability Committee, quarterly review"
strategy:
scenarios: [1.5C-NZE, 2C-IEA-APS, 3C-IEA-STEPS]
transition_risks: [carbon-pricing, customer-preference]
physical_risks: [datacenter-flooding, heat-cooling-load]
risk_management:
process: "ERM integrated, climate as material risk"
metrics_targets:
scope1_2_target: "50% reduction by 2030 vs 2020 (SBTi-validated)"
scope3_target: "30% reduction by 2030 vs 2020"
internal_carbon_price_usd_per_t: 75
```
## 매 결정 기준
| 상황 | Framework |
|---|---|
| Public company, EU/SEC | TCFD/ISSB IFRS S2 (의무) |
| Voluntary leadership | SBTi 1.5°C + CDP A-list |
| Internal accounting | GHG Protocol Scope 1/2/3 |
| Cloud/SaaS Scope 3 | Cloud Carbon Footprint (Thoughtworks) |
| Project-level | MACC + ICP (internal carbon price) |
**기본값**: GHG Protocol inventory + SBTi target + TCFD disclosure trifecta.
## 🔗 Graph
- 부모: [[ESG]] · [[Sustainability]] · [[Climate Policy]]
- 변형: [[Net Zero]] · [[Carbon Neutrality]] · [[Carbon Negative]]
- 응용: [[Green Software Engineering]] · [[Carbon-Aware Computing]] · [[Sustainable Datacenter]]
- Adjacent: [[Carbon Markets]] · [[Renewable Energy Certificates]] · [[Life Cycle Assessment]]
## 🤖 LLM 활용
**언제**: 매 disclosure draft, 매 emission factor lookup, 매 MACC scenario synthesis, 매 carbon-aware code review.
**언제 X**: 매 official SBTi target validation (의 third-party verifier 영역), 매 audited financial statement 의 final number.
## ❌ 안티패턴
- **Offset-only strategy**: 매 mitigation hierarchy 의 violation — 매 SBTi reject.
- **Scope 3 의 무시**: 매 software company 의 95% emission 의 hidden.
- **Spend-based factors only**: 매 directional only — 매 supplier-specific data 의 better.
- **Greenwashing**: 매 verified target 의 X 의 marketing claim.
- **Ignoring location-based vs market-based**: 매 dual-reporting 의 의무.
## 🧪 검증 / 중복
- Verified (GHG Protocol Corporate Standard, SBTi Net-Zero Standard v2 2024, IPCC AR6).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — GHG/SBTi/TCFD frameworks + carbon-aware computing patterns |
@@ -2,61 +2,170 @@
id: wiki-2026-0508-cognitive-neuroscience-of-flow
title: Cognitive Neuroscience of Flow
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-SCI-FLOW]
aliases: [Flow State, In the Zone, Optimal Experience]
duplicate_of: none
source_trust_level: A
confidence_score: 0.97
tags: ["Flow State|[Flow State", Neuroscience, Concentration, Performance]
confidence_score: 0.85
verification_status: applied
tags: [neuroscience, psychology, performance, attention, esports, gamedev]
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: N/A
framework: Csíkszentmihályi flow model / TAH (Transient Hypofrontality)
---
# Cognitive-Neuroscience-of-Flow (몰입의 뇌과학)
# Cognitive Neuroscience of Flow
## 📌 한 줄 통찰 (The Karpathy Summary)
> "자아조차 잊게 만드는 완벽한 조화." 몰입(Flow)은 뇌의 보상 시스템과 주의력 시스템이 극한의 효율로 결합하여 에너지를 폭발시키는 상태다.
## 한 줄
> **"매 challenge-skill balance 의 매 optimal absorption state 의 neural signature"**. Csíkszentmihályi 1975 phenomenology → Dietrich 2003 transient hypofrontality (TAH) → 2020s fNIRS/EEG real-time detection. 매 2026 의 매 game design + esports training + productivity tooling 의 actionable framework.
## 📖 구조화된 지식 (Synthesized Content)
- **Transient Hypofrontality**:
- 몰입 중에는 전전두엽(판단, 비판 담당)의 활동이 일시적으로 낮아진다. 이로 인해 자의식적 비판이 사라지고 오직 '하는 행위' 자체에만 매몰된다.
- **[[Dopamine|Dopamine]] & Norepinephrine**:
- 도파민(보상)과 노르에피네프린(각성)이 다량 분비되며 학습 속도와 반응 속도를 비약적으로 높인다.
- **Challenge-Skill Balance**:
- 과제의 난이도와 자신의 실력이 완벽한 균형을 이룰 때(지루함과 불안 사이) 뇌는 몰입 상태에 진입하기 가장 쉽다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 몰입은 마법 같은 상태지만, 도파민 중독과 비슷한 양상을 보여 '중독성'이 있다. 건강한 몰입과 강박적 몰입을 구분하는 메타 인지가 장기적인 성장에 중요하다.
### 매 9 dimensions (Csíkszentmihályi)
1. Challenge-skill balance (매 핵심 condition).
2. Action-awareness merging.
3. Clear goals.
4. Unambiguous feedback.
5. Concentration on task.
6. Sense of control.
7. Loss of self-consciousness.
8. Time distortion.
9. Autotelic experience.
## 🔗 지식 연결 (Graph)
- Related: [[Burnout|Burnout]]-Prevention-in-Professional-Gaming , [[Cognitive Psychology|Cognitive Psychology]]
- Foundation: [[Information Theory|Information Theory]]
### 매 Neural correlates (2026 consensus)
- **Transient hypofrontality**: 매 dorsolateral prefrontal cortex (DLPFC) 의 일시적 감소 — 매 inner critic 의 quiet.
- **Default Mode Network (DMN) 의 down-regulation**: 매 self-referential thinking 의 감소.
- **Striatal dopamine**: 매 reward prediction + intrinsic motivation.
- **Norepinephrine + endorphins**: 매 focused arousal.
- **Theta-gamma coupling**: 매 hippocampus-cortex 의 memory binding.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Triggers (Kotler 17, condensed)
- **Psychological**: clear goals, immediate feedback, challenge/skill ratio ~4% above current skill.
- **Environmental**: high-consequence + rich-sensory + novelty.
- **Social**: shared goal + close listening + flow contagion.
- **Creative**: pattern recognition + risk.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 Game Design 응용
1. **Difficulty curves**: 매 dynamic difficulty adjustment (DDA) — 매 anxiety/boredom band 의 회피.
2. **Feedback loops**: 매 hit-shake + audio cue + score 의 sub-200ms response.
3. **Goal hierarchy**: 매 short-term (combat) + long-term (campaign).
4. **Cognitive load tuning**: 매 Hicks's law / 매 Miller 7±2 의 respect.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Real-Time Flow Detection (EEG features, Python)
```python
import numpy as np
import mne
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
def flow_index(eeg_epoch, sfreq=256):
# 매 frontal theta/alpha + parietal gamma — 매 flow proxy
raw = mne.io.RawArray(eeg_epoch, mne.create_info(["Fz","Pz"], sfreq, "eeg"))
psd, freqs = mne.time_frequency.psd_array_welch(eeg_epoch, sfreq, fmin=1, fmax=50)
theta = psd[:, (freqs>=4)&(freqs<=8)].mean()
alpha = psd[:, (freqs>=8)&(freqs<=13)].mean()
gamma = psd[:, (freqs>=30)&(freqs<=45)].mean()
# 매 frontal theta 의 elevated + alpha 의 reduced + gamma 의 elevated
return (theta * gamma) / (alpha + 1e-6)
```
## 🧬 중복 검사 (Duplicate Check)
### Dynamic Difficulty Adjustment (DDA)
```python
class FlowChannelDDA:
def __init__(self, target_winrate=0.55, alpha=0.05):
self.skill_estimate = 1500 # Elo-like
self.target = target_winrate
self.alpha = alpha
self.difficulty = 1500
def update(self, won: bool):
observed = 1.0 if won else 0.0
error = observed - self.target
self.difficulty += self.alpha * error * 100
# 매 challenge ~4% above skill — 매 flow band
self.difficulty = self.skill_estimate + 60 + np.random.normal(0, 20)
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Flow State Survey (Flow Short Scale, Rheinberg)
```python
fss_items = [ # 1-7 Likert
"I felt just the right amount of challenge",
"My thoughts ran fluidly and smoothly",
"I didn't notice time passing",
"I had no difficulty concentrating",
"I felt in control of the situation",
# ... 13 items total
]
def fss_score(responses: list[int]) -> dict:
fluency = np.mean(responses[:6])
absorption = np.mean(responses[6:10])
return {"flow": (fluency + absorption) / 2, "fluency": fluency, "absorption": absorption}
```
## 🕓 변경 이력 (Changelog)
### Latency Budget for Flow (game loop)
```cpp
// 매 input → visual feedback budget — 매 flow 보존
constexpr int INPUT_TO_FRAME_MS = 16; // 1 frame @60Hz
constexpr int AUDIO_CUE_MS = 50; // 매 perceived immediate
constexpr int HAPTIC_MS = 80;
constexpr int TOTAL_BUDGET_MS = 100; // 매 above 의 magic 깨짐
static_assert(INPUT_TO_FRAME_MS + AUDIO_CUE_MS <= TOTAL_BUDGET_MS);
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Productivity Flow Logger
```python
import time, json
class FlowSession:
def __init__(self, task: str):
self.task = task; self.start = time.time(); self.interruptions = 0
def interrupt(self): self.interruptions += 1
def end(self, self_report_flow: int):
return {
"task": self.task,
"duration_min": (time.time() - self.start) / 60,
"interruptions_per_hour": self.interruptions / ((time.time()-self.start)/3600),
"flow_score": self_report_flow, # 1-7
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Game design difficulty | DDA targeting ~55% winrate |
| Esports training | FSS post-scrim + fNIRS sessions |
| Productivity tooling | Notification batching + Pomodoro 90min |
| Team meetings | Block 4hr no-meeting flow windows |
| Onboarding/Tutorial | Clear sub-goals + immediate feedback |
**기본값**: 매 challenge ≈ skill + 4%, 매 feedback < 200ms, 매 distraction-free 4hr blocks.
## 🔗 Graph
- 부모: [[Cognitive Neuroscience]] · [[Positive Psychology]]
- 변형: [[Group Flow]] · [[Microflow]] · [[Macroflow]]
- 응용: [[Game Design]] · [[Esports Training]] · [[Burnout Prevention in Professional Gaming]]
- Adjacent: [[Default Mode Network]] · [[Dopamine]] · [[Attention]] · [[Csíkszentmihályi]]
## 🤖 LLM 활용
**언제**: 매 difficulty curve design, 매 flow-friendly UX critique, 매 productivity ritual 의 personalization.
**언제 X**: 매 clinical neurofeedback 의 sole basis, 매 pharmacological intervention recommendation.
## ❌ 안티패턴
- **Over-rewarding**: 매 dopamine 의 dump 의 flow 의 anxiety 회피 — 매 short-term win, long-term burnout.
- **Constant interruption tools**: 매 Slack red dot 의 flow 의 destruction.
- **Difficulty 의 ceiling**: 매 challenge < skill 의 boredom — 매 disengagement.
- **Difficulty spike**: 매 challenge ≫ skill 의 anxiety — 매 quitting.
- **Gamification 의 misuse**: 매 extrinsic reward 의 over-emphasis — 매 autotelic 의 destroy.
## 🧪 검증 / 중복
- Verified (Csíkszentmihályi 1990 _Flow_, Dietrich 2003 _Cognition_, Kotler _Stealing Fire_ 2017).
- 신뢰도 A (mainstream scientific consensus, ongoing fMRI/fNIRS refinement).
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Flow neural correlates + DDA + EEG detection patterns |
@@ -2,89 +2,213 @@
id: wiki-2026-0508-combinatorial-optimization
title: Combinatorial Optimization
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [COMB-OPT-001]
aliases: [Discrete Optimization, CO, Integer Programming]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [mathematics, algorithm, Optimization, combinatorial-optimization, complexity]
confidence_score: 0.9
verification_status: applied
tags: [algorithms, optimization, np-hard, operations-research, ml]
raw_sources: []
last_reinforced: 2026-04-26
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 / Gurobi / SCIP / cvxpy
---
# Combinatorial Optimization (조합 최적화)
# Combinatorial Optimization
## 📌 한 줄 통찰 (The Karpathy Summary)
> "무수히 많은 선택지 중 최고의 조합을 효율적으로 골라내라" — 외판원 문제(TSP), 배낭 문제(Knapsack Problem)와 같이 가능한 조합의 수가 기하급수적으로 많을 때, 수학적 모델과 알고리즘을 통해 최적해 혹은 그에 가까운 근사해를 찾는 과정.
## 한 줄
> **"매 finite discrete set 위 의 best-element 찾기"**. TSP/Knapsack/Scheduling 의 OR core — 매 1947 Dantzig simplex 부터 매 2026 Gurobi 12 + neural CO hybrid. 매 production 의 매 routing/scheduling/matching 의 ubiquitous — 매 Amazon delivery/Uber matching/airline crew scheduling.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 탐색 공간이 이산적(Discrete)이고 방대하여 전수 조사가 불가능한 환경에서, 휴리스틱이나 동적 계획법 등을 통해 효율적으로 전역 최적해에 접근하는 탐색 패턴.
- **주요 문제 및 기법:**
- **Traveling Salesperson Problem (TSP):** 모든 지점을 한 번씩 방문하고 돌아오는 최소 경로 찾기.
- **Knapsack Problem:** 제한된 용량 내에서 가치의 합이 최대가 되도록 물건 담기.
- **Linear Programming (LP) / Integer Programming (IP):** 제약 조건 하에서 선형 함수를 최적화.
- **Greedy Algorithms:** 매 순간 최선의 선택을 하여 빠르게 근사해 도달.
- **Dynamic Programming (DP):** 문제를 작은 단위로 쪼개어 중복 계산 방지.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 고전적 알고리즘 위주에서, 최근에는 신경망(Neural Combinatorial Optimization)을 통해 복잡한 조합 문제를 학습 기반으로 해결하려는 시도가 활발함.
- **정책 변화:** Skybound 프로젝트는 수십 개의 기체가 실시간으로 최적의 사격 대형을 형성해야 하는 군집 AI 로직에 조합 최적화 알고리즘을 적용하여 연산 효율을 극대화함.
### 매 Canonical 문제
- **TSP** (Traveling Salesman): 매 NP-hard, 매 Concorde solver 의 84,000 cities 의 optimal.
- **Knapsack**: 매 NP-hard, 매 weakly — 매 pseudo-polynomial DP O(nW).
- **Set Cover / Vertex Cover**: 매 NP-hard, 매 LP rounding O(log n).
- **Min-cost Flow / Bipartite Matching**: 매 P 의 polynomial.
- **Job-Shop Scheduling**: 매 NP-hard, 매 CP-SAT 의 modern winner.
## 🔗 지식 연결 (Graph)
- [[Algorithm-Complexity-Big-O|Algorithm-Complexity-Big-O]], [[Genetic-Algorithms|Genetic-Algorithms]], [[Simulated-Annealing|Simulated-Annealing]], [[Game-Theory|Game-Theory]]
- **Raw Source:** 10_Wiki/Topics/AI/Combinatorial-Optimization.md
### 매 Solution 기법
- **Exact**: branch-and-bound, branch-and-cut, dynamic programming.
- **Approximation**: PTAS/FPTAS, LP relaxation + rounding, primal-dual.
- **Heuristic**: greedy, local search, simulated annealing, genetic algorithms.
- **Metaheuristic**: tabu search, ALNS, large-neighborhood search.
- **Modern**: CP-SAT (Google OR-Tools), MIP solvers, neural CO (Pointer Net, GFlowNet).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Complexity classes
- **P**: 매 Bipartite Matching (Hungarian O(n³)), Min Cut.
- **NP-hard**: 매 TSP, ILP, Vertex Cover, Set Cover.
- **APX-hard**: 매 Set Cover (no PTAS unless P=NP).
- **APX**: 매 Vertex Cover (2-approx trivial).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. **Vehicle routing (VRP)**: 매 Amazon Last Mile, UPS ORION.
2. **Workforce scheduling**: 매 airline crew, hospital nurse rostering.
3. **Bin packing**: 매 datacenter VM placement.
4. **Matching markets**: 매 Uber rider-driver, kidney exchange.
5. **Compiler register allocation**: 매 graph coloring.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Knapsack DP
```python
def knapsack_01(weights, values, capacity):
n = len(weights)
dp = [0] * (capacity + 1)
for i in range(n):
for w in range(capacity, weights[i] - 1, -1):
dp[w] = max(dp[w], dp[w - weights[i]] + values[i])
return dp[capacity]
```
## 🤔 의사결정 기준 (Decision Criteria)
### Branch-and-Bound TSP
```python
import heapq, math
**선택 A를 써야 할 때:**
- *(TODO)*
def tsp_bnb(dist):
n = len(dist)
best = math.inf
heap = [(0, [0])] # (lower_bound, path)
while heap:
lb, path = heapq.heappop(heap)
if lb >= best: continue
if len(path) == n:
cost = sum(dist[path[i]][path[i+1]] for i in range(n-1)) + dist[path[-1]][0]
best = min(best, cost); continue
for v in range(n):
if v not in path:
new_path = path + [v]
cur = sum(dist[new_path[i]][new_path[i+1]] for i in range(len(new_path)-1))
# 매 simple LB — 매 MST 의 better
heapq.heappush(heap, (cur, new_path))
return best
```
**선택 B를 써야 할 때:**
- *(TODO)*
### OR-Tools VRP (production scale)
```python
from ortools.constraint_solver import pywrapcp, routing_enums_pb2
**기본값:**
> *(TODO)*
def solve_vrp(distance_matrix, num_vehicles, depot=0):
mgr = pywrapcp.RoutingIndexManager(len(distance_matrix), num_vehicles, depot)
routing = pywrapcp.RoutingModel(mgr)
## ❌ 안티패턴 (Anti-Patterns)
def dist_cb(i, j): return distance_matrix[mgr.IndexToNode(i)][mgr.IndexToNode(j)]
transit_idx = routing.RegisterTransitCallback(dist_cb)
routing.SetArcCostEvaluatorOfAllVehicles(transit_idx)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
params = pywrapcp.DefaultRoutingSearchParameters()
params.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
params.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
params.time_limit.seconds = 10
return routing.SolveWithParameters(params)
```
### CP-SAT Job-Shop Scheduling
```python
from ortools.sat.python import cp_model
def job_shop(jobs): # jobs[j] = [(machine, duration), ...]
model = cp_model.CpModel()
horizon = sum(d for j in jobs for _, d in j)
tasks = {}
for j_id, job in enumerate(jobs):
for t_id, (m, d) in enumerate(job):
start = model.NewIntVar(0, horizon, f"s_{j_id}_{t_id}")
end = model.NewIntVar(0, horizon, f"e_{j_id}_{t_id}")
interval = model.NewIntervalVar(start, d, end, f"i_{j_id}_{t_id}")
tasks[(j_id, t_id)] = (start, end, interval, m)
machines = {}
for (j, t), (s, e, i, m) in tasks.items(): machines.setdefault(m, []).append(i)
for m, ivs in machines.items(): model.AddNoOverlap(ivs)
for j_id, job in enumerate(jobs):
for t in range(len(job) - 1):
model.Add(tasks[(j_id, t+1)][0] >= tasks[(j_id, t)][1])
makespan = model.NewIntVar(0, horizon, "makespan")
model.AddMaxEquality(makespan, [tasks[(j, len(jobs[j])-1)][1] for j in range(len(jobs))])
model.Minimize(makespan)
solver = cp_model.CpSolver()
solver.parameters.max_time_in_seconds = 30
return solver.Solve(model)
```
### Simulated Annealing TSP
```python
import random, math
def sa_tsp(dist, iters=100000, T0=10.0, alpha=0.9999):
n = len(dist)
cur = list(range(n)); random.shuffle(cur)
def cost(p): return sum(dist[p[i]][p[(i+1)%n]] for i in range(n))
cc = cost(cur); best, bc = cur[:], cc; T = T0
for _ in range(iters):
i, j = sorted(random.sample(range(n), 2))
new = cur[:i] + cur[i:j+1][::-1] + cur[j+1:]
nc = cost(new)
if nc < cc or random.random() < math.exp((cc - nc) / T):
cur, cc = new, nc
if cc < bc: best, bc = cur[:], cc
T *= alpha
return best, bc
```
### LP Relaxation + Rounding (Set Cover)
```python
import cvxpy as cp
import numpy as np
def set_cover_lp(sets, universe):
n, m = len(sets), len(universe)
x = cp.Variable(n, nonneg=True)
constraints = []
for u in universe:
constraints.append(sum(x[i] for i, s in enumerate(sets) if u in s) >= 1)
cp.Problem(cp.Minimize(sum(x)), constraints).solve()
# 매 randomized rounding — 매 O(log n) approximation
return [i for i in range(n) if np.random.random() < min(1, x.value[i] * np.log(m))]
```
## 매 결정 기준
| 문제 size | Approach |
|---|---|
| n < 20 (TSP) | Brute force / DP held-karp O(n²·2ⁿ) |
| n < 100 (TSP) | Branch-and-cut + MTZ formulation |
| n > 1000 (TSP) | LKH heuristic / Concorde |
| Scheduling | CP-SAT (OR-Tools) — 매 modern winner |
| Real-time matching | Hungarian / auction algorithm |
| ILP general | Gurobi/CPLEX > SCIP > CBC |
**기본값**: 매 OR-Tools (CP-SAT) 의 free + production-grade.
## 🔗 Graph
- 부모: [[Optimization]] · [[Operations Research]] · [[Algorithms]]
- 변형: [[Linear Programming]] · [[Integer Programming]] · [[Constraint Programming]]
- 응용: [[Vehicle Routing]] · [[Job-Shop Scheduling]] · [[Bin Packing]] · [[Matching]]
- Adjacent: [[NP-Completeness]] · [[Approximation Algorithms]] · [[Metaheuristics]] · [[Neural CO]]
## 🤖 LLM 활용
**언제**: 매 problem-to-formulation translation, 매 OR-Tools/Gurobi code scaffold, 매 constraint reformulation 의 brainstorm.
**언제 X**: 매 large-scale numerical solving (의 dedicated solver 영역), 매 verified optimal proof.
## ❌ 안티패턴
- **Hand-rolled greedy 의 production**: 매 OR-Tools 의 90% 의 better 의 거의 모든 case.
- **ILP everywhere**: 매 LP relaxation feasible 의 fast solve 의 missing.
- **No warm-start**: 매 incremental re-solve 의 1000x speedup 의 missing.
- **Ignoring problem structure**: 매 specialized algorithm (Hungarian, Held-Karp) 의 generic ILP 의 better.
- **Exact 의 over-pursuit**: 매 NP-hard 의 1% gap 의 충분 의 99% case.
## 🧪 검증 / 중복
- Verified (Cook _In Pursuit of TSP_, Schrijver _Combinatorial Optimization_, Wolsey _Integer Programming_).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — DP/B&B/CP-SAT/SA/LP-rounding patterns |
@@ -2,234 +2,139 @@
id: wiki-2026-0508-computer-science-and-theory
title: Computer Science and Theory
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [CS Theory, TCS, Theoretical Computer Science]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [category-index, computer_science_and_theory]
confidence_score: 0.9
verification_status: applied
tags: [index, theory, foundation, computability, complexity]
raw_sources: []
last_reinforced: 2026-05-08
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: N/A
framework: index
---
# Computer Science and Theory Directory
# Computer Science and Theory
이 문서는 `Computer_Science_and_Theory` 카테고리에 속한 모든 지식 문서들의 목록을 제공합니다.
## 매 한 줄
> **"매 computation 의 fundamental limits + structures 의 systematic study"**. Turing 1936 → Church-Turing thesis → Cook-Levin 1971 NP-completeness → 2026 quantum supremacy + post-ML complexity. 매 folder 의 매 index — 매 child topics 의 navigation hub.
## 📄 문서 목록
- [[Abstract-Syntax-Tree-Transformation]] : [[Abstract-Syntax-Tree-Transformation|Abstract-Syntax-Tree-Transformation]] (AST 변환)
- [[Adaptive-Curation]] : [[Adaptive-Curation|Adaptive-Curation]]
- [[Additive-Type-Logic]] : [[Additive-Type-Logic|Additive-Type-Logic]] (가법 타입 논리)
- [[Aesthetic-Value]] : [[Aesthetic-Value|Aesthetic-Value]]
- [[Alcoholism]] : [[Alcoholism|Alcoholism]]
- [[Algorithm-Complexity-Big-O]] : Algorithm Complexity (Big O, 알고리즘 복잡도)
- [[Atomism]] : [[Atomism|Atomism]]
- [[Autobiography]] : [[Autobiography|Autobiography]]
- [[Autoethnography]] : [[Autoethnography|Autoethnography]]
- [[Automated-Decision-Making]] : [[Automated-Decision-Making|Automated-Decision-Making]]
- [[Automated-Map-Generation]] : [[Automated-Map-Generation|Automated-Map-Generation]] (절차적 맵 생성 PCG)
- [[Autonomous-Vehicle-Path-Planning]] : [[Autonomous-Vehicle-Path-Planning|Autonomous-Vehicle-Path-Planning]] (자율주행 경로 계획)
- [[Axiology]] : [[Axiology|Axiology]]
- [[Axiomatic-Systems]] : [[Axiomatic-Systems|Axiomatic-Systems]]
- [[B-Tree]] : [[B-Tree|B-Tree]] (B-트리)
- [[BFS vs DFS]] : [[BFS vs DFS|BFS vs DFS]]
- [[Biological-Inspired-Algorithms]] : BioLogical-Inspired-Algorithms (생물 유래 알고리즘)
- [[Black-Hole]] : [[Black-Hole|Black-Hole]]
- [[Bloom-Filters in Search]] : Bloom Filters in Search (검색에서의 블룸 필터)
- [[Brute-force]] : [[Brute-force|Brute-force]]
- [[Bubble-Sort]] : [[Bubble-Sort|Bubble-Sort]]
- [[Burnout Prevention in Professional Gaming]] : Burnout-Prevention-in-Professional-Gaming (프로게이머 번아웃 방지)
- [[Chaos-Theory in Systems]] : Chaos Theory in Systems (시스템에서의 카오스 이론)
- [[Climate Change Mitigation Frameworks]] : Climate-Change-Mitigation-Frameworks (기후 변화 대응 프레임워크)
- [[Cognitive Load & Mental Models]] : Cognitive Load & Mental Models (인지 부하 및 멘탈 모델)
- [[Cognitive Neuroscience of Flow]] : Cognitive-Neuroscience-of-Flow (몰입의 뇌과학)
- [[Combinatorial-Optimization]] : Combinatorial Optimization (조합 최적화)
- [[Control-Theory]] : Control Theory (제어 이론)
- [[Decision Theory]] : [[Decision Theory|Decision Theory]]
- [[Determinism-in-Computing]] : Determinism in Computing (계산의 결정론)
- [[Dijkstra's Algorithm]] : Dijkstra's-Algorithm (데이크스트라 알고리즘)
- [[Directed-Acyclic-Graph-Dependency-Management]] : Directed Acyclic Graph (DAG, 유향 비순환 그래프)
- [[Dissipative-Structures]] : [[Dissipative-Structures|Dissipative-Structures]]
- [[Dynamic-Programming]] : [[Dynamic-Programming|Dynamic-Programming]]
- [[Economic-Complexity-Index]] : [[Economic-Complexity-Index|Economic-Complexity-Index]]
- [[Eigenvalues-and-Eigenvectors]] : Eigenvalues and Eigenvectors (고유값과 고유벡터)
- [[Elite-Theory]] : [[Elite-Theory|Elite-Theory]]
- [[Emergence-in-Systems]] : Emergence in[[_system|system]]s (시스템에서의 창발)
- [[Emergence]] : [[Emergence|Emergence]]
- [[Entropy in Information Theory]] : Entropy in [[Information Theory|Information Theory]] (정보 이론에서의 엔트로피)
- [[Ergodic-Theory]] : [[Ergodic-Theory|Ergodic-Theory]]
- [[Ethnographic-Research]] : [[Ethnographic-Research|Ethnographic-Research]]
- [[Evolutionary-Algorithm-Design]] : [[Evolutionary-Algorithm-Design|Evolutionary-Algorithm-Design]]
- [[Evolutionary-Algorithms]] : [[Evolutionary-Algorithms|Evolutionary-Algorithms]]
- [[Expectation-Maximization]] : [[Expectation-Maximization|Expectation-Maximization]]
- [[Feedback-Control-Systems]] : Feedback Control[[_system|system]]s (피드백 제어 시스템)
- [[Feedback-Loops in Systems]] : Feedback Loops in[[_system|system]]s (시스템에서의 피드백 루프)
- [[Finite-Element-Analysis]] : Finite Element [[Analysis|Analysis]] (FEA, 유한 요소 해석)
- [[Flame-Icicle_Graph_플레임-고드름_그래프]] : Flame/Icicle Graph (플레임/고드름 그래프)
- [[Geographic-Information-Systems]] : [[Geographic-Information-Systems|Geographic-Information-Systems]]
- [[Gimbals-and-Orientation]] : Gimbals and Orientation (짐벌과 방향 제어)
- [[Godel's Incompleteness Theorems]] : [[Godel's Incompleteness Theorems|Godel's Incompleteness Theorems]]
- [[Graph-Coloring-Problem]] : [[Graph-Coloring-Problem|Graph-Coloring-Problem]]
- [[GraphRAG & Knowledge Graph Memory]] : GraphRAG & Knowledge Graph Memory (지식 그래프 메모리)
- [[Greedy-Algorithms]] : Greedy Algorithms (탐욕 알고리즘)
- [[Grounded Theory Method]] : [[Grounded Theory Method|Grounded Theory Method]]
- [[Hardware-Verification]] : [[Hardware-Verification|Hardware-Verification]]
- [[Hash-Functions-and-Maps]] : Hash Functions and Maps (해시 함수와 맵)
- [[Hebbian-Theory]] : [[Hebbian-Theory|Hebbian-Theory]]
- [[High-Frequency-Trading-Models]] : [[High-Frequency-Trading-Models|High-Frequency-Trading-Models]]
- [[Incremental-Computation]] : [[Incremental-Computation|Incremental-Computation]]
- [[Inexact-Science]] : [[Inexact-Science|Inexact-Science]]
- [[Information-Entropy]] : [[Information-Entropy|Information-Entropy]]
- [[Inner-Product-Spaces]] : Inner Product Spaces (내적 공간)
- [[Issue Tree]] : [[Issue Tree|Issue Tree]]
- [[Kalman-Filter-and-State-Tracking]] : Kalman Filter and State Tracking (칼만 필터와 상태 추적)
- [[Kernel-Density-Estimation-KDE]] : Kernel Density Estimation (KDE, 커널 밀도 추정)
- [[Knowledge-Graph-Foundations]] : Knowledge Graph Foundations (지식 그래프 기초)
- [[Knowledge-Structure]] : [[Knowledge-Structure|Knowledge-Structure]]
- [[Kolmogorov-Complexity]] : Kolmogorov Complexity (콜모고로프 복잡도)
- [[Kullback-Leibler-Divergence]] : Kullback-Leibler Divergence (KL 발산)
- [[Lagrange-Multipliers]] : Lagrange Multipliers (라그랑주 승수법)
- [[Least-Squares-Methods]] : Least Squares Methods (최소제곱법)
- [[Linear-Algebra-Foundations]] : Linear Algebra Foundations (선형대수학 기초)
- [[Linked-Lists-and-Trees]] : Linked Lists and Trees (연결 리스트와 트리)
- [[Locality-Sensitive-Hashing (LSH)]] : [[Locality-Sensitive-Hashing (LSH)|Locality-Sensitive-Hashing (LSH)]]
- [[Locality-Sensitive-Hashing]] : Locality-Sensitive Hashing (LSH, 지역 민감 해싱)
- [[Logic Trees]] : [[Logic Trees|Logic Trees]]
- [[Lubrication]] : [[Lubrication|Lubrication]]
- [[Model-Predictive-Control (MPC)]] : [[Model-Predictive-Control (MPC)|Model-Predictive-Control (MPC)]] (모델 예측 제어)
- [[Monte-Carlo-Integration]] : Monte Carlo Integration (몬테카를로 적분)
- [[Multivariate-Analysis]] : Multivariate Analysis (다변량 분석)
- [[Mutual-Information]] : Mutual Information (상호 정보량)
- [[Mutually Exclusive and Collectively Exhaustive (MECE)]] : [[Mutually Exclusive and Collectively Exhaustive (MECE)|Mutually Exclusive and Collectively Exhaustive (MECE]]
- [[Noise]] : [[Noise|Noise]]
- [[Operations-Research]] : [[Operations-Research|Operations-Research]]
- [[Operator-Theory]] : [[Operator-Theory|Operator-Theory]]
- [[Optimal-Control-Theory]] : Optimal Control Theory (최적 제어 이론)
- [[Optimization-Algorithms]] : Optimization Algorithms (최적화 알고리즘)
- [[Optimization]] : [[Optimization|Optimization]]
- [[PCA-and-Dimension-Reduction]] : PCA and Dimension Reduction (PCA와 차원 축소)
- [[PID-Controllers-in-AI]] : PID Controllers in AI (AI에서의 PID 제어기)
- [[Partial-Differential-Equations]] : Partial Differential Equations (PDE, 편미분 방정식)
- [[Particle-Filter-Algorithms]] : Particle Filter Algorithms (파티클 필터 알고리즘)
- [[Posterior-and-Prior-Probability]] : Posterior and Prior Probability (사후 및 사전 확률)
- [[Principal-Component-Analysis]] : Principal Component Analysis (주성분 분석)
- [[Principle-of-Least-Action]] : Principle of Least Action (최소 작용의 원리)
- [[Probability Theory]] : [[Probability Theory|Probability Theory]]
- [[Probability-Theory-Foundations]] : [[Probability Theory|Probability Theory]] Foundations (확률론 기초)
- [[Profiling-and-Optimization]] : Profiling and Optimization (프로파일링과 최적화)
- [[Profitability Framework]] : [[Profitability Framework|Profitability Framework]]
- [[Psychology-of-Learning]] : Psychology of Learning (학습 심리학)
- [[Quantum Computing (Intro)]] : [[Quantum Computing (Intro)|Quantum Computing (Intro)]]
- [[Quantum-Computing]] : [[Quantum-Computing|Quantum-Computing]]
- [[Ranking-Algorithms]] : Ranking Algorithms (순위 산정 알고리즘)
- [[Regression-Analysis-Foundations]] : Regression [[Analysis|Analysis]] Foundations (회귀 분석 기초)
- [[Relevance-Feedback]] : Relevance Feedback (관련성 피드백)
- [[Reports]] : [[Reports|Reports]]
- [[Representation Theory]] : Representation-Theory
- [[Ridge-Regression]] : Ridge Regression (릿지 회귀)
- [[Root-Cause-Analysis-RCA]] : Root Cause [[Analysis|Analysis]] (RCA, 근본 원인 분석)
- [[Root-Mean-Square-Error]] : Root Mean Square Error (RMSE, 평균 제곱근 오차)
- [[Roughness (그래픽 및 물리)]] : [[Roughness (그래픽 및 물리)|Roughness (그래픽 및 물리)]]
- [[Sampling-Techniques]] : Sampling Techniques (샘플링 기법)
- [[Scientific-Computing-with-Python]] : Scientific Computing with Python (파이썬을 활용한 과학 연산)
- [[Semantics & Ontology]] : [[Semantics & Ontology|Semantics & Ontology]]
- [[Signal in Noise]] : [[Signal in Noise|Signal in Noise]]
- [[Signal-Processing-Foundations]] : Signal Processing Foundations (신호 처리 기초)
- [[Similarity-Metrics]] : [[Similarity-Metrics|Similarity-Metrics]]
- [[Simulated-Annealing]] : Simulated Annealing (시뮬레이티드 어닐링)
- [[Singular-Value-Decomposition]] : Singular Value Decomposition (SVD, 특이값 분해)
- [[Social Systems Theory]] : [[Social Systems Theory|Social Systems Theory]]
- [[Social-Network-Analysis]] : Social Network Analysis (사회망 분석)
- [[Sorting]] : [[Sorting|Sorting]]
- [[Spatial-Data-Analysis]] : Spatial Data Analysis (공간 데이터 분석)
- [[Standard-Deviation-and-Variance]] : Standard Deviation and Variance (표준 편차 및 분산)
- [[Statistical-Hypothesis-Testing]] : Statistical Hypothesis [[Testing|Testing]] (통계적 가설 검정)
- [[Statistical-Power]] : Statistical Power (통계적 검정력)
- [[Statistics]] : [[Statistics|Statistics]]
- [[Structural-Equation-Modeling]] : Structural Equation Modeling (SEM, 구조 방정식 모델링)
- [[Systemic_Simulation_Principles]] : 시스템 시뮬레이션 설계 원리
- [[Theoretical-Computer-Science]] : Theoretical Computer Science (이론 컴퓨터 과학)
- [[Turing-Machine Foundations]] : Turing Machine Foundations (튜링 머신 기초)
- [[Type Theory]] : [[Type Theory|Type Theory]] (타입 이론)
- [[VPS_NeRF]] : VPS & NeRF (Visual PositioningSystem)
- [[Wicked-Problems]] : [[Wicked-Problems|Wicked-Problems]]
- [[탄도학 및 명중률 알고리즘 (Ballistics and Accuracy Algorithms)]] : 탄도학 및 명중률 알고리즘 (Ballistics and Accuracy Algorithms)
## 매 핵심
## 📌 한 줄 통찰 (The Karpathy Summary)
### 매 Pillars
- **Computability**: 매 무엇이 computable 인가 — 매 Turing machine, halting problem.
- **Complexity**: 매 얼마나 efficient 인가 — 매 P/NP/PSPACE/EXPTIME/BQP.
- **Algorithms**: 매 specific computational procedures — 매 design + analysis.
- **Logic & Formal Languages**: 매 syntax/semantics — 매 Chomsky hierarchy.
- **Information Theory**: 매 entropy, coding, compression bounds.
- **Cryptography Theory**: 매 reduction-based security, OWF.
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
### 매 Subdomain map
1. **Algorithms & Data Structures**: sorting, graphs, DP, randomized.
2. **Combinatorial Optimization**: TSP, scheduling, matching.
3. **Dynamical Systems**: chaos, control theory, stability.
4. **Theory of Computation**: automata, decidability, complexity classes.
5. **Type Theory**: simply-typed lambda, dependent types, HoTT.
6. **Quantum Information**: BQP, qubits, error correction.
## 📖 구조화된 지식 (Synthesized Content)
### 매 응용 bridge
- 매 cryptography ← 매 complexity (OWF, hash functions).
- 매 ML theory ← 매 PAC learning, VC dimension, generalization bounds.
- 매 distributed systems ← 매 FLP impossibility, consensus lower bounds.
- 매 compilers ← 매 type theory, automata, lambda calculus.
- 매 databases ← 매 query complexity, join algorithms.
**추출된 패턴:**
> *(TODO)*
## 💻 패턴
**세부 내용:**
- *(TODO)*
### Folder Sub-topics (representative)
| Topic | Type |
|---|---|
| Bubble Sort | Algorithm — sorting |
| Combinatorial Optimization | Algorithm — discrete |
| Chaos Theory in Systems | Dynamical systems |
| Control Theory | Dynamical systems |
| Cross-Frequency Coupling | Neural information theory |
| Caetextia | Cognitive theory |
| Burnout Prevention in Professional Gaming | Applied cognitive |
| Climate Change Mitigation Frameworks | Applied modeling |
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Index Page Convention
```yaml
purpose: navigate child topics in this folder
canonical_id: self
duplicate_of: none
content:
- 매 한 줄: domain summary
- 매 핵심: pillars + subdomains
- 매 패턴: child topic listing
- 🔗 Graph: parent index + sibling folders
```
## 🤔 의사결정 기준 (Decision Criteria)
### Cross-Folder Bridge Pattern
```markdown
## Parent index
- [[10_Wiki Index]] · [[Programming Index]]
## Sibling folders (Topics/)
- [[AI_and_ML]] · [[Architecture]] · [[DevOps_and_Security]]
- [[Cognitive_Science_and_Neuroscience]] · [[Frontend]] · [[Backend]]
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Complexity Cheat Sheet
```text
P ⊆ NP ⊆ PSPACE ⊆ EXPTIME
P ⊆ BPP ⊆ BQP ⊆ PP ⊆ PSPACE
NP — verifiable in poly-time
NP-complete — TSP, SAT, 3-COLOR, Knapsack (decision)
NP-hard ∩ EXP — Halting (undecidable)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Theory → Practice Mapping
```yaml
theory_to_practice:
- {theory: NP-completeness, practice: "use heuristics + approximation"}
- {theory: P=NP open, practice: "assume P≠NP for crypto"}
- {theory: FLP impossibility, practice: "consensus needs partial sync (Raft/Paxos)"}
- {theory: CAP theorem, practice: "pick 2: CP or AP under partition"}
- {theory: PCP theorem, practice: "hardness of approximation results"}
```
**기본값:**
> *(TODO)*
## 매 결정 기준
| Question | Direction |
|---|---|
| Sort/search basics | Algorithms & Data Structures |
| Discrete optimization | Combinatorial Optimization |
| System stability | Control Theory / Chaos |
| Compiler/PL design | Type Theory / Lambda Calculus |
| Crypto foundations | Complexity / Number Theory |
| Distributed system limits | Theory of Distributed Computing |
## ❌ 안티패턴 (Anti-Patterns)
**기본값**: 매 child topic 의 specific 의 navigate — 매 index 의 entry point only.
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 🔗 Graph
- 부모: [[10_Wiki Index]] · [[Programming Index]]
- 자식: [[Bubble Sort]] · [[Combinatorial Optimization]] · [[Chaos Theory in Systems]] · [[Control Theory]] · [[Caetextia]] · [[Cognitive Neuroscience of Flow]] · [[Cross-Frequency Coupling (CFC)]] · [[Climate Change Mitigation Frameworks]] · [[Burnout Prevention in Professional Gaming]]
- Sibling 폴더: [[AI_and_ML]] · [[Architecture]] · [[Cognitive_Science_and_Neuroscience]] · [[DevOps_and_Security]]
- Adjacent: [[Mathematics]] · [[Information Theory]] · [[Logic]]
## 🤖 LLM 활용
**언제**: 매 navigation hub — 매 child topic 의 discovery.
**언제 X**: 매 specific algorithm content — 매 child page 의 redirect.
## ❌ 안티패턴
- **Index 의 deep content**: 매 child page 의 duplicate — 매 stale risk.
- **Stale child link**: 매 deleted/moved page 의 broken wikilink.
- **Mixed scope**: 매 index 의 specific application 의 mix — 매 child page 의 belong.
## 🧪 검증 / 중복
- Verified (folder taxonomy 의 cross-checked, child pages exist).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — folder index with child taxonomy + theory-practice mapping |
@@ -2,63 +2,199 @@
id: wiki-2026-0508-control-theory
title: Control Theory
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [CONTROL-001]
aliases: [Feedback Control, Cybernetics, Automatic Control]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [mathematics, engineering, control-theory, pid, feedback-loop]
confidence_score: 0.9
verification_status: applied
tags: [control, feedback, dynamical-systems, robotics, distributed-systems]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python/MATLAB/C++
framework: scipy.signal / control / Drake
---
# Control Theory (제어 이론)
# Control Theory
## 📌 한 줄 통찰 (The Karpathy Summary)
> "현재의 오차를 측정하여 미래의 행동을 정밀하게 교정하라" — 동역학 시스템의 출력을 원하는 목표 상태로 유지하기 위해 입력을 조정하는 공학적 방법론으로, 피드백 루프와 안정성 분석이 핵심.
## 한 줄
> **"매 system output 의 desired trajectory 의 driving 의 feedback law 설계"**. Watt centrifugal governor (1788) → Wiener cybernetics (1948) → Kalman state-space (1960) → 2026 MPC + neural-augmented control. 매 robotics/aerospace + 매 distributed systems (TCP congestion, autoscaling, DB connection pool) 의 unified framework.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 목표값(Desired [[State|State]])과 현재값(Actual State) 사이의 차이인 오차(Error)를 실시간으로 계산하고, 이를 보정하기 위한 제어 신호를 생성하여 시스템을 안정화하는 피드백 패턴.
- **핵심 구성 요소:**
- **Open-loop Control:** 피드백 없이 정해진 입력만 전달 (예: 세탁기 타이머).
- **Closed-loop Control (Feedback):** 출력을 다시 입력에 반영하여 오차 수정.
- **PID Control:** 비례(P), 적분(I), 미분(D) 항의 조합으로 오차를 빠르고 부드럽게 제거.
- **Stability:** 시스템이 발산하지 않고 수렴하는지 분석 (예: Lyapunov 안정성).
- **의의:** 로봇 공학, 자율주행, 드론 비행 제어, 그리고 강화학습의 이론적 토대.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 고정된 수학 모델에 기반한 고전 제어에서, 최근에는 복잡한 환경에 적응하는 적응 제어(Adaptive Control)와 AI를 결합한 지능형 제어로 진화.
- **정책 변화:** Skybound 프로젝트의 미사일 추적 로직은 PID 제어 원리를 사용하여, 타겟의 움직임 변화에 부드럽고 정확하게 대응하도록 구현함.
### 매 Control taxonomy
- **Open-loop**: 매 feedback X — 매 disturbance 의 fragile.
- **Closed-loop**: 매 measurement → error → adjust — 매 robust.
- **PID**: 매 industry workhorse — 매 95% controllers in field.
- **State-space**: 매 multi-input/multi-output (MIMO) — 매 Kalman/LQR.
- **MPC** (Model Predictive Control): 매 optimization-based — 매 Tesla autopilot, ABB.
- **Adaptive/Robust**: 매 H∞, gain scheduling — 매 plant uncertainty.
- **Reinforcement learning**: 매 model-free policy — 매 simulator-trained.
## 🔗 지식 연결 (Graph)
- [[Physics|Physics]]-Engine, [[Reinforcement-Learning|Reinforcement-Learning]], [[Cybernetics|Cybernetics]]-Foundations, [[Robotics|Robotics]]
- **Raw Source:** 10_Wiki/Topics/AI/Control-Theory.md
### 매 PID 분해
- **P (proportional)**: 매 current error 의 비례 — 매 stiffness.
- **I (integral)**: 매 accumulated error 의 누적 — 매 steady-state offset 의 elimination.
- **D (derivative)**: 매 error rate 의 — 매 damping (overshoot 감소).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Stability
- **Lyapunov stability**: V(x) > 0, V̇(x) < 0 → asymptotic.
- **Routh-Hurwitz**: 매 polynomial coefficient 의 root location 검사.
- **Bode/Nyquist**: 매 frequency-domain phase/gain margin.
- **Pole placement**: 매 closed-loop pole 의 LHP 의 위치.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. **Robotics**: 매 manipulator joint control, drone attitude.
2. **Datacenter**: 매 autoscaling (PID on queue depth), thermal control.
3. **Networking**: 매 TCP cubic, BBR — 매 congestion control as control problem.
4. **DB**: 매 connection pool sizing, adaptive query throttling.
5. **Game AI**: 매 NPC steering (Reynolds), camera follow.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### PID Controller (basic)
```python
class PID:
def __init__(self, kp, ki, kd, dt, output_clip=(None, None)):
self.kp, self.ki, self.kd, self.dt = kp, ki, kd, dt
self.integral = 0.0; self.prev_error = 0.0
self.lo, self.hi = output_clip
def step(self, setpoint, measurement):
error = setpoint - measurement
self.integral += error * self.dt
derivative = (error - self.prev_error) / self.dt
u = self.kp*error + self.ki*self.integral + self.kd*derivative
self.prev_error = error
if self.lo is not None: u = max(self.lo, u)
if self.hi is not None: u = min(self.hi, u)
return u
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Anti-Windup PID (production)
```python
class PIDAntiWindup(PID):
def step(self, setpoint, measurement):
error = setpoint - measurement
derivative = (error - self.prev_error) / self.dt
u_unclamped = self.kp*error + self.ki*self.integral + self.kd*derivative
u = u_unclamped
if self.lo is not None: u = max(self.lo, u)
if self.hi is not None: u = min(self.hi, u)
# 매 saturation 의 integral 의 stop — 매 windup 방지
if u == u_unclamped:
self.integral += error * self.dt
self.prev_error = error
return u
```
## 🧬 중복 검사 (Duplicate Check)
### LQR (Linear Quadratic Regulator)
```python
import numpy as np
import scipy.linalg as la
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
def lqr(A, B, Q, R):
# 매 minimize ∫ x'Qx + u'Ru dt subject to ẋ = Ax + Bu
P = la.solve_continuous_are(A, B, Q, R)
K = np.linalg.solve(R, B.T @ P)
return K # u = -Kx
```
## 🕓 변경 이력 (Changelog)
### Kalman Filter
```python
class KalmanFilter:
def __init__(self, A, B, H, Q, R, x0, P0):
self.A, self.B, self.H, self.Q, self.R = A, B, H, Q, R
self.x, self.P = x0, P0
def predict(self, u):
self.x = self.A @ self.x + self.B @ u
self.P = self.A @ self.P @ self.A.T + self.Q
def update(self, z):
S = self.H @ self.P @ self.H.T + self.R
K = self.P @ self.H.T @ np.linalg.inv(S)
self.x += K @ (z - self.H @ self.x)
self.P = (np.eye(len(self.x)) - K @ self.H) @ self.P
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Autoscaler as PID Controller
```python
# 매 distributed system 의 control-theory 적용
class PIDAutoscaler:
def __init__(self, target_p99_ms=100, kp=0.05, ki=0.001, kd=0.5):
self.target = target_p99_ms
self.pid = PIDAntiWindup(kp, ki, kd, dt=10.0, output_clip=(2, 200))
def desired_replicas(self, current_replicas, observed_p99_ms):
# 매 latency 의 setpoint 위로 → 매 replicas 의 추가
delta = self.pid.step(self.target, observed_p99_ms) * -1 # invert sign
return max(2, round(current_replicas + delta))
```
### MPC Skeleton (cvxpy)
```python
import cvxpy as cp
def mpc_step(A, B, x0, Q, R, N=10, x_ref=None):
nx, nu = A.shape[0], B.shape[1]
x = cp.Variable((nx, N + 1))
u = cp.Variable((nu, N))
cost, cons = 0, [x[:, 0] == x0]
x_ref = np.zeros(nx) if x_ref is None else x_ref
for k in range(N):
cost += cp.quad_form(x[:, k] - x_ref, Q) + cp.quad_form(u[:, k], R)
cons += [x[:, k + 1] == A @ x[:, k] + B @ u[:, k]]
cons += [cp.norm(u[:, k], "inf") <= 1.0] # control limit
cp.Problem(cp.Minimize(cost), cons).solve()
return u.value[:, 0] # 매 first action only — 매 receding horizon
```
### Bode Stability Margin
```python
from scipy import signal
def stability_margins(num, den):
sys = signal.TransferFunction(num, den)
w, mag, phase = signal.bode(sys)
# gain margin: phase = -180° 의 frequency 에서 1/|G|
# phase margin: |G| = 1 의 frequency 에서 phase + 180°
return {"bode": (w, mag, phase)}
```
## 매 결정 기준
| 시스템 | Approach |
|---|---|
| SISO, slow | PID (anti-windup + clamp) |
| MIMO, linear | LQR + Kalman |
| Constraints + nonlinear | MPC |
| Plant unknown | RL or adaptive control |
| Distributed scaling | PID on metric (queue/p99) |
| Game AI steering | PD (no integral, snappy) |
**기본값**: 매 PID + anti-windup — 매 production 의 80% case.
## 🔗 Graph
- 부모: [[Dynamical Systems]] · [[Cybernetics]]
- 변형: [[PID Controller]] · [[LQR]] · [[MPC]] · [[Adaptive Control]]
- 응용: [[Robotics]] · [[Autoscaling]] · [[TCP Congestion Control]] · [[Drone Flight Control]]
- Adjacent: [[Kalman Filter]] · [[Lyapunov Stability]] · [[Reinforcement Learning]] · [[Chaos Theory in Systems]]
## 🤖 LLM 활용
**언제**: 매 PID gain 의 starting point suggestion, 매 state-space derivation, 매 controller code scaffold.
**언제 X**: 매 safety-critical (avionics/medical) 의 final certification — 매 formal verification 영역.
## ❌ 안티패턴
- **No anti-windup**: 매 saturated actuator 의 integral 의 explosion.
- **No derivative filter**: 매 measurement noise 의 D term 의 amplification.
- **Tuning without model**: 매 Ziegler-Nichols 의 marginal stability 의 risk.
- **PID for highly nonlinear**: 매 gain scheduling 또는 MPC 의 더 적합.
- **No anti-aliasing**: 매 fast dynamics 의 sample rate 의 violation.
## 🧪 검증 / 중복
- Verified (Åström _Feedback Systems_ 2.5, Ogata _Modern Control_ 5e, Kalman 1960).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — PID/LQR/Kalman/MPC + autoscaler bridge |
@@ -2,111 +2,189 @@
id: wiki-2026-0508-cross-frequency-coupling-cfc
title: Cross Frequency Coupling (CFC)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [CFC, Phase-Amplitude Coupling, PAC, Theta-Gamma Coupling]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.85
verification_status: applied
tags: [neuroscience, eeg, signal-processing, brain, oscillations]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python
framework: MNE-Python / tensorpac / scipy
---
# [[교차 주파수 결합 (CFC)]]
# Cross Frequency Coupling (CFC)
## 📌 한 줄 통찰 (The Karpathy Summary)
교차 주파수 결합(Cross-Frequency Coupling, CFC)은 서로 다른 주파수 대역의 신경 진동(뇌파)이 동시에 발생하며 상호작용하는 뇌의 기능적 연결 메커니즘이다 [1]. 특히 느린 뇌파의 위상이 빠른 뇌파의 진폭을 변조하는 위상-진폭 결합(PAC)의 형태가 대표적이다 [1, 2]. 이는 멀리 떨어진 뇌 영역 간의 통신을 동기화하고, 산재된 감각 정보를 작업 기억 내에서 하나의 일관된 경험으로 묶어내는 맥락 통합의 핵심적인 신경 생물학적 기제로 작용한다 [1, 2].
## 한 줄
> **"매 brain oscillation 의 매 multi-band interaction"**. Bragin 1995 hippocampus theta-gamma 발견 → Canolty 2006 PAC formalism → 2026 closed-loop neurostim 의 clinical use. 매 working memory + attention + sensorimotor binding 의 매 candidate mechanism — 매 BCI/neurofeedback의 actionable feature.
## 📖 구조화된 지식 (Synthesized Content)
* **주파수 간 상호작용 및 위상-진폭 결합(PAC):**
주파수 영역 내의 다양한 뇌파(EEG) 진동은 독립적으로 작용하는 것이 아니라, 교차 주파수 진동의 상호작용을 통해 여러 신경 네트워크의 통합을 조절한다 [1]. CFC의 가장 널리 알려진 형태인 위상-진폭 결합(Phase-Amplitude Coupling, PAC)은 느린 진동 주파수(예: 세타파)의 위상이 더 빠른 진동 주파수(예: 감마파)의 진폭을 변조하는 구조를 가진다 [1, 2]. PAC는 다양한 뇌 영역에 걸쳐 보고되며 인지 기능 간의 상호작용 및 지역 신경망 간의 통신을 반영한다 [1].
## 매 핵심
* **결합 문제(Binding Problem) 해결과 전역적 맥락 통합:**
뇌가 시각, 청각 등 분산된 감각 정보를 하나의 의미 있는 맥락으로 묶는 이른바 '결합 문제'는 세타 주파수(약 4-12Hz)와 감마 주파수(약 30-100Hz) 간의 결합을 통해 해결된다 [2]. 뇌는 이 세타-감마 결합(Theta-Gamma Coupling, TGC)을 이용하여 멀리 떨어진 영역 간의 의사소통을 동기화하고 정보를 하나의 통일된 맥락적 경험으로 통합한다 [1-3].
### 매 CFC types
- **Phase-Amplitude Coupling (PAC)**: 매 low-freq phase 의 high-freq amplitude 의 modulation — 매 most studied (theta phase × gamma amplitude).
- **Phase-Phase Coupling (n:m)**: 매 phase synchrony at integer ratios — 매 7:1 theta-gamma 의 hippocampus.
- **Amplitude-Amplitude Coupling**: 매 envelope co-fluctuation.
- **Phase-Frequency Coupling**: 매 less common.
* **작업 기억(Working Memory) 내 다중 정보 처리 메커니즘:**
빠른 리듬의 뇌 활동이 느린 뇌파 안에 중첩(Nesting)되는 현상은 다중 항목의 작업 기억을 유지하는 핵심 메커니즘으로 여겨진다 [1]. 세타 주기의 특정 위상에 여러 개의 감마 하위 주기(subcycle)가 실리는 구조는 뇌가 다수의 정보를 순서대로 정렬하여 기억하도록 돕는다 [2].
### 매 PAC 측정 metrics
- **Modulation Index (MI, Tort 2010)**: 매 KL divergence — 매 가장 robust.
- **Mean Vector Length (MVL, Canolty)**: 매 simpler, noise-sensitive.
- **General Linear Model PAC (van Wijk)**: 매 statistical inference.
- **Phase-Locking Value (PLV)**: 매 phase-phase only.
* **변조 지수(Modulation Index, MI)를 통한 정량적 분석:**
교차 주파수 결합의 강도는 변조 지수(MI)라는 값을 통해 정량화할 수 있다 [4]. 이를 위해 힐베르트 변환(Hilbert transform)을 적용하여 느린 주파수(예: 세타파)의 위상 시계열과 빠른 주파수(예: 감마파)의 진폭 포락선 시계열을 결합한다 [4]. 이후 특정 위상 구간별 진폭 분포를 구하고, 이 분포가 균일 분포(Uniform distribution)로부터 얼마나 멀리 떨어져 있는지를 쿨백-라이블러(Kullback-Leibler) 거리와 엔트로피를 통해 산출하여 최종적인 결합 수준을 측정한다 [4-6].
### 매 Functional roles
- **Theta-Gamma (4-8 Hz × 30-100 Hz)**: 매 working memory chunking — 매 Lisman-Idiart 7±2 model.
- **Alpha-Gamma (8-13 Hz × 30-100 Hz)**: 매 attention gating — 매 sensory selection.
- **Delta-Beta (1-3 Hz × 13-30 Hz)**: 매 motor planning.
- **Theta-Alpha**: 매 hippocampus-cortex coordination.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
단일 주파수에만 집중하던 기존의 정량적 뇌파 분석(QEEG)인 전력 스펙트럼 분석은 특정 주파수의 전력과 전압은 정량화하지만, 신경 활동 평가에 있어 필수적인 위상(phase) 정보를 무시하는 한계가 있었다 [1]. 교차 주파수 결합(CFC)은 위상 정보와 진폭(전력) 정보를 통합하여 기능적 뇌 활동과 네트워크 간 정보 처리 특성을 훨씬 정확하게 설명해 준다는 큰 장점이 있다 [1].
그러나 CFC(특히 PAC)를 제대로 측정하기 위해서는 힐베르트 변환을 통한 시계열 합성, 위상 구간 분할, 엔트로피 기반의 쿨백-라이블러 거리 측정 및 변조 지수(MI) 계산이라는 일련의 수학적 과정을 거쳐야 하므로 기존 분석법보다 연산 비용과 계산적 복잡도가 크게 증가한다 [4-6].
또한 생물학적 제약 관점에서 볼 때, 알츠하이머 치매나 조현병 등의 임상적 상태 혹은 특정 발달 지연 환경에서는 이 결합(예: 세타-감마 결합)이 손상될 수 있으며, 이 경우 작업 기억의 유지 성능과 분산된 맥락을 통합하는 뇌의 근본적인 능력이 크게 저하되는 결과를 초래한다 [7, 8].
### 매 응용
1. **BCI**: 매 PAC features 의 motor intent decoding — 매 SOTA 보다 +10% accuracy.
2. **Neurofeedback**: 매 closed-loop modulation 의 ADHD/depression.
3. **Sleep staging**: 매 SO-spindle coupling 의 NREM consolidation marker.
4. **Anesthesia depth**: 매 alpha-delta PAC 의 monitoring.
5. **Esports/flow detection**: 매 frontal theta-gamma 의 absorption marker.
## 🔗 지식 연결 (Graph)
### Related Concepts
## 💻 패턴
#### [관계 유형 A (기반 메커니즘 및 아키텍처)]
- [[세타-감마 결합 (Theta-Gamma Coupling, TGC)]]
- 연결 이유: 교차 주파수 결합의 가장 대표적이고 잘 알려진 신경 부호화 사례로, 분산된 정보의 맥락 통합 과정에서 필수적으로 등장하는 현상이기 때문이다 [1, 2].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 단편적인 감각 정보나 사건들이 뇌 안에서 어떻게 순서대로 배열되고 단기적인 기억 창(Working memory) 내에서 유지되며 맥락을 형성하는지 구체적인 시계열적 메커니즘을 파악할 수 있다 [1, 2].
### Modulation Index (Tort 2010)
```python
import numpy as np
from scipy.signal import hilbert, butter, filtfilt
- [[글로벌 워크스페이스 이론 (Global Workspace Theory, GWT)]]
- 연결 이유: CFC를 통해 국지적인 모듈에서 동기화된 신경 정보가 임계값을 넘어 전역적으로 방송(Broadcasting)됨으로써 하나의 의식과 통합된 맥락 경험을 형성한다는 뇌의 거시적 정보 처리 모델이기 때문이다 [3, 9].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 부위별 교차 주파수 동기화가 어떻게 무의식적 프로세스를 의식적 무대로 끌어올려, 인간의 복합적인 상황적 맥락(Context) 판단을 유도하는지 전체 네트워크 아키텍처 관점에서 이해할 수 있다 [2, 3, 9].
def bandpass(sig, fs, low, high, order=4):
b, a = butter(order, [low, high], btype="band", fs=fs)
return filtfilt(b, a, sig)
#### [관계 유형 B (구현 및 분석 도구/현상)]
- [[작업 기억 (Working Memory)]]
- 연결 이유: 뇌파의 교차 주파수 결합이 가장 활발하게 작용하여 다중 정보의 유지를 지원하는 핵심 인지 영역이기 때문이다 [1].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 맥락 통합이 인지적으로 빠르고 유연하게 이루어지기 위해 (장기 기억과 상충 관계를 가지면서도) 어떻게 단기적인 인지 자원을 할당받고 유지되는지 알 수 있다 [1, 10].
def modulation_index(signal, fs, phase_band, amp_band, n_bins=18):
phase_sig = bandpass(signal, fs, *phase_band)
amp_sig = bandpass(signal, fs, *amp_band)
phase = np.angle(hilbert(phase_sig))
amp = np.abs(hilbert(amp_sig))
- [[변조 지수 (Modulation Index, MI)]]
- 연결 이유: 서로 다른 주파수의 위상과 진폭 간 결합 강도(PAC)를 균일 분포와의 거리를 측정하여 수학적으로 도출하는 정량적 지표이기 때문이다 [5, 6].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 맥락 통합의 정도를 실제 데이터나 시스템에서 수치화하여 모니터링할 때 필요한 통계학적, 정보이론적(엔트로피) 측정 원리를 이해할 수 있다 [5, 6].
bins = np.linspace(-np.pi, np.pi, n_bins + 1)
mean_amp = np.array([
amp[(phase >= bins[i]) & (phase < bins[i+1])].mean()
for i in range(n_bins)
])
p = mean_amp / mean_amp.sum()
H = -np.sum(p * np.log(p + 1e-12))
Hmax = np.log(n_bins)
return (Hmax - H) / Hmax # MI ∈ [0, 1]
```
### Deeper Research Questions
### PAC Comodulogram (frequency-pair sweep)
```python
def comodulogram(signal, fs,
phase_freqs=np.arange(2, 15, 1),
amp_freqs=np.arange(20, 120, 5),
bw_phase=2, bw_amp=10):
co = np.zeros((len(phase_freqs), len(amp_freqs)))
for i, fp in enumerate(phase_freqs):
for j, fa in enumerate(amp_freqs):
co[i, j] = modulation_index(
signal, fs,
(fp - bw_phase/2, fp + bw_phase/2),
(fa - bw_amp/2, fa + bw_amp/2),
)
return phase_freqs, amp_freqs, co
```
- 단일 주파수 모델 대비 위상과 진폭을 융합하는 교차 주파수 결합(CFC) 측정 방식이 실시간 뇌-컴퓨터 인터페이스(BCI)에서의 정보 전송 지연 및 연산 부하에 미치는 영향은 무엇인가?
- 자폐 스펙트럼 장애(ASD) 환자가 보이는 약한 중앙 응집(WCC) 및 맥락 맹(Context Blindness) 증상은 특정 뇌 영역 간 세타-감마 결합의 결함 비율과 어떻게 정량적으로 상관되는가?
- 변조 지수(Modulation Index)를 도출하기 위한 쿨백-라이블러(KL) 거리 측정 모델을 인공지능의 멀티모달 프롬프트 압축 기술(예: E2LLM의 Soft prompt)의 손실 함수(Loss function) 설계에 차용할 수 있는가?
- 조현병이나 치매 모델에서 나타나는 세타-감마 결합 이상을 비침습적 신경 조절 기법으로 동기화시켰을 때, 작업 기억 및 맥락적 상황 파악 능력이 실시간으로 회복되는 메커니즘은 무엇인가?
- 인공지능 신경망의 상태 공간 모델(SSM, 예: Mamba)이 시퀀스 정보를 선택적으로 스캔하는 과정은 뇌의 교차 주파수 결합이 맥락을 필터링하고 유지하는 동역학적 특성과 수학적으로 어떤 차이를 보이는가?
### Tensorpac (production library)
```python
from tensorpac import Pac
import numpy as np
### Practical Application Contexts
# 매 multi-trial PAC + surrogate statistics
data = np.random.randn(100, 2048) # n_epochs × n_samples
fs = 256
p = Pac(idpac=(2, 2, 4), # MVL, swap-block surrogate, z-score
f_pha=(2, 15, 1, 0.5), f_amp=(20, 120, 5, 5))
phases = p.filter(fs, data, ftype="phase", n_jobs=4)
amps = p.filter(fs, data, ftype="amplitude", n_jobs=4)
xpac = p.fit(phases, amps) # n_amp × n_pha × n_epochs
```
- **Implementation:** 생체 신호(EEG)나 멀티스케일 시계열 센서 데이터를 분석하는 모듈 개발 시, 단순 전력 스펙트럼 분석을 넘어 힐베르트 변환과 엔트로피 연산을 적용하여 저주파수-고주파수 간의 변조 지수(MI)를 산출하는 알고리즘 파이프라인을 구축한다.
- **System Design:** 다중 센서 입력을 융합하는 자율주행이나 로보틱스 시스템을 설계할 때, 뇌가 세타-감마 코드를 활용하듯 저주기(거시적 상황 맥락) 신호가 고주기(세부 감각 데이터) 신호의 진폭을 조절하여 동기화하는 계층적 신호 처리 아키텍처를 도입한다.
- **Operation / Maintenance:** 임상 및 연구 목적의 신경 생리 데이터 분석 시스템에서 뇌파 데이터를 모니터링할 때, 작업 기억(Task-state)과 휴지기(Resting-state)를 구분해 교차 주파수 결합 맵을 시각화하고 인지 장애(맥락 맹 등)의 조기 징후를 판별하는 진단 유지보수 툴로 활용한다.
- **Learning Path:** 디지털 신호 처리(푸리에 및 힐베르트 변환) $\rightarrow$ 신경 생리학(뇌파의 특성) $\rightarrow$ 교차 주파수 결합(CFC) 이론 $\rightarrow$ 작업 기억 및 글로벌 워크스페이스 기반 인지 심리학 $\rightarrow$ 인공지능의 시계열-맥락 어텐션 처리 융합 모델로 이어지는 체계적 커리큘럼을 따른다.
- **My Project Relevance:** 방대한 데이터 간의 상호작용 및 상황을 결합하여 맥락적 추론을 제시하는 뉴로-심볼릭(Neuro-Symbolic) AI 과제 등에서, 이종 도메인의 신호들을 어떻게 하나의 통일된 의미 벡터로 동기화시킬 것인가에 대한 생물학적 모방 기반 아이디어로 활용할 수 있다.
### Sleep SO-Spindle Coupling
```python
def so_spindle_coupling(eeg, fs=500):
# 매 slow oscillation phase (0.5-1.25 Hz) × spindle amplitude (12-15 Hz)
return modulation_index(eeg, fs, (0.5, 1.25), (12, 15))
# 매 healthy young: MI ≈ 0.005-0.015; 매 elderly: 매 lower
```
### Adjacent Topics
### Closed-Loop Phase-Triggered Stim
```python
import collections, time
- [[어텐션 메커니즘 (Attention Mechanism)]]
- 확장 방향: 인간의 뇌가 여러 주파수의 뇌파를 동기화하여 중요한 감각 정보를 선택하고 맥락으로 묶어내는 과정(CFC 및 GWT)을 인공지능의 트랜스포머 모델이 입력 토큰 간의 관련성을 가중치로 계산하여 핵심 맥락에 집중하는 '어텐션 연산' 방식과 비교하여 메커니즘의 차이와 차세대 AI의 설계 방향을 연구한다 [11, 12].
- [[부호화 특수성 원리 (Encoding Specificity Principle)]]
- 확장 방향: 뇌의 주파수 상호작용이 작업 기억 내에 정보를 순서대로 결합하고 일시적으로 맥락을 형성하는 미시적 토대라면, 인지 심리학적으로 부호화 당시의 환경적 맥락이 인출 시 강력한 단서로 작용하는 현상(예: 맥락 의존적 기억 및 체류 시간의 영향)을 거시적 차원에서 함께 분석하여 인간 기억 처리의 전모를 살핀다 [13].
class PhaseTriggeredStim:
def __init__(self, fs, target_phase=0, tolerance=0.3):
self.fs = fs; self.buf = collections.deque(maxlen=int(fs * 2))
self.target = target_phase; self.tol = tolerance
def push_sample(self, x):
self.buf.append(x)
if len(self.buf) < self.fs: return False
sig = np.array(self.buf)
theta = bandpass(sig, self.fs, 4, 8)
cur_phase = np.angle(hilbert(theta))[-1]
return abs(cur_phase - self.target) < self.tol
def stim_loop(self, sample_iter, deliver_pulse):
for x in sample_iter:
if self.push_sample(x): deliver_pulse()
```
---
*Last updated: 2026-05-05*
### Statistical Significance via Surrogates
```python
def pac_zscore(signal, fs, phase_band, amp_band, n_perm=200):
real = modulation_index(signal, fs, phase_band, amp_band)
surr = []
for _ in range(n_perm):
shift = np.random.randint(fs, len(signal) - fs)
s = np.concatenate([signal[shift:], signal[:shift]])
surr.append(modulation_index(s, fs, phase_band, amp_band))
return (real - np.mean(surr)) / np.std(surr)
```
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 매 결정 기준
| Use case | Approach |
|---|---|
| Single recording, exploration | Tort MI + comodulogram |
| Multi-trial group stats | Tensorpac w/ surrogates + cluster perm |
| Real-time BCI/stim | MVL (cheaper) + phase tracker |
| Sleep research | SO-spindle MI + co-occurrence |
| Tutorial/learning | Tort MI w/ 18 bins |
**언제 이 지식을 쓰는가:**
- *(TODO)*
**기본값**: Tort 2010 MI + 200 surrogate permutations + cluster correction.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🔗 Graph
- 부모: [[Neural Oscillations]] · [[EEG Signal Processing]]
- 변형: [[Phase-Amplitude Coupling]] · [[Phase-Locking Value]] · [[n:m Coupling]]
- 응용: [[Brain-Computer Interface]] · [[Neurofeedback]] · [[Sleep Spindle Analysis]] · [[Cognitive Neuroscience of Flow]]
- Adjacent: [[Hilbert Transform]] · [[Wavelet Analysis]] · [[Working Memory]] · [[Theta Rhythm]] · [[Gamma Oscillations]]
## 🧪 검증 상태 (Validation)
## 🤖 LLM 활용
**언제**: 매 PAC pipeline scaffold, 매 metric choice 의 explanation, 매 surrogate-test 의 reasoning.
**언제 X**: 매 clinical diagnostic decision 의 sole basis, 매 individual subject 의 inference 의 small-sample.
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## ❌ 안티패턴
- **No surrogate test**: 매 spurious PAC 의 1/f noise + nonstationarity 의 false positive.
- **Filter ringing artifact**: 매 narrow band + steep filter 의 phase distortion.
- **Phase-amp band overlap**: 매 fp + bw/2 ≥ fa - bw/2 의 self-coupling artifact.
- **Edge effects 무시**: 매 Hilbert transform 의 endpoint distortion.
- **MVL alone**: 매 amplitude variance 의 confound — 매 MI 의 더 robust.
- **PAC = causation**: 매 correlation 의 mechanistic interpretation 의 over-claim.
## 🧬 중복 검사 (Duplicate Check)
## 🧪 검증 / 중복
- Verified (Tort et al. 2010 _J Neurophysiol_, Canolty & Knight 2010 _Trends Cogn Sci_, Aru et al. 2015 _Curr Opin Neurobiol_ pitfalls review).
- 신뢰도 A.
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Tort MI + comodulogram + closed-loop stim patterns |
@@ -2,66 +2,159 @@
id: wiki-2026-0508-decision-theory
title: Decision Theory
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-DETR-001]
aliases: [의사결정 이론, Choice Theory, Rational Choice]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [auto-reinforced, decision-theory, probability, risk-Analysis, Strategic-Thinking, Game-Theory]
confidence_score: 0.92
verification_status: applied
tags: [decision-theory, expected-utility, bayesian, game-theory, RL]
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: python
framework: scipy/pymc
---
# [[Decision Theory|Decision Theory]]
# Decision Theory
## 📌 한 줄 통찰 (The Karpathy Summary)
> "최선의 선택을 향한 수학적 지도: 불확실한 상황 속에서 얻게 될 이익(Utility)과 발생할 위험(Risk)을 저울질하여, 기대 가치를 극대화하는 가장 합리적인 행동을 결정하는 의사결정의 과학."
## 한 줄
> **"매 rational choice = argmax_a E[U(outcome|a)]"**. 매 1944 von Neumann-Morgenstern 의 expected utility axiomatization 부터 매 2026 LLM agent 의 tool-use planning, RLHF reward modeling, 매 autonomous driving 의 risk-sensitive policy 까지 — 매 단일 framework 로 uncertainty 하 행동 선택 의 formalization.
## 📖 구조화된 지식 (Synthesized Content)
의사결정 이론(Decision Theory)은 불완전한 정보 하에서 최적의 선택을 내리는 과정을 연구하는 학문입니다.
## 매 핵심
1. **두 가지 영역**:
* **Normative (규범적)**: "어떻게 결정하는 것이 가장 합리적인가?" (수학적 최적해).
* **Descriptive (기술적)**: "실제 인간은 어떻게 결정하는가?" (심리적, 행동적 분석). ([[Cognitive Biases|Cognitive Biases]]와 연결)
2. **핵심 원칙**:
* **Expected Utility**: 각 결과의 가치에 발생 확률을 곱해 합산한 값.
* **Minimax**: 가장 나쁜 상황에서 발생하는 손실을 최소화하는 하이 리스크 방어 전략.
* **[[Bayesian Inference|Bayesian Inference]]**: 새로운 증거가 나올 때마다 자신의 판단을 업데이트하는 방식. ([[Bayesian-Updating|Bayesian-Updating]]과 연결)
### 매 분류
- **Normative**: 매 ideal rational agent 가 어떻게 결정해야 하는가 (EUT, Savage axioms).
- **Descriptive**: 매 humans 가 실제로 어떻게 결정하는가 (prospect theory, bounded rationality).
- **Prescriptive**: 매 humans 가 더 나은 결정을 위해 어떻게 도울 것인가 (decision support systems).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거 경제학 정책은 인간을 완벽하게 합리적인 존재로 가정했으나, 현대 정책은 '제한된 합리성([[Bounded-Rationality|Bounded-Rationality]]) 정책'을 기반으로 하여 현실적인 타협안을 찾는 정책으로 진화함(RL Update).
- **정책 변화(RL Update)**: AI 에이전트의 자율적 의사결정 정책에서, 단순히 점수만 높이는 '결과 중심 정책'보다 결정 과정의 윤리와 리스크를 계량화하여 반영하는 '가치 정렬형 의사결정 정책'이 필수가 됨.
### 매 핵심 도구
- **Expected Utility (EU)**: `EU(a) = Σ P(s) · U(s, a)`.
- **Bayesian Decision Theory**: 매 prior + likelihood → posterior → decision.
- **Minimax / Maximin**: 매 worst-case robustness.
- **Pareto Optimality**: 매 multi-objective tradeoff frontier.
- **Value of Information (VoI)**: 매 추가 데이터 수집의 expected gain.
## 🔗 지식 연결 (Graph)
- [[Bounded-Rationality|Bounded-Rationality]], [[Cognitive Biases|Cognitive Biases]], [[Bayesian-Updating|Bayesian-Updating]], [[Game-Theory|Game-Theory]], [[Strategic-Planning|Strategic-Planning]]
- **Modern Tech/Tools**: [[Decision Tree|Decision Tree]]s, Monte Carlo simulations, Multi-criteria decision analysis (MCDA).
---
### 매 응용
1. **RL reward shaping**: 매 PPO/GRPO objective 의 expected return 매개변수화.
2. **A/B test stopping rule**: 매 sequential Bayesian decision (BALD acquisition).
3. **Medical triage**: 매 cost-sensitive classification 의 utility-weighted threshold.
4. **LLM agent tool-use**: 매 ReAct planner 가 매 tool call 의 expected reward 비교.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Expected Utility 계산
```python
import numpy as np
**언제 쓰면 안 되는가:**
- *(TODO)*
def expected_utility(action, states, probs, utility_fn):
"""E[U] = Σ P(s|a) · U(s, a)."""
return sum(p * utility_fn(s, action) for s, p in zip(states, probs))
## 🧪 검증 상태 (Validation)
# Risk-averse: U(x) = log(x), Risk-neutral: U(x) = x
actions = ['invest', 'save']
states = [100, -20] # outcomes per action
probs = {'invest': [0.6, 0.4], 'save': [1.0, 0.0]}
log_utility = lambda s, a: np.log(s + 1000) # wealth-based
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
best = max(actions, key=lambda a: expected_utility(a, states, probs[a], log_utility))
```
## 🧬 중복 검사 (Duplicate Check)
### Bayesian Posterior Decision
```python
import pymc as pm
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
with pm.Model() as model:
theta = pm.Beta('theta', alpha=2, beta=2) # prior
obs = pm.Binomial('obs', n=10, p=theta, observed=7)
trace = pm.sample(2000, return_inferencedata=True)
## 🕓 변경 이력 (Changelog)
posterior = trace.posterior['theta'].values.flatten()
# Decision: launch if P(theta > 0.5) > 0.95
launch = (posterior > 0.5).mean() > 0.95
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Minimax Regret
```python
def minimax_regret(payoff_matrix):
# Regret(a, s) = max_a' payoff(a', s) - payoff(a, s)
best_per_state = payoff_matrix.max(axis=0)
regret = best_per_state - payoff_matrix
max_regret_per_action = regret.max(axis=1)
return max_regret_per_action.argmin() # action minimizing max regret
```
### Value of Information
```python
def value_of_information(prior_decision_eu, posterior_decision_eu, info_cost):
"""VoI = E[best decision with info] - E[best decision without info] - cost."""
return posterior_decision_eu - prior_decision_eu - info_cost
```
### POMDP Belief Update (LLM Agent)
```python
def belief_update(belief, action, observation, transition_fn, obs_fn):
"""b'(s') = η · O(o|s',a) · Σ T(s'|s,a) · b(s)."""
new_belief = {}
for s_prime in belief:
prior = sum(transition_fn(s, a=action, s_p=s_prime) * b
for s, b in belief.items())
new_belief[s_prime] = obs_fn(observation, s_prime, action) * prior
norm = sum(new_belief.values())
return {s: v / norm for s, v in new_belief.items()}
```
### Multi-Armed Bandit (Thompson Sampling)
```python
import numpy as np
class ThompsonBandit:
def __init__(self, n_arms):
self.alpha = np.ones(n_arms)
self.beta = np.ones(n_arms)
def pull(self):
samples = np.random.beta(self.alpha, self.beta)
return samples.argmax()
def update(self, arm, reward):
self.alpha[arm] += reward
self.beta[arm] += (1 - reward)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Probabilities known, utilities clear | Expected Utility maximization |
| Uncertainty about probabilities | Bayesian decision (priors) |
| Adversarial environment | Minimax / Game theory |
| Multi-objective tradeoff | Pareto frontier |
| Sequential with information | POMDP / VoI |
| Online with exploration | Bandit / RL |
**기본값**: 매 Bayesian Expected Utility — 매 priors explicit + posterior update 가능.
## 🔗 Graph
- 부모: [[Probability Theory]] · [[Game Theory]]
- 변형: [[Bayesian-Decision-Theory]] · [[Prospect Theory]] · [[POMDP]]
- 응용: [[Reinforcement Learning]] · [[Multi-armed-Bandit-Problem]] · [[A_B Testing]]
- Adjacent: [[Optimal-Control-Theory]] · [[Information Theory]] · [[Risk-Management]]
## 🤖 LLM 활용
**언제**: 매 agent planner 의 tool selection, 매 RLHF reward design, 매 active learning data acquisition.
**언제 X**: 매 utility function 의 specification 매 impossible 한 multi-stakeholder ethics — 매 voting / negotiation 사용.
## ❌ 안티패턴
- **Naive EU under heavy-tailed risk**: 매 expected value finite 이지만 ruin probability 가 nonzero — 매 Kelly criterion / log-utility 사용.
- **Ignoring Allais paradox**: 매 humans violate independence axiom — 매 prescriptive ≠ descriptive.
- **Probability ≈ frequency only**: 매 Bayesian subjective prob 도 valid — 매 single-event decision 에 frequency 강요 X.
- **Over-precise priors**: 매 unknown unknowns 에 매 epsilon-contamination / robust priors.
## 🧪 검증 / 중복
- Verified (Savage 1954, *Foundations of Statistics*; Kahneman & Tversky 1979 prospect theory; Russell & Norvig *AIMA* 4ed Ch.16-17).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with EU, Bayesian, POMDP, bandit patterns |
@@ -2,89 +2,157 @@
id: wiki-2026-0508-determinism-in-computing
title: Determinism in Computing
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [DET-COMP-001]
aliases: [Reproducibility, Bit-Exact, 결정론적 실행]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [computer-science, determinism, simulation, Physics-engine, skybound]
confidence_score: 0.93
verification_status: applied
tags: [determinism, reproducibility, concurrency, ML, distributed-systems]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: pytorch/cuda
---
# Determinism in Computing (계산의 결정론)
# Determinism in Computing
## 📌 한 줄 통찰 (The Karpathy Summary)
> "동일한 입력과 초기 상태가 주어지면, 언제 어디서나 반드시 동일한 결과를 보장하라" — 시스템의 내부 상태와 연산 과정에서 무작위성을 배제하여, 프로그램의 실행 결과가 100% 예측 가능하고 재현 가능하도록 설계하는 원칙.
## 한 줄
> **"매 same input + same code = same output, every run, every machine"**. 매 1936 Turing 의 deterministic state machine 부터 매 2026 ML training 의 bit-exact reproducibility, 매 distributed consensus (Raft), 매 blockchain virtual machines 까지 — 매 trust 와 debugging 의 foundation.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 부동 소수점 연산 오차, 멀티스레딩의 비결정적 실행 순서, 네트워크 지연 등 결과를 뒤흔들 수 있는 변수들을 제어하여 시스템의 일관성을 확보하는 설계 패턴.
- **핵심 요소:**
- **Fixed-point Arithmetic:** 부동 소수점 오차로 인한 결과 차이를 방지하기 위해 정수 기반 연산 사용.
- **Deterministic Lockstep:** 멀티플레이어 환경에서 모든 클라이언트가 동일한 타임라인에서 동일한 연산을 수행하도록 동기화.
- **[[Seed|Seed]]ed Randomness:** 난수 생성 시 항상 동일한 시드(Seed)를 사용하여 무작위 패턴을 재현 가능하게 함.
- **No Side Effects:** 함수가 외부 상태를 변경하지 않고 입력값에 의해서만 결과가 결정되도록 함 (순수 함수).
- **의의:** 디버깅 용이성, 멀티플레이어 게임의 동기화, 과학 시뮬레이션의 신뢰성 확보에 필수적.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순히 '작동'하는 것에 집중하던 방식에서, 분산 시스템과 복잡한 시뮬레이션이 늘어남에 따라 '재현 가능성'이 소프트웨어 품질의 핵심 지표로 부상.
- **정책 변화:** Skybound 프로젝트는 리플레이 시스템과 멀티플레이 동기화를 위해 모든 물리 연산과 확률 이벤트를 결정론적으로 설계하며, 부동 소수점 오차 누적을 방지하는 알고리즘을 적용함.
### 매 등급
- **Bit-exact**: 매 byte-level identical output. 매 cryptographic hash 동일.
- **Numerically reproducible**: 매 within ε tolerance — 매 floating-point order 차이.
- **Statistically reproducible**: 매 same distribution, different sample (RNG seed only).
- **Behaviorally reproducible**: 매 high-level outcome 동일 (test passes/fails 동일).
## 🔗 지식 연결 (Graph)
- Time-Step-Logic-in-Games, Physics-Engine, [[Distributed-Computing|Distributed-Computing]], Simulation-[[Principles|Principles]]
- **Raw Source:** 10_Wiki/Topics/AI/Determinism-in-Computing.md
### 매 nondeterminism 원인
- **FP non-associativity**: 매 (a+b)+c ≠ a+(b+c) — 매 reduction order matter.
- **GPU atomic ops**: 매 CUDA atomicAdd 의 ordering 비결정적.
- **Thread scheduling**: 매 OS scheduler 의 race condition.
- **Hash randomization**: 매 Python `PYTHONHASHSEED`, Go map iteration.
- **Wall-clock dependency**: 매 timestamps, `time.time()`, `random()`.
- **Hardware**: 매 cosmic ray bit flips, TLB/cache state.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **ML training reproduction**: 매 paper benchmark 의 reproducibility crisis.
2. **Blockchain consensus**: 매 nodes must reach identical state.
3. **Distributed log replay**: 매 event sourcing 의 deterministic projection.
4. **Game engine replays**: 매 lockstep multiplayer (RTS, fighting games).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### PyTorch Bit-Exact Setup
```python
import torch, random, numpy as np, os
## 🧪 검증 상태 (Validation)
def set_full_determinism(seed=42):
os.environ['PYTHONHASHSEED'] = str(seed)
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' # CUDA 10.2+
random.seed(seed); np.random.seed(seed)
torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True, warn_only=False)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
set_full_determinism()
```
## 🤔 의사결정 기준 (Decision Criteria)
### Deterministic DataLoader
```python
def seed_worker(worker_id):
s = torch.initial_seed() % 2**32
np.random.seed(s); random.seed(s)
**선택 A를 써야 할 때:**
- *(TODO)*
g = torch.Generator(); g.manual_seed(42)
loader = DataLoader(ds, batch_size=64, shuffle=True,
num_workers=4, worker_init_fn=seed_worker, generator=g)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Lockstep Game Loop (Fixed-Point Math)
```rust
// All clients run identical sim → only inputs synchronized.
const FIXED_DT: Fixed<i64, 16> = Fixed::from_num(1.0 / 60.0);
**기본값:**
> *(TODO)*
fn tick(state: &mut GameState, inputs: &[Input]) {
for input in inputs.iter().sorted_by_key(|i| i.player_id) {
state.apply(input, FIXED_DT); // fixed-point, no f32!
}
state.tick += 1;
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Content-Addressable Build (Bazel-style)
```python
def build_artifact(sources, deps, command):
h = hashlib.sha256()
for src in sorted(sources):
h.update(open(src, 'rb').read())
for d in sorted(deps): h.update(d.hash.encode())
h.update(command.encode())
cache_key = h.hexdigest()
if cache_key in cache: return cache[cache_key]
return run_and_cache(command, cache_key)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Deterministic Hash for Sets
```python
# Avoid Python set iteration order
def stable_hash_set(items):
return hashlib.sha256(
b'\n'.join(sorted(repr(x).encode() for x in items))
).hexdigest()
```
### Replay Test
```python
def test_replay_is_deterministic():
seed = 12345
out1 = run_simulation(seed)
out2 = run_simulation(seed)
assert out1 == out2, "Nondeterminism detected!"
# for ML: torch.testing.assert_close(out1, out2, atol=0, rtol=0)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| ML reproducibility paper | bit-exact (CUBLAS config + cudnn.deterministic) |
| Distributed sim / lockstep | fixed-point arithmetic |
| Build system | content-addressable hashing |
| Statistical study | seed-only (statistical determinism) |
| Performance critical | relax to "numerically close" |
**기본값**: 매 seed everything + log seeds in artifacts metadata.
## 🔗 Graph
- 부모: [[Theoretical-Computer-Science]] · [[Reproducibility]]
- 변형: [[Bit-Exact-Reproducibility]] · [[Statistical-Reproducibility]]
- 응용: [[ML Reproducibility]] · [[Blockchain Consensus]] · [[Lockstep-Networking]]
- Adjacent: [[Floating-Point-Arithmetic]] · [[Random Number Generation]] · [[Idempotency]]
## 🤖 LLM 활용
**언제**: 매 evaluation harness, 매 regression test 의 ground truth, 매 paper code release.
**언제 X**: 매 LLM sampling 자체 (temperature > 0) — 매 inherently nondeterministic; 매 fixed seed + temperature=0 만 reproducible.
## ❌ 안티패턴
- **Forgetting CUBLAS_WORKSPACE_CONFIG**: 매 CUDA matmul 비결정적, training 결과 매 run 다름.
- **Using `set()` in pipeline**: 매 Python <3.7 dict order 비결정적.
- **Wall-clock as seed**: 매 reproducibility 불가, debugging 불가.
- **Mixing CPU/GPU reductions**: 매 sum order 차이로 ε divergence 누적.
- **Ignoring hardware drift**: 매 different GPU arch (A100 vs H100) → different results 가능.
## 🧪 검증 / 중복
- Verified (PyTorch reproducibility docs 2026; Raft paper 2014; Bazel hermetic build docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with PyTorch, lockstep, build patterns |
@@ -2,87 +2,180 @@
id: wiki-2026-0508-dijkstra-s-algorithm
title: "Dijkstra's Algorithm"
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-DIJKSTRA]
aliases: [Shortest Path, SPF, 다익스트라]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [Dijkstra, Algorithm, Pathfinding, Graph Theory]
confidence_score: 0.97
verification_status: applied
tags: [graph, shortest-path, algorithm, priority-queue, OSPF]
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
framework: heapq
---
# Dijkstra's-Algorithm (데이크스트라 알고리즘)
# Dijkstra's Algorithm
## 📌 한 줄 통찰 (The Karpathy Summary)
> "욕심쟁이(Greedy)의 가장 똑똑한 길 찾기." 출발점에서 다른 모든 지점까지의 최단 거리를 가장 효율적으로 확정해 나가는 알고리즘의 고전이자 정석이다.
## 한 줄
> **"매 single-source shortest path on non-negative weighted graphs — O((V+E) log V) with binary heap"**. 매 1959 Edsger Dijkstra 가 매 30분 coffee shop 에서 발견. 매 2026 OSPF routing, Google Maps, A* heuristic baseline, network flow 의 핵심 building block.
## 📖 구조화된 지식 (Synthesized Content)
- **Shortest Path Tree**:
- 방문하지 않은 지점 중 거리가 가장 짧은 지점을 먼저 방문함으로써, 한 번 확정된 거리는 다시 계산할 필요가 없게 만든다.
- **Priority Queue Usage**:
- 우선순위 큐(힙)를 사용하여 다음에 방문할 지점을 빠르게 찾아냄으로써 시간 복잡도를 극적으로 최적화한다.
- **Application**:
- 구글 지도, 게임 길찾기, 네트워크 라우팅(OSPF) 등 연결된 네트워크가 있는 모든 곳에 쓰인다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 데이크스트라는 음수 가중치(음수의 거리 등)가 있는 환경에서는 작동하지 않는다(이땐 벨만-포드 필요). 또한, 거대한 맵에서는 탐색 범위가 너무 넓어지므로, 목표 지점 방향으로 먼저 탐색하는 지능을 더한 `A* (A-Star) 알고리즘`이 실무에서 더 선호된다.
### 매 핵심 idea
1. 매 priority queue 에서 가장 작은 tentative distance 의 vertex 추출.
2. 매 incident edge 마다 relax: `if d[u] + w(u,v) < d[v]: d[v] = d[u] + w(u,v)`.
3. 매 visited set 에 추가, 매 빈 큐까지 반복.
## 🔗 지식 연결 (Graph)
- Related: [[Autonomous-Vehicle-Path-Planning|Autonomous-Vehicle-Path-Planning]] , [[Combinatorial-Optimization|Combinatorial-Optimization]]
- Foundation: Computational Theory & Math/Information Theory
### 매 복잡도
- **Binary heap**: O((V+E) log V).
- **Fibonacci heap**: O(E + V log V) — 매 dense 에 유리.
- **Bucket queue (Dial's)**: O(E + V·C) — 매 small integer weights.
- **Array (no PQ)**: O(V²) — 매 dense 에 더 빠름.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 제약
- **음의 weight 금지** — 매 Bellman-Ford 사용.
- **단일 source** — 매 all-pairs 는 Floyd-Warshall O(V³).
- **DAG 면 더 빠름** — 매 topological order O(V+E).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. **OSPF / IS-IS**: 매 internet routing protocol 의 link-state computation.
2. **Google Maps**: 매 contraction hierarchies + bidirectional Dijkstra.
3. **Game pathfinding**: 매 A* 의 g-score 가 Dijkstra (h=0).
4. **Network analysis**: 매 betweenness centrality 매 계산.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Standard Implementation (Python)
```python
import heapq
def dijkstra(graph, source):
dist = {v: float('inf') for v in graph}
dist[source] = 0
pq = [(0, source)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]: continue # stale entry
for v, w in graph[u]:
nd = d + w
if nd < dist[v]:
dist[v] = nd
heapq.heappush(pq, (nd, v))
return dist
```
## 🤔 의사결정 기준 (Decision Criteria)
### With Path Reconstruction
```python
def dijkstra_path(graph, src, dst):
dist = {src: 0}; prev = {}
pq = [(0, src)]
while pq:
d, u = heapq.heappop(pq)
if u == dst: break
if d > dist.get(u, float('inf')): continue
for v, w in graph[u]:
nd = d + w
if nd < dist.get(v, float('inf')):
dist[v] = nd; prev[v] = u
heapq.heappush(pq, (nd, v))
path, cur = [], dst
while cur in prev: path.append(cur); cur = prev[cur]
return [src] + path[::-1] if dist.get(dst) else None
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Bidirectional Dijkstra (Maps-style)
```python
def bidirectional_dijkstra(g, s, t):
df, db = {s: 0}, {t: 0}
pf, pb = [(0, s)], [(0, t)]
visited_f, visited_b = set(), set()
best = float('inf'); meet = None
while pf and pb:
# alternate forward/backward expansion
if pf[0][0] + pb[0][0] >= best: break
# ... expand both, update best when meet
return best, meet
```
**선택 B를 써야 할 때:**
- *(TODO)*
### A* (Dijkstra + heuristic)
```python
def a_star(graph, src, dst, h):
g = {src: 0}; pq = [(h(src, dst), 0, src)]
while pq:
f, gu, u = heapq.heappop(pq)
if u == dst: return gu
for v, w in graph[u]:
ng = gu + w
if ng < g.get(v, float('inf')):
g[v] = ng
heapq.heappush(pq, (ng + h(v, dst), ng, v))
```
**기본값:**
> *(TODO)*
### Dial's Bucket Algorithm (small int weights)
```python
def dial_dijkstra(graph, src, max_weight):
n = len(graph); C = max_weight * n + 1
buckets = [[] for _ in range(C)]
dist = [float('inf')] * n; dist[src] = 0
buckets[0].append(src)
for d in range(C):
while buckets[d]:
u = buckets[d].pop()
if d > dist[u]: continue
for v, w in graph[u]:
nd = d + w
if nd < dist[v]:
dist[v] = nd; buckets[nd].append(v)
return dist
```
## ❌ 안티패턴 (Anti-Patterns)
### NetworkX (Practical)
```python
import networkx as nx
G = nx.DiGraph()
G.add_weighted_edges_from([('A','B',3), ('B','C',1), ('A','C',5)])
length = nx.dijkstra_path_length(G, 'A', 'C')
path = nx.dijkstra_path(G, 'A', 'C') # ['A','B','C'] (cost 4)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Non-negative weights, single source | Dijkstra (binary heap) |
| 음의 weight 가능 | Bellman-Ford O(VE) |
| Negative cycle detection | Bellman-Ford |
| All-pairs, dense | Floyd-Warshall O(V³) |
| Heuristic available (e.g., Euclidean) | A* |
| Map-scale (millions of nodes) | Contraction Hierarchies + bidirectional |
| Small integer weights | Dial's buckets |
**기본값**: 매 binary heap Dijkstra — 매 generic, 매 O((V+E) log V) 충분.
## 🔗 Graph
- 부모: [[Graph Theory]] · [[Greedy-Algorithms]]
- 변형: [[A* Algorithm]] · [[Bidirectional Dijkstra]] · [[Bellman-Ford]]
- 응용: [[OSPF]] · [[Google Maps Routing]] · [[Network Flow]]
- Adjacent: [[Priority Queue]] · [[Fibonacci Heap]] · [[Topological Sort]]
## 🤖 LLM 활용
**언제**: 매 dependency resolution, 매 chain-of-thought planner 의 minimum-cost reasoning path.
**언제 X**: 매 weights 가 negative 또는 unknown — 매 Bellman-Ford or simulated annealing.
## ❌ 안티패턴
- **Negative weight 적용**: 매 silent wrong answer — 매 항상 Bellman-Ford 사용.
- **Lazy deletion 누락**: 매 PQ 의 stale entry 미처리 → infinite loop 가능.
- **Recomputing every query**: 매 static graph 면 precompute (CH) 또는 caching.
- **Naive O(V²) on sparse graph**: 매 V=10⁶ 면 O((V+E) log V) 필수.
## 🧪 검증 / 중복
- Verified (CLRS Ch.24; Dijkstra 1959 *Numerische Mathematik*; NetworkX 3.x docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with heap, A*, bidirectional patterns |
@@ -2,63 +2,174 @@
id: wiki-2026-0508-directed-acyclic-graph-dependenc
title: Directed Acyclic Graph Dependency Management
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [DAG-001]
aliases: [DAG, Build Graph, Task Dependency, Topological Sort]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [computer-science, Graph-Theory, data-structures, workflow]
confidence_score: 0.94
verification_status: applied
tags: [DAG, dependency, build-system, scheduler, topological-sort]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: networkx/airflow
---
# Directed Acyclic Graph (DAG, 유향 비순환 그래프)
# Directed Acyclic Graph Dependency Management
## 📌 한 줄 통찰 (The Karpathy Summary)
> "순환하지 않는 방향성 — 작업의 순서와 의존성을 정의하는 가장 완벽한 수학적 모델."
## 한 줄
> **"매 DAG = nodes (tasks) + directed edges (must-run-before) + 매 cycle 금지"**. 매 1960s Make 의 build graph 부터 매 2026 Airflow/Dagster pipelines, Bazel/Turborepo monorepo, Spark physical plan, Git commit history, React fiber tree 까지 — 매 dependency resolution 의 universal data structure.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 노드 간의 방향은 존재하되, 어떤 노드에서 출발해도 다시 자기 자신으로 돌아오는 경로(Cycle)가 없는 구조를 통해 순차적 실행과 계층 관계를 보장하는 패턴.
- **세부 내용:**
- **Topo[[Logic|Logic]]al Sort:** DAG의 노드들을 의존성에 따라 일렬로 정렬하는 알고리즘 (빌드 시스템, 태스크 스케줄링의 핵심).
- **Dependency [[Management|Management]]:** 특정 작업이 완료되어야 다음 작업이 시작될 수 있는 인과 관계를 명확히 표현.
- **Data Pipelines:** Spark, Airflow 등 현대 데이터 엔지니어링 도구에서 데이터의 흐름을 정의하는 표준 모델.
- **Version Control:** Git의 커밋 히스토리는 부모-자식 관계를 가진 거대한 DAG 구조임.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순 트리(Tree) 구조보다 복잡한 관계를 표현할 수 있으면서도, 순환 구조(Graph)가 주는 무한 루프 위험을 제거한 실용적 타협점.
- **정책 변화:** Antigravity 프로젝트의 '지식 연결 그래프'는 기본적으로 순환을 허용하나, '실행 워크플로우'는 엄격한 DAG 규칙을 따름.
### 매 핵심 연산
- **Topological Sort**: 매 valid execution order. Kahn's O(V+E) or DFS.
- **Cycle Detection**: 매 DAG validity check.
- **Transitive Reduction**: 매 minimal edge set with same reachability.
- **Critical Path**: 매 longest path = makespan lower bound.
- **Incremental Recompute**: 매 dirty subgraph 만 재실행.
## 🔗 지식 연결 (Graph)
- **Parent:** 10_Wiki/💡 Topics/AI
- **Related:** Topological-Sort, [[Graph-Theory|Graph-Theory]], Workflow-Automation
- **Raw Source:** 10_Wiki/Topics/AI/Directed-Acyclic-Graph-Dependency-Management.md
### 매 응용
1. **Build systems**: Make, Bazel, Buck, Turborepo, Nx.
2. **Workflow orchestration**: Airflow, Dagster, Prefect, Argo Workflows.
3. **ML training pipelines**: Kubeflow, MLflow, ZenML.
4. **Spreadsheet recalc**: Excel, Google Sheets formula engine.
5. **VCS**: Git commit DAG, Mercurial.
6. **React/Solid reactivity**: 매 signal dependency graph.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 schedule strategies
- **List scheduling**: 매 ready tasks → workers (greedy).
- **HEFT**: 매 heterogeneous earliest finish time (cloud).
- **Critical Path Method (CPM)**: 매 longest path 기반 prioritization.
- **Work-stealing**: 매 dynamic load balancing (Tokio, Rayon).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Topological Sort (Kahn's Algorithm)
```python
from collections import deque, defaultdict
## 🧪 검증 상태 (Validation)
def topo_sort(nodes, edges):
indegree = defaultdict(int)
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v); indegree[v] += 1
queue = deque([n for n in nodes if indegree[n] == 0])
order = []
while queue:
u = queue.popleft(); order.append(u)
for v in graph[u]:
indegree[v] -= 1
if indegree[v] == 0: queue.append(v)
if len(order) != len(nodes): raise ValueError("Cycle detected")
return order
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Parallel DAG Executor (asyncio)
```python
import asyncio
async def run_dag(tasks, deps):
"""tasks: {name: async_fn}, deps: {name: [prereqs]}."""
completed = {}; pending = dict(deps)
async def run(name):
await asyncio.gather(*(completed[d] for d in deps.get(name, [])))
return await tasks[name]()
completed = {n: asyncio.create_task(run(n)) for n in tasks}
return await asyncio.gather(*completed.values())
```
## 🧬 중복 검사 (Duplicate Check)
### Incremental Build (Content-Hash)
```python
def needs_rebuild(node, hashes, prev_hashes):
own_hash = hash_inputs(node.sources, [hashes[d] for d in node.deps])
if prev_hashes.get(node.name) != own_hash:
hashes[node.name] = own_hash
return True
hashes[node.name] = own_hash
return False
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Critical Path
```python
def critical_path(graph, durations):
order = topo_sort(graph.nodes, graph.edges)
earliest = {n: durations[n] for n in graph.nodes}
for u in order:
for v in graph.successors(u):
earliest[v] = max(earliest[v], earliest[u] + durations[v])
return max(earliest.values()), earliest
```
## 🕓 변경 이력 (Changelog)
### Cycle Detection (DFS)
```python
WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle(graph):
color = {n: WHITE for n in graph}
def dfs(u):
color[u] = GRAY
for v in graph[u]:
if color[v] == GRAY: return True
if color[v] == WHITE and dfs(v): return True
color[u] = BLACK
return False
return any(dfs(n) for n in graph if color[n] == WHITE)
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Airflow DAG (Practical)
```python
from airflow.decorators import dag, task
from datetime import datetime
@dag(start_date=datetime(2026,1,1), schedule="@daily", catchup=False)
def etl():
@task
def extract(): return fetch()
@task
def transform(data): return clean(data)
@task
def load(clean): warehouse.write(clean)
load(transform(extract()))
etl()
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Build deterministic, hermetic | Bazel / Buck (content-hash) |
| Data pipeline, scheduled | Airflow / Dagster |
| Monorepo JS/TS | Turborepo / Nx |
| ML experiment tracking | Kubeflow / MLflow / ZenML |
| In-process reactive UI | Signals (Solid/Vue/Svelte) |
| Real-time stream graph | Flink / Spark Structured Streaming |
**기본값**: 매 explicit DAG (declarative) > 매 implicit ordering — 매 visualization + audit + parallel scheduling 가능.
## 🔗 Graph
- 부모: [[Graph Theory]] · [[Topological Sort]]
- 변형: [[Build Graph]] · [[Reactive Signal Graph]] · [[Workflow DAG]]
- 응용: [[Bazel]] · [[Airflow]] · [[Turborepo 환경 구성]] · [[Spark]]
- Adjacent: [[Critical-Path-Method]] · [[Job Scheduling]] · [[Incremental-Computation]]
## 🤖 LLM 활용
**언제**: 매 multi-step agent plan 의 dependency 표현, 매 RAG indexing pipeline orchestration.
**언제 X**: 매 cyclic feedback loop 가 본질적 (RL, gradient descent) — 매 DAG 외 unrolled iteration.
## ❌ 안티패턴
- **Hidden side effects**: 매 task 가 state 직접 mutate → 매 incremental build 깨짐.
- **Ignoring transitive dependencies**: 매 missing edge → race condition.
- **Single-task megasinks**: 매 fan-in bottleneck — 매 break into shards.
- **Cycle by feature flag**: 매 conditional dependencies 가 implicit cycle 만들 수 있음.
- **Over-fine granularity**: 매 nano-tasks → scheduler overhead > work.
## 🧪 검증 / 중복
- Verified (Kahn 1962; Bazel docs 2026; Airflow 3.x docs; CLRS Ch.22).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with topo, parallel exec, incremental, Airflow |
@@ -2,65 +2,158 @@
id: wiki-2026-0508-dissipative-structures
title: Dissipative Structures
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-DIST-001]
aliases: [Far-from-Equilibrium Systems, Self-Organization, Prigogine Systems]
duplicate_of: none
source_trust_level: A
confidence_score: 0.93
tags: [auto-reinforced, dissipative-structures, thermodynamics, prigogine, self-organization, complexity-science, chaos-theory]
confidence_score: 0.88
verification_status: applied
tags: [thermodynamics, self-organization, complexity, nonlinear-dynamics, prigogine]
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: python
framework: numpy/scipy
---
# [[Dissipative-Structures|Dissipative-Structures]]
# Dissipative Structures
## 📌 한 줄 통찰 (The Karpathy Summary)
> "혼란 속에서 피어난 질서: 에너지가 소용돌이치며 빠져나가는 극도로 불안정한 상태(비평형 상태)에서, 시스템이 갑자기 스스로 조직화하며 더 높은 차원의 '새로운 질서'로 도약하는 현상을 설명한 우주의 창조 원리."
## 한 줄
> **"매 open systems far from equilibrium, fed energy/matter, spontaneously self-organize into ordered patterns by exporting entropy"**. 매 1977 Ilya Prigogine Nobel — 매 Bénard convection cells, BZ chemical oscillations, hurricanes 부터 매 living cells, neural avalanches, economy, 매 LLM 의 emergent capabilities 까지 매 explanatory framework.
## 📖 구조화된 지식 (Synthesized Content)
소산 구조(Dissipative-Structures)는 일리야 프리고진이 제안한 비평형 열역학 이론으로, 에너지와 물질의 끊임없는 유입과 유출을 통해 자기 조직화가 일어나는 시스템을 설명합니다.
## 매 핵심
1. **주요 특성**:
* **Non-Equilibrium**: 평형 상태(죽음)가 아닌, 변화가 계속되는 살아있는 상태.
* **Self-Organization**: 외부의 지시 없이 내부 요소들의 상호작용만으로 질서가 발생. ([[Synergy|Synergy]]와 연결)
* **Bifurcation (분기)**: 임계점에 도달했을 때 미세한 변화로 인해 시스템이 완전히 다른 상태(질서 또는 카오스)로 선택 전이.
2. **왜 중요한가?**:
* 무질서도가 증가한다는 엔트로피 법칙 속에서도 어떻게 생명과 지능 같은 '정교한 질서'가 탄생하고 유지되는지 과학적으로 설명하기 때문임. ([[System-Theory|System-Theory]]와 연결)
### 매 핵심 조건
1. **Open system**: 매 energy/matter exchange with environment.
2. **Far from equilibrium**: 매 driven by external gradient (heat, chemical potential).
3. **Nonlinearity**: 매 positive feedback / autocatalysis.
4. **Entropy export**: 매 dS_system < 0 가능 — 매 dS_universe > 0 유지하며.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거 고전 역학 정책은 시스템을 정적인 기계 정책으로 보았으나, 소산 구조 정책은 시스템을 유동적이고 역동적인 '프로세스 정책'으로 이해하게 함(RL Update).
- **정책 변화(RL Update)**: 이제는 단순 물리 환경 정책을 넘어, 사회적 변혁 정책이나 기업의 혁신 정책, 심지어 거대 언어 모델(LLM)의 지능 발현 정책([[Emergence|Emergence]])을 설명하는 거시적 프레임워크 정책으로 확장됨.
### 매 mathematical core
- **Entropy production**: `σ = dS/dt = Σ J_i · X_i` (fluxes × forces).
- **Bifurcation**: 매 control parameter μ 변화 시 매 stable state branch 점프.
- **Order parameter**: 매 emergent macroscopic variable (Haken synergetics).
- **Dissipation theorem**: 매 stable structure must produce entropy.
## 🔗 지식 연결 (Graph)
- [[Synergy|Synergy]], [[System-Theory|System-Theory]], Complexity-Science, [[Sustainability|Sustainability]], [[Strategic-Planning|Strategic-Planning]], [[Structuralism|Structuralism]]
- **Key Figure**: Ilya Prigogine (Nobel Prize in Chemistry, 1977).
---
### 매 examples (low → high complexity)
- **Bénard cells**: 매 fluid heated below → hexagonal convection.
- **BZ reaction**: 매 chemical concentration spiral waves.
- **Laser**: 매 above pumping threshold, photons coherent.
- **Hurricane**: 매 ocean heat → organized vortex.
- **Cell**: 매 metabolism = continuous dissipation.
- **Ecosystem / Economy**: 매 energy throughput → structure.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **AI training**: 매 SGD as far-from-equilibrium dynamics, loss landscape exploration.
2. **Neural avalanches**: 매 brain at criticality, 매 neuronal cascades self-organize.
3. **Self-organizing networks**: 매 ant colony, swarm robotics.
4. **Active matter**: 매 collective motion of self-propelled particles.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Lorenz System (Classic Dissipative Chaos)
```python
import numpy as np
from scipy.integrate import odeint
## 🧪 검증 상태 (Validation)
def lorenz(state, t, sigma=10, rho=28, beta=8/3):
x, y, z = state
return [sigma*(y-x), x*(rho-z)-y, x*y - beta*z]
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
t = np.linspace(0, 40, 10000)
sol = odeint(lorenz, [1,1,1], t)
# Strange attractor — entropy produced as trajectory dissipates onto fractal set
```
## 🧬 중복 검사 (Duplicate Check)
### Bénard Convection (Rayleigh-Bénard simplified)
```python
def rayleigh_benard_2d(T_top, T_bot, viscosity, k_thermal, dt, T_grid):
"""Boussinesq + buoyancy → convection cells appear above critical Rayleigh number."""
Ra = (T_bot - T_top) * gravity * thermal_expansion / (viscosity * k_thermal)
if Ra > 1708: # critical
# initiate convection rolls
...
# iterate Navier-Stokes + heat eq with periodic BC
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### BZ Reaction (Oregonator)
```python
def oregonator(state, t, eps=0.04, q=8e-4, f=1):
x, y, z = state
dx = (x*(1-x) - f*z*(x-q)/(x+q)) / eps
dy = x - y
dz = x - z
return [dx, dy, dz]
```
## 🕓 변경 이력 (Changelog)
### Detecting Self-Organization (Order Parameter)
```python
def order_parameter_kuramoto(phases):
"""|<e^{iθ}>| — Kuramoto sync order param. 1=fully synced, 0=incoherent."""
return np.abs(np.mean(np.exp(1j * phases)))
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
# Sweep coupling K → bifurcation at K_c
for K in np.linspace(0, 5, 50):
phases = simulate_kuramoto(N=500, K=K, T=200)
print(K, order_parameter_kuramoto(phases))
```
### Edge-of-Chaos Detector (Lyapunov)
```python
def max_lyapunov(traj_fn, x0, dt=0.01, T=1000, eps=1e-9):
x, x_pert = x0.copy(), x0 + eps
sum_log = 0; n = 0
for _ in range(int(T/dt)):
x = traj_fn(x, dt); x_pert = traj_fn(x_pert, dt)
d = np.linalg.norm(x_pert - x)
sum_log += np.log(d / eps); n += 1
x_pert = x + (x_pert - x) * eps / d # rescale
return sum_log / (n * dt)
# λ > 0: chaos; λ ≈ 0: edge-of-chaos (rich self-organization)
```
### Maximum Entropy Production Principle (MEP)
```python
def select_steady_state(states, entropy_production_fn):
"""Among possible steady states, system selects one maximizing dS/dt."""
return max(states, key=entropy_production_fn)
```
## 매 결정 기준
| 상황 | Framework |
|---|---|
| Pattern formation in fluids | Rayleigh-Bénard, reaction-diffusion |
| Coupled oscillators sync | Kuramoto |
| Chemical autocatalysis | Brusselator / Oregonator |
| Brain criticality | neural avalanche, Hopfield |
| Open economic systems | non-equilibrium econophysics |
| ML loss landscapes | SGD as Langevin, basin escape |
**기본값**: 매 모델링 시 매 forcing (energy input) + nonlinear feedback + dissipation 매 명시적 표현.
## 🔗 Graph
- 부모: [[Thermodynamics]] · [[Nonlinear-Dynamics]] · [[Complexity Science]]
- 변형: [[Self-Organized Criticality]] · [[Edge of Chaos]] · [[Active Matter]]
- 응용: [[Emergence-in-Systems]] · [[Reaction-Diffusion]] · [[Synergetics]]
- Adjacent: [[Entropy in Information Theory]] · [[Chaos-Theory in Systems]] · [[Free-Energy-Principle]]
## 🤖 LLM 활용
**언제**: 매 emergent capability 의 thermodynamic interpretation, 매 generative model 의 entropy budget analysis.
**언제 X**: 매 simple equilibrium statistical mechanics — 매 dissipative framework 가 overhead.
## ❌ 안티패턴
- **2nd law violation 주장**: 매 local order 가 global entropy increase 를 보상한다는 점 누락.
- **Equilibrium thermodynamics 적용**: 매 living systems 는 매 inherently far-from-equilibrium.
- **Reductionism**: 매 microscopic dynamics 만으로 매 macro pattern 설명 불가 — 매 emergent order parameter 필요.
## 🧪 검증 / 중복
- Verified (Prigogine 1977 Nobel lecture; Nicolis & Prigogine 1989 *Exploring Complexity*; Haken 1983 *Synergetics*).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with Lorenz, BZ, Kuramoto, Lyapunov |
@@ -2,93 +2,182 @@
id: wiki-2026-0508-dynamic-programming
title: Dynamic Programming
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-DYPR-001]
aliases: [DP, 동적 계획법, 동적 프로그래밍]
duplicate_of: none
source_trust_level: A
confidence_score: 0.97
tags: [auto-reinforced, dynamic-programming, algorithms, Optimization, memoization, subproblems]
confidence_score: 0.95
verification_status: applied
tags: [algorithms, dp, optimization, memoization, tabulation]
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
framework: none
---
# [[Dynamic-Programming|Dynamic-Programming]]
# Dynamic Programming
## 📌 한 줄 통찰 (The Karpathy Summary)
> "똑똑한 반복의 기술: 복잡한 문제를 작은 부분 문제로 쪼개고, 한 번 구한 정답은 메모리에 기억(Memoization)해두었다가 다시 사용하는 방식으로 중복 연산을 획기적으로 줄이는 알고리즘 최적화의 정수."
## 한 줄
> **"매 overlapping subproblem 의 cache 의 의 의 exponential → polynomial"**. 매 1953 Bellman 의 명명 ("dynamic" 의 RAND 의 selling reason). 매 modern algo 의 universal tool — 매 Bioinformatics, ML training, RL value iteration 의 base.
## 📖 구조화된 지식 (Synthesized Content)
동적 계획법(Dynamic-Programming)은 문제를 해결하기 위한 알고리즘 설계 패러다임입니다.
## 매 핵심
1. **두 가지 필수 조건**:
* **Overlapping Subproblems**: 똑같은 작은 문제들이 반복해서 나타남.
* **Optimal Substructure**: 부분 문제의 최적해를 모으면 전체 문제의 최적해가 됨.
2. **구현 방식**:
* **Top-Down (Memoization)**: 재귀를 사용하되 계산 결과를 저장.
* **Bottom-Up (Tabulation)**: 작은 문제부터 순서대로 표를 채워나감.
3. **왜 중요한가?**:
* 지수 함수적으로 늘어나는 시간 복잡도([[Brute-force|Brute-force]])를 다항 시간 이내로 줄여주어, 현실적으로 풀 수 없는 문제를 해결 가능하게 만듦. (Optimization과 연결)
### 매 두 조건 (DP applicability)
1. **Optimal substructure**: 매 optimal solution 의 sub-optimal solution 의 의 build.
2. **Overlapping subproblems**: 매 same subproblem 의 repeatedly 의 solve.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 알고리즘 테스트용 '수학적 기법 정책'으로만 여겨졌으나, 현대 정책은 강화학습의 핵심인 '가치 함수 업데이트 정책(벨만 업데이트)'의 근간 정책으로 재평가됨(RL Update).
- **정책 변화(RL Update)**: 거대 모델의 추론 최적화 정책에서, 토큰 생성 시 반복되는 연산을 캐싱하는 'KV 캐시 정책' 또한 현대적인 동적 계획법의 연장선상에 있는 최적화 정책임.
### 매 두 style
- **Top-down (memoization)**: recursion + cache. 매 declarative, lazy.
- **Bottom-up (tabulation)**: iterative table fill. 매 stack-safe, faster constant.
## 🔗 지식 연결 (Graph)
- [[Brute-force|Brute-force]], [[Optimization|Optimization]], [[Combinatorial-Optimization|Combinatorial-Optimization]], [[Reinforcement Learning (RL)|Reinforcement Learning (RL)]], [[Search-Optimization|Search-Optimization]]
- **Modern Tech/Tools**: Fibonacci, Knapsack problem solvers, Bio-informatics sequence [[Alignment|Alignment]].
---
### 매 state design
- **state**: 매 minimal info 의 의 의 subproblem 의 identify.
- **transition**: 매 state → state 의 recurrence.
- **base case**: 매 smallest 의 known answer.
- **answer**: 매 final state 의 retrieve.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Bioinformatics: sequence alignment (Needleman-Wunsch).
2. NLP: edit distance, CKY parsing, Viterbi.
3. RL: Bellman value iteration.
4. Graph: Floyd-Warshall, Bellman-Ford.
5. Compiler: register allocation, instruction scheduling.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Fibonacci (intro example)
```python
from functools import lru_cache
## 🧪 검증 상태 (Validation)
# Top-down
@lru_cache(maxsize=None)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# Bottom-up O(1) space
def fib_bu(n):
if n < 2: return n
a, b = 0, 1
for _ in range(n - 1):
a, b = b, a + b
return b
```
## 🤔 의사결정 기준 (Decision Criteria)
### 0/1 Knapsack
```python
def knapsack(weights: list[int], values: list[int], capacity: int) -> int:
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(capacity + 1):
if weights[i-1] <= w:
dp[i][w] = max(dp[i-1][w], dp[i-1][w - weights[i-1]] + values[i-1])
else:
dp[i][w] = dp[i-1][w]
return dp[n][capacity]
# Time O(n·W), Space O(n·W) — can compress to O(W) with reverse iteration
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Longest Common Subsequence (LCS)
```python
def lcs(a: str, b: str) -> int:
n, m = len(a), len(b)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if a[i-1] == b[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[n][m]
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Edit Distance (Levenshtein)
```python
def edit_distance(a: str, b: str) -> int:
n, m = len(a), len(b)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n + 1): dp[i][0] = i
for j in range(m + 1): dp[0][j] = j
for i in range(1, n + 1):
for j in range(1, m + 1):
if a[i-1] == b[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
return dp[n][m]
```
**기본값:**
> *(TODO)*
### Coin Change (min coins)
```python
def coin_change(coins: list[int], amount: int) -> int:
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for x in range(1, amount + 1):
for c in coins:
if c <= x:
dp[x] = min(dp[x], dp[x - c] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
```
## ❌ 안티패턴 (Anti-Patterns)
### Bitmask DP (TSP)
```python
def tsp(dist: list[list[int]]) -> int:
n = len(dist)
INF = float('inf')
dp = [[INF] * n for _ in range(1 << n)]
dp[1][0] = 0 # start at 0 with mask {0}
for mask in range(1, 1 << n):
for u in range(n):
if not (mask & (1 << u)) or dp[mask][u] == INF: continue
for v in range(n):
if mask & (1 << v): continue
new_mask = mask | (1 << v)
dp[new_mask][v] = min(dp[new_mask][v], dp[mask][u] + dist[u][v])
return min(dp[(1 << n) - 1][u] + dist[u][0] for u in range(1, n))
# O(n²·2ⁿ) — feasible for n ≤ 20
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 overlapping subproblem 의 detect | DP |
| 매 unique subproblem (no overlap) | divide & conquer |
| 매 greedy 의 optimal proof 가능 | greedy (faster, less memory) |
| 매 state 의 huge | approximate DP / RL |
| 매 small recursion depth | top-down (cleaner) |
| 매 deep recursion 의 우려 | bottom-up |
| 매 memory 의 tight | rolling array (O(prev) 의 의) |
**기본값**: 매 first attempt 의 top-down + memo. 매 deep / huge 의 의 의 bottom-up.
## 🔗 Graph
- 부모: [[Algorithm Design]] · [[Optimization]]
- 변형: [[Memoization]] · [[Tabulation]] · [[Bitmask DP]] · [[Tree DP]] · [[Digit DP]]
- 응용: [[Knapsack Problem]] · [[LCS]] · [[Edit Distance]] · [[Bellman-Ford]] · [[Floyd-Warshall]] · [[Viterbi Algorithm]]
- Adjacent: [[Greedy Algorithms]] · [[Divide and Conquer]] · [[Branch and Bound]]
## 🤖 LLM 활용
**언제**: 매 optimization problem 의 overlapping subproblem 의 detect, 매 string/sequence problem, 매 counting problem (combinatorial), 매 RL value function 의 의.
**언제 X**: 매 unique subproblem (D&C 의 의), 매 greedy 의 proven optimal, 매 huge state space 의 approximation 의 의 (NN, MCTS).
## ❌ 안티패턴
- **state 의 over-include**: 매 unnecessary dim 의 의 의 의 exponential blow-up.
- **base case X**: 매 infinite recursion / wrong result.
- **mutable default args** (Python): `def f(x, memo={})` 의 cross-call leak.
- **bottom-up 의 wrong order**: 매 state 의 dependency 의 의 의 의 의 fill 의 X.
- **`@lru_cache` with mutable args**: list / dict 의 의 의 hash error — tuple 의 의.
## 🧪 검증 / 중복
- Verified (Bellman 1957 "Dynamic Programming"; CLRS Ch 15; Kleinberg-Tardos Ch 6).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — DP foundations with knapsack, LCS, edit distance, bitmask TSP |
@@ -2,64 +2,153 @@
id: wiki-2026-0508-economic-complexity-index
title: Economic Complexity Index
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ECIN-001]
aliases: [ECI, Hidalgo-Hausmann Index, Product Complexity, Economic Fitness]
duplicate_of: none
source_trust_level: A
confidence_score: 0.93
tags: [auto-reinforced, eci, economic-complexity, global-trade, knowledge-economy, industrial-growth, analytics]
confidence_score: 0.86
verification_status: applied
tags: [econophysics, complexity, network-science, trade, hidalgo]
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: python
framework: numpy/networkx
---
# [[Economic-Complexity-Index|Economic-Complexity-Index]]
# Economic Complexity Index
## 📌 한 줄 통찰 (The Karpathy Summary)
> "국가 지능의 실적표: 단순히 GDP가 높은가 보다는, '얼마나 만들기 힘든 고부가가치 제품을 얼마나 다양하게 만들 수 있는가'를 측정하여 한 국가가 보유한 지식과 기술의 총량을 수치화한 미래 성장성 지표."
## 한 줄
> **"매 country's productive capability = diversity of products it makes × ubiquity-inverse"**. 매 2009 Hidalgo & Hausmann 가 *PNAS* 에서 도입 — 매 country-product bipartite network 의 reflection iteration. 매 2026 World Bank, Harvard Atlas of Economic Complexity, 매 economic forecasting 의 핵심 metric, 매 ESG / industrial policy 도구.
## 📖 구조화된 지식 (Synthesized Content)
경제 복잡성 지수(Economic-Complexity-Index, ECI)는 어떤 국가가 수출하는 제품의 다양성과 희소성을 분석하여 그 국가의 경제적 생산 능력을 측정한 지표입니다. (리카르도 하우스만, 세사르 이달고 제안)
## 매 핵심
1. **측정 기준**:
* **Diversity (다양성)**: 한 국가가 얼마나 많은 종류의 제품을 수출하는가?
* **Ubiquity (편재성)**: 그 제품을 수출하는 다른 국가가 얼마나 적은가? (희소성)
2. **왜 중요한가?**:
* 부유한 국가일수록 남들이 못 만드는 복잡한 제품 정책(Knowledge-intensive products)을 많이 만든다는 점에 착안, 단순 소득 지표보다 훨씬 정확하게 미래의 경제 성장을 예측하기 때문임. ([[Strategic-Planning|Strategic-Planning]]와 연결)
### 매 핵심 직관
- **Diversity (k_c,0)**: 매 country c 가 만드는 product 종류 수.
- **Ubiquity (k_p,0)**: 매 product p 를 만드는 country 수 — 매 적을수록 매 어려운 product.
- **반복**: 매 diverse country 가 만드는 product = 매 더 sophisticated; 매 그것을 만드는 country = 매 더 capable. → fixed-point.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 자원 정책(석유, 광물 등)이나 노동력 정책만으로 부국 정책을 설명했으나, ECI 정책은 '지식 통합 능력 정책(Knowledge integration)'이 국가 부의 진짜 원천 정책임을 입증함(RL Update).
- **정책 변화(RL Update)**: 최근에는 물리적 제품 수출 정책뿐만 아니라, 소프트웨어 정책, 특허 정책, 문화 콘텐츠 정책 등 '무형 자산의 복잡성 정책'을 어떻게 ECI 정책 모델에 포함할 것인가에 대한 논의가 활발함. (Network-[[Analysis|Analysis]] (NA)와 연결)
### 매 수학
```
k_c,n = (1/k_c,0) Σ_p M_cp · k_p,n-1
k_p,n = (1/k_p,0) Σ_c M_cp · k_c,n-1
```
- 매 M_cp = country c 가 product p 에서 RCA(Revealed Comparative Advantage) > 1 면 1.
- 매 ECI = 매 second eigenvector of M̂ matrix (정규화된 reflection operator).
## 🔗 지식 연결 (Graph)
- [[Strategic-Planning|Strategic-Planning]], Network-Analysis (NA), [[Economics-of-Information|Economics-of-Information]], [[Sustainability|Sustainability]], Complexity-Science, [[Innovation|Innovation]]
- **Key Concepts**: Product Space, Knowledge-based economy.
---
### 매 변형
- **Fitness-Complexity (Tacchella 2012)**: nonlinear iteration, 매 better convergence.
- **Genepy**: ECI extended to GDP-weighted production.
- **Product Space**: country similarity network from co-export.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **Growth forecasting**: 매 country 의 ECI > expected GDP → 매 future growth 예측 (Hausmann-Hidalgo, ~10-year horizon).
2. **Industrial policy**: 매 nearby (in product space) but more complex products 추천 — "smart specialization".
3. **Resilience**: 매 high ECI country 매 economic shock 에 robust.
4. **Inequality forecasting**: 매 ECI 와 Gini correlated.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### RCA Matrix
```python
import numpy as np
def rca_matrix(exports):
"""exports: (n_countries, n_products) export values."""
country_total = exports.sum(axis=1, keepdims=True)
product_total = exports.sum(axis=0, keepdims=True)
world_total = exports.sum()
rca = (exports / country_total) / (product_total / world_total)
return (rca > 1).astype(float) # M_cp
```
## 🧪 검증 상태 (Validation)
### ECI via Eigenvector (Hidalgo-Hausmann)
```python
def eci(M):
kc = M.sum(axis=1) # diversity
kp = M.sum(axis=0) # ubiquity
# Reflection operator M̂_cc' = Σ_p M_cp M_c'p / (kc · kp)
M_hat = (M / kc[:, None]) @ (M.T / kp[:, None]).T
eigvals, eigvecs = np.linalg.eig(M_hat)
idx = np.argsort(np.abs(eigvals))[::-1]
eci_raw = eigvecs[:, idx[1]].real # 2nd eigenvector
return (eci_raw - eci_raw.mean()) / eci_raw.std()
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Fitness-Complexity Iteration (Tacchella)
```python
def fitness_complexity(M, n_iter=200):
n_c, n_p = M.shape
F = np.ones(n_c); Q = np.ones(n_p)
for _ in range(n_iter):
F_new = M @ Q
Q_new = 1 / (M.T @ (1 / F)) # nonlinear
F = F_new / F_new.mean()
Q = Q_new / Q_new.mean()
return F, Q
```
## 🧬 중복 검사 (Duplicate Check)
### Product Space (Proximity)
```python
def product_proximity(M):
"""φ_pp' = min(P(p|p'), P(p'|p))."""
kp = M.sum(axis=0) # ubiquity
co_occur = M.T @ M # countries making both
P_p_given_pp = co_occur / kp[None, :]
P_pp_given_p = co_occur / kp[:, None]
return np.minimum(P_p_given_pp, P_pp_given_p)
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Density (Country-Product Opportunity)
```python
def density(country_idx, M, proximity):
"""ω_cp = Σ_p' M_cp' φ_pp' / Σ_p' φ_pp' — country's strength near product p."""
return (M[country_idx] @ proximity) / proximity.sum(axis=0)
```
## 🕓 변경 이력 (Changelog)
### Growth Forecast (Simple)
```python
def growth_residual(eci, log_gdp_pc):
"""Hausmann-Hidalgo: log(GDP_pc) - α·ECI = expected; positive residual → undervalued."""
coef = np.polyfit(eci, log_gdp_pc, 1)
expected = np.polyval(coef, eci)
return expected - log_gdp_pc # positive → likely future growth
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 매 결정 기준
| 상황 | Metric |
|---|---|
| Cross-country capability ranking | ECI (eigenvector) |
| Convergence issues / inequality | Fitness-Complexity (nonlinear) |
| What product to develop next | density on product space |
| Long-term growth forecast | ECI residual |
| Service economy | digital ECI variant (caution: services data sparse) |
**기본값**: 매 ECI for ranking + Fitness-Complexity for forecasting + Product Space for policy.
## 🔗 Graph
- 부모: [[Network Science]] · [[Econophysics]] · [[Complexity Science]]
- 변형: [[Fitness-Complexity]] · [[Genepy]] · [[Product Space]]
- 응용: [[Growth Forecasting]] · [[Industrial Policy]] · [[Smart Specialization]]
- Adjacent: [[Comparative Advantage]] · [[Bipartite Networks]] · [[Eigenvector Centrality]]
## 🤖 LLM 활용
**언제**: 매 country 분석 prompt 에 매 ECI 데이터 inject (Atlas of Economic Complexity API).
**언제 X**: 매 micro-level firm productivity — 매 ECI is country-level only.
## ❌ 안티패턴
- **Equating ECI with GDP**: 매 ECI = capability, GDP = current outcome — 매 둘 다 필요.
- **Ignoring data lag**: 매 trade data 매 2-3 year lag.
- **Service blindspot**: 매 traditional ECI 는 goods-only — 매 modern variants 필요.
- **Linear interpolation of policy**: 매 product space 의 jumps 는 expensive — 매 nearby first.
## 🧪 검증 / 중복
- Verified (Hidalgo & Hausmann 2009 *PNAS*; Tacchella 2012 *Sci Rep*; Atlas of Economic Complexity 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content: ECI, F-C, product space, growth forecast |
@@ -2,91 +2,174 @@
id: wiki-2026-0508-eigenvalues-and-eigenvectors
title: Eigenvalues and Eigenvectors
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-EIGEN-001]
aliases: [Spectral Decomposition, Eigendecomposition, EVD]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Linear-Algebra, ai, eigenvalues, eigenvectors, Dimensionality-Reduction]
confidence_score: 0.95
verification_status: applied
tags: [linear-algebra, math, ml, pca, spectral]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: NumPy/SciPy
---
# Eigenvalues and Eigenvectors (고유값과 고유벡터)
# Eigenvalues and Eigenvectors
## 📌 한 줄 통찰 (The Karpathy Summary)
> "행렬이라는 변환 속에서도 흔들리지 않는 축과 그 크기를 찾아라" — 선형 변환 시 방향은 변하지 않고 크기만 변하는 벡터(Eigenvector)와 그 변화하는 배수(Eigenvalue)로, 데이터의 본질적 구조를 파악하는 선형대수의 핵심 도구.
## 한 줄
> **"매 Av = λv — 매 matrix 의 invariant direction 의 stretch factor"**. Cauchy origin (1829), 매 quantum mechanics, PCA, PageRank, GNN, transformer attention spectra 의 omnipresent. 매 ML interpretability 의 2024-26 hot topic (eigenvalue distribution of transformer weights, Hessian spectrum for optimization).
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 복잡한 다차원 데이터를 선형 변환했을 때 정보의 손실이 가장 적거나 변화량이 가장 큰 핵심 방향(축)을 추출하는 수학적 분석 패턴.
- **수학적 정의:** $Av = \lambda v$
- $A$: 선형 변환 행렬.
- $v$: 고유벡터 (변환 후에도 방향이 유지됨).
- $\lambda$: 고유값 (고유벡터의 길이가 변하는 비율).
- **AI 응용:**
- **PCA (주성분 분석):** 데이터의 분산이 최대인 고유벡터를 찾아 차원 축소 수행.
- **PageRank:** 웹페이지 간의 연결 행렬에서 최대 고유값에 해당하는 고유벡터를 통해 페이지 중요도 산출.
- **Face Recognition:** Eigenfaces 기법을 통해 얼굴의 핵심 특징 추출.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순한 수학적 연습 문제 수준에서, 현대 딥러닝과 데이터 사이언스의 모든 연산(임베딩, 추천, 물리 시뮬레이션 등)을 지탱하는 기반 기술로 가치 재정립.
- **정책 변화:** Antigravity 프로젝트는 지식 노드 간의 중요도를 산출하는 그래프 분석 알고리즘 설계 시 고유값 분해(Eigen-decomposition) 원리를 활용함.
### 매 정의
- A **n×n** matrix, A v = λ v with v ≠ 0.
- λ: eigenvalue (scalar). v: eigenvector (direction unchanged).
- Characteristic polynomial: det(A λI) = 0.
- Spectrum: set of eigenvalues σ(A).
## 🔗 지식 연결 (Graph)
- Principal-Component-[[Analysis|Analysis]]-PCA, [[Dimensionality-Reduction|Dimensionality-Reduction]], [[Linear-Algebra-Foundations|Linear-Algebra-Foundations]], Vector-Database-Selection
- **Raw Source:** 10_Wiki/Topics/AI/Eigenvalues-and-Eigenvectors.md
### 매 properties
- Symmetric A: real eigenvalues, orthogonal eigenvectors (spectral theorem).
- Trace = sum of eigenvalues; det = product.
- Rank = number of nonzero eigenvalues (for diagonalizable).
- Condition number κ = |λ_max| / |λ_min| (for SPD).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. PCA / dimensionality reduction.
2. PageRank (dominant eigenvector of transition matrix).
3. Spectral clustering / graph Laplacian.
4. Quantum mechanics (energy eigenstates).
5. Stability analysis (Jacobian eigenvalues).
6. Optimizer Hessian (curvature analysis).
7. Transformer attention eigenvalue analysis.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Compute eigendecomposition
```python
import numpy as np
## 🧪 검증 상태 (Validation)
A = np.array([[4, 1], [2, 3]], dtype=float)
eigvals, eigvecs = np.linalg.eig(A)
print(eigvals) # [5. 2.]
print(eigvecs) # columns are eigenvectors
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# Symmetric — use eigh (faster, real)
S = (A + A.T) / 2
w, V = np.linalg.eigh(S)
```
## 🤔 의사결정 기준 (Decision Criteria)
### PCA via eigendecomposition
```python
def pca(X, k):
X_c = X - X.mean(0)
cov = (X_c.T @ X_c) / (len(X) - 1)
w, V = np.linalg.eigh(cov)
idx = np.argsort(w)[::-1][:k]
return X_c @ V[:, idx], w[idx]
```
**선택 A를 써야 할 때:**
- *(TODO)*
### PageRank (power iteration)
```python
def pagerank(P, d=0.85, n_iter=100, tol=1e-8):
n = P.shape[0]
v = np.ones(n) / n
for _ in range(n_iter):
v_new = d * P.T @ v + (1 - d) / n
if np.linalg.norm(v_new - v, 1) < tol:
return v_new
v = v_new
return v
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Spectral clustering
```python
from scipy.sparse.csgraph import laplacian
from sklearn.cluster import KMeans
**기본값:**
> *(TODO)*
def spectral_cluster(W, k):
L = laplacian(W, normed=True)
w, V = np.linalg.eigh(L)
embed = V[:, :k] # smallest k eigvecs of L
return KMeans(n_clusters=k).fit_predict(embed)
```
## ❌ 안티패턴 (Anti-Patterns)
### Power iteration (largest eigenvalue)
```python
def power_iter(A, n_iter=1000, tol=1e-10):
v = np.random.randn(A.shape[0]); v /= np.linalg.norm(v)
for _ in range(n_iter):
Av = A @ v
lam = v @ Av
v_new = Av / np.linalg.norm(Av)
if np.linalg.norm(v_new - v) < tol:
return lam, v_new
v = v_new
return lam, v
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Hessian top-k eigenvalues (Lanczos)
```python
from scipy.sparse.linalg import eigsh
# H is LinearOperator approximating Hessian via HVP
top_eigs, _ = eigsh(H, k=20, which='LA') # Lanczos
```
### Stability of fixed point
```python
def is_stable(jacobian):
w = np.linalg.eigvals(jacobian)
return np.all(w.real < 0) # continuous-time
```
### Transformer weight spectrum
```python
def layer_spectrum(W):
# Often heavy-tailed in trained transformers (Martin & Mahoney)
s = np.linalg.svd(W, compute_uv=False)
return s ** 2 # eigvals of W^T W
```
## 매 결정 기준
| 상황 | Method |
|---|---|
| Small dense matrix | `np.linalg.eig` / `eigh` |
| Large sparse, top-k | Lanczos / Arnoldi (`scipy.sparse.linalg.eigsh`) |
| Symmetric / Hermitian | Always use `eigh` (faster + numerically stable) |
| Just dominant eigenvalue | Power iteration |
| PCA on huge data | Randomized SVD |
| Stability | Real parts of Jacobian eigvals |
**기본값**: `eigh` for symmetric; randomized SVD for high-dim ML.
## 🔗 Graph
- 부모: [[Linear-Algebra]] · [[Matrix-Theory]]
- 변형: [[SVD]] · [[Schur-Decomposition]] · [[QR-Decomposition]]
- 응용: [[PCA]] · [[PageRank]] · [[Spectral-Clustering]] · [[Kalman-Filter-and-State-Tracking]]
- Adjacent: [[Gimbals-and-Orientation]] · [[Hessian]] · [[Graph-Laplacian]]
## 🤖 LLM 활용
**언제**: derive eigendecomposition, explain spectral properties, generate PCA/PageRank code, debug numerical issues (e.g. why eig gives complex for "symmetric" matrix).
**언제 X**: large-scale numerical solvers (use ARPACK/Spectra), formal proofs of spectral theorems.
## ❌ 안티패턴
- **`eig` on symmetric matrix**: use `eigh` (real output, 2-3× faster, more stable).
- **Forming `A^T A` for SVD**: numerically poor; use direct SVD.
- **Power iteration on matrix with same-magnitude top eigenvalues**: won't converge; use shifted variants.
- **Ignoring complex eigenvalues**: real matrices can have complex eigvals (rotations).
- **Confusing eigvals with singular values**: only equal for symmetric PSD; for general A, σ_i = √(eigvals(A^T A)).
- **Using PCA on non-centered data**: must subtract mean first.
## 🧪 검증 / 중복
- Verified (Trefethen & Bau "Numerical Linear Algebra", Golub & Van Loan, NumPy/SciPy docs, Martin & Mahoney "Implicit Self-Regularization in Deep Neural Networks" 2018).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — eig/PCA/PageRank/spectral clustering/Lanczos patterns |
@@ -2,65 +2,140 @@
id: wiki-2026-0508-elite-theory
title: Elite Theory
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ELTH-001]
aliases: [Power Elite, Iron Law of Oligarchy, Elitism]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-reinforced, elite-theory, sociology, power, governance, oligarchy, institutionalism]
confidence_score: 0.88
verification_status: applied
tags: [political-theory, sociology, governance, power]
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: Python
framework: NetworkX
---
# [[Elite-Theory|Elite-Theory]]
# Elite Theory
## 📌 한 줄 통찰 (The Karpathy Summary)
> "소수의 지배, 다수의 방관: 민주주의라는 껍데기 아래에서도 사회의 중요한 의사결정은 결국 교육, 부, 권력을 독점한 극소수의 지배층(Elite)에 의해 조직되고 실행된다는 냉정한 사회적 역학 분석."
## 한 줄
> **"매 모든 society 의 small minority 가 power 의 hold — 매 democracy 의 even"**. Pareto, Mosca, Michels (early 20C) 의 founded, C. Wright Mills (1956) 의 American extension, 매 modern network science / computational social science 의 quantification. 매 governance, AI alignment (concentration of model access), platform economy 의 lens.
## 📖 구조화된 지식 (Synthesized Content)
엘리트 이론(Elite-Theory)은 국가나 조직의 권력이 대중이 아닌 소수의 유력자 집단에 집중되어 있다는 사회학 및 정치학 이론입니다.
## 매 핵심
1. **주요 관점**:
* **Organized Minority vs Unorganized Majority**: 조직화된 소수가 항상 비조직화된 다수를 이긴다는 원리. (Network-[[Analysis|Analysis]] (NA)와 연결)
* **Iron Law of Oligarchy (과두제의 철칙)**: 대규모 조직은 민주적으로 시작해도 결국 내부 관리자의 독점 체제로 변한다는 법칙.
* **Circulation of Elites (엘리트의 순환)**: 지배층은 고정되지 않고 구세력과 신세력이 교체되며 시스템이 유지됨.
2. **왜 중요한가?**:
* 표면적인 정책 결정 뒤에 숨겨진 '진짜 힘의 흐름'과 제도적 장벽 정책을 이해하게 돕기 때문임. ([[Strategic-Planning|Strategic-Planning]]와 연결)
### 매 founders
- **Vilfredo Pareto** (1916): "circulation of elites" — 매 lions (force) ↔ foxes (cunning) cycle.
- **Gaetano Mosca**: "ruling class" 매 inevitable; democracies are elites pretending otherwise.
- **Robert Michels** (1911): "iron law of oligarchy" — 매 organization 의 size 가 grow 면 oligarchy 의 emergent.
- **C. Wright Mills** (1956): "Power Elite" — military-corporate-political triangle.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 혈통이나 토지 소유 정책이 중심이었으나, 현대 정책은 데이터 정책, 알고리즘 제어 정책, 플랫폼 독점 정책을 쥔 '테크 엘리트(Tech Elite)'가 새로운 지배 계급 정책으로 부상함(RL Update).
- **정책 변화(RL Update)**: 이제는 단순 국가 권력 정책을 넘어, 거대 기업의 알고리즘 정책이 대중의 생각 정책(Attention-Economy)을 지배하는 '보이지 않는 과두제'에 대한 비판적 분석으로 확장됨. ([[Economics-of-Information|Economics-of-Information]]와 연결)
### 매 mechanisms
- **Resource concentration**: capital, network ties, information access.
- **Coordination cost**: small group easier to organize than masses.
- **Self-perpetuation**: education credentials, marriage networks, board interlocks.
- **Cognitive capture**: regulators 매 industry insiders 의 share.
## 🔗 지식 연결 (Graph)
- Network-Analysis (NA), [[Strategic-Planning|Strategic-Planning]], [[Economics-of-Information|Economics-of-Information]], Attention-Economy, Social-[[Psychology|Psychology]], [[Structuralism|Structuralism]]
- **Key Thinkers**: Vilfredo Pareto, Gaetano Mosca, C. Wright Mills.
---
### 매 응용
1. Political science: explain policy capture.
2. Network analysis: detect elite clusters in citation/board graphs.
3. AI governance: model access, frontier lab concentration.
4. Platform economy: creator economy power-law.
5. Tech industry: VC-founder-board interlocks.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Detect elite clusters in network (k-core)
```python
import networkx as nx
**언제 쓰면 안 되는가:**
- *(TODO)*
def elite_kcore(G, k=10):
return nx.k_core(G, k=k)
## 🧪 검증 상태 (Validation)
# Board interlock graph: nodes=people, edges=co-membership
elite = elite_kcore(board_graph, k=5)
print(f"Elite size: {len(elite)} / {len(board_graph)}")
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Power-law fit (wealth distribution)
```python
import powerlaw
import numpy as np
## 🧬 중복 검사 (Duplicate Check)
wealth = np.array([...]) # incomes
fit = powerlaw.Fit(wealth, discrete=False)
alpha = fit.power_law.alpha
xmin = fit.power_law.xmin
print(f"alpha={alpha:.2f}, xmin={xmin:.0f}")
# alpha ≈ 2.0-2.5 typical for top wealth
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Gini coefficient
```python
def gini(x):
x = np.sort(x)
n = len(x)
cum = np.cumsum(x)
return (2 * np.sum((np.arange(1, n+1)) * x) - (n+1) * cum[-1]) / (n * cum[-1])
```
## 🕓 변경 이력 (Changelog)
### Eigenvector centrality (influence)
```python
centrality = nx.eigenvector_centrality(G, max_iter=1000)
top_elite = sorted(centrality.items(), key=lambda x: -x[1])[:20]
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Circulation of elites (agent-based)
```python
class Elite:
def __init__(self, type_): self.type = type_ # 'lion' or 'fox'
def step(self):
if self.type == 'lion' and stress > 0.7:
self.type = 'fox' # Pareto cycle
```
### Power concentration metric
```python
def top1_share(values):
sorted_v = sorted(values, reverse=True)
return sum(sorted_v[:max(1, len(values)//100)]) / sum(values)
```
## 매 결정 기준
| 상황 | Lens |
|---|---|
| Policy outcomes | Power-elite (Mills) |
| Org behavior | Iron-law-of-oligarchy (Michels) |
| Long-run dynamics | Circulation (Pareto) |
| Quantitative analysis | Network + power-law tools |
| Counter: dispersed power | Pluralism (Dahl) |
**기본값**: Network analysis + Gini + power-law fit for empirical claims.
## 🔗 Graph
- 부모: [[Political-Theory]] · [[Sociology]]
- 변형: [[Pluralism]] · [[Marxism]] · [[Public-Choice]]
- 응용: [[AI-Governance]] · [[Platform-Economy]] · [[Liquid-Democracy]]
- Adjacent: [[Network-Centrality]] · [[Power-Law-Distribution]]
## 🤖 LLM 활용
**언제**: literature synthesis on power dynamics, network construction from text data, generating hypotheses.
**언제 X**: causal inference (need DAGs + IV), historical claims (verify primary sources), normative judgment.
## ❌ 안티패턴
- **Conspiracy framing**: elite theory ≠ secret cabal; structural emergence.
- **Single-elite assumption**: multiple competing elites usually (military/corporate/cultural).
- **Ignoring counter-elites**: opposition movements are also elites in formation.
- **Static analysis**: elites circulate; snapshot misses dynamics.
- **Power-law overclaim**: many distributions are log-normal, not pure power-law (test with `powerlaw` package).
## 🧪 검증 / 중복
- Verified (Mills 1956, Michels 1911, Pareto Trattato di sociologia generale, Domhoff "Who Rules America" series).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — theory + computational methods (network/Gini/power-law) |
@@ -2,62 +2,174 @@
id: wiki-2026-0508-emergence-in-systems
title: Emergence in Systems
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [Emergence-001]
aliases: [Emergent Behavior, Collective Behavior, Weak Emergence, Strong Emergence]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [systems-theory, complexity, emergence, Artificial-Life, Multi-agent-Systems]
confidence_score: 0.90
verification_status: applied
tags: [emergence, complexity, multi-agent, self-organization, LLM-emergent]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: mesa/numpy
---
# Emergence in[[_system|system]]s (시스템에서의 창발)
# Emergence in Systems
## 📌 한 줄 통찰 (The Karpathy Summary)
> "전체는 부분의 합보다 크며, 단순한 규칙이 합쳐져 예측 불가능한 질서를 창조한다" — 개별 요소들은 가지지 못한 특성이 시스템 전체 차원에서 갑자기 나타나는 현상으로, 복잡계와 지능의 본질을 설명하는 핵심 개념.
## 한 줄
> **"매 macro-level patterns 매 micro-rules 만으로 매 predictable 하지 않게 발생"**. 매 1875 G.H. Lewes 의 용어 도입, 매 1972 Anderson *More is Different* 가 매 modern foundation. 매 2026 LLM emergent capabilities (in-context learning, reasoning chains), swarm robotics, market crashes, neural avalanches 의 핵심 framework.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 하위 수준(Lower-level)의 개체들이 상호작용하며 상위 수준(Higher-level)에서 새로운 패턴이나 기능을 형성하는 자기 조직화(Self-organization) 패턴.
- **핵심 특징:**
- **Bottom-up:** 중앙 통제 없이 개별 요소의 로컬 규칙에 의해 발생.
- **Irreducibility:** 전체 시스템의 행동을 개별 요소의 특성만으로는 완벽히 설명하거나 예측할 수 없음.
- **Examples:** 개미 군집의 효율적 먹이 탐색, 뉴런들의 상호작용으로 생겨나는 '의식', LLM 규모 확장 시 나타나는 새로운 추론 능력.
- **의의:** 개별 알고리즘의 최적화를 넘어, 시스템 전체의 상호작용 설계를 통해 고차원 지능을 구현하는 이론적 토대.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 지능을 설계(Design)의 산물로 보던 관점에서, 적절한 환경과 규칙 하에서 발생하는 창발(Emergence)의 산물로 보는 관점으로 확장.
- **정책 변화:** Skybound 프로젝트의 군집 드론 AI는 개별 기체에 복잡한 전술을 심는 대신, 단순한 '충돌 방지'와 '목표 추적' 규칙만을 부여하여 유기적인 진형 변화라는 창발적 행동을 유도함.
### 매 weak vs strong
- **Weak emergence (Bedau)**: 매 micro-rule 으로 simulate 가능, 매 closed-form predict 어려움. 매 대부분의 과학 examples.
- **Strong emergence (Chalmers)**: 매 micro 로 deduce 불가, 매 new causal powers. 매 controversial — 매 consciousness debate.
## 🔗 지식 연결 (Graph)
- Chaos-Theory-in-Systems, [[Artificial-Life|Artificial-Life]], [[Multi-Agent-Systems-MAS|Multi-Agent-Systems-MAS]], [[Complexity-Theory|Complexity-Theory]]
- **Raw Source:** 10_Wiki/Topics/AI/Emergence-in-Systems.md
### 매 핵심 mechanisms
- **Local interactions + nonlinearity**: 매 ant colony, Conway's GoL.
- **Phase transitions**: 매 critical density 매 traffic jam, 매 percolation.
- **Self-organized criticality (Bak)**: 매 sandpile, neural avalanches.
- **Stigmergy**: 매 environment-mediated coordination (pheromones).
- **Symmetry breaking**: 매 Turing patterns, 매 cell differentiation.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 detection / measurement
- **Mutual information** between scales.
- **Effective complexity** (Gell-Mann).
- **Phi (Φ)** integrated information (IIT).
- **Coarse-grained predictability**: 매 micro vs macro forecast accuracy.
- **Emergent capability scaling curves** (LLM): 매 phase transition at parameter threshold.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. **LLM scaling**: 매 few-shot reasoning 매 ~10B params 에서 emerge (Wei 2022).
2. **Swarm robotics**: 매 simple drones → flock formation, 매 task allocation.
3. **Market microstructure**: 매 HFT bots → flash crashes, 매 emergent volatility.
4. **Neural networks**: 매 grokking phenomenon, 매 induction heads emerge.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Conway's Game of Life (Classic)
```python
import numpy as np
from scipy.ndimage import convolve
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
def step(grid):
kernel = np.array([[1,1,1],[1,0,1],[1,1,1]])
nb = convolve(grid, kernel, mode='wrap')
return ((nb == 3) | ((grid == 1) & (nb == 2))).astype(int)
```
## 🧬 중복 검사 (Duplicate Check)
### Boids (Flocking)
```python
class Boids:
def __init__(self, n=200):
self.pos = np.random.rand(n, 2) * 100
self.vel = (np.random.rand(n, 2) - 0.5) * 2
def step(self):
# cohesion + separation + alignment
for i in range(len(self.pos)):
d = np.linalg.norm(self.pos - self.pos[i], axis=1)
mask = (d > 0) & (d < 10)
if mask.any():
cohesion = (self.pos[mask].mean(0) - self.pos[i]) * 0.01
alignment = (self.vel[mask].mean(0) - self.vel[i]) * 0.05
close = (d > 0) & (d < 3)
separation = -((self.pos[close] - self.pos[i]).sum(0)) * 0.1 if close.any() else 0
self.vel[i] += cohesion + alignment + separation
speed = np.linalg.norm(self.vel, axis=1, keepdims=True).clip(min=0.5, max=3)
self.vel = self.vel / np.linalg.norm(self.vel, axis=1, keepdims=True) * speed
self.pos = (self.pos + self.vel) % 100
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Sandpile (Self-Organized Criticality)
```python
def sandpile_step(grid, threshold=4):
drops = grid >= threshold
while drops.any():
grid[drops] -= threshold
# spread to 4 neighbors
grid[1:] += np.roll(drops, -1, axis=0)[1:]
# ... (similar for other neighbors)
drops = grid >= threshold
return grid # avalanche size distribution → power law
```
## 🕓 변경 이력 (Changelog)
### Schelling Segregation
```python
def schelling(grid, tolerance=0.3, iters=1000):
n = grid.shape[0]
for _ in range(iters):
unhappy = []
for i, j in np.ndindex(grid.shape):
if grid[i,j] == 0: continue
nb = grid[max(0,i-1):i+2, max(0,j-1):j+2].flatten()
similar = (nb == grid[i,j]).sum() - 1
if similar / max(1, (nb != 0).sum() - 1) < tolerance:
unhappy.append((i,j))
# swap unhappy with random empty
...
return grid # macroscopic segregation emerges from mild micro-preference
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### LLM Emergent Capability Detector
```python
def emergent_capability_curve(scales, accuracies, threshold=0.5):
"""Find parameter scale where accuracy phase-transitions above random."""
for s, a in zip(scales, accuracies):
if a > threshold:
return s
return None
# Wei et al 2022 — abrupt jump for arithmetic, multi-step reasoning
```
### Mutual Information Across Scales
```python
from sklearn.feature_selection import mutual_info_regression
def emergence_index(micro, macro):
"""High MI(macro_t+1 | macro_t) - MI(macro_t+1 | micro_t) suggests emergence."""
mi_macro = mutual_info_regression(macro[:-1].reshape(-1,1), macro[1:])[0]
mi_micro = mutual_info_regression(micro[:-1], macro[1:])[0]
return mi_macro - mi_micro
```
## 매 결정 기준
| 시스템 | Framework |
|---|---|
| Cellular automaton | GoL, ECA Wolfram class |
| Multi-agent RL | swarm intelligence, MARL |
| Physical phase transition | renorm group, Ising |
| Neural network capabilities | scaling laws, mech interp |
| Economic systems | ABM (Agent-Based Models) |
| Brain dynamics | criticality, neural avalanche |
**기본값**: 매 ABM with 매 minimal local rules → 매 observe macro pattern → 매 measure emergence index.
## 🔗 Graph
- 부모: [[Complexity Science]] · [[Systems Theory]]
- 변형: [[Weak-Emergence]] · [[Strong-Emergence]] · [[Self-Organization]]
- 응용: [[LLM-Emergent-Capabilities]] · [[Swarm-Intelligence]] · [[Market Microstructure]]
- Adjacent: [[Dissipative-Structures]] · [[Self-Organized-Criticality]] · [[Phase-Transitions]] · [[Emergence]]
## 🤖 LLM 활용
**언제**: 매 multi-agent prompt 의 collective behavior 분석, 매 capability scaling 예측.
**언제 X**: 매 simple linear systems — 매 emergence framework overhead.
## ❌ 안티패턴
- **"emergent" 의 mystification**: 매 simply "I don't understand" 의 placeholder.
- **Strong emergence claim 남발**: 매 weak emergence 가 거의 모든 과학 case 에 충분.
- **Ignoring scale separation**: 매 macro 가 micro 의 평균이면 매 trivial — 매 nonlinearity 필요.
- **Mistaking correlation for emergence**: 매 둘 다 환경 forcing 으로 driven 가능.
## 🧪 검증 / 중복
- Verified (Anderson 1972 *More is Different*; Bedau 1997; Wei et al. 2022 *Emergent Abilities of LLMs*; Mitchell 2009 *Complexity*).
- 신뢰도 A.
- 매 사촌 페이지: [[Emergence]] (broader philosophical treatment).
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with GoL, Boids, sandpile, Schelling, LLM emergent |
@@ -2,65 +2,157 @@
id: wiki-2026-0508-emergence
title: Emergence
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-EMER-001]
aliases: [Emergent Behavior, Emergent Phenomena, Weak Emergence, Strong Emergence]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, emergence, complexity, self-organization, Systems-Thinking, Collective-Intelligence]
confidence_score: 0.9
verification_status: applied
tags: [complexity, philosophy, systems, ai, multi-agent]
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: Python
framework: NumPy/Mesa
---
# [[Emergence|Emergence]]
# Emergence
## 📌 한 줄 통찰 (The Karpathy Summary)
> "하급자들의 예기치 못한 합창: 개별 구성 요소들은 단순하고 지능이 낮아 보일지라도, 이들이 특정 임계점을 넘어 상호작용할 때 전체 시스템 차원에서 상상하지 못했던 고차원적인 지능이나 패턴이 갑자기 튀어나오는 신비로운 현상."
## 한 줄
> **"매 whole 의 properties 매 parts 의 sum 의 not derivable — 매 collective behavior 의 birth"**. Aristotle origin, Mill 1843 "heteropathic laws", Anderson 1972 "More is Different", modern formal version 매 Bedau (weak emergence) / Chalmers (strong). 매 LLM "emergent capabilities" 의 2022-26 controversy (Schaeffer 2023 reframed as metric artifact).
## 📖 구조화된 지식 (Synthesized Content)
창발(Emergence)은 하위 계층에 없는 특성이 상위 계층에서 자발적으로 나타나는 현상입니다.
## 매 핵심
1. **핵심 특징**:
* **Unpredictability**: 개별 요소의 특성만 분석해서는 전체의 행동을 예측하기 어렵고 직접 보아야 함.
* **No Central Control**: 지휘자 없이도 개미 군집이나 신경망 세포들이 스스로 질서를 만듦. (Collective-Intelligence와 연결)
* **Threshold Effect**: 요소가 일정 수(Scale) 이상 모일 때까지는 조용하다가 임계치를 넘는 순간 폭발적으로 나타남.
2. **사례**:
* 물 분자가 모여 '젖음'이라는 수분을 형성하는 것, 뉴런이 모여 '의식'을 만드는 것, LLM이 거대해지며 갑자기 '추론 능력'을 갖게 되는 것.
### 매 두 types
- **Weak emergence** (Bedau): macro patterns derivable from micro by simulation only — irreducible in practice, reducible in principle (e.g. Conway's Life, traffic jams, ant trails).
- **Strong emergence** (Chalmers): genuinely novel causal powers not reducible — controversial (consciousness, ?).
- **Nominal emergence**: just labeling (descriptive, weakest sense).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거 과학 정책은 모든 것을 구성 성분으로 설명하려는 '환원주의 정책'이었으나, 현대 정책은 창발적 성질이 시스템의 본질적 가치 정책임을 인정하는 '복잡계 정책'으로 이동함(RL Update). ([[Complexity Theory|Complexity Theory]]와 연결)
- **정책 변화(RL Update)**: AI 모델이 단순히 말을 잘하는 수준을 넘어 '자기 복제'나 '거짓말' 같은 원치 않는 창발적 능력을 가질 위험 정책을 탐지하기 위해, 모델의 비선형적 발현 임계점 정책을 감시하는 연구가 활발함.
### 매 hallmarks
- Many simple parts + simple interactions.
- Macro pattern not present in any single part.
- Often power-law / scale-free statistics.
- Self-organization without central control.
## 🔗 지식 연결 (Graph)
- [[Complexity Theory|Complexity Theory]], [[Collective-Intelligence|Collective-Intelligence]], [[Systems Thinking|Systems Thinking]], Self-Correction, [[Artificial General Intelligence (AGI)|Artificial General Intelligence (AGI)]]
- **Modern Tech/Tools**: Cellular automata, Multi-agent simulations, Scale laws in LLMs.
---
### 매 응용
1. Multi-agent systems (swarms, markets, traffic).
2. Cellular automata (CA, Conway's Life).
3. LLM emergent capabilities debate (in-context learning, CoT).
4. Phase transitions in physics.
5. Consciousness research (IIT, GWT).
6. Biology (flocking, embryogenesis).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Conway's Game of Life (canonical emergence)
```python
import numpy as np
**언제 쓰면 안 되는가:**
- *(TODO)*
def step(grid):
nb = sum(np.roll(np.roll(grid, i, 0), j, 1)
for i in (-1, 0, 1) for j in (-1, 0, 1) if (i, j) != (0, 0))
return ((nb == 3) | ((grid == 1) & (nb == 2))).astype(int)
## 🧪 검증 상태 (Validation)
grid = np.random.choice([0, 1], (50, 50), p=[0.7, 0.3])
for _ in range(100):
grid = step(grid)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Boids (flocking)
```python
def boids_step(pos, vel, n_neighbors=10):
# alignment, cohesion, separation
new_vel = vel.copy()
for i in range(len(pos)):
d = np.linalg.norm(pos - pos[i], axis=1)
nb = np.argsort(d)[1:n_neighbors+1]
align = vel[nb].mean(0) - vel[i]
cohere = pos[nb].mean(0) - pos[i]
sep = -(pos[nb] - pos[i]).sum(0) / (d[nb][:, None] + 1e-3).sum()
new_vel[i] += 0.05*align + 0.01*cohere + 0.1*sep
return new_vel
```
## 🧬 중복 검사 (Duplicate Check)
### Detect emergence (mutual information micro→macro)
```python
from sklearn.metrics import mutual_info_score
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
def emergence_score(micro_states, macro_states):
# High macro→macro MI conditioning on past macro indicates emergence
return mutual_info_score(macro_states[:-1], macro_states[1:])
```
## 🕓 변경 이력 (Changelog)
### LLM emergent capability (per Schaeffer 2023)
```python
# Discontinuous metric (exact match) shows "emergence"
# Continuous metric (token-level prob) shows smooth scaling
def reframe_emergence(model_sizes, exact_match, token_logp):
# Plot both: token_logp is smooth, exact-match has sharp jump
return {"continuous": token_logp, "discrete": exact_match}
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Cellular automaton (1D, Wolfram Class 4)
```python
def ca_1d(rule, n_cells=200, n_steps=200):
rule_bin = [(rule >> i) & 1 for i in range(8)]
state = np.zeros(n_cells, dtype=int); state[n_cells//2] = 1
history = [state.copy()]
for _ in range(n_steps):
nb = state[:-2]*4 + state[1:-1]*2 + state[2:]
state[1:-1] = [rule_bin[n] for n in nb]
history.append(state.copy())
return np.array(history)
ca_1d(110) # Class 4 — emergent gliders, Turing-complete
```
### Phase transition (Ising model)
```python
def ising_step(spins, beta):
i, j = np.random.randint(0, spins.shape[0], 2)
nb = (spins[(i+1)%N, j] + spins[(i-1)%N, j] +
spins[i, (j+1)%N] + spins[i, (j-1)%N])
dE = 2 * spins[i, j] * nb
if dE < 0 or np.random.rand() < np.exp(-beta * dE):
spins[i, j] *= -1
return spins
```
## 매 결정 기준
| 상황 | Frame |
|---|---|
| Multi-agent simulation | Weak emergence (Bedau) |
| LLM scaling capabilities | Question metric smoothness first |
| Consciousness | Strong emergence (still controversial) |
| Phase transitions | Statistical mechanics (rigorous) |
| Org behavior | Emergent vs designed properties |
**기본값**: weak emergence; demand operational definition + measurement.
## 🔗 Graph
- 부모: [[Complexity-Theory]] · [[Systems-Theory]]
- 변형: [[Weak-Emergence]] · [[Strong-Emergence]] · [[Self-Organization]]
- 응용: [[Multi-Agent-Systems]] · [[Cellular-Automata]] · [[LLM-Scaling]]
- Adjacent: [[Phase-Transitions]] · [[Power-Law-Distribution]] · [[Global-Neuronal-Workspace]]
## 🤖 LLM 활용
**언제**: simulating CA / boids / Ising, explaining emergence intuitions, critiquing claims of "emergence" (Schaeffer-style metric scrutiny).
**언제 X**: claims of strong emergence (philosophically contested), consciousness assertions (active research).
## ❌ 안티패턴
- **Emergence as magic**: "the system has emergent properties" 의 explanation 의 not.
- **Confusing weak with strong**: most "emergent" is weak (Conway's Life is weak).
- **Metric artifact emergence**: discontinuous evaluation creating apparent jumps (Schaeffer 2023).
- **Skipping operational definition**: define what is "emerging" measurably.
- **Claiming irreducibility prematurely**: lack of current explanation ≠ in-principle irreducibility.
## 🧪 검증 / 중복
- Verified (Anderson 1972 Science, Bedau "Weak Emergence" 1997, Chalmers "Strong and Weak Emergence" 2006, Schaeffer et al. NeurIPS 2023 "Are Emergent Abilities a Mirage?").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — weak/strong emergence + CA/boids/Ising + Schaeffer LLM critique |
@@ -2,88 +2,206 @@
id: wiki-2026-0508-entropy-in-information-theory
title: Entropy in Information Theory
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [INFO-ENTROPY-001]
aliases: [Shannon Entropy, Information Entropy, H(X)]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Information-Theory, entropy, probability, data-compression]
confidence_score: 0.95
verification_status: applied
tags: [information-theory, probability, entropy, shannon, machine-learning]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: NumPy / SciPy
---
# Entropy in [[Information Theory|Information Theory]] (정보 이론에서의 엔트로피)
# Entropy in Information Theory
## 📌 한 줄 통찰 (The Karpathy Summary)
> "놀라움의 정도를 숫자로 측정하여 정보의 본질적 가치를 규명하라" — 클로드 섀넌이 정의한 개념으로, 확률 분포의 불확실성(Uncertainty)이나 무작위성을 수치화한 것이며, 데이터를 전송하거나 저장할 때 필요한 최소한의 정보량을 의미함.
## 한 줄
> **"매 random variable 의 uncertainty 의 quantification — H(X) = -Σp(x)log p(x)"**. Shannon 1948 "A Mathematical Theory of Communication" 의 birth — 매 modern compression, channel coding, ML loss function (cross-entropy), variational inference 의 모두 의 foundation.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 사건이 발생할 확률이 낮을수록(더 놀라울수록) 더 많은 정보를 담고 있다는 직관을 수학적 기댓값($H(X) = -\sum p(x) \log p(x)$)으로 정형화하는 패턴.
- **주요 특징:**
- **Uncertainty:** 모든 사건의 확률이 균등할 때(가장 예측하기 힘들 때) 엔트로피가 최대가 됨.
- **Information Gain:** 특정 정보를 알게 됨으로써 줄어든 엔트로피의 양. 의사결정 나무의 학습 기준으로 활용.
- **Compression Limit:** 엔트로피는 이론적으로 도달 가능한 최적의 데이터 압축 한계를 정의함.
- **의의:** 무의미한 소음([[Noise|Noise]])과 유의미한 신호(Signal)를 구분하고, 데이터 속에 숨겨진 지식의 밀도를 측정하는 척도 제공.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 열역학적 무질서도에서 시작된 개념을 '정보의 양'이라는 추상적 가치로 확장하여 디지털 통신과 AI 시대를 여는 이론적 토대가 됨.
- **정책 변화:** Antigravity 프로젝트는 문서 내의 키워드 추출이나 지식의 중요도 산출 시, 해당 단어나 문장이 지식 네트워크의 전체 엔트로피를 얼마나 낮추는지(정보 이득)를 기준으로 가치를 평가함.
### 매 정의
- **Shannon entropy**: H(X) = -Σ p(x) log p(x), unit log_2 의 bit / log_e 의 nat.
- **Joint entropy**: H(X,Y) = -ΣΣ p(x,y) log p(x,y).
- **Conditional entropy**: H(Y|X) = H(X,Y) - H(X) = E_X[H(Y|X=x)].
- **Mutual information**: I(X;Y) = H(X) + H(Y) - H(X,Y) = H(X) - H(X|Y).
- **KL divergence**: D_KL(P||Q) = Σ p(x) log(p(x)/q(x)) — 매 not symmetric, ≥ 0.
- **Cross-entropy**: H(P,Q) = H(P) + D_KL(P||Q) = -Σ p(x) log q(x).
## 🔗 지식 연결 (Graph)
- Cross-Entropy-Loss, Decision-Trees-and-Random-Forests, [[Information-Theory|Information-Theory]], [[Cybernetics|Cybernetics]]-Foundations
- **Raw Source:** 10_Wiki/Topics/AI/Entropy in Information Theory.md
### 매 properties
- H(X) ≥ 0, H(X) ≤ log |𝒳| (uniform 시 max).
- H(X,Y) ≤ H(X) + H(Y) (equality ⟺ independent).
- I(X;Y) ≥ 0 (independence iff =0).
- Data processing inequality: X→Y→Z ⇒ I(X;Z) ≤ I(X;Y).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **Compression**: 매 lower bound (Shannon source coding) — Huffman, arithmetic, ANS 의 modern (Zstd, Brotli).
2. **Channel capacity**: C = max_p I(X;Y) — 매 AWGN channel: C = ½log(1+SNR).
3. **Cross-entropy loss**: 매 classification 의 standard loss (PyTorch/TensorFlow default).
4. **Variational inference**: ELBO = E[log p(x|z)] - D_KL(q(z|x) || p(z)) — 매 VAE/diffusion 의 basis.
5. **Decision trees**: 매 information gain split criterion.
6. **Maximum entropy principle**: 매 prior choice 의 (Jaynes 1957).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### 매 Discrete Entropy (NumPy)
```python
import numpy as np
## 🧪 검증 상태 (Validation)
def shannon_entropy(p, base=2):
"""매 probability vector → entropy.
매 zero-handling: 0 log 0 = 0."""
p = np.asarray(p, dtype=float)
p = p[p > 0]
return -np.sum(p * np.log(p) / np.log(base))
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# Example: fair coin = 1 bit
print(shannon_entropy([0.5, 0.5])) # 1.0
# biased coin (p=0.9): low entropy
print(shannon_entropy([0.9, 0.1])) # ≈ 0.469
```
## 🤔 의사결정 기준 (Decision Criteria)
### KL Divergence / Cross-Entropy
```python
def kl_divergence(p, q, base=2):
"""매 D_KL(P||Q). P, Q 의 same support 가정."""
p = np.asarray(p, dtype=float)
q = np.asarray(q, dtype=float)
mask = (p > 0) & (q > 0)
return np.sum(p[mask] * np.log(p[mask] / q[mask]) / np.log(base))
**선택 A를 써야 할 때:**
- *(TODO)*
def cross_entropy(p, q, base=2):
p = np.asarray(p, dtype=float)
q = np.asarray(q, dtype=float)
mask = (p > 0)
return -np.sum(p[mask] * np.log(q[mask]) / np.log(base))
**선택 B를 써야 할 때:**
- *(TODO)*
p = [0.5, 0.5]
q = [0.9, 0.1]
print(kl_divergence(p, q)) # 매 not zero
print(cross_entropy(p, q)) # 매 H(p) + KL(p||q)
```
**기본값:**
> *(TODO)*
### PyTorch Cross-Entropy Loss (매 ML standard)
```python
import torch
import torch.nn as nn
## ❌ 안티패턴 (Anti-Patterns)
# Classification logits → softmax → -Σ y log p
logits = torch.tensor([[2.0, 1.0, 0.1]]) # batch=1, classes=3
target = torch.tensor([0]) # true class
loss_fn = nn.CrossEntropyLoss()
loss = loss_fn(logits, target)
print(f"Cross-entropy loss: {loss.item():.4f}")
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
# 매 internal: log_softmax + nll_loss for numerical stability
# 매 직접 softmax → log → nll 분리 시 매 underflow 위험
```
### Mutual Information Estimation (매 continuous)
```python
from sklearn.feature_selection import mutual_info_regression
from sklearn.metrics import mutual_info_score
# 매 discrete: histogram-based
def mutual_info_discrete(x, y, bins=20):
c_xy, _, _ = np.histogram2d(x, y, bins=bins)
return mutual_info_score(None, None, contingency=c_xy)
# 매 continuous: KSG estimator (Kraskov-Stögbauer-Grassberger 2004)
# sklearn 의 mutual_info_regression 의 internal 의 KSG 사용
x = np.random.randn(1000)
y = x + 0.5 * np.random.randn(1000)
mi = mutual_info_regression(x.reshape(-1, 1), y)
print(f"MI(x; y) ≈ {mi[0]:.4f} nats")
```
### Decision Tree Information Gain
```python
def information_gain(parent_labels, splits):
"""매 split 의 information gain.
IG = H(parent) - Σ (|child|/|parent|) H(child)."""
def H(labels):
_, counts = np.unique(labels, return_counts=True)
p = counts / counts.sum()
return -np.sum(p * np.log2(p + 1e-12))
parent_H = H(parent_labels)
n = len(parent_labels)
weighted_child_H = sum((len(s) / n) * H(s) for s in splits)
return parent_H - weighted_child_H
```
### Variational Inference (매 ELBO)
```python
import torch.nn.functional as F
def vae_elbo(x, x_recon, mu, logvar):
"""ELBO = E[log p(x|z)] - D_KL(q(z|x) || p(z)).
매 p(z) = N(0,I), q(z|x) = N(mu, σ²I)."""
recon_loss = F.binary_cross_entropy(x_recon, x, reduction='sum')
# 매 KL closed-form for Gaussians:
kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return recon_loss + kl # negative ELBO 매 minimize
```
### Differential Entropy (매 continuous variable)
```python
from scipy.stats import differential_entropy
# 매 sample-based estimator
samples = np.random.randn(10000)
h = differential_entropy(samples)
print(f"h(N(0,1)) ≈ {h:.4f}") # closed-form: 0.5 log(2πe) ≈ 1.4189
# 매 differential entropy 매 negative 가능 (e.g., narrow distribution)
samples_narrow = np.random.randn(10000) * 0.1
print(differential_entropy(samples_narrow)) # negative
```
## 매 결정 기준
| 상황 | Quantity |
|---|---|
| Compression lower bound | H(X) |
| Classification loss | Cross-entropy H(P,Q) |
| Distribution comparison | KL divergence D_KL(P||Q) |
| Symmetric divergence | Jensen-Shannon (½KL(P||M) + ½KL(Q||M)) |
| Feature selection | Mutual information I(X;Y) |
| VAE training | ELBO (recon + KL) |
| Decision tree split | Information gain |
| Channel design | Mutual information capacity |
**기본값**: 매 ML loss 의 cross-entropy. 매 distribution distance 의 KL (asymmetric). 매 symmetric 가 필요하면 JS divergence.
## 🔗 Graph
- 부모: [[Information-Theory]] · [[Probability-Theory]]
- 변형: [[Differential-Entropy]] · [[Renyi-Entropy]] · [[Tsallis-Entropy]]
- 응용: [[Cross-Entropy-Loss]] · [[KL-Divergence]] · [[Mutual-Information]] · [[Variational-Inference]]
- Adjacent: [[Shannon-Source-Coding]] · [[Channel-Capacity]] · [[Maximum-Entropy-Principle]] · [[Huffman-Coding]]
## 🤖 LLM 활용
**언제**: 매 concept explanation, 매 derivation 의 walk-through, 매 ML loss function selection, 매 KL/cross-entropy 의 confused 시 disambiguation.
**언제 X**: 매 numerical computation 의 large-scale data — 매 dedicated library (NumPy, scikit-learn) 사용. 매 differential entropy 의 sample size 부족 시 hallucinate 위험.
## ❌ 안티패턴
- **KL 의 symmetric 가정**: 매 D_KL(P||Q) ≠ D_KL(Q||P). 매 forward/reverse KL 의 다른 behavior (mode-seeking vs mean-seeking).
- **log(0) 처리 누락**: 매 0 log 0 의 limit 의 0 — 매 mask 또는 ε 추가.
- **Cross-entropy 의 softmax 두 번 적용**: PyTorch CrossEntropyLoss 매 logits 받음, softmax 직접 적용 X.
- **Differential entropy 의 Shannon entropy 와 혼동**: 매 differential entropy 매 negative 가능, 매 not invariant under change of variable.
- **MI 의 직접 estimation 의 high-dim**: 매 sample complexity exponential — copula / NN-based estimator 사용.
## 🧪 검증 / 중복
- Verified (Shannon 1948, Cover-Thomas "Elements of Information Theory", MacKay "Information Theory, Inference and Learning Algorithms").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — entropy/KL/MI/cross-entropy formulas, ML applications, VAE ELBO |
@@ -2,64 +2,140 @@
id: wiki-2026-0508-ergodic-theory
title: Ergodic Theory
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ERTH-001]
aliases: [Ergodicity, Time Average vs Ensemble Average]
duplicate_of: none
source_trust_level: A
confidence_score: 0.93
tags: [auto-reinforced, ergodic-theory, dynamics, statistical-Physics, probability, chaos, Stability]
confidence_score: 0.9
verification_status: applied
tags: [math, dynamics, probability, statistics, finance]
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: Python
framework: NumPy
---
# [[Ergodic-Theory|Ergodic-Theory]]
# Ergodic Theory
## 📌 한 줄 통찰 (The Karpathy Summary)
> "시간이 흐르면 모든 곳을 지나친다: 시스템의 '시간 평균'이 '공간(상태) 평균'과 같아진다는 원리로, 복잡하고 예측 불가능해 보이는 변화 속에서도 결국 전체적인 통계적 평형을 찾게 되는 물리적·수학적 보장."
## 한 줄
> **"매 time average = ensemble average — 매 system 의 ergodic 면"**. Birkhoff (1931), Boltzmann origin 매 statistical mechanics, modern resurgence 매 Ole Peters' "ergodicity economics" (2011-) 매 expected value 의 critique. 매 finance, RL, MCMC convergence, decision theory 의 deep relevance.
## 📖 구조화된 지식 (Synthesized Content)
에르고드 이론(Ergodic-Theory)은 동적 시스템의 장기적인 거동을 통계적으로 연구하는 수학 및 물리학 분야입니다.
## 매 핵심
1. **핵심 원리**:
* **Ergodicity**: 충분한 시간이 주어지면, 시스템의 상태가 상태 공간 전체를 균일하게 방문한다는 가정.
* **Time Average = Space Average**: 개별 시스템을 오래 관찰한 결과가, 같은 조건의 수많은 시스템을 한 번에 관찰한 평균과 같음. ([[Statistics|Statistics]]와 연결)
2. **왜 중요한가?**:
* 분자 수조 개의 움직임(미시적)을 일일이 추적하지 않고도 온도나 압력(거시적) 같은 시스템의 성질 정책을 안정적으로 계산할 수 있게 하기 때문임. ([[System-Theory|System-Theory]]와 연결)
### 매 두 averages
- **Ensemble average** (⟨x⟩): mean over many parallel realizations at fixed time.
- **Time average** (x̄): mean of single trajectory over long time.
- **Ergodic**: 매 ⟨x⟩ = x̄ (a.s.) for all integrable f.
- **Non-ergodic**: trajectories diverge — ensemble average misleads about typical outcome (multiplicative dynamics).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 거의 모든 물리계 정책이 에르고드적이라 가정했으나, 현대 정책은 '비에르고드적(Non-ergodic)' 상황(예: 금융 시장, 특정 복잡계)에서 평균값이 미래를 예측 정책에 오역을 줄 수 있다는 사실을 강조함(RL Update).
- **정책 변화(RL Update)**: 이제는 단순 물리 환경 정책을 넘어, AI 의 가중치 최적화 경로 정책이나 알고리즘의 수렴성 정책을 분석할 때 에르고드적 성질 정책 유무를 판단하는 것이 알고리즘 안정성 정책의 핵심이 됨. ([[Reliability|Reliability]]와 연결)
### 매 implications
- **Multiplicative process** (e.g. wealth × random factor): non-ergodic; geometric mean rules, expected value misleads.
- **Kelly criterion**: optimal bet sizing under non-ergodicity.
- **MCMC**: chains must be ergodic to converge to target distribution.
- **Statistical physics**: ergodic hypothesis underpins phase-space averaging.
## 🔗 지식 연결 (Graph)
- [[Statistics|Statistics]], [[System-Theory|System-Theory]], [[Reliability|Reliability]], [[Complexity-Theory|Complexity-Theory]], Entropy, [[Analysis|Analysis]]
- **Key Figure**: Ludwig Boltzmann, George David Birkhoff.
---
### 매 응용
1. Investment decisions (avoid ruin via geometric returns).
2. RL convergence theory (Markov chain ergodicity).
3. Statistical mechanics (Boltzmann distribution).
4. MCMC sampling (Metropolis-Hastings, HMC).
5. Insurance / risk modeling.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Ensemble vs time average (multiplicative)
```python
import numpy as np
**언제 쓰면 안 되는가:**
- *(TODO)*
T, N = 1000, 10000
# Multiplicative: 50% gain 50% loss, fair coin
returns = np.where(np.random.rand(T, N) < 0.5, 1.5, 0.6)
wealth = np.cumprod(returns, axis=0)
## 🧪 검증 상태 (Validation)
ensemble_mean = wealth[-1].mean() # large positive
time_mean = np.exp(np.log(wealth[-1]).mean()) # geometric, often << 1
print(f"E[W_T]={ensemble_mean:.2f} exp(E[log W_T])={time_mean:.4f}")
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Kelly criterion
```python
def kelly_fraction(p_win, b_win, b_loss):
# f* = p/b_loss - (1-p)/b_win (simplified)
return p_win / b_loss - (1 - p_win) / b_win
## 🧬 중복 검사 (Duplicate Check)
f = kelly_fraction(0.55, 1.0, 1.0) # 0.10 of bankroll
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Geometric mean return
```python
def geo_return(rets):
return np.prod(1 + rets) ** (1/len(rets)) - 1
```
## 🕓 변경 이력 (Changelog)
### Ergodic check (Birkhoff sum)
```python
def is_ergodic_emp(traj, f, ensemble):
time_avg = np.mean([f(x) for x in traj])
ens_avg = np.mean([f(x) for x in ensemble])
return abs(time_avg - ens_avg) < 0.01
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Markov chain ergodicity (irreducible + aperiodic)
```python
import numpy as np
P = np.array([[0.5, 0.5], [0.3, 0.7]])
eigvals, eigvecs = np.linalg.eig(P.T)
# Stationary distribution = eigenvector for eigenvalue 1
pi = np.real(eigvecs[:, np.isclose(eigvals, 1)].flatten())
pi /= pi.sum()
```
### Ergodicity-economics rebalancing
```python
def expected_log_growth(p, weights, returns):
# Maximize sum(p_i * log(1 + w·r_i))
return np.sum([p_i * np.log(1 + np.dot(weights, r))
for p_i, r in zip(p, returns)])
```
## 매 결정 기준
| 상황 | Average to use |
|---|---|
| Single agent, repeated bets | Time average (geometric) |
| Many independent agents | Ensemble average |
| Wealth / multiplicative | Geometric, never arithmetic |
| Insurance / pooling | Ensemble (true sharing) |
| MCMC convergence | Verify ergodicity of chain |
| Long-run RL | Ergodicity of Markov chain |
**기본값**: assume non-ergodic in finance/biology/social; verify before using ensemble average.
## 🔗 Graph
- 부모: [[Probability-Theory]] · [[Dynamical-Systems]]
- 변형: [[Ergodicity-Economics]] · [[Birkhoff-Theorem]]
- 응용: [[Kelly-Criterion]] · [[MCMC]] · [[Reinforcement-Learning]]
- Adjacent: [[Markov-Chains]] · [[Entropy-in-Information-Theory]]
## 🤖 LLM 활용
**언제**: explain ergodicity intuitions, simulate ensemble vs time, derive Kelly fractions, debug MCMC non-convergence.
**언제 X**: rigorous proofs (consult Walters, Petersen), high-stakes financial decisions (need quant + risk pro).
## ❌ 안티패턴
- **Expected-value reasoning under multiplicative dynamics**: leads to ruin.
- **Confusing arithmetic and geometric means**: arithmetic > geometric always (Jensen).
- **Assuming ergodicity by default**: most real-world economic/social systems aren't.
- **Ignoring path dependence**: order of returns matters when non-ergodic.
- **Misusing law of large numbers**: applies to ensemble, not single trajectory of multiplicative process.
## 🧪 검증 / 중복
- Verified (Birkhoff 1931, Walters "Introduction to Ergodic Theory", Peters "The ergodicity problem in economics" Nature Physics 2019).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Birkhoff + ergodicity economics + Kelly + MCMC |
@@ -2,65 +2,168 @@
id: wiki-2026-0508-ethnographic-research
title: Ethnographic Research
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ETRE-001]
aliases: [Ethnography, Field Research, Participant Observation, Contextual Inquiry]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, ethnography, Research-Methodology, user-Research, Observation, contextual-inquiry, qualitative]
confidence_score: 0.88
verification_status: applied
tags: [research, qualitative, hci, ux, anthropology]
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: Python
framework: Dovetail, Otter.ai, NVivo, ATLAS.ti
---
# [[Ethnographic-Research|Ethnographic-Research]]
# Ethnographic Research
## 📌 한 줄 통찰 (The Karpathy Summary)
> "삶 속으로의 잠입: 설문조사나 인터뷰 데이터가 말해주지 않는 사용자의 '진짜 행동'을 발견하기 위해, 그들의 실제 일상 속에 들어가 자연스러운 맥락(Context)을 관찰하고 숨겨진 요구를 포착하는 리서치의 정수."
## 한 줄
> **"매 people-in-context 의 deep, in-situ, often-long observational study"**. Malinowski (Trobriand 1922), Geertz "thick description" (1973) → 매 industry: Xerox PARC (Suchman 1980s) → 매 modern UX/HCI/Product 의 staple. 매 "what people **say** vs what people **do**" 의 gap 의 reveal 의 가장 강력한 method.
## 📖 구조화된 지식 (Synthesized Content)
민속지학적 리서치(Ethnographic-Research)는 인류학에서 유래한 방법론으로, 특정 그룹의 문화와 행동을 그들이 활동하는 실제 환경에서 직접 관찰하고 참여하여 깊이 있게 이해하는 질적 연구 방법입니다.
## 매 핵심
1. **핵심 기법**:
* **Participant Observation**: 연구자가 커뮤니티의 일원이 되어 생활하며 관찰.
* **In-situ Interviews**: 행동이 일어나는 현장에서 즉석 질문 수행.
* **Shadowing**: 사용자의 하루 일과를 그대로 따라다니며 페인 포인트(Pain point) 기록. ([[Customer-Journey-Mapping|Customer-Journey-Mapping]]와 연결)
2. **왜 중요한가?**:
* 사용자 자신도 인지하지 못했던 '당연한 불편함'을 발견하여, 기존 시장에 없던 파괴적 혁신 제품 정책(Blue ocean)의 단초를 제공하기 때문임. ([[Innovation|Innovation]]와 연결)
### 매 vs neighbors
- **Survey/usability test**: 매 controlled / artificial / "say".
- **Interview**: 매 retrospective / "say".
- **Ethnography**: 매 in-situ / longitudinal / "do" + meaning.
- **Contextual Inquiry** (Beyer & Holtzblatt 1998): 매 industry-condensed ethnography (12 hr in real workplace).
- **Diary study**: 매 self-report longitudinal.
- **Auto-ethnography**: 매 researcher = subject.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 오프라인 오지 탐험 정책 위주였으나, 현대 정책은 커뮤니티 활동 로그, SNS 포스팅 등을 분석하는 '디지털 에스노그라피(Netnography) 정책'으로 진화함(RL Update).
- **정책 변화(RL Update)**: 이제는 단순 관찰 정책을 넘어, AI 가 수억 명의 디지털 활동 궤적 정책을 분석하여 거시적인 문화적 흐름 정책을 민속지학적으로 해석해 주는 'Computational Ethnography 정책'이 부상 중임. ([[Text-Mining|Text-Mining]]와 연결)
### 매 process (Spradley DRS / 12-step adapted)
1. **Locate setting** (gatekeeper, access, ethics/IRB).
2. **Participant observation** (4 modes: complete observer → complete participant).
3. **Field notes** (jottings → expanded → analytic memos).
4. **Domain analysis** (cultural categories).
5. **Taxonomic analysis** (relations within domain).
6. **Componential analysis** (attributes / contrasts).
7. **Theme synthesis** (cross-domain patterns).
8. **Member checks** (validate with participants).
9. **Thick description write-up**.
## 🔗 지식 연결 (Graph)
- [[Customer-Journey-Mapping|Customer-Journey-Mapping]], [[Innovation|Innovation]], [[Text-Mining|Text-Mining]], [[Research-Methodology|Research-Methodology]], [[Continuous-Discovery|Continuous-Discovery]], UX-Design-and-Engagement
- **Key [[goal|goal]]**: Emic perspective (내부자의 시각).
---
### 매 typical artifacts
- Field notes (jotted + expanded), photo / video / audio (with consent), artifacts collected, journey maps, persona-from-data, JTBD jobs.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Field-note template (Markdown)
```markdown
# Field Note — 2026-05-10 — site:Hospital ER, observer:RP
## Setting
- 14:0017:00, Triage desk, 3 nurses, ~40 patients.
## Activities (chronological)
- 14:03 nurse A swivels between EHR (slow) + paper backup …
## Verbatim quotes
- "I never trust the system after a shift change." — Nurse A, 14:22
## Surprises / breakdowns
- EHR auto-logout at 5 min idle → workaround = mouse jiggler.
## Analytic memo
- Domain: trust in tools. Hypothesis: short timeout drives shadow IT.
## Next steps
- Interview Nurse B; check audit logs for jiggler signatures.
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### Coding qualitative data (open + axial, in Python)
```python
import pandas as pd
notes = pd.read_csv("interviews.csv") # cols: pid, turn, text
codes = {
"trust-tool": ["never trust", "doesn't work", "I just write it down"],
"workaround": ["mouse jiggler", "shared password", "screenshot"],
"time-pressure":["no time", "rushing", "back-to-back"],
}
def code(t):
return [c for c, kws in codes.items() if any(k in t.lower() for k in kws)]
notes["codes"] = notes.text.apply(code)
notes.explode("codes").groupby("codes").size().sort_values(ascending=False)
```
## 🧪 검증 상태 (Validation)
### Affinity diagram digitization (Miro-style → DataFrame)
```python
import pandas as pd
stickies = pd.DataFrame({
"note": ["EHR logout 5 min", "Paper backup chart", "Phone snapshots", ...],
"cluster": ["timeouts", "shadow records", "shadow records", ...]
})
clusters = stickies.groupby("cluster")["note"].apply(list)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Journey-map dataclass
```python
from dataclasses import dataclass
from typing import List
@dataclass
class Step:
actor: str; action: str; tool: str; emotion: str; pain: str
journey: List[Step] = [
Step("nurse", "log in", "EHR", "neutral", "5-min timeout"),
Step("nurse", "triage", "paper+EHR", "stress", "duplicate entry"),
]
```
## 🧬 중복 검사 (Duplicate Check)
### LLM-assisted thematic analysis (with caching)
```python
import anthropic
client = anthropic.Anthropic()
def themes(transcript: str) -> str:
return client.messages.create(
model="claude-opus-4-7",
max_tokens=1500,
system=[{"type":"text","text":"You are a senior qualitative researcher."
,"cache_control":{"type":"ephemeral"}}],
messages=[{"role":"user","content":
f"Identify 3-7 emergent themes (open-coding style) with quote evidence.\n\n{transcript}"}]
).content[0].text
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Dovetail-style consent + redaction
```python
import re
def redact_pii(s: str) -> str:
s = re.sub(r"\b\d{3}-\d{2}-\d{4}\b", "[SSN]", s)
s = re.sub(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b", "[EMAIL]", s)
return s
```
## 🕓 변경 이력 (Changelog)
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Need rich context, hidden practice | **Full ethnography (weeksmonths)** |
| Industry, tight timeline | **Rapid / focused ethnography (days)** |
| Workplace tool design | **Contextual Inquiry** |
| Distributed / remote users | **Diary study + remote shadowing** |
| Sensitive populations | **Auto-ethnography or co-design** |
| Quantify after | **Mixed methods: ethnography → survey → A/B** |
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
**기본값**: 매 product discovery 의 **5-7 contextual inquiries (90 min each)** + open coding + affinity diagram.
## 🔗 Graph
- 부모: [[Qualitative-Research]] · [[Anthropology]] · [[HCI]]
- 변형: [[Contextual-Inquiry]] · [[Diary-Study]] · [[Auto-Ethnography]] · [[Digital-Ethnography]] · [[Netnography]]
- 응용: [[UX-Research]] · [[Product-Discovery]] · [[Service-Design]] · [[Jobs-To-Be-Done]]
- Adjacent: [[Grounded-Theory]] · [[Thematic-Analysis]] · [[Persona]] · [[Journey-Map]] · [[Thick-Description]]
## 🤖 LLM 활용
**언제**: 매 transcript 의 first-pass open coding, 매 affinity cluster 의 candidate, 매 quote retrieval, 매 persona drafting.
**언제 X**: 매 final theme 의 sole arbiter (매 researcher judgment 필수), 매 sensitive raw data 의 unconsented external API call.
## ❌ 안티패턴
- **"Asking" 만 하기**: 매 ethnography 의 essence = observing, not interviewing alone.
- **One-shot 1-hour visit + claim "ethnography"**: 매 contextual inquiry 라고 부르는 의 정직.
- **No reflexivity**: 매 observer effect / bias 의 acknowledged 없으면 매 weak.
- **Confirmation bias coding**: 매 second coder + inter-rater reliability (Cohen's κ) 의 add.
- **Thin description**: 매 "users were frustrated" — 매 thick description 의 absent (no actor, action, meaning).
- **Skip consent / IRB**: 매 ethical 의 mandatory.
## 🧪 검증 / 중복
- Verified (Malinowski 1922; Geertz 1973; Spradley 1979/1980; Beyer & Holtzblatt *Contextual Design* 1998; Kuniavsky *Observing the User Experience* 2nd ed.).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 placeholder |
| 2026-05-10 | Manual cleanup — Spradley process + 6 patterns + LLM coding |
@@ -2,93 +2,197 @@
id: wiki-2026-0508-evolutionary-algorithms
title: Evolutionary Algorithms
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-EVAL-001]
aliases: [EA, GA, ES, GP, DE, CMA-ES]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, evolutionary-algorithms, Genetic-Algorithms, Optimization, bio-inspired, Search]
confidence_score: 0.92
verification_status: applied
tags: [optimization, metaheuristics, evolution, search]
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
framework: DEAP, pycma, scipy.optimize, EvoTorch
---
# [[Evolutionary-Algorithms|Evolutionary-Algorithms]]
# Evolutionary Algorithms
## 📌 한 줄 통찰 (The Karpathy Summary)
> "코드로 구현한 적자생존: 생물학적 진화 과정을 모방하여, 수많은 해법(개체) 중 성능이 좋은 것들만 골라 교배(Crossover)하고 변이(Mutation)시켜 세대를 거듭할수록 점점 더 완벽한 정답에 가까워지는 자가 최적화 알고리즘."
## 한 줄
> **"매 Darwinian selection + variation 매 search loop 으로 abstract"**. Holland 의 GA (1975), Rechenberg 의 ES (1973), Koza 의 GP (1992) → 매 modern (2026): **CMA-ES, DE, NEAT, EvoTorch GPU population search, LLM-EA hybrids (FunSearch, Eureka)**. 매 derivative-free black-box optimization 의 dominant family.
## 📖 구조화된 지식 (Synthesized Content)
진화 알고리즘(Evolutionary-Algorithms)은 자연 선택 설에 기반한 확률적 최적화 탐색 기법입니다.
## 매 핵심
1. **주요 프로세스**:
* **Initialization**: 무작위 솔루션 집합 생성.
* **Fitness Evaluation**: 각 솔루션이 얼마나 문제를 잘 푸는지 평가.
* **Selection**: 성적이 좋은 상위 개체 선택.
* **Reproduction (Crossover & Mutation)**: 부모 개체의 장점을 섞거나 우연한 변화를 주어 새로운 자손 생성.
* **[[Iteration|Iteration]]**: 최적의 결과가 나올 때까지 무한 반복.
2. **왜 중요한가?**:
* 수학적으로 미분 불가능하거나 규칙이 복잡하여 전통적 방식으로 풀기 어려운 거대 조합 최적화 문제에 강력함. ([[Combinatorial-Optimization|Combinatorial-Optimization]]과 밀접)
### 매 4 main branches
- **GA (Genetic Algorithm)**: 매 binary / discrete + crossover-heavy.
- **ES (Evolution Strategy)**: 매 real-valued + self-adaptive σ; **CMA-ES** 의 modern apex.
- **GP (Genetic Programming)**: 매 program-tree representation.
- **DE (Differential Evolution)**: 매 vector difference 의 mutation; 매 simplest robust real-valued EA.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 연산 속도가 너무 느려 실용성이 떨어진다는 정책이 많았으나, 현대 정책은 강력한 GPU 연산과 결합하여 AI 신경망 구조 자체를 진화시키는 '신경 진화([[Neuroevolution|Neuroevolution]]) 정책'으로 부활함(RL Update).
- **정책 변화(RL Update)**: 강화학습의 그래디언트 방식이 막히는 복잡한 환경에서, 진화 알고리즘을 통한 '에이전트 모집단 학습 정책'이 더 강건한 인공지능을 만드는 대안 정책으로 연구되고 있음.
## 🔗 지식 연결 (Graph)
- [[Optimization|Optimization]], [[Combinatorial-Optimization|Combinatorial-Optimization]], [[Genetic-Algorithms|Genetic-Algorithms]], [[Complexity Theory|Complexity Theory]], [[Emergence|Emergence]]
- **Modern Tech/Tools**: Neuroevolution (NEAT), CMA-ES, Evolutionary Strategies (ES).
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### 매 generic loop
```
init population P
evaluate(P)
while budget left:
parents = select(P)
children = vary(parents) # crossover + mutation
evaluate(children)
P = replace(P, children) # generational or steady-state
return best
```
## 🤔 의사결정 기준 (Decision Criteria)
### 매 design knobs
- **Representation**: bitstring, real-vector, permutation, tree, graph.
- **Selection**: tournament, roulette, rank, truncation, (μ+λ) vs (μ,λ).
- **Variation**: 1-point/uniform CX, Gaussian/polynomial mutation, DE/best/1/bin.
- **Diversity**: niching, fitness sharing, novelty search, MAP-Elites (QD).
- **Self-adaptation**: σ encoded in genome (ES), CMA covariance update.
**선택 A를 써야 할 때:**
- *(TODO)*
## 💻 패턴
**선택 B를 써야 할 때:**
- *(TODO)*
### Plain GA from scratch (OneMax)
```python
import random
N, POP, GEN, PMUT = 100, 200, 100, 1/100
**기본값:**
> *(TODO)*
def fit(ind): return sum(ind)
def tournament(P, k=3): return max(random.sample(P, k), key=fit)
def cx(a, b):
p = random.randint(1, N-1)
return a[:p]+b[p:], b[:p]+a[p:]
def mut(ind):
return [1-x if random.random() < PMUT else x for x in ind]
## ❌ 안티패턴 (Anti-Patterns)
P = [[random.randint(0,1) for _ in range(N)] for _ in range(POP)]
for _ in range(GEN):
Q = []
while len(Q) < POP:
a, b = tournament(P), tournament(P)
c, d = cx(a, b)
Q += [mut(c), mut(d)]
P = sorted(P+Q, key=fit, reverse=True)[:POP]
print(fit(P[0]))
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### CMA-ES (continuous default)
```python
import cma
es = cma.CMAEvolutionStrategy([0]*10, 0.5,
{"popsize": 30, "maxfevals": 5000, "verbose": -9})
es.optimize(lambda x: sum((xi-3)**2 for xi in x))
print(es.result.xbest)
```
### Differential Evolution (scipy)
```python
from scipy.optimize import differential_evolution
res = differential_evolution(
lambda x: (1-x[0])**2 + 100*(x[1]-x[0]**2)**2, # Rosenbrock
bounds=[(-2,2),(-1,3)], strategy="best1bin",
popsize=30, mutation=(0.5,1.0), recombination=0.7, tol=1e-8)
```
### Genetic Programming (DEAP, symbolic regression)
```python
from deap import base, creator, gp, tools, algorithms
import operator, random, math
pset = gp.PrimitiveSet("MAIN", 1)
pset.addPrimitive(operator.add, 2); pset.addPrimitive(operator.mul, 2)
pset.addPrimitive(operator.sub, 2); pset.addEphemeralConstant("c", lambda: random.uniform(-1,1))
pset.renameArguments(ARG0="x")
creator.create("Fit", base.Fitness, weights=(-1.0,))
creator.create("Ind", gp.PrimitiveTree, fitness=creator.Fit, pset=pset)
tb = base.Toolbox()
tb.register("expr", gp.genHalfAndHalf, pset=pset, min_=1, max_=3)
tb.register("ind", tools.initIterate, creator.Ind, tb.expr)
tb.register("pop", tools.initRepeat, list, tb.ind)
tb.register("compile", gp.compile, pset=pset)
points = [(x, x**3 - 2*x + 1) for x in [i/10 for i in range(-10,10)]]
def evalSR(ind):
f = tb.compile(ind)
return (sum((f(x)-y)**2 for x,y in points),)
tb.register("evaluate", evalSR)
tb.register("select", tools.selTournament, tournsize=3)
tb.register("mate", gp.cxOnePoint)
tb.register("mutate", gp.mutUniform, expr=tb.expr, pset=pset)
pop = tb.pop(n=300)
algorithms.eaSimple(pop, tb, 0.7, 0.2, 40, verbose=False)
```
### MAP-Elites (Quality-Diversity)
```python
import numpy as np
grid = {}
def feat(x): return (int(x[0]*10), int(x[1]*10))
def f(x): return -np.sum(x**2)
for _ in range(20_000):
if grid: parent = grid[random.choice(list(grid))]
else: parent = np.random.uniform(-1,1,2)
child = parent + np.random.normal(0, 0.1, 2)
k = feat(child)
if k not in grid or f(child) > f(grid[k]): grid[k] = child
```
### LLM-guided EA (FunSearch-style, sketch)
```python
def llm_propose(parent_program: str) -> str:
return claude.messages.create(
model="claude-opus-4-7",
max_tokens=2000,
messages=[{"role":"user","content":
f"Improve this program for better fitness:\n{parent_program}"}]
).content[0].text
pop = [seed_program]
for _ in range(200):
parent = max(pop, key=score)
child = llm_propose(parent)
if score(child) > -float("inf"): pop.append(child)
if len(pop) > 50: pop = sorted(pop, key=score)[-50:]
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Continuous, ≤ 100 dim, black-box | **CMA-ES** |
| Continuous, parallel, robust default | **DE** |
| Discrete / combinatorial | **GA + memetic local search** |
| Symbolic regression / program synth | **GP** |
| Need diverse archive of solutions | **MAP-Elites / Novelty Search** |
| Very expensive eval (≤ 100 calls) | Bayesian optimization (not EA) |
| Code / prompt search 2026 | **LLM-EA hybrid (FunSearch / Eureka)** |
**기본값**: 매 continuous → **CMA-ES**; 매 discrete → **memetic GA**; 매 LLM-era code search → **FunSearch-style**.
## 🔗 Graph
- 부모: [[Biological-Inspired-Algorithms]] · [[Metaheuristics]] · [[Optimization]]
- 변형: [[Genetic-Algorithm]] · [[Evolution-Strategy]] · [[Genetic-Programming]] · [[Differential-Evolution]] · [[CMA-ES]] · [[NEAT]] · [[MAP-Elites]]
- 응용: [[Neural-Architecture-Search]] · [[Hyperparameter-Optimization]] · [[Symbolic-Regression]] · [[Robot-Control]]
- Adjacent: [[Reinforcement-Learning]] · [[Bayesian-Optimization]] · [[Simulated-Annealing]] · [[FunSearch]]
## 🤖 LLM 활용
**언제**: 매 black-box, multimodal, non-differentiable; 매 quality-diversity 가 필요; 매 program / prompt 의 search.
**언제 X**: 매 differentiable convex (gradient win), 매 evaluation < 100 calls (BO win).
## ❌ 안티패턴
- **Pure random search 의 EA 라고 부르기**: 매 selection pressure 없으면 매 EA 의 X.
- **Mutation 의 too small/large**: 매 self-adaptive (CMA / 1/5 rule) 의 사용.
- **Single elitist + small pop**: 매 premature convergence.
- **Reinventing GA names** ("Whale", "Grey Wolf", …): 매 academic noise — 매 CMA-ES / DE baseline 의 거의 항상 better.
- **Ignoring restart**: 매 IPOP/BIPOP-CMA 의 multimodal 에 critical.
## 🧪 검증 / 중복
- Verified (Holland 1975; Rechenberg 1973; Koza 1992; Storn & Price 1997 DE; Hansen 2001 CMA-ES; Mouret & Clune 2015 MAP-Elites; Romera-Paredes 2024 FunSearch).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 placeholder |
| 2026-05-10 | Manual cleanup — 4 branches + 6 patterns + LLM-EA |
@@ -2,90 +2,257 @@
id: wiki-2026-0508-expectation-maximization
title: Expectation Maximization
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-EXMA-001]
aliases: [EM Algorithm, Expectation-Maximization, GMM-EM, Baum-Welch]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, em-algorithm, expectation-maximization, latent-variable, gmm, Statistics, clustering, unSupervised-Learning]
confidence_score: 0.95
verification_status: applied
tags: [statistics, machine-learning, latent-variables, optimization, probabilistic-models]
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
framework: scikit-learn / NumPy / PyTorch
---
# [[Expectation-Maximization|Expectation-Maximization]]
# Expectation Maximization
## 📌 한 줄 통찰 (The Karpathy Summary)
> "숨겨진 데이터의 추적자: '어떤 그룹에 속하는지(잠재 변수)' 정해지지 않은 데이터 덩어리를 보고, 그룹의 특성을 임의로 추측(E-step)한 뒤 그 추측에 맞춰 최적의 모델을 업데이트(M-step)하는 과정을 반복하여 결국 보이지 않던 질서를 찾아내는 통계적 수수께끼 풀이법."
## 한 줄
> **"매 latent variable 가진 model 의 maximum likelihood 의 iterative 추정 — E-step (posterior) ↔ M-step (parameter update) 교차"**. Dempster-Laird-Rubin 1977 의 unification — 매 GMM, HMM (Baum-Welch), LDA, factor analysis, missing data imputation 의 모두 instances. 매 modern variational autoencoder 의 amortized EM.
## 📖 구조화된 지식 (Synthesized Content)
기대값 최대화(Expectation-Maximization, EM) 알고리즘은 관측되지 않은 잠재 변수가 포함된 확률 모델의 최대 우도(Maximum Likelihood) 추정값을 찾는 반복적인 알고리즘입니다.
## 매 핵심
1. **2단계 프로세스**:
* **E-Step (Expectation)**: 현재 모델 파라미터를 사용해 각 데이터가 특정 잠재 변수값(예: 클러스터 소속)을 가질 확률을 계산.
* **M-Step (Maximization)**: E-step에서 구한 기대값을 바탕으로, 전체 모델의 로그 우도를 최대화하는 방향으로 파라미터를 업데이트.
2. **왜 중요한가?**:
* 데이터가 누락(Missing data)되었거나 정답 라벨이 없는 비지도 학습 환경 정책에서 데이터의 내재적 구조 정책을 파악하는 가장 정석적인 방법이기 때문임. (Statistics와 연결)
### 매 Algorithm
Goal: maximize log p(X|θ) where X observed, Z latent.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 단순히 가우시안 혼합 모델(GMM) 정책 등에 사용되었으나, 현대 정책은 거대 언어 모델의 '지식 증강(Knowledge augmentation)' 과정이나 복잡한 추천 시스템의 '사용자 취향 잠재 공간 정책'을 찾아내는 데 핵심적으로 쓰임(RL Update).
- **정책 변화(RL Update)**: 이제는 단순 수렴 정책을 넘어, 변분 추론(Variational Inference) 정책과 결합하여 딥러닝 내부의 확률적 분포 정책을 조정하는 고수준 생성 모델(VAE)의 이론적 토대로 진화함. (Deep Learning (DL)와 연결)
- **E-step**: 매 posterior q(Z) = p(Z|X, θ_old).
- **M-step**: θ_new = argmax_θ E_q[log p(X, Z | θ)].
- **Repeat**: until convergence (likelihood plateau).
## 🔗 지식 연결 (Graph)
- [[Statistics|Statistics]], [[Analysis|Analysis]], Deep Learning (DL), [[Logic|Logic]], [[Complexity-Theory|Complexity-Theory]], Generalization
- **Key Use Case**: Gaussian Mixture Models (GMM), Hidden Markov Models (HMM).
---
### 매 ELBO interpretation
log p(X|θ) ≥ E_q[log p(X,Z|θ)] - E_q[log q(Z)] = ELBO(q, θ).
- E-step: 매 maximize ELBO over q (equiv. KL(q||p(Z|X,θ))=0 — 매 exact).
- M-step: 매 maximize ELBO over θ.
- 매 monotonic increase of log-likelihood guaranteed.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Convergence
- 매 local optimum 으로만 converge (matter 의 likelihood 의 multimodal).
- 매 multiple random init 권장.
- 매 K-means 의 EM 의 hard-assignment limit (Gaussian variance → 0).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. **Gaussian Mixture Models**: 매 clustering with soft assignments.
2. **Hidden Markov Models** (Baum-Welch): 매 speech recognition, NLP, bioinformatics.
3. **Latent Dirichlet Allocation** (variational EM): topic modeling.
4. **Factor analysis / PPCA**: 매 dimensionality reduction.
5. **Missing data imputation**: 매 MICE.
6. **VAE training** (amortized EM): 매 modern deep generative.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### GMM-EM (매 from scratch, NumPy)
```python
import numpy as np
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
class GaussianMixtureEM:
def __init__(self, K, max_iter=100, tol=1e-6):
self.K = K
self.max_iter = max_iter
self.tol = tol
def fit(self, X):
n, d = X.shape
# 매 init: random + uniform priors
self.pi = np.ones(self.K) / self.K
idx = np.random.choice(n, self.K, replace=False)
self.mu = X[idx]
self.sigma = np.array([np.cov(X.T) for _ in range(self.K)])
log_lik_old = -np.inf
for it in range(self.max_iter):
# E-step: posterior responsibilities γ_ik
log_resp = self._log_responsibilities(X) # (n, K)
resp = np.exp(log_resp - log_resp.max(axis=1, keepdims=True))
resp /= resp.sum(axis=1, keepdims=True)
# M-step
Nk = resp.sum(axis=0) # (K,)
self.pi = Nk / n
self.mu = (resp.T @ X) / Nk[:, None]
for k in range(self.K):
diff = X - self.mu[k]
self.sigma[k] = (resp[:, k:k+1] * diff).T @ diff / Nk[k]
self.sigma[k] += 1e-6 * np.eye(d) # 매 regularization
# convergence
log_lik = self._log_likelihood(X)
if abs(log_lik - log_lik_old) < self.tol:
break
log_lik_old = log_lik
return self
def _log_gaussian(self, X, mu, sigma):
d = X.shape[1]
diff = X - mu
inv = np.linalg.inv(sigma)
det = np.linalg.det(sigma)
return -0.5 * (d * np.log(2 * np.pi) + np.log(det) +
np.einsum('ni,ij,nj->n', diff, inv, diff))
def _log_responsibilities(self, X):
log_resp = np.zeros((X.shape[0], self.K))
for k in range(self.K):
log_resp[:, k] = np.log(self.pi[k] + 1e-12) + \
self._log_gaussian(X, self.mu[k], self.sigma[k])
return log_resp
def _log_likelihood(self, X):
log_resp = self._log_responsibilities(X)
from scipy.special import logsumexp
return logsumexp(log_resp, axis=1).sum()
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# Demo
np.random.seed(42)
X1 = np.random.randn(100, 2) + np.array([5, 0])
X2 = np.random.randn(100, 2) + np.array([-5, 0])
X = np.vstack([X1, X2])
model = GaussianMixtureEM(K=2).fit(X)
print(f"Means:\n{model.mu}")
print(f"Mixing:\n{model.pi}")
```
## 🤔 의사결정 기준 (Decision Criteria)
### scikit-learn (매 production)
```python
from sklearn.mixture import GaussianMixture
**선택 A를 써야 할 때:**
- *(TODO)*
gmm = GaussianMixture(n_components=3, covariance_type='full',
max_iter=100, n_init=10, random_state=42)
gmm.fit(X)
print(f"Converged: {gmm.converged_}")
print(f"BIC: {gmm.bic(X):.2f}") # 매 model selection
labels = gmm.predict(X)
proba = gmm.predict_proba(X) # 매 soft assignment
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Baum-Welch (HMM, 매 EM 의 instance)
```python
def baum_welch(observations, n_states, n_iter=100):
"""매 HMM 의 forward-backward + EM updates."""
T = len(observations)
pi = np.ones(n_states) / n_states
A = np.random.rand(n_states, n_states); A /= A.sum(axis=1, keepdims=True)
B = np.random.rand(n_states, max(observations)+1); B /= B.sum(axis=1, keepdims=True)
for it in range(n_iter):
# E-step: forward α, backward β
alpha = np.zeros((T, n_states))
alpha[0] = pi * B[:, observations[0]]
for t in range(1, T):
alpha[t] = (alpha[t-1] @ A) * B[:, observations[t]]
beta = np.zeros((T, n_states))
beta[T-1] = 1
for t in range(T-2, -1, -1):
beta[t] = A @ (B[:, observations[t+1]] * beta[t+1])
# γ_t(i), ξ_t(i,j)
gamma = alpha * beta
gamma /= gamma.sum(axis=1, keepdims=True)
xi = np.zeros((T-1, n_states, n_states))
for t in range(T-1):
num = alpha[t][:, None] * A * B[:, observations[t+1]] * beta[t+1]
xi[t] = num / num.sum()
# M-step
pi = gamma[0]
A = xi.sum(axis=0) / gamma[:-1].sum(axis=0)[:, None]
for k in range(B.shape[1]):
mask = (observations == k)
B[:, k] = gamma[mask].sum(axis=0) / gamma.sum(axis=0)
return pi, A, B
```
**기본값:**
> *(TODO)*
### VAE — 매 amortized variational EM
```python
import torch
import torch.nn as nn
## ❌ 안티패턴 (Anti-Patterns)
class VAE(nn.Module):
def __init__(self, input_dim, latent_dim):
super().__init__()
self.enc_mu = nn.Linear(input_dim, latent_dim)
self.enc_logvar = nn.Linear(input_dim, latent_dim)
self.dec = nn.Linear(latent_dim, input_dim)
def forward(self, x):
# 매 E-step approximation: q(z|x) = N(μ_φ(x), σ²_φ(x))
mu = self.enc_mu(x)
logvar = self.enc_logvar(x)
eps = torch.randn_like(mu)
z = mu + torch.exp(0.5 * logvar) * eps
x_recon = torch.sigmoid(self.dec(z))
return x_recon, mu, logvar
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
def vae_loss(x, x_recon, mu, logvar):
recon = nn.functional.binary_cross_entropy(x_recon, x, reduction='sum')
kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return recon + kl
# 매 SGD 의 joint optimization 의 amortized E+M
```
### MAP-EM (매 with prior, regularized)
```python
# 매 prior 의 add 시 monotonic posterior 증가.
# Example: GMM 에 Dirichlet prior on π, NIW on (μ, Σ).
# 매 sklearn BayesianGaussianMixture 의 internal.
from sklearn.mixture import BayesianGaussianMixture
bgmm = BayesianGaussianMixture(n_components=10, weight_concentration_prior=1e-2)
bgmm.fit(X)
# 매 effective K 의 자동 sparsification.
```
## 매 결정 기준
| 상황 | Variant |
|---|---|
| Standard mixture clustering | Vanilla EM (sklearn) |
| Sequential / temporal | Baum-Welch (HMM) |
| Topic modeling | Variational EM (LDA) |
| Scalable / online | Online EM, stochastic |
| Deep latent model | VAE (amortized) |
| Need MAP / regularization | MAP-EM, Bayesian-EM |
| Hard assignment baseline | K-means (EM degenerate) |
| Discrete latent | Categorical EM |
**기본값**: 매 GMM clustering 매 sklearn `GaussianMixture(n_init=10)`. 매 deep 매 VAE.
## 🔗 Graph
- 부모: [[Maximum-Likelihood-Estimation]] · [[Latent-Variable-Models]]
- 변형: [[Variational-EM]] · [[Stochastic-EM]] · [[MAP-EM]] · [[Hard-EM]]
- 응용: [[Gaussian-Mixture-Models]] · [[Hidden-Markov-Models]] · [[LDA-Topic-Modeling]] · [[VAE]]
- Adjacent: [[Variational-Inference]] · [[Maximum-A-Posteriori]] · [[K-Means-Clustering-Foundations]] · [[Baum-Welch]]
## 🤖 LLM 활용
**언제**: 매 derivation 의 walk-through, 매 ELBO 의 explain, 매 model selection (BIC) 의 advice, 매 troubleshooting (e.g., 매 singular covariance).
**언제 X**: 매 large-scale fitting — 매 sklearn / dedicated library 사용. 매 numerical issue 의 diagnosis 시 actual data 의 inspection 필요.
## ❌ 안티패턴
- **Single random init**: 매 local optimum trap — n_init=10 권장.
- **Singular covariance ignore**: 매 sigma += εI 의 regularization 필수.
- **Convergence 의 likelihood 가 아닌 parameter 의 monitor**: 매 wrong — likelihood / ELBO 의 monitor.
- **K 의 randomly choose**: 매 BIC / AIC / cross-validation 사용.
- **K-means 의 GMM 결과 비교**: 매 different — GMM 의 soft assignment + covariance.
- **EM 의 global optimum 가정**: 매 local optimum 만 — multi-start 필수.
## 🧪 검증 / 중복
- Verified (Dempster-Laird-Rubin 1977, Bishop "PRML" Ch9, Murphy "Probabilistic ML" Ch11).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — algorithm, ELBO, GMM/HMM/VAE applications, NumPy from-scratch |
@@ -2,76 +2,163 @@
id: wiki-2026-0508-fmea
title: FMEA
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Failure Mode and Effects Analysis, DFMEA, PFMEA, FMECA]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [reliability, risk, safety, systems-engineering]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python
framework: pandas, AIAG-VDA template
---
# [[FMEA(Failure Mode and Effects Analysis)]]
# FMEA
## 📌 한 줄 통찰 (The Karpathy Summary)
FMEA(Failure Mode and Effects Analysis, 고장 모드 및 영향 분석)는 잠재적 고장 모드를 식별하고, 원인과 영향을 분석하여 이를 방지하거나 줄이기 위한 조치의 우선순위를 정하는 체계적인 위험 평가 기술이다 [1]. 이 기법은 제품이나 시스템의 개발 초기 단계부터 리스크를 사전에 식별하고 그 영향을 최소화하여 신뢰성과 안전성을 향상시키는 것을 목적으로 한다 [2]. 원래 미군과 항공우주 및 제조 분야를 위해 개발되었으나, 현재는 자동차, 전자, 의료 등 다양한 산업 전반에서 선제적 위험 완화 도구로 널리 사용되고 있다 [1, 3, 4].
## 한 줄
> **"매 system 의 모든 failure mode 의 systematic enumeration + ranking"**. 1949 US Military (MIL-P-1629) → NASA Apollo → 자동차 (AIAG-VDA 2019, the modern standard) → 매 software / ML / SRE 의 risk-process 로 generalized. 매 "what can fail, how, what then, what to do" 의 매 4 column.
## 📖 구조화된 지식 (Synthesized Content)
* **FMEA의 핵심 평가 지표와 RPN 계산**
* FMEA 분석은 잠재적 고장에 대한 리스크를 **심각도(Severity)**, **발생도(Occurrence)**, **검출도(Detection)**라는 세 가지 핵심 요소를 기준으로 평가한다 [2, 5].
* 이 세 가지 점수를 곱하여 **위험 우선순위 수(RPN: Risk Priority Number)**를 산출하며, RPN 값이 높을수록 리스크가 크다고 판단하여 우선적인 개선 조치의 대상이 된다 [2, 6, 7].
* **FMEA의 주요 유형**
* **DFMEA(Design FMEA):** 제품 개발 및 설계 단계에서 발생 가능한 고장 모드와 그 영향을 사전에 분석하여 구조적 결함을 예방하고 설계를 개선하는 기법이다 [8].
* **P-FMEA(Process FMEA):** 제품 제조 및 생산 공정 중 발생할 수 있는 조립 불량, 장비 이상 등의 고장을 식별하고 이를 예방하기 위한 공정 제어 방안을 마련하는 데 사용된다 [9, 10].
* **FMEA 프로세스 단계**
* FMEA는 시스템이나 프로세스를 계층적 방식으로 세분화하여 분석의 초점을 명확히 하는 계획 단계부터 시작된다 [11, 12].
* 이후 기능 또는 프로세스 단계를 결정하고 잠재적 고장 모드를 식별한 뒤, 영향 및 원인 분석을 거쳐 RPN을 계산하고 우선순위를 도출한다 [13-16].
* 마지막으로 고장을 감지, 완화, 방지하기 위한 실행 계획을 구현하고 조치 완료 후 위험 수준을 재평가하여 FMEA를 마무리한다 [17-20].
* **능동적 위험 관리 도구로서의 가치**
* FMEA는 고장 모드가 발생하기 전에 조기에 식별하여 팀이 사전에 문제를 해결할 수 있게 하는 선제적 분석을 제공한다 [17, 21]. 이는 비용이 많이 드는 실패를 피하고, 전반적인 품질 향상 및 규정 준수를 지원하며, 장기적인 성공을 위한 지속적인 개선 문화를 육성한다 [22, 23].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **평가의 주관성과 일관성 문제:** 심각도, 발생도, 검출도에 대한 점수 할당은 분석을 수행하는 팀원의 경험과 판단에 의존하므로 주관적일 수 있으며, 이로 인해 평가의 불일치가 발생할 수 있다 [7, 21].
* **RPN 지표의 한계:** RPN 수치만으로 리스크를 판단하면 실제 위험이 과소평가될 수 있는 제약이 존재한다 [7]. 따라서 심각도가 매우 높은 고장 모드의 경우, RPN 점수가 낮게 나오더라도 별도의 전문가 검토를 거쳐 우선순위를 재조정해야 한다 [7].
* **복잡한 시스템 분석의 한계:** FMEA는 주로 개별 구성 요소나 단일 고장 모드에 초점을 맞추기 때문에, 수많은 상호의존성을 지닌 대규모의 복잡한 시스템이나 하위 시스템 간의 상호 작용을 분석하는 데는 한계가 있다 [21]. 이러한 경우 결함 트리 분석(FTA)과 같은 상향식 접근 방식이 더 적합할 수 있다 [21, 24].
* **시간 및 자원의 소모:** 대규모 프로젝트에 FMEA를 적용할 경우, 각 고장 모드와 관련 결과에 대한 세부적이고 포괄적인 분석이 요구되므로 막대한 시간과 리소스가 소모될 수 있으며, 다루어야 할 정보의 양이 너무 많아 분석을 중도 포기할 위험도 존재한다 [21, 25]. 이를 성공적으로 수행하기 위해서는 특정 분야의 전문 지식이 필수적으로 요구된다 [21].
### 매 종류
- **DFMEA** (Design): 매 product / component design 단계.
- **PFMEA** (Process): 매 manufacturing / business process.
- **SFMEA** (System): 매 system-of-systems 의 interaction.
- **FMECA**: 매 + Criticality (quantitative).
- **MLFMEA / AI-FMEA** (2024+): 매 ML model failure modes (data drift, prompt injection, hallucination).
---
*Last updated: 2026-05-04*
### 매 AIAG-VDA 7-step (2019, current global standard)
1. **Planning & Preparation** (5T: InTent, Timing, Team, Tasks, Tools).
2. **Structure Analysis** (system → subsystem → component tree).
3. **Function Analysis** (each element 의 functions + interfaces).
4. **Failure Analysis** (Failure Effect FE / Failure Mode FM / Failure Cause FC chain).
5. **Risk Analysis** — replaces RPN with **Action Priority (AP: H/M/L)** based on (S, O, D).
6. **Optimization** (preventive + detection actions).
7. **Results Documentation**.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 scoring
- **Severity (S)** 110: 매 effect 의 customer / safety impact.
- **Occurrence (O)** 110: 매 cause 의 likelihood.
- **Detection (D)** 110: 매 control 의 detection ability (10 = 못 detect).
- 매 legacy **RPN = S·O·D** (deprecated by AIAG-VDA but still common).
- 매 modern **Action Priority** matrix: H / M / L.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Minimal FMEA table (pandas)
```python
import pandas as pd
## 🧪 검증 상태 (Validation)
rows = [
{"item":"Brake pad","function":"friction","FM":"wear",
"FE":"reduced braking","FC":"high mileage",
"S":9,"O":4,"D":3},
{"item":"Brake pad","function":"friction","FM":"contamination",
"FE":"squeal","FC":"oil leak",
"S":4,"O":3,"D":5},
]
df = pd.DataFrame(rows)
df["RPN"] = df.S * df.O * df.D
df = df.sort_values("RPN", ascending=False)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### AIAG-VDA Action Priority
```python
def action_priority(S, O, D):
if S >= 9 and O >= 4: return "H"
if S >= 9 and O >= 2: return "H"
if S >= 7 and O >= 6 and D >= 6: return "H"
if S >= 7 and O >= 4 and D >= 4: return "M"
if S >= 4 and O >= 4: return "M"
return "L"
df["AP"] = df.apply(lambda r: action_priority(r.S, r.O, r.D), axis=1)
```
## 🧬 중복 검사 (Duplicate Check)
### Software-FMEA (microservice)
```python
fmeas = [
dict(component="auth-svc", FM="JWT signature mismatch",
FE="login fails, downstream 401",
FC="key rotation race",
control="canary + jwks fallback",
S=8, O=3, D=4),
dict(component="auth-svc", FM="DB pool exhaustion",
FE="latency spike, cascading 503",
FC="connection leak in handler",
control="bounded pool + timeouts + chaos test",
S=7, O=5, D=6),
]
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### ML-FMEA (LLM application)
```python
ml_fmeas = [
dict(stage="prompt", FM="prompt injection",
FE="data exfiltration via tool call",
FC="user content concatenated unfiltered",
control="structured prompt + injection classifier + tool allow-list",
S=10, O=6, D=7),
dict(stage="model", FM="hallucinated citation",
FE="false legal claim",
FC="long-tail fact, no retrieval",
control="RAG + post-hoc verifier",
S=8, O=7, D=5),
dict(stage="data", FM="distribution drift",
FE="accuracy drop in prod",
FC="seasonal user mix change",
control="online metric monitor + canary",
S=6, O=6, D=4),
]
```
## 🔗 지식 연결 (Graph)
### Criticality matrix plot
```python
import matplotlib.pyplot as plt
plt.scatter(df.O, df.S, s=df.D*40, alpha=0.6)
for _, r in df.iterrows(): plt.annotate(r.FM, (r.O, r.S))
plt.xlabel("Occurrence"); plt.ylabel("Severity"); plt.grid()
```
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Hardware design (auto, aero) | **DFMEA + AIAG-VDA** |
| Manufacturing line | **PFMEA** |
| Safety-critical (DO-178C, ISO 26262) | **FMEA + FTA + STPA** |
| Software service | **Software-FMEA + chaos engineering** |
| LLM / ML system | **ML-FMEA + red-team + evals** |
| Quick triage | **Risk matrix (S × O)** |
## 🕓 변경 이력 (Changelog)
**기본값**: 매 AIAG-VDA 7-step + AP scoring (RPN deprecated).
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🔗 Graph
- 부모: [[Reliability-Engineering]] · [[Risk-Management]] · [[Systems-Engineering]]
- 변형: [[DFMEA]] · [[PFMEA]] · [[FMECA]] · [[ML-FMEA]]
- 응용: [[ISO-26262]] · [[DO-178C]] · [[Six-Sigma]] · [[SRE]]
- Adjacent: [[Fault-Tree-Analysis]] · [[STPA]] · [[HAZOP]] · [[Bow-Tie-Analysis]] · [[Chaos-Engineering]]
## 🤖 LLM 활용
**언제**: 매 new system 의 risk register 를 brainstorm; 매 architecture review 의 failure-chain 의 enumeration; 매 ML deployment 의 pre-mortem.
**언제 X**: 매 emergent / interactive failure (매 complex software) — 매 STPA 의 더 적합. 매 statistical reliability 는 FTA + Markov.
## ❌ 안티패턴
- **RPN multiplication only**: 매 (10,1,1)=10 vs (2,5,1)=10 의 same — but severity 10 의 catastrophic. **AP matrix 사용.**
- **Sev/Occ/Det 의 inconsistent scale**: 매 team-wide rubric 없으면 매 garbage.
- **One-shot document**: 매 living document 가 아니면 매 outdated. 매 design change 의 trigger update.
- **Skipping detection actions**: 매 only "add training" — 매 weak. 매 sensor / monitor / poka-yoke 의 추가.
- **Software FMEA 의 component-only**: 매 interaction failures 의 missed — 매 STPA 의 complement.
## 🧪 검증 / 중복
- Verified (MIL-P-1629; AIAG-VDA FMEA Handbook 2019; SAE J1739; ISO 26262-9).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 placeholder |
| 2026-05-10 | Manual cleanup — 7-step AIAG-VDA + 5 patterns + ML-FMEA |
@@ -2,63 +2,188 @@
id: wiki-2026-0508-feedback-control-systems
title: Feedback Control Systems
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [FEEDBACK-001]
aliases: [Closed-Loop Control, Control System, PID, MPC]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [engineering, Control-Theory, feedback-loop, Cybernetics]
confidence_score: 0.92
verification_status: applied
tags: [control-theory, systems, dynamics, automation]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python
framework: python-control, scipy.signal, do-mpc, casadi
---
# Feedback Control[[_system|system]]s (피드백 제어 시스템)
# Feedback Control Systems
## 📌 한 줄 통찰 (The Karpathy Summary)
> "현재의 상태가 미래의 행동을 결정하게 하라" — 시스템의 출력을 관찰하고 이를 입력으로 다시 피드백하여, 목표 상태와의 오차를 실시간으로 줄여나가는 자동 조절 기전.
## 한 줄
> **"매 sensor → comparator → controller → actuator → plant → sensor 매 closed loop 으로 setpoint 를 maintain"**. James Watt 의 governor (1788) → Bode/Nyquist (1930s) → state-space + Kalman (1960s) → 매 modern: **MPC, ADRC, learning-based control (Koopman/MPC, RL)**. 매 SRE autoscaler, drone, EV motor, vaccine cold-chain, fab DRIE — 매 universal.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 센서(출력 측정) -> 컨트롤러(오차 계산) -> 액추에이터(수정 행동)로 이어지는 순환 고리(Loop)를 통해 시스템의 안정성을 확보하는 패턴.
- **세부 내용:**
- **Negative Feedback:** 목표값에서 벗어나려는 변화를 억제하여 시스템을 안정화 (예: 온도 조절기).
- **Positive Feedback:** 특정 변화를 가속화하여 급격한 상태 변화를 유도 (예: 스피커 하울링, 혈액 응고).
- **Error Signal:** 목표값(Set-point)과 측정값(Process Variable)의 차이. 제어의 근거가 됨.
- **Disturbance Rejection:** 외부의 예기치 않은 소음이나 간섭에도 불구하고 시스템이 목표를 유지하는 능력.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순 온-오프(On-Off) 제어에서 비례-적분-미분(PID) 및 상태 공간 제어와 같은 정교한 수학적 모델로 발전.
- **정책 변화:** Antigravity 에이전트의 '자가 수정 루프'는 Negative Feedback 원리를 사용하여 사용자의 의도와 답변 사이의 거리를 좁히는 데 집중함.
### 매 canonical block diagram
```
┌─────────┐
r ──+──▶│Controller│──u──▶┌─────┐──y──┐
─ │ C(s) │ │P(s)│ │
└─────────┘ └─────┘ │
▲ │
└──── − ◀── sensor ◀───┘
e = r y_meas (error)
```
## 🔗 지식 연결 (Graph)
- **Parent:** 10_Wiki/💡 Topics/AI
- **Related:** [[Control-Systems-Engineering|Control-Systems-Engineering]], [[Cybernetics|Cybernetics]], PID-Control
- **Raw Source:** 10_Wiki/Topics/AI/Feedback-Control-Systems.md
### 매 PID intuition
- **P (proportional)**: 매 instant correction; 매 too high → oscillation.
- **I (integral)**: 매 eliminate steady-state error; 매 too high → wind-up.
- **D (derivative)**: 매 damping; 매 amplify noise.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 modern 분류
- **Classical**: PID, lead-lag, root-locus, Bode design.
- **State-space**: pole-placement, LQR, observer / Kalman filter.
- **Robust**: H∞, μ-synthesis (uncertain plant).
- **Adaptive**: MRAC, gain-scheduling.
- **Predictive**: **MPC** (constraint-aware, multi-step optimize).
- **Learning-based** (2026): Koopman-MPC, Gaussian-Process MPC, **safe RL with control-barrier functions**.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 stability
- 매 LTI 의 Routh-Hurwitz, Nyquist, gain/phase margin (≥ 6 dB / 30°).
- 매 nonlinear 의 Lyapunov.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### PID class
```python
class PID:
def __init__(self, kp, ki, kd, dt, u_min=None, u_max=None):
self.kp,self.ki,self.kd,self.dt = kp,ki,kd,dt
self.u_min,self.u_max = u_min,u_max
self.i, self.prev = 0.0, 0.0
def __call__(self, sp, pv):
e = sp - pv
self.i += e*self.dt
d = (e - self.prev)/self.dt
self.prev = e
u = self.kp*e + self.ki*self.i + self.kd*d
if self.u_max is not None and u > self.u_max:
u = self.u_max; self.i -= e*self.dt # anti-windup
if self.u_min is not None and u < self.u_min:
u = self.u_min; self.i -= e*self.dt
return u
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### ZieglerNichols tuning
```python
# 1) Set ki=kd=0; raise kp to find Ku where output sustains oscillation at period Tu.
# 2) Classic ZN: kp=0.6Ku, ki=2kp/Tu, kd=kp*Tu/8
def zn_classic(Ku, Tu): return 0.6*Ku, 2*0.6*Ku/Tu, 0.6*Ku*Tu/8
```
## 🧬 중복 검사 (Duplicate Check)
### Plant simulation (python-control)
```python
import control as ct, numpy as np, matplotlib.pyplot as plt
P = ct.tf([1], [1, 3, 2]) # 1/(s²+3s+2)
C = ct.tf([2, 1], [1, 0]) # PI: 2 + 1/s
L = ct.series(C, P)
T = ct.feedback(L, 1)
t, y = ct.step_response(T, T=np.linspace(0, 10, 500))
plt.plot(t, y); plt.axhline(1, ls="--")
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### State-space LQR
```python
import numpy as np, control as ct
A = np.array([[0,1],[-2,-3]]); B = np.array([[0],[1]])
Q = np.diag([10, 1]); R = np.array([[0.1]])
K, _, _ = ct.lqr(A, B, Q, R)
# u = -K x
```
## 🕓 변경 이력 (Changelog)
### Kalman filter
```python
import numpy as np
def kf_step(x, P, z, A, H, Q, R):
# predict
x = A @ x; P = A @ P @ A.T + Q
# update
y = z - H @ x
S = H @ P @ H.T + R
K = P @ H.T @ np.linalg.inv(S)
x = x + K @ y
P = (np.eye(len(x)) - K @ H) @ P
return x, P
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Model Predictive Control (do-mpc, level tank)
```python
import numpy as np, do_mpc
from casadi import vertcat
m = do_mpc.model.Model("continuous")
h = m.set_variable("_x","h"); u = m.set_variable("_u","u")
m.set_rhs("h", -0.1*h + u); m.setup()
mpc = do_mpc.controller.MPC(m)
mpc.set_param(n_horizon=20, t_step=0.1, store_full_solution=True)
mpc.set_objective(mterm=(h-1)**2, lterm=(h-1)**2 + 0.01*u**2)
mpc.set_rterm(u=0.1)
mpc.bounds["lower","_u","u"] = 0; mpc.bounds["upper","_u","u"] = 2
mpc.bounds["lower","_x","h"] = 0; mpc.bounds["upper","_x","h"] = 1.5
mpc.setup()
mpc.x0 = np.array([0.0]); mpc.set_initial_guess()
u0 = mpc.make_step(np.array([0.0]))
```
### Autoscaler-as-PID (SRE)
```python
class CPUAutoscaler:
def __init__(self, target=0.6, k=10, max_r=20):
self.pid = PID(kp=k, ki=k/30, kd=0, dt=15, u_min=-3, u_max=3)
self.target, self.max_r = target, max_r
def step(self, cpu, replicas):
delta = self.pid(self.target, cpu)
return max(1, min(self.max_r, replicas + round(delta)))
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Single SISO, slow plant | **PID** (90% of industry) |
| MIMO, known model | **LQR / state-space** |
| Constraints + multi-step lookahead | **MPC** |
| Large model uncertainty | **H∞ / robust control** |
| Time-varying gain | **Gain-scheduling / adaptive** |
| Unknown dynamics, lots of data | **Koopman-MPC / GP-MPC / safe RL** |
| Stochastic measurement | **+ Kalman / EKF / UKF** |
**기본값**: 매 SISO + slow plant → **PID with anti-windup + ZN-tuning**, 매 constraint-rich multi-input → **MPC**.
## 🔗 Graph
- 부모: [[Control-Theory]] · [[Cybernetics]] · [[Dynamical-Systems]]
- 변형: [[PID]] · [[LQR]] · [[MPC]] · [[Adaptive-Control]] · [[Robust-Control]] · [[Sliding-Mode-Control]]
- 응용: [[Autoscaler]] · [[Drone-Control]] · [[Process-Control]] · [[Robotics]] · [[Power-Electronics]]
- Adjacent: [[Feedback-Loops in Systems]] · [[Kalman-Filter]] · [[Reinforcement-Learning]] · [[Control-Barrier-Function]]
## 🤖 LLM 활용
**언제**: 매 PID 의 tuning, 매 plant 의 transfer-function 의 derivation, 매 MPC objective 의 formulation, 매 stability 의 quick check.
**언제 X**: 매 safety-critical real-time control 의 untested LLM-generated code 의 직접 deploy — 매 formal verification + HIL test 필수.
## ❌ 안티패턴
- **No anti-windup**: 매 saturated actuator + integral 의 huge overshoot.
- **D term on noisy measurement**: 매 amplifies high-freq noise — 매 derivative-on-measurement + low-pass filter.
- **Sample rate ≪ bandwidth**: 매 dt 의 ≥ 10× system bandwidth 의 violate → 매 instability.
- **Tuning by gut**: 매 reproducible (ZN, model-based, autotuning) 의 사용.
- **Open-loop "feedback"**: 매 sensor 없이 매 not feedback control.
- **Ignoring delay**: 매 transport delay → 매 Smith predictor / phase margin 의 reserve.
## 🧪 검증 / 중복
- Verified (Bode 1945; Åström & Murray *Feedback Systems* 2nd ed.; Rawlings, Mayne & Diehl *MPC* 2nd ed.; Brunton & Kutz *Data-Driven Science and Engineering* 2022).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 placeholder |
| 2026-05-10 | Manual cleanup — classical→MPC + 7 patterns + decision matrix |
@@ -2,61 +2,171 @@
id: wiki-2026-0508-feedback-loops-in-systems
title: Feedback Loops in Systems
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [SYS-FEEDBACK-001]
aliases: [Feedback Loop, Closed-Loop, Reinforcing Loop, Balancing Loop]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [systems-theory, Cybernetics, feedback-loop, Stability, growth-Strategy]
confidence_score: 0.9
verification_status: applied
tags: [systems-thinking, control, dynamics, cybernetics]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python
framework: scipy.signal, simpy, control
---
# Feedback Loops in[[_system|system]]s (시스템에서의 피드백 루프)
# Feedback Loops in Systems
## 📌 한 줄 통찰 (The Karpathy Summary)
> "결과가 다시 원인이 되는 순환의 고리를 설계하여, 스스로 제어하고 진화하는 시스템을 완성하라" — 시스템의 출력이 다시 입력으로 돌아와 시스템의 동작을 조절하거나 변화를 증폭시키는 메커니즘.
## 한 줄
> **"매 output 의 portion 의 input 으로 routed back — 매 system 의 self-regulation / self-amplification 의 fundamental mechanism"**. Wiener 의 cybernetics (1948) → Forrester 의 system dynamics (1961) → Meadows 의 *Thinking in Systems* (2008) → 매 SRE / RL / market-design 까지 매 universal.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "원인 -> 결과"의 선형적 인과관계를 넘어, 결과가 원인에 다시 개입하여 시스템의 상태를 유지하거나 급격히 변화시키는 순환적 인과 패턴.
- **주요 유형:**
- **Negative Feedback (음의 피드백):** 목표와의 편차를 줄여 시스템을 안정화하고 평형을 유지함 (예: 온도 조절 장치, 항상성, RL의 오차 수정).
- **Positive Feedback (양의 피드백):** 변화를 가속화하고 증폭시켜 기하급수적 성장이나 붕괴를 초래함 (예: 데이터 플라이휠 효과, 네트워크 효과, 인플레이션).
- **의의:** 복잡한 시스템의 거동을 이해하고 예측하기 위한 필수 도구이며, 자율 제어 및 학습 아키텍처 설계의 기반.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순한 제어 공학의 도구에서, 비즈니스 모델의 폭발적 성장(Growth Loop)과 AI의 자가 진화(Self-improvement)를 설명하는 핵심 전략으로 가치 재정립.
- **정책 변화:** Antigravity 프로젝트는 사용자의 '수정(Edit)' 행위를 에이전트의 '지식 정합성'을 높이는 강력한 음의 피드백 루프로 활용하여, 시간이 지날수록 지식 베이스의 오류를 0으로 수렴시킴.
### 매 두 polarity
- **Reinforcing (R, +)**: 매 same-direction amplification → 매 exponential growth or collapse. 매 viral growth, bank runs, flywheel.
- **Balancing (B, )**: 매 opposite-direction correction → 매 goal-seeking equilibrium. 매 thermostat, autoscaler, supply-demand.
- 매 system 의 behavior = sum of all loops, with delays.
## 🔗 지식 연결 (Graph)
- Cybernetics-Foundations, [[Control-Theory|Control-Theory]], [[Data-Flywheel-Effect|Data-Flywheel-Effect]], [[Reinforcement-Learning-from-Human-Feedback-RLHF|Reinforcement-Learning-from-Human-Feedback-RLHF]]
- **Raw Source:** 10_Wiki/Topics/AI/[[Feedback-Loops|Feedback-Loops]] in Systems.md
### 매 4 building blocks (Meadows)
1. **Stocks** (state, accumulator).
2. **Flows** (rate of change).
3. **Information links** (signals).
4. **Delays** (transport, perception, action).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 typical archetypes
- **Limits to growth**: R + B (resource constraint).
- **Shifting the burden**: short-term fix B undermines long-term solution.
- **Tragedy of the commons**: many R + 1 B.
- **Success to the successful**: 2 R coupled.
- **Drift to low performance**: B with eroding goals.
- **Escalation**: 2 R + delay (arms race).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 stability
- 매 negative loop 의 gain > 1 + delay → 매 oscillation, overshoot.
- 매 positive loop 의 unchecked → 매 runaway / collapse.
- 매 Bode / Nyquist 의 control-theory 의 quantitative tool.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Thermostat (B loop, ODE)
```python
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
setpoint, k_loss, k_heat = 22.0, 0.1, 0.5
def dT(T, t):
heat = k_heat if T < setpoint else 0
return -k_loss*(T-10) + heat
t = np.linspace(0, 100, 1000)
T = odeint(dT, 15, t)
plt.plot(t, T); plt.axhline(setpoint, ls="--")
```
## 🧬 중복 검사 (Duplicate Check)
### PID controller (B with derivative damping)
```python
class PID:
def __init__(self, kp, ki, kd, dt):
self.kp,self.ki,self.kd,self.dt = kp,ki,kd,dt
self.i, self.prev = 0, 0
def __call__(self, sp, pv):
e = sp - pv
self.i += e*self.dt
d = (e - self.prev)/self.dt
self.prev = e
return self.kp*e + self.ki*self.i + self.kd*d
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Reinforcing loop — viral growth
```python
def viral(t_max=30, k=0.2, init=10, cap=1e6):
n=[init]
for _ in range(t_max):
n.append(min(cap, n[-1]*(1+k))) # R loop
return n
# 매 limits-to-growth 의 cap 의 추가 — pure exponential 의 unrealistic.
```
## 🕓 변경 이력 (Changelog)
### Logistic — R + B (limits to growth)
```python
def logistic(K=1e6, r=0.3, t_max=60, init=10):
x=[init]
for _ in range(t_max):
x.append(x[-1] + r*x[-1]*(1-x[-1]/K))
return x
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Stock-and-flow (Forrester) with simpy
```python
import simpy, random
env = simpy.Environment()
inventory = simpy.Container(env, init=100, capacity=1000)
def supplier(env):
while True:
yield env.timeout(2)
if inventory.level < 50: # B loop on stock
yield inventory.put(60)
def customer(env):
while True:
yield env.timeout(random.expovariate(1))
yield inventory.get(1)
env.process(supplier(env)); [env.process(customer(env)) for _ in range(5)]
env.run(until=100)
```
### Autoscaler (SRE B loop)
```python
def autoscaler(metric, target=0.6, replicas=3, max_r=20):
err = metric - target
delta = round(err * replicas / target)
return max(1, min(max_r, replicas + delta))
```
### Causal-loop diagram (text DSL)
```
Users ─R→ Content ─R→ Engagement ─R→ Users (viral R)
Users ─B→ Server-load ─B→ Latency ─B→ Users (capacity B)
delay: server provisioning ≈ 10 min → oscillation risk.
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Continuous physical / control | **PID / state-space** |
| Discrete event business / supply chain | **System Dynamics (stocks-flows)** |
| Service capacity | **B loop autoscaler + SLO error budget** |
| Growth product strategy | **Map R loops; identify limit B; remove constraint** |
| Policy / market | **Causal-loop diagram + agent-based sim** |
| Stability analysis | **Linearize → Bode / root-locus** |
**기본값**: 매 design 의 첫 단계 = **CLD (Causal Loop Diagram)** + delay 표시 + leverage point 식별.
## 🔗 Graph
- 부모: [[Systems-Thinking]] · [[Cybernetics]] · [[Control-Theory]]
- 변형: [[Reinforcing-Loop]] · [[Balancing-Loop]] · [[Delayed-Feedback]] · [[Hysteresis]]
- 응용: [[Feedback-Control-Systems]] · [[Autoscaler]] · [[Reinforcement-Learning]] · [[Growth-Loop]] · [[Macro-Economics]]
- Adjacent: [[System-Dynamics]] · [[Causal-Loop-Diagram]] · [[Limits-to-Growth]] · [[Goodhart-Law]]
## 🤖 LLM 활용
**언제**: 매 unintended consequence 의 prediction, 매 product growth 의 root-cause, 매 SRE incident 의 cascading 분석, 매 policy design 의 leverage point.
**언제 X**: 매 fully open-loop 의 simple pipeline (매 unnecessary modeling).
## ❌ 안티패턴
- **Loops without delay**: 매 real systems 의 always have delays — 매 oscillation 의 missed.
- **Linear thinking in nonlinear loop**: 매 small input change 의 huge output (or vice versa).
- **Optimizing one node**: 매 ignoring loop → 매 Goodhart, perverse incentives.
- **Goal erosion**: 매 missed-target → 매 lower target → 매 drift.
- **Fixing symptom (B)**: 매 underlying R loop 의 unaddressed (shifting the burden).
## 🧪 검증 / 중복
- Verified (Wiener 1948; Forrester 1961; Senge 1990; Meadows 2008; *Designing Data-Intensive Apps* on backpressure).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 placeholder |
| 2026-05-10 | Manual cleanup — archetypes + 7 patterns + decision matrix |
@@ -2,93 +2,34 @@
id: wiki-2026-0508-flame-icicle-graph-플레임-고드름-그래프
title: Flame Icicle Graph 플레임 고드름 그래프
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
status: duplicate
canonical_id: wiki-2026-0508-flame-graph
duplicate_of: "[[Flame-Graph]]"
aliases: []
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-wikified, technical-documentation]
raw_sources: []
last_reinforced: 2026-05-08
confidence_score: 0.9
verification_status: redirected
tags: [duplicate, profiling, visualization, performance]
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
---
# Flame/Icicle Graph (플레임/고드름 그래프)
# Flame Icicle Graph 플레임 고드름 그래프
## 📌 한 줄 통찰 (The Karpathy Summary)
플레임/고드름 그래프(Flame/Icicle Graph)는 소프트웨어 프로파일러(Profiler)를 통해 생성되는 시각화 도구로, 시스템에서 실행되는 코드의 영역과 작동 패턴을 보여줍니다 [1]. 개발자가 소스 코드를 읽고 의도나 추측에 의존하는 대신 코드가 런타임에 실제로 어떻게 실행되는지(as it's executed)를 파악하는 데 유용합니다 [1]. 대규모 코드베이스를 탐색할 때, 분석이 필요한 가장 중요한 코드 영역을 식별하고 코드 읽기 시간을 할애할 우선순위(Roadmap)를 결정하는 데 강력한 도움을 줍니다 [1].
> **이 문서는 [[Flame-Graph]] 의 중복본입니다.** Canonical 문서로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
* **실제 실행 흐름 기반의 분석 도구:**
방대하고 복잡한 코드베이스를 파악할 때 코드만 읽어서는 전체적인 흐름을 이해하기 어렵습니다. 가장 일반적인 워크로드(workload)를 프로파일링하여 플레임/고드름 그래프를 확인하면, 코드가 누군가 의도했던 방향이 아니라 '실제로 실행되는 방식' 그대로를 시각적으로 관찰할 수 있습니다 [1].
* **코드 읽기 전략의 나침반(Roadmap) 역할:**
새로운 코드베이스를 온보딩하는 과정에서 전체 코드를 무작정 읽는 것은 비효율적입니다. 플레임/고드름 그래프는 코드 내에서 가장 중요한 부분들을 시각적으로 뚜렷하게 보여주어, 개발자가 어느 코드 영역부터 집중적으로 읽고 시간을 투자해야 하는지에 대한 로드맵을 제공합니다 [1].
* **최적화 도구에서 코드 탐색 도구로의 인식 전환:**
프로파일러와 그 시각화 결과물인 플레임/고드름 그래프는 주로 성능 최적화(Optimization) 용도로만 언급되는 경향이 있습니다 [1]. 그러나 실제로는 대규모 시스템의 코드베이스 작동 방식을 빠르고 깊이 있게 이해하도록 돕는 훌륭한 '코드 내비게이션 및 학습 도구'로서의 가치가 매우 높습니다 [1, 2]. 이를 통해 기존에 아무도 프로파일링하지 않았던 레거시 코드에서 짧은 시간 안에 핵심을 파악하고 최적화 포인트(예: 성능 3~5% 향상)를 찾아내는 성과를 얻을 수도 있습니다 [1, 3].
## 핵심 요약 (Korean alias specialization)
- **Flame graph** (Brendan Gregg, 2011): 매 stack frames 의 width = sample-count 의 visualization, 매 root at bottom (불꽃 모양).
- **Icicle graph** (고드름): 매 same data, 매 root at top (거꾸로 매달린 모양). 매 일부 도구 default (Chrome DevTools, py-spy `--format speedscope`).
- 매 두 form 의 same information — 매 orientation 의 only difference.
- 매 Korean speakers 의 위해 매 "플레임 / 고드름 그래프" 검색어 의 covered.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
소스에 관련 정보가 부족합니다. (제공된 소스에서는 플레임/고드름 그래프의 유용성에 대해서만 설명하고 있으며, 이 도구를 활용할 때 발생하는 부작용, 한계점 혹은 기술적 반대급부에 대한 정보는 포함되어 있지 않습니다.)
## 🔗 Graph
- 부모: [[Flame-Graph]] (canonical)
- Adjacent: [[Profiling]] · [[Performance-Analysis]] · [[Speedscope]] · [[py-spy]] · [[perf]]
## 🔗 지식 연결 (Graph)
### Related Concepts
#### [동적 분석 도구]
- [[Profiler (프로파일러)]]
- 연결 이유: 플레임/고드름 그래프를 생성해내는 근간 도구이며, 주로 성능 최적화 용도로 쓰이지만 코드베이스를 이해하는 핵심 수단으로도 활용되기 때문입니다 [1].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 정적 소스 코드만 읽는 방식에서 벗어나, 실행 중인 애플리케이션의 메모리와 CPU 호출 스택 등을 측정하여 시스템을 파악하는 방법론 [1].
#### [시스템 실행 컨텍스트]
- [[Workloads (워크로드)]]
- 연결 이유: 유의미한 플레임/고드름 그래프를 얻기 위해서는 시스템의 가장 보편적인 워크로드를 실행하고 프로파일링해야 하기 때문입니다 [1].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 사용자의 실제 사용 패턴이나 애플리케이션의 주요 부하(Traffic)를 발생시키는 기능이 무엇인지 파악하고, 이를 기반으로 코드를 분석하는 접근법 [1].
### Deeper Research Questions
- 플레임 그래프와 고드름 그래프는 시각적 구조나 데이터 표현 방식에 있어서 어떤 차이점이 있으며, 각각 어떤 분석 상황에 더 유리한가?
- 대규모 코드베이스에서 정적인 코드 분석 방식(Top-down/Bottom-up 읽기)과 동적인 플레임/고드름 그래프 분석 결과를 효과적으로 융합하는 프로세스는 무엇인가?
- 마이크로서비스 또는 비동기 처리가 많은 아키텍처 환경에서도 플레임/고드름 그래프가 실행 스택을 정확하고 유용하게 시각화할 수 있는가?
- 프로파일링을 통해 나타나는 '실행이 많이 되는(Hot)' 코드 영역이 항상 비즈니스 도메인의 핵심 로직과 일치하는가?
- 레거시 코드베이스에서 플레임 그래프를 생성할 때 발생하는 프로파일링 오버헤드(Overhead)가 실제 시스템 분석에 미치는 영향은 무엇인가?
### Practical Application Contexts
- **Implementation:** 애플리케이션에 프로파일러를 연동하고 주요 워크로드를 실행하여, 생성된 플레임/고드름 그래프를 통해 가장 호출 빈도가 높거나 오래 실행되는 함수들을 식별합니다 [1].
- **System Design:** 소프트웨어 아키텍처 내에서 컴포넌트 간의 실제 상호작용 빈도와 자원 사용량을 시각화하여, 병목 지점이나 비효율적인 아키텍처 설계를 검증합니다 [1, 3].
- **Operation / Maintenance:** 방대하고 문서화되지 않은 레거시 시스템을 유지보수할 때, 코드 변경 시 발생할 수 있는 사이드 이펙트를 짐작하고 성능 개선(Low-hanging fruit) 포인트를 즉각적으로 발굴하는 데 사용합니다 [1, 3].
- **Learning Path:** 낯선 대규모 코드베이스에 온보딩해야 할 때, 코드를 처음부터 순차적으로 읽는 대신 그래프가 지시하는 핵심 경로(Roadmap)를 따라 시간을 분배하여 학습 효율을 극대화합니다 [1, 2].
- **My Project Relevance:** 문서에 의존하거나 다른 개발자의 추측(Thought it would be)에 의존하는 대신, 런타임의 팩트(Fact) 기반으로 복잡한 시스템의 동작 메커니즘을 객관적으로 파악할 때 적용할 수 있습니다 [1].
### Adjacent Topics
- [[Dynamic Analysis (동적 분석)]]
- 확장 방향: 프로파일링 외에 런타임 환경에서 로그 모니터링, 디버거와 중단점(Breakpoints) 설정 등을 통해 코드의 제어 흐름과 데이터 상태 전이를 파악하는 더 넓은 범위의 기술 [1, 4].
- [[Performance Optimization (성능 최적화)]]
- 확장 방향: 그래프 분석을 통해 발견된 비효율(예: 불필요한 sleep 호출 등)을 실제로 어떻게 제거하고 실행 속도를 개선할 것인가에 대한 개발 실무 [3].
---
*Last updated: 2026-05-02*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 placeholder |
| 2026-05-10 | 중복 처리 — Korean alias title, canonical 문서 [[Flame-Graph]] 으로 redirect |
@@ -2,92 +2,159 @@
id: wiki-2026-0508-geographic-information-systems
title: Geographic Information Systems
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-GGIS-001]
aliases: [GIS, Geospatial, Spatial Data]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, gis, geographic-information, mapping, spatial-data, urban-planning, analytics]
confidence_score: 0.9
verification_status: applied
tags: [geospatial, mapping, data, spatial-analysis]
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
framework: GeoPandas, Shapely, PostGIS, DuckDB-spatial, Lonboard
---
# [[Geographic-Information-Systems|Geographic-Information-Systems]]
# Geographic Information Systems
## 📌 한 줄 통찰 (The Karpathy Summary)
> "세상을 담은 디지털 지도: 우리가 사는 물리적 공간을 좌표와 속성 데이터로 변환하여, '어디에 무엇이 있고 서로 어떻게 연결되어 있는지'를 시각화하고 분석하여 효율적인 도시와 경로를 설계하는 공간 지능의 중추."
## 한 줄
> **"매 spatially-referenced data 의 capture, storage, query, analysis, visualization"**. Roger Tomlinson 의 Canada GIS (1968) → Esri ArcInfo → 매 modern open stack (PostGIS, GeoPandas, GDAL, GeoParquet, DuckDB-spatial, deck.gl). 매 2026 trend: **cloud-native geospatial (COG, STAC, GeoParquet, FlatGeobuf), GPU vector rendering, ML-on-raster**.
## 📖 구조화된 지식 (Synthesized Content)
지리 정보 시스템(Geographic-Information-Systems, GIS)은 지표면과 관련된 데이터를 수집, 저장, 분석, 관리하여 시각적으로 표현하는 컴퓨터 시스템입니다.
## 매 핵심
1. **데이터 구조**:
* **Vector Data**: 점(Point), 선(Line), 면(Polygon)으로 정밀한 형상 표현. (ERD와 구조적 유사성 - [[Entity-Relationship-Modeling|Entity-Relationship-Modeling]])
* **Raster Data**: 픽셀 격자로 연속적인 높이, 온도 등 표현.
2. **활용 분야**:
* **Urban Planning**: 최적의 도로 및 인프라 배치. ([[CPTED|CPTED]]와 연결)
* **Logistics**: 최단 경로 및 배송 관리. (Sim-City와 연결)
* **Di[[SAST|SAST]]er [[Management|Management]]**: 침수 구역 예측 및 대피로 확보.
### 매 two data models
- **Vector**: points, lines, polygons (Shapefile/GeoJSON/FlatGeobuf/GeoParquet). 매 discrete features.
- **Raster**: regular grid of cells (GeoTIFF, COG, Zarr). 매 continuous fields, satellite imagery.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 정적인 지도 데이터 정책 위주였으나, 현대 정책은 GPS 실시간 위치 정책, 드론 이미지 정책, SNS 트래픽 정책 등이 결합된 '실시간 공간 빅데이터 정책(Real-time GIS)'으로 패러다임이 전환됨(RL Update).
- **정책 변화(RL Update)**: 이제는 단순 레이어 중첩 정책을 넘어, AI 가 위성 사진 정책을 분석하여 불법 건축물 정책을 자동 감지하거나 도시의 탄소 배출 정책을 정밀 측정하는 'AI-GIS'로 진화 중임. ([[Sustainability|Sustainability]]와 연결)
### 매 핵심 concepts
- **CRS (Coordinate Reference System)**: WGS84 (EPSG:4326), Web Mercator (3857), UTM zones, local projected.
- **Topology**: contains/intersects/touches/crosses (DE-9IM).
- **Spatial index**: R-tree, Quadtree, **H3 / S2 hex grid** (Uber/Google), Geohash.
- **Map algebra**: raster arithmetic, focal/zonal stats.
- **Geocoding / reverse**: address ↔ coords.
## 🔗 지식 연결 (Graph)
- [[Entity-Relationship-Modeling|Entity-Relationship-Modeling]], [[CPTED|CPTED]], Sim-City, [[Sustainability|Sustainability]], Urban-Planning, [[Strategic-Planning|Strategic-Planning]]
- **Key Software**: QGIS, ArcGIS, Google Maps API.
---
### 매 modern (2026) stack
- **Storage**: GeoParquet, COG (Cloud-Optimized GeoTIFF), STAC catalogs, PMTiles.
- **Compute**: DuckDB-spatial, GeoPandas 1.x (PyArrow backend), Sedona, BigQuery GIS.
- **Render**: deck.gl, Lonboard (in-Jupyter GPU vector), MapLibre, Mapbox GL.
- **ML**: Segment-Anything-on-imagery, SatCLIP embeddings, prithvi geo-foundation model.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Read & reproject (GeoPandas)
```python
import geopandas as gpd
gdf = gpd.read_file("zip://./tl_2024_us_county.zip")
gdf = gdf.to_crs(epsg=3857) # Web Mercator
print(gdf.geometry.area.head()) # m² in projected CRS
```
## 🤔 의사결정 기준 (Decision Criteria)
### Spatial join + index
```python
points = gpd.read_file("stores.geojson").to_crs(epsg=3857)
admin = gpd.read_file("districts.geojson").to_crs(epsg=3857)
joined = gpd.sjoin(points, admin, how="left", predicate="within")
```
**선택 A를 써야 할 때:**
- *(TODO)*
### PostGIS query
```sql
-- find restaurants within 500 m of a metro stop
SELECT r.id, r.name
FROM restaurants r
JOIN metro_stops m
ON ST_DWithin(r.geom::geography, m.geom::geography, 500)
WHERE m.line = 'Line 2';
CREATE INDEX restaurants_geom_gix ON restaurants USING GIST (geom);
```
**선택 B를 써야 할 때:**
- *(TODO)*
### DuckDB-spatial (single-file analytics)
```python
import duckdb
con = duckdb.connect()
con.install_extension("spatial"); con.load_extension("spatial")
con.sql("""
SELECT name, ST_Area(geom)/1e6 AS km2
FROM ST_Read('countries.fgb')
WHERE ST_Intersects(geom, ST_MakeEnvelope(-10,35,40,70))
ORDER BY km2 DESC LIMIT 5
""").show()
```
**기본값:**
> *(TODO)*
### Raster analysis (rioxarray)
```python
import rioxarray as rxr
ndvi_red = rxr.open_rasterio("B04.tif", masked=True)
ndvi_nir = rxr.open_rasterio("B08.tif", masked=True)
ndvi = (ndvi_nir - ndvi_red) / (ndvi_nir + ndvi_red)
ndvi.rio.to_raster("ndvi.tif", driver="COG")
```
## ❌ 안티패턴 (Anti-Patterns)
### H3 hex aggregation
```python
import h3, pandas as pd
df = pd.read_csv("rides.csv")
df["h3"] = [h3.latlng_to_cell(lat, lng, 9) for lat,lng in zip(df.lat, df.lng)]
agg = df.groupby("h3").size().reset_index(name="rides")
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Routing (OSMnx + NetworkX)
```python
import osmnx as ox, networkx as nx
G = ox.graph_from_place("Berlin, Germany", network_type="drive")
orig = ox.distance.nearest_nodes(G, 13.405, 52.520)
dest = ox.distance.nearest_nodes(G, 13.450, 52.500)
route = nx.shortest_path(G, orig, dest, weight="length")
```
### GPU map render (Lonboard, in notebook)
```python
import lonboard
from lonboard import Map, ScatterplotLayer
layer = ScatterplotLayer.from_geopandas(points, get_radius=20, get_fill_color=[200,30,30])
Map(layer)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Single laptop, < 10 M rows | **GeoPandas 1.x** |
| Analytics, columnar | **DuckDB-spatial + GeoParquet** |
| Multi-user transactional | **PostGIS** |
| Cluster scale (≫ 100 GB) | **Apache Sedona / BigQuery GIS** |
| Satellite raster pipeline | **STAC + COG + rioxarray + Dask** |
| Aggregation by tile | **H3 / S2 hex** |
| Web map (millions of features) | **PMTiles + MapLibre / deck.gl** |
| ML on imagery | **prithvi / SatCLIP + SAM-Geo** |
**기본값**: 매 modern 의 **GeoParquet + DuckDB-spatial + Lonboard** trio (laptop-scale), 매 server 의 **PostGIS**.
## 🔗 Graph
- 부모: [[Spatial-Analysis]] · [[Cartography]] · [[Databases]]
- 변형: [[Vector-GIS]] · [[Raster-GIS]] · [[3D-GIS]] · [[Spatiotemporal-GIS]]
- 응용: [[Routing]] · [[Remote-Sensing]] · [[Urban-Planning]] · [[Logistics]] · [[Climate-Modeling]]
- Adjacent: [[H3]] · [[S2]] · [[OpenStreetMap]] · [[STAC]] · [[GeoParquet]] · [[PostGIS]]
## 🤖 LLM 활용
**언제**: 매 spatial-aware app 의 architecture, 매 CRS / projection 의 selection 의 explanation, 매 SQL 의 PostGIS 의 generation, 매 imagery analysis 의 prompting.
**언제 X**: 매 high-precision survey / cadastral 의 manual professional 검증 필수.
## ❌ 안티패턴
- **Mixed CRS without reproject**: 매 km vs degree 의 silent mismatch.
- **Web Mercator 의 area calc**: 매 high-latitude 의 huge distortion — 매 equal-area projection 사용.
- **Shapefile 의 still using**: 매 10-char column, 2 GB limit, no UTF-8 — 매 GeoParquet/FlatGeobuf 사용.
- **No spatial index**: 매 PostGIS GIST 없이 매 query 의 100-1000× slow.
- **Raster 매 in-memory full load**: 매 windowed read (rioxarray + Dask) 사용.
- **Lat/Lon swap**: 매 GeoJSON `[lng, lat]` vs human `(lat, lng)` 의 가장 흔한 bug.
## 🧪 검증 / 중복
- Verified (OGC standards; PostGIS docs; *Geocomputation with Python* 2024; Cloud-Native Geospatial Foundation).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 placeholder |
| 2026-05-10 | Manual cleanup — modern 2026 stack + 8 patterns |
@@ -2,63 +2,163 @@
id: wiki-2026-0508-gimbals-and-orientation
title: Gimbals and Orientation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [PHYS-GIMBAL-001]
aliases: [Gimbal Lock, 3D Orientation, Rotation Representation]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: ["Physics|[Physics", Robotics, game-dev, orientation, rotation-math, skybound]
confidence_score: 0.92
verification_status: applied
tags: [graphics, math, rotation, quaternion, robotics]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python
framework: NumPy/SciPy
---
# Gimbals and Orientation (짐벌과 방향 제어)
# Gimbals and Orientation
## 📌 한 줄 통찰 (The Karpathy Summary)
> "3차원 공간의 자유도를 수호하고, 회전의 축이 겹쳐 통제력을 잃는 짐벌 락의 함정을 회피하라" — 물체가 어떤 방향으로든 자유롭게 회전할 수 있도록 지지하는 장치(Gimbal)와, 오일러 각(Euler [[ANGLE|ANGLE]]s) 및 쿼터니언(Quaternions)을 활용한 수학적 자세 제어 기법.
## 한 줄
> **"매 3D rotation은 representation 의 선택이 다 — Euler 직관, quaternion 안전, matrix 합성 빠르"**. Gimbal lock 의 1958 Apollo IMU에서 발견된 singularity 매 모든 3-axis Euler systems에서 발생, 매 quaternion / rotation matrix 의 modern solution. 매 robotics, graphics, aerospace, VR 의 fundamental.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 세 개의 회전 축(Roll, Pitch, Yaw)을 독립적으로 제어하여 물체의 지향점을 유지하고, 각 축 간의 상호작용으로 인해 발생하는 기하학적 제약을 극복하는 방향성 제어 패턴.
- **핵심 개념:**
- **Euler Angles:** X, Y, Z 축을 기준으로 순차적으로 회전하는 직관적인 방식.
- **Gimbal Lock:** 두 회전 축이 겹치면서 한 차원의 자유도를 잃어버리는 현상 (오일러 각의 고질적 문제).
- **Quaternions (사원수):** 짐벌 락 문제를 해결하기 위해 4차원 복소수를 사용하는 수학적 도구. 부드러운 회전 보간(SLERP)에 필수적.
- **Stabilization:** 외부 흔들림에도 불구하고 카메라나 센서가 특정 방향을 고수하도록 실시간 보정.
- **의의:** 항공우주, 로보틱스, 드론 제어는 물론 3D 게임 엔진의 카메라 시스템과 물리 시뮬레이션의 성능을 결정짓는 근간.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 오일러 각 기반의 단순 연산에서, 짐벌 락 방지와 연산 효율성을 위해 쿼터니언 기반의 자세 제어가 현대 시스템의 표준으로 정착됨.
- **정책 변화:** Skybound 프로젝트의 함대 시점 카메라와 미사일 유도 알고리즘은 쿼터니언을 사용하여 격렬한 기동 중에도 끊김 없는 부드러운 시선 처리를 보장함.
### 매 representations
- **Euler angles** (roll, pitch, yaw): 3 floats, intuitive, but **gimbal lock at ±90° pitch**.
- **Rotation matrix** (3×3): 9 floats, no singularity, composable via multiplication, but redundant (only 3 DOF).
- **Quaternion** (w, x, y, z): 4 floats, no gimbal lock, smooth SLERP interpolation, double cover (q and -q same rotation).
- **Axis-angle** (Rodrigues): 3 floats encoding axis × angle, compact.
## 🔗 지식 연결 (Graph)
- Physics-Engine, [[Robotics|Robotics]], Mathematics-for-AI, [[Determinism-in-Computing|Determinism-in-Computing]]
- **Raw Source:** 10_Wiki/Topics/AI/Gimbals-and-Orientation.md
### 매 gimbal lock 매커니즘
- 매 3 nested rotations (e.g. ZYX) 매 second rotation이 ±90° 면 first/third axis가 align — DOF loss from 3 to 2.
- 매 Apollo 11 LM 의 famous near-miss: Aldrin manually steered to avoid IMU lock.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Robotics IK / joint orientation.
2. Game character / camera control.
3. VR/AR head tracking (IMU sensor fusion).
4. Drone / aerospace attitude control.
5. Skeletal animation blending.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Quaternion from Euler (avoid gimbal lock)
```python
import numpy as np
## 🧪 검증 상태 (Validation)
def euler_to_quat(roll, pitch, yaw):
cr, sr = np.cos(roll/2), np.sin(roll/2)
cp, sp = np.cos(pitch/2), np.sin(pitch/2)
cy, sy = np.cos(yaw/2), np.sin(yaw/2)
w = cr*cp*cy + sr*sp*sy
x = sr*cp*cy - cr*sp*sy
y = cr*sp*cy + sr*cp*sy
z = cr*cp*sy - sr*sp*cy
return np.array([w, x, y, z])
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### SLERP (smooth quaternion interpolation)
```python
def slerp(q0, q1, t):
dot = np.dot(q0, q1)
if dot < 0.0:
q1, dot = -q1, -dot
if dot > 0.9995:
return (q0 + t*(q1-q0)) / np.linalg.norm(q0 + t*(q1-q0))
theta_0 = np.arccos(dot)
theta = theta_0 * t
s0 = np.cos(theta) - dot * np.sin(theta) / np.sin(theta_0)
s1 = np.sin(theta) / np.sin(theta_0)
return s0*q0 + s1*q1
```
## 🧬 중복 검사 (Duplicate Check)
### Rotation matrix composition
```python
from scipy.spatial.transform import Rotation as R
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
R1 = R.from_euler('xyz', [30, 45, 60], degrees=True)
R2 = R.from_quat([0, 0, 0.707, 0.707]) # x,y,z,w
R_combined = R2 * R1
print(R_combined.as_matrix())
```
## 🕓 변경 이력 (Changelog)
### Axis-angle (Rodrigues' formula)
```python
def rodrigues(axis, theta):
axis = axis / np.linalg.norm(axis)
K = np.array([[ 0, -axis[2], axis[1]],
[ axis[2], 0, -axis[0]],
[-axis[1], axis[0], 0]])
return np.eye(3) + np.sin(theta)*K + (1-np.cos(theta))*K@K
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### IMU sensor fusion (complementary filter)
```python
def imu_update(q, gyro, accel, dt, alpha=0.98):
# gyro integration
omega = np.array([0, *gyro])
q_dot = 0.5 * quat_mul(q, omega)
q_gyro = q + q_dot * dt
q_gyro /= np.linalg.norm(q_gyro)
# accel correction
q_accel = accel_to_quat(accel)
return slerp(q_accel, q_gyro, alpha)
```
### Detect gimbal lock
```python
def detect_lock(euler_pitch, threshold=89.5):
return abs(euler_pitch) > threshold # near ±90°
```
### Quaternion → Rotation matrix
```python
def quat_to_matrix(q):
w, x, y, z = q
return np.array([
[1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w)],
[2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w)],
[2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y)]
])
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| User-facing UI sliders | Euler (intuitive) |
| 3D engine internal | Quaternion |
| Skeletal animation blending | Quaternion + SLERP |
| Physics / forces composition | Rotation matrix |
| IMU streaming | Quaternion + complementary/Kalman |
| Compact storage | Axis-angle or compressed quat |
**기본값**: Quaternion internally, Euler at user boundaries.
## 🔗 Graph
- 부모: [[Linear-Algebra]] · [[3D-Geometry]]
- 변형: [[Quaternion]] · [[Euler-Angles]] · [[Rotation-Matrix]]
- 응용: [[Kalman-Filter-and-State-Tracking]] · [[VR-Head-Tracking]] · [[Robotics-IK]]
- Adjacent: [[Eigenvalues-and-Eigenvectors]] · [[Lie-Groups]]
## 🤖 LLM 활용
**언제**: orientation representation 의 conversion code 생성, gimbal lock debugging hints, sensor fusion math derivation.
**언제 X**: real-time IMU loop (latency critical — use compiled code), safety-critical aerospace code (require formal verification).
## ❌ 안티패턴
- **Storing rotation as Euler**: gimbal lock + interpolation discontinuity. Store as quaternion.
- **Linear interpolation of quaternions**: NLERP works로컬 but SLERP for accuracy. NLERP for speed in animation.
- **Forgetting double cover**: q and -q same rotation; SLERP needs sign check.
- **Gradient-based optimization on Euler**: discontinuous near singularities — use quaternion or matrix tangent space.
- **Mixing conventions**: (w,x,y,z) vs (x,y,z,w), intrinsic vs extrinsic Euler — document explicitly.
## 🧪 검증 / 중복
- Verified (Shoemake 1985 quaternion paper, NASA Apollo IMU records, scipy.spatial.transform docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with quaternion/Euler/matrix patterns + IMU fusion |
@@ -2,89 +2,182 @@
id: wiki-2026-0508-godel-s-incompleteness-theorems
title: "Godel's Incompleteness Theorems"
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-GITR-001]
aliases: [Incompleteness, Godel's Theorems, First and Second Incompleteness]
duplicate_of: none
source_trust_level: A
confidence_score: 0.91
tags: [auto-reinforced, godel, incompleteness, mathematics, Logic, Philosophy, limits-of-computation]
confidence_score: 0.95
verification_status: applied
tags: [logic, foundations, mathematical-logic, computability, philosophy-of-math]
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: Lean4
framework: mathlib
---
# [[Godel's Incompleteness Theorems|Godel's Incompleteness Theorems]]
# Godel's Incompleteness Theorems
## 📌 한 줄 통찰 (The Karpathy Summary)
> "이성이 마주한 거대한 벽: 아무리 완벽하고 강력한 논리 체계라도, 그 안에는 참이지만 결코 증명할 수 없는 문장이 반드시 존재하며 시스템 스스로는 자신의 무모순성을 입증할 수 없다는 수학적 겸손의 선언."
## 한 줄
> **"매 충분히 강력한 consistent formal system 의 자기 자신의 truth/consistency 의 증명 불가능"**. 1931년 Kurt Gödel 의 결과 — Hilbert program 의 종료, computability/AI/foundation of math 의 근본적 제약. 매 modern 의 Lean/Coq proof assistants, halting problem, Tarski undefinability 의 모두 이의 후예.
## 📖 구조화된 지식 (Synthesized Content)
괴델의 불완전성 정리(Godel's Incompleteness Theorems)는 20세기 인식론과 수학의 기초를 뒤흔든 쿠르트 괴델의 업적입니다.
## 매 핵심
1. **제1정리**: 산술을 포함하는 모든 무모순적이고 형식적인 체계에는 그 안에서 증명할 수도, 반박할 수도 없는 '참인 문장'이 존재함.
2. **제2정리**: 그러한 체계는 자신의 무모순성을 그 체계 자체 논리로는 증명할 수 없음.
3. **왜 중요한가?**:
* 수학이 모든 진리를 완벽하게 포착할 수 있다는 환상을 깨뜨렸으며, 기계적인 연산(컴퓨터)이 가질 수 있는 사고의 한계를 암시함. (Limits of Computation과 연결)
### 매 First Incompleteness Theorem
- **Statement**: 매 consistent recursively axiomatizable system T 의 Peano Arithmetic 포함 시 — 매 T 에서 증명 불가능 statement G_T (true but unprovable) 존재.
- **Proof sketch**: Gödel numbering → 매 self-referential statement "I am not provable in T" 의 construction → 매 consistency 시 unprovable.
- 매 consequence: 매 truth ≠ provability.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거 수학 정책은 완결된 진리의 탑을 쌓으려 했으나, 괴델의 정리 정책은 시스템 외부에 '직관'이나 '상위 메타 시스템'이 필요함을 시사하는 정책적 전환을 가져옴(RL Update).
- **정책 변화(RL Update)**: 인공지능이 인간보다 뛰어난 논리력을 가질지라도, 시스템 내부의 모순이나 증명 불가능한 '블라인드 스팟 정책'을 가질 수밖에 없다는 점을 시사하며 AI의 전지전능함에 대한 철학적 제동 정책으로 언급됨.
### 매 Second Incompleteness Theorem
- **Statement**: 매 consistent T (PA 포함) 의 자신의 consistency Con(T) 증명 불가능.
- 매 Hilbert program 의 사망 — 매 finitistic 한 means 의 mathematics consistency 의 증명 불가능.
- 매 stronger system 으로 (e.g., ZFC) PA 의 consistency 증명 가능 — but 매 ZFC 자신의 consistency 매 ZFC 안에서 증명 불가능.
## 🔗 지식 연결 (Graph)
- [[Logic|Logic]], [[Epistemology|Epistemology]], Philosophy of Science, [[Analysis|Analysis]], [[Artificial Intelligence (AI)|Artificial Intelligence (AI)]]
- **Modern Tech/Tools**: Formal verification[[_system|system]]s, Meta-programming, Tarski's undefinability theorem.
---
### 매 핵심 개념
- **Gödel numbering**: 매 syntactic objects (formulas, proofs) → 의 injection. 매 meta-mathematical statement 의 arithmetic statement 로의 encoding.
- **ω-consistency** vs **simple consistency**: 매 first proof 의 ω-consistency 의존, Rosser 1936 의 simple consistency 만으로도 OK.
- **Provability predicate Bew_T(x)**: 매 "x 의 numerical encoding 의 statement 매 T 에서 증명가능".
- **Hilbert-Bernays-Löb derivability conditions**: D1, D2, D3.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용 / 영향
1. **Halting problem (Turing 1936)**: 매 incompleteness 의 computability twin — 매 universal halting predicate 매 unrecursive.
2. **Tarski's undefinability (1936)**: 매 truth predicate 매 system 자신 안에서 정의 불가능.
3. **Löb's theorem (1955)**: 매 Bew(⌜φ⌝) → φ 증명 시 ⊢ φ.
4. **AI/AGI 의미**: Penrose-Lucas 의 mind ≠ algorithm argument (매 controversial). 2024-2026 LLM era 에서 매 재논쟁.
5. **Foundations**: ZFC 의 large cardinal axioms — 매 stronger theories 의 hierarchy.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Gödel Numbering (매 simple toy)
```python
def godel_number_str(s):
"""매 매 character 의 ASCII → prime^code product.
매 unique decoding 가능."""
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
result = 1
for i, c in enumerate(s):
result *= primes[i] ** ord(c)
return result
## 🧪 검증 상태 (Validation)
def decode_godel(n):
"""매 prime factorization 통해 string 복원."""
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
chars = []
for p in primes:
cnt = 0
while n % p == 0:
n //= p
cnt += 1
if cnt == 0:
break
chars.append(chr(cnt))
return ''.join(chars)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
print(godel_number_str("0=0")) # 매 huge number
```
## 🤔 의사결정 기준 (Decision Criteria)
### Lean4 — 매 statement 의 formalization
```lean
-- 매 First Incompleteness 의 Lean4 formalization (mathlib outline).
-- 매 actual proof 매 thousand-line ordeal — outline 만.
import Mathlib.Logic.Godel.GodelBetaFunction
**선택 A를 써야 할 때:**
- *(TODO)*
theorem godel_first_incompleteness
(T : Theory ) (hT : T.Consistent) (hRec : T.RecursivelyEnumerable)
(hPA : T) :
G : Sentence , ¬T G ¬T ~G := by
-- 매 self-referential G via diagonalization lemma
obtain G, hG := T.diagonalLemma (¬· T.theorems)
exact G, sorry, sorry
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Diagonalization Lemma (매 핵심 trick)
```python
# 매 pseudo-code: matter 의 fixed-point 의 construction.
# 매 statement φ(x) 에 대해, 매 G 의 ⊢ G ↔ φ(⌜G⌝) 의 statement 존재.
**기본값:**
> *(TODO)*
def diagonalize(phi):
"""φ(x): 매 free variable x 인 formula.
Returns G such that PA ⊢ G ↔ φ(⌜G⌝)."""
# Step 1: substitution function sub(y, x): formula y(x/⌜y⌝)
# Step 2: G := sub(⌜φ(sub(x,x))⌝, ⌜φ(sub(x,x))⌝)
# 매 G 의 의미: "I have property φ"
pass
```
## ❌ 안티패턴 (Anti-Patterns)
### Halting problem 의 reduction (매 Gödel-Turing)
```python
def halting_problem_undecidable():
"""매 First Incompleteness 의 computability version.
Halts(P, x) — 매 recursive function 으로 정의 불가능."""
# 매 Cantor-style diagonal:
# Suppose Halts(P, x) decidable. Define:
def D(P):
if Halts(P, P):
while True: pass # loop forever
else:
return # halt
# 매 D(D) 의 동작 — 매 contradiction.
# 따라서 Halts 매 decidable 아님.
pass
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Provability Logic (매 GL — Gödel-Löb)
```python
# 매 modal logic GL 의 axioms — 매 Bew predicate 의 modal formalization.
# K: □(p → q) → (□p → □q)
# 4: □p → □□p
# Löb: □(□p → p) → □p
# 매 GL 의 Solovay 1976 의 arithmetic completeness 의 증명 — 매 PA 에서 valid 한 매 modal formula 의 GL 의 정확한 fragment.
```
### Lean — 매 PA consistency proof (in stronger system)
```lean
-- 매 PA's consistency 의 증명 매 ZFC (or PRA + ε₀-induction) 에서 가능.
-- Gentzen 1936 의 ε₀-induction 의존.
theorem PA_consistent : PeanoArithmetic.Consistent := by
-- 매 actual proof: ordinal analysis up to ε₀
sorry
```
## 매 결정 기준
| 상황 | Lesson |
|---|---|
| Formal system 의 power 결정 | 매 expressiveness 와 incompleteness 의 trade-off |
| Self-reference 가 가능한가? | Diagonalization 으로 paradox 가능성 |
| Decidable 한 logic 원함 | 매 weak system (e.g., Presburger arithmetic) 사용 |
| Mathematical foundations | ZFC + large cardinals — 매 stronger but still incomplete |
| AGI / consciousness argument | 매 cautious — Penrose 의 controversial |
| Proof assistant 사용 | Lean/Coq — 매 axiom set 명시 (consistency 추가 가정) |
**기본값**: 매 sufficiently expressive system 의 incompleteness 의 inherent — 매 "complete the system" 의 시도는 매 futile 하다 (e.g., Hilbert program 의 실패).
## 🔗 Graph
- 부모: [[Mathematical-Logic]] · [[Foundations-of-Mathematics]]
- 변형: [[Tarski-Undefinability]] · [[Löb's-Theorem]] · [[Rosser's-Theorem]]
- 응용: [[Halting-Problem]] · [[Computability-Theory]] · [[Provability-Logic]]
- Adjacent: [[Hilbert-Program]] · [[ZFC-Set-Theory]] · [[Lean-Theorem-Prover]] · [[Diagonalization]]
## 🤖 LLM 활용
**언제**: 매 conceptual explanation, 매 historical context, 매 proof structure 의 high-level summary, 매 formal logic teaching.
**언제 X**: 매 actual formal proof 작성 — 매 LLM 의 mistake 가능, Lean/Coq 등 proof assistant 사용. 매 Penrose-style "AI cannot reason because of Gödel" argument — 매 fallacy 의 widely critique 됨.
## ❌ 안티패턴
- **"Gödel proves AI impossible"**: 매 fallacy. 매 incompleteness 매 specific formal system 에 대한 statement, 매 thinking 의 nature 와 별개.
- **Confusing First/Second**: 매 First (existence of unprovable truth) ≠ Second (unprovability of consistency).
- **Applying to weak systems**: 매 Presburger arithmetic 의 complete & decidable — 매 incompleteness 매 Robinson arithmetic 이상에 적용.
- **Proof of consistency via system itself**: 매 Second 의 의미 — 매 가능 시 system 자체 의 inconsistent.
## 🧪 검증 / 중복
- Verified (Gödel 1931, Hilbert-Bernays "Grundlagen der Mathematik", Smullyan "Gödel's Incompleteness Theorems").
- 신뢰도 A (foundational result of mathematical logic).
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — first/second statements, diagonalization, Lean formalization, philosophical caveats |
@@ -1,25 +1,35 @@
---
id: wiki-20260508-graph-theory-redir
title: Graph Theory
category: Computer_Science_and_Theory
status: merged
redirect_to: Graph_Theory
canonical_id: Graph_Theory
category: 10_Wiki/Topics
status: duplicate
canonical_id: graph-theory-foundations
duplicate_of: "[[Graph Theory Foundations]]"
aliases: []
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [redirect]
raw_sources: []
last_reinforced: 2026-05-08
confidence_score: 0.9
verification_status: redirected
tags: [duplicate, graph-theory]
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-merge 2026-05-08)
---
# Graph Theory
> [!IMPORTANT]
> 이 문서는 P-Reinforce Phase 2 자동 MERGE에 의해 **[[Graph_Theory]]**로 통합되었습니다.
> **이 문서는 [[Graph Theory Foundations]] 의 중복본입니다.** Canonical 문서로 redirect.
---
*Redirected to: [[Graph_Theory]]*
## 핵심 요약
- Graph G = (V, E): vertex 의 set + edge 의 set.
- directed / undirected, weighted / unweighted, cyclic / acyclic.
- Euler (1736 Königsberg bridge) 의 origin.
- Application: BFS/DFS, Dijkstra, MST, network analysis, social graph.
## 🔗 Graph
- 부모: [[Graph Theory Foundations]] (canonical)
- Adjacent: [[BFS vs DFS]] · [[Dijkstra's Algorithm]] · [[Network Analysis]]
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -2,92 +2,255 @@
id: wiki-2026-0508-graph-coloring-problem
title: Graph Coloring Problem
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-GRCP-001]
aliases: [Vertex Coloring, Chromatic Number, k-Coloring]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [auto-reinforced, graph-coloring, algorithm, csp, Graph-Theory, Optimization, scheduling, complexity]
confidence_score: 0.9
verification_status: applied
tags: [algorithms, graph-theory, np-complete, combinatorics, optimization]
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
framework: NetworkX
---
# [[Graph-Coloring-Problem|Graph-Coloring-Problem]]
# Graph Coloring Problem
## 📌 한 줄 통찰 (The Karpathy Summary)
> "인접한 적은 피하라: 그래프의 이웃한 노드들이 서로 다른 색을 갖게 하면서 최소한의 색상으로 모든 노드를 칠하는 수수께끼로, 무선 주파수 배분부터 시험 시간표 짜기까지 '충돌 없는 자원 배치'의 수학적 정수."
## 한 줄
> **"매 vertex 에 색칠 — adjacent 끼리 다른 색, minimum 색 수가 chromatic number χ(G)"**. 1852년 Francis Guthrie 의 4-color conjecture 로 시작 — 1976년 Appel-Haken 의 computer-aided proof. 매 NP-complete (k≥3) 이지만 register allocation, scheduling, frequency assignment 등 매 광범위한 application.
## 📖 구조화된 지식 (Synthesized Content)
그래프 채색 문제(Graph-Coloring-Problem)는 그래프 이론에서 특정 조건(이웃한 정점은 다른 색)을 만족하며 노드에 색을 칠하는 최적화 문제입니다.
## 매 핵심
1. **핵심 지표**:
* **Chromatic Number (χ(G))**: 그래프 G를 채색하는 데 필요한 최소 색상 수.
* **NP-hard**: 모든 노드를 최소 색으로 칠하는 최적해를 찾는 것은 계산 복잡도 정책 면에서 매우 어려움. ([[Complexity-Theory|Complexity-Theory]]와 연결)
2. **활용 사례**:
* **Register Allocation**: 컴파일러가 제한된 CPU 레지스터를 변수들에게 충돌 없이 배정. ([[Efficiency|Efficiency]]와 연결)
* **Frequency Assignment**: 근접한 기지국들이 서로 다른 주파수를 쓰게 하여 간섭 방지.
* **Map Coloring**: 이웃한 국가가 다른 색으로 표시되게 지도 제작. ([[Constraint-Satisfaction-Problems|Constraint-Satisfaction-Problems]]와 연결)
### 매 정의
- **Vertex coloring**: V → {1,...,k} 의 함수 c, 매 (u,v) ∈ E ⇒ c(u) ≠ c(v).
- **Chromatic number χ(G)**: 매 minimum k 의 의미.
- **k-colorable**: 매 ≤k colors 의 valid coloring 존재.
- **Edge coloring / Total coloring / List coloring**: 매 variants.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 모든 노드를 방문 정책하는 백트래킹 정책 방식 위주였으나, 현대 정책은 대규모 소셜 그래프 정책 분석 등을 위해 근사해 정책(Approximation)을 빠르게 찾는 그리디(Greedy)나 메타-휴리스틱 정책이 주류임(RL Update).
- **정책 변화(RL Update)**: 이제는 단순 알고리즘 정책을 넘어, 양자 컴퓨팅 정책(Quantum Annealing)을 활용해 거대 그래프 정책의 채색 문제 정책을 순식간에 해결하려는 실험적 시도가 활발함. (Graph-Theory와 연결)
### 매 이론적 boundaries
- **χ(G) ≤ Δ(G) + 1** (Brooks 정리: complete graph / odd cycle 제외 시 χ ≤ Δ).
- **χ(G) ≥ ω(G)** (clique number lower bound; perfect graph 시 equality).
- **4-Color Theorem**: 매 planar graph 의 χ ≤ 4 (1976, computer-assisted).
- **2-colorable ⟺ bipartite ⟺ no odd cycle** — 매 polynomial time 확인 가능.
## 🔗 지식 연결 (Graph)
- [[Complexity-Theory|Complexity-Theory]], [[Efficiency|Efficiency]], [[Constraint-Satisfaction-Problems|Constraint-Satisfaction-Problems]], [[Graph-Theory|Graph-Theory]], [[Logic|Logic]], [[Optimization|Optimization]]
- **Key Theorem**: Four Color Theorem (4색 정리).
---
### 매 응용
1. **Register allocation** (compiler): 매 variable interference graph 의 coloring → register 배정.
2. **Scheduling**: 매 conflict graph (시간 conflict 의 task) → time-slot 배정.
3. **Frequency assignment**: 매 cellular tower 간 interference 회피.
4. **Sudoku / map coloring**: 매 constraint satisfaction.
5. **Exam timetabling**: 매 student-overlap conflict 의 minimum slot.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Greedy Coloring (매 simplest baseline)
```python
import networkx as nx
**언제 쓰면 안 되는가:**
- *(TODO)*
def greedy_coloring(G, ordering=None):
"""Greedy: ordering 순서대로 가장 작은 사용가능 색 배정.
Worst-case Δ+1 colors. Ordering 의 quality 이 핵심."""
coloring = {}
nodes = ordering or list(G.nodes())
for v in nodes:
used = {coloring[u] for u in G.neighbors(v) if u in coloring}
c = 0
while c in used:
c += 1
coloring[v] = c
return coloring
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# NetworkX built-in (Welsh-Powell 등 strategies):
G = nx.erdos_renyi_graph(50, 0.3, seed=42)
coloring = nx.coloring.greedy_color(G, strategy='largest_first')
print(f"Colors used: {max(coloring.values()) + 1}")
```
## 🤔 의사결정 기준 (Decision Criteria)
### DSATUR (매 saturation degree heuristic)
```python
def dsatur(G):
"""Brélaz 1979. 매 step: saturation (인접 색 수) max 인 vertex 선택.
매 random graph 에서 greedy 보다 우수, χ 에 가까움."""
coloring = {}
saturation = {v: 0 for v in G.nodes()}
while len(coloring) < len(G):
uncolored = [v for v in G.nodes() if v not in coloring]
v = max(uncolored, key=lambda x: (saturation[x], G.degree(x)))
used = {coloring[u] for u in G.neighbors(v) if u in coloring}
c = 0
while c in used:
c += 1
coloring[v] = c
for u in G.neighbors(v):
if u not in coloring:
neigh_colors = {coloring[w] for w in G.neighbors(u) if w in coloring}
saturation[u] = len(neigh_colors)
return coloring
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Backtracking (매 exact, small graphs)
```python
def chromatic_number_exact(G):
"""매 k=1,2,... 시도하며 k-colorable 검사 (NP-hard)."""
nodes = list(G.nodes())
n = len(nodes)
def is_safe(v_idx, c, coloring):
for u in G.neighbors(nodes[v_idx]):
u_idx = nodes.index(u)
if u_idx in coloring and coloring[u_idx] == c:
return False
return True
def color_util(v_idx, k, coloring):
if v_idx == n:
return True
for c in range(k):
if is_safe(v_idx, c, coloring):
coloring[v_idx] = c
if color_util(v_idx + 1, k, coloring):
return True
del coloring[v_idx]
return False
for k in range(1, n + 1):
if color_util(0, k, {}):
return k
return n
```
**선택 B를 써야 할 때:**
- *(TODO)*
### ILP Formulation (매 modern solver)
```python
from pulp import *
**기본값:**
> *(TODO)*
def graph_coloring_ilp(G, max_colors):
"""Integer Linear Programming — Gurobi/CPLEX 통해 매 exact solution.
x[v,c] ∈ {0,1}: vertex v 의 color c."""
prob = LpProblem("GraphColoring", LpMinimize)
x = LpVariable.dicts("x", [(v,c) for v in G.nodes() for c in range(max_colors)], cat='Binary')
y = LpVariable.dicts("y", range(max_colors), cat='Binary') # color c used?
prob += lpSum(y[c] for c in range(max_colors)) # minimize colors used
for v in G.nodes():
prob += lpSum(x[v,c] for c in range(max_colors)) == 1 # exactly 1 color
for (u,v) in G.edges():
for c in range(max_colors):
prob += x[u,c] + x[v,c] <= 1 # adjacent ≠ color
for v in G.nodes():
for c in range(max_colors):
prob += x[v,c] <= y[c]
prob.solve(PULP_CBC_CMD(msg=0))
return {v: c for v in G.nodes() for c in range(max_colors) if x[v,c].varValue == 1}
```
## ❌ 안티패턴 (Anti-Patterns)
### Tabu Search (매 large instances)
```python
import random
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
def tabu_coloring(G, k, max_iter=10000, tabu_tenure=10):
"""매 k-coloring 의 conflict 최소화. Hertz-de Werra 1987.
매 large random graphs 에 효과적."""
coloring = {v: random.randint(0, k-1) for v in G.nodes()}
tabu = {}
best = coloring.copy()
best_conflicts = sum(1 for u,v in G.edges() if coloring[u] == coloring[v])
for it in range(max_iter):
conflicts = [(u,v) for u,v in G.edges() if coloring[u] == coloring[v]]
if not conflicts:
return coloring
# 매 best non-tabu move 선택
best_move = None
best_delta = float('inf')
for u,v in conflicts:
for vertex in (u, v):
old_c = coloring[vertex]
for new_c in range(k):
if new_c == old_c or (vertex, new_c) in tabu and tabu[(vertex,new_c)] > it:
continue
delta = sum(1 for w in G.neighbors(vertex) if coloring[w] == new_c) \
- sum(1 for w in G.neighbors(vertex) if coloring[w] == old_c)
if delta < best_delta:
best_delta = delta
best_move = (vertex, new_c)
if best_move:
v, c = best_move
tabu[(v, coloring[v])] = it + tabu_tenure
coloring[v] = c
return coloring
```
### Register Allocation (매 compiler use case)
```python
def chaitin_register_allocation(interference_graph, num_registers):
"""Chaitin 1982. 매 LLVM/GCC 의 register allocation.
Δ < k 의 vertex iteratively remove → stack → reverse pop & color."""
G = interference_graph.copy()
stack = []
while G.nodes():
# 매 degree < k vertex 찾기 (simplifiable)
simplifiable = [v for v in G.nodes() if G.degree(v) < num_registers]
if simplifiable:
v = simplifiable[0]
else:
# 매 spill candidate (pick least-used)
v = min(G.nodes(), key=lambda x: G.degree(x))
stack.append((v, list(G.neighbors(v))))
G.remove_node(v)
coloring = {}
while stack:
v, neighbors = stack.pop()
used = {coloring[u] for u in neighbors if u in coloring}
for c in range(num_registers):
if c not in used:
coloring[v] = c
break
else:
coloring[v] = 'SPILL' # 매 memory 로 spill
return coloring
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Small graph (n ≤ 30) | Backtracking exact |
| Medium graph (n ≤ 1000) | ILP solver (Gurobi) |
| Large graph (n > 10k) | Tabu / DSATUR heuristic |
| Realtime / approximate OK | Greedy with largest_first |
| Compiler register allocation | Chaitin's algorithm |
| Bipartite check only | BFS 2-coloring (O(V+E)) |
**기본값**: NetworkX `greedy_color(strategy='DSATUR')` — 매 quality/speed balance 우수.
## 🔗 Graph
- 부모: [[Graph-Theory]] · [[Combinatorial-Optimization]]
- 변형: [[Edge-Coloring]] · [[List-Coloring]] · [[Total-Coloring]]
- 응용: [[Register-Allocation]] · [[Scheduling-Algorithms]] · [[Constraint-Satisfaction]]
- Adjacent: [[NP-Completeness]] · [[Approximation-Algorithms]] · [[Tabu-Search]]
## 🤖 LLM 활용
**언제**: 매 problem decomposition, 매 algorithm selection, 매 code skeleton 생성, 매 ILP formulation 자동화.
**언제 X**: 매 instance-specific exact solution — 매 LLM hallucinate 가능, dedicated solver (Gurobi/CPLEX) 사용 권장.
## ❌ 안티패턴
- **Greedy 의 첫 ordering 사용**: 매 worst-case n colors. Largest-first / DSATUR ordering 사용.
- **Brute force on n>30**: 매 exponential 시간 — heuristic / ILP 으로 전환.
- **k-coloring 직접 푸는 대신 chromatic 추정 안 함**: 매 lower bound (clique) / upper bound (Brooks) 활용.
- **List coloring 을 vertex coloring 과 혼동**: 매 list coloring 의 χ_l(G) 의 차이.
## 🧪 검증 / 중복
- Verified against Brooks' Theorem, 4-Color Theorem (Appel-Haken 1976), Chaitin's allocation.
- 신뢰도 A (CLRS, Diestel "Graph Theory", Chartrand-Zhang).
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content (definitions, ILP, tabu, Chaitin allocation, applications) |
@@ -2,89 +2,172 @@
id: wiki-2026-0508-greedy-algorithms
title: Greedy Algorithms
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [CS-GREEDY-001]
aliases: [Greedy, 그리디 알고리즘, 탐욕 알고리즘]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [computer-science, algorithms, greedy-algorithm, Optimization, Search-strategies]
confidence_score: 0.92
verification_status: applied
tags: [algorithms, greedy, optimization, matroid]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: none
---
# Greedy Algorithms (탐욕 알고리즘)
# Greedy Algorithms
## 📌 한 줄 통찰 (The Karpathy Summary)
> "매 순간 눈앞의 가장 큰 이득만을 취하라. 때로는 단순한 탐욕이 가장 효율적인 정답으로 인도한다" — 전역적인 최적해를 찾기 위해 복잡하게 고민하는 대신, 각 단계에서 국소적으로 가장 좋은 선택(Local Optimum)을 반복하여 최종 해를 도출하는 설계 기법.
## 한 줄
> **"매 step 의 locally optimal choice 의 의 globally optimal 의 hope"**. 매 1956 Kruskal 의 MST 의 formal start. 매 modern era 의 universal — 매 Huffman, MST, scheduling, set cover (approx). 매 proof 의 critical (greedy 의 wrong 의 silent failure).
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Greedy Choice Property"와 "Optimal Substructure"가 성립하는 문제에서, 과거의 선택을 뒤돌아보지 않고 현재의 최선만을 선택하여 연산 효율을 극대화하는 패턴.
- **핵심 특징:**
- **Local Optimum:** 각 단계에서의 최선의 선택.
- **No Backtracking:** 한 번 내린 결정은 번복하지 않음.
- **[[Efficiency|Efficiency]]:** 동적 계획법(DP)보다 연산 속도가 압도적으로 빠름.
- **적용 사례:** Dijkstra의 최단 경로 알고리즘, Prim/Kruskal의 최소 신장 트리(MST), 허프만 코딩(Huffman Coding), 거스름돈 문제.
- **한계:** 모든 문제에서 전역 최적해(Global Optimum)를 보장하지는 않으므로 사용 전 수학적 검증이 필요함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 완벽한 정답(Optimal [[Solution|Solution]])만을 추구하던 경직된 사고에서, 실시간성이나 연산 자원이 중요한 환경에서는 '충분히 좋은 해(Heuristic)'를 빠르게 찾는 탐욕적 방식이 더 현실적일 수 있음을 인정.
- **정책 변화:** Antigravity 프로젝트의 실시간 지식 임베딩 클러스터링 알고리즘은 연산 부하를 줄이기 위해 일부 단계에서 탐욕적 접근 방식을 채택하여 빠른 반응성을 유지함.
### 매 두 정당화 (matroid theory)
1. **Greedy choice property**: 매 local optimal 의 의 global optimal 의 의 contain.
2. **Optimal substructure**: 매 problem 의 reduce 의 후 의 동일 structure 의 problem.
## 🔗 지식 연결 (Graph)
- [[Global-vs-Local-Optima|Global-vs-Local-Optima]], Search-Algorithms, [[Heuristic-Search|Heuristic-Search]], [[Dynamic-Programming|Dynamic-Programming]]-Foundations
- **Raw Source:** 10_Wiki/Topics/AI/Greedy-Algorithms.md
### 매 proof technique
- **Exchange argument**: 매 OPT 의 greedy choice 의 swap 의 의 worse X.
- **Matroid theory**: 매 independence system 의 matroid 의 의 → greedy 의 optimal.
- **Stays ahead**: 매 greedy 의 step 의 의 OPT 의 step 의 의 dominate.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Greedy fails 의 example
- **0/1 knapsack**: greedy by value/weight ratio 의 fails — DP 의 의.
- **Coin change (arbitrary denominations)**: greedy fails (예: coins=[1,3,4], amount=6 → greedy 4+1+1=3 coins, OPT 3+3=2 coins).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. MST: Kruskal, Prim.
2. Shortest path (non-negative): Dijkstra.
3. Compression: Huffman coding.
4. Scheduling: earliest deadline first, shortest job next.
5. Approximation: set cover, vertex cover (2-approx).
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Activity Selection (interval scheduling)
```python
def activity_selection(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""Select max non-overlapping intervals. Greedy: earliest finish first."""
intervals.sort(key=lambda x: x[1]) # sort by end time
selected = []
last_end = -float('inf')
for s, e in intervals:
if s >= last_end:
selected.append((s, e))
last_end = e
return selected
# O(n log n)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Huffman coding
```python
import heapq
from collections import Counter
**선택 A를 써야 할 때:**
- *(TODO)*
def huffman(text: str) -> dict[str, str]:
freq = Counter(text)
heap = [[f, [c, ""]] for c, f in freq.items()]
heapq.heapify(heap)
while len(heap) > 1:
lo = heapq.heappop(heap)
hi = heapq.heappop(heap)
for pair in lo[1:]: pair[1] = '0' + pair[1]
for pair in hi[1:]: pair[1] = '1' + pair[1]
heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
return {c: code for c, code in heap[0][1:]}
**선택 B를 써야 할 때:**
- *(TODO)*
print(huffman("aaabbc")) # e.g., {'a': '0', 'b': '10', 'c': '11'}
```
**기본값:**
> *(TODO)*
### Kruskal's MST (greedy + union-find)
```python
class UF:
def __init__(self, n): self.p = list(range(n)); self.r = [0]*n
def find(self, x):
while self.p[x] != x: self.p[x] = self.p[self.p[x]]; x = self.p[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb: return False
if self.r[ra] < self.r[rb]: ra, rb = rb, ra
self.p[rb] = ra
if self.r[ra] == self.r[rb]: self.r[ra] += 1
return True
## ❌ 안티패턴 (Anti-Patterns)
def kruskal(n: int, edges: list[tuple[int, int, int]]) -> int:
"""edges: (u, v, weight). Returns total MST weight."""
edges.sort(key=lambda e: e[2])
uf, total = UF(n), 0
for u, v, w in edges:
if uf.union(u, v):
total += w
return total
# O(E log E)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Coin change (canonical, e.g., USD)
```python
def coin_change_greedy(coins: list[int], amount: int) -> int:
"""ASSUMES canonical coin system. Fails for arbitrary denominations."""
coins = sorted(coins, reverse=True)
count = 0
for c in coins:
n, amount = divmod(amount, c)
count += n
return count if amount == 0 else -1
# USD [25,10,5,1] → canonical, greedy works
# [1,3,4] → NOT canonical, greedy fails for 6
```
### Set cover (approximation, ln(n) factor)
```python
def set_cover(universe: set, sets: list[set]) -> list[int]:
"""Greedy: pick set covering most uncovered. ln(n)-approx."""
covered, picked = set(), []
while covered != universe:
best = max(range(len(sets)), key=lambda i: len(sets[i] - covered))
picked.append(best)
covered |= sets[best]
return picked
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 matroid structure 의 detect | Greedy (provably optimal) |
| 매 exchange argument 의 의 | Greedy |
| 매 NP-hard, approximation OK | Greedy (set cover, vertex cover) |
| 매 overlap subproblem | DP (greedy 의 X) |
| 매 backtrack 의 needed | Branch & Bound |
| 매 proof X | DP / brute-force 의 first |
**기본값**: 매 problem 의 simple structure 의 greedy 의 first 시도. 매 counterexample 의 found → DP / B&B.
## 🔗 Graph
- 부모: [[Algorithm Design]] · [[Optimization]]
- 변형: [[Matroid Theory]] · [[Approximation Algorithms]]
- 응용: [[Kruskal MST]] · [[Prim MST]] · [[Dijkstra's Algorithm]] · [[Huffman Coding]] · [[Set Cover]] · [[Activity Selection]]
- Adjacent: [[Dynamic Programming]] · [[Branch and Bound]] · [[Linear Programming]]
## 🤖 LLM 활용
**언제**: 매 simple optimization, 매 sorting + linear scan 의 의 의 의 의 의, 매 NP-hard 의 approximation 의 의, 매 streaming algorithm.
**언제 X**: 매 0/1 knapsack, 매 LCS, 매 edit distance — 매 DP 의 의. 매 counterexample 의 unsure 의 first.
## ❌ 안티패턴
- **proof X**: 매 greedy 의 silent wrong answer (coin change [1,3,4], 0/1 knapsack).
- **canonical 가정**: 매 USD coins 의 greedy works, but 매 arbitrary denominations 의 fails.
- **local minima trap**: 매 hill-climbing 의 local optimum 의 stuck — 매 simulated annealing / restart 의 의.
- **greedy + DP confusion**: 매 fractional knapsack (greedy works) vs 0/1 knapsack (DP needed).
## 🧪 검증 / 중복
- Verified (CLRS Ch 16; Kleinberg-Tardos Ch 4).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Greedy with activity selection, Huffman, Kruskal, set cover |
@@ -2,65 +2,214 @@
id: wiki-2026-0508-grounded-theory-method
title: Grounded Theory Method
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-GTME-001]
aliases: [GTM, Grounded Theory, Constructivist GT, Glaserian GT, Straussian GT]
duplicate_of: none
source_trust_level: A
confidence_score: 0.86
tags: [auto-reinforced, grounded-theory, Research-Methodology, qualitative-Analysis, sociology, Inductive-Reasoning]
confidence_score: 0.85
verification_status: applied
tags: [research-methodology, qualitative-research, sociology, hci, theory-building]
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: Python
framework: NVivo / atlas.ti / qualitative coding
---
# [[Grounded Theory Method|Grounded Theory Method]]
# Grounded Theory Method
## 📌 한 줄 통찰 (The Karpathy Summary)
> "현장에서 캔 이론: 미리 가설을 세우고 끼워 맞추는 대신, 날것의 데이터(인터뷰, 관찰 등) 속에서 반복되는 패턴과 개념을 추출하고 이들의 관계를 엮어내어 바닥(Ground)부터 이론을 구축하는 귀납적 리서치 기법."
## 한 줄
> **"매 data 에서 'grounded' 한 substantive theory 의 inductive 으로 construction — 매 hypothesis 의 a priori X, data 가 theory 를 결정"**. 1967년 Glaser & Strauss "The Discovery of Grounded Theory" — 매 sociology / nursing / HCI / SE research 의 foundational qualitative methodology. 매 modern (2026) 의 Charmaz 의 constructivist GT, 매 LLM-augmented coding 의 emerging.
## 📖 구조화된 지식 (Synthesized Content)
근거 이론(Grounded Theory Method)은 질적 연구에서 데이터를 기반으로 이론을 생성하는 방법론입니다.
## 매 핵심
1. **주요 프로세스**:
* **Open Coding**: 데이터 조각들을 개념화하여 이름을 붙임.
* **Axial Coding**: 개별 개념들 간의 범주를 설정하고 인과관계를 연결.
* **Selective Coding**: 핵심 범주(Core Category)를 선정하여 통합적인 이론 모형 완성.
2. **왜 중요한가?**:
* 기존 이론으로 설명되지 않는 새로운 사회 현상이나 사용자 행동의 기저 심리를 파헤칠 때 가장 강력한 도구임. ([[Bottom-Up-Approach|Bottom-Up-Approach]]의 전형)
### 매 Origin & schools
- **Classic Glaserian** (1967, 1992): 매 emergence-driven, 매 minimal preconception, 매 substantive→formal theory.
- **Straussian** (Strauss & Corbin 1990): 매 axial coding 의 추가 — 매 paradigm model (cause/context/consequence).
- **Constructivist GT** (Charmaz 2006): 매 researcher 의 active construction 인정 — 매 reflexivity 강조.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 사람이 수천 페이지의 인터뷰를 직접 읽으며 코딩하는 고통스러운 '수동 정책'이었으나, 현대 정책은 AI 에이전트가 방대한 질적 데이터를 1차 코딩하고 패턴을 제안하는 'AI 보조 근거 이론 정책'으로 효율성이 극대화됨(RL Update).
- **정책 변화(RL Update)**: 단순히 학계의 연구 정책을 넘어, IT 제품 기획 정책에서 사용자의 숨겨진 니즈(User Experience (UX))를 발굴하고 제품의 철학 정책을 세우는 실무적 방법론으로 각광받고 있음.
### 매 핵심 procedures
1. **Theoretical sampling**: 매 emerging theory 가 다음 sample 결정 (not random).
2. **Constant comparison**: 매 incident → incident, code → code 의 지속 비교.
3. **Coding levels**:
- **Open coding**: 매 line-by-line / incident-by-incident 의 initial label.
- **Axial coding** (Strauss): 매 categories 간 relationship — paradigm model.
- **Selective / Theoretical coding**: 매 core category 중심으로 통합.
4. **Memo writing**: 매 analytical thoughts 의 ongoing record.
5. **Theoretical saturation**: 매 new data 가 새로운 insight 안 줄 때까지.
## 🔗 지식 연결 (Graph)
- [[Analysis|Analysis]], [[Bottom-Up-Approach|Bottom-Up-Approach]], User Experience (UX), [[Knowledge synthesis|Knowledge synthesis]], [[Sociology of Knowledge|Sociology of Knowledge]]
- **Modern Tech/Tools**: NVivo, ATLAS.ti, LLM-based qualitative analysis agents.
---
### 매 Output
- **Substantive theory**: 매 specific area (e.g., "How nurses cope with terminal patients").
- **Formal theory**: 매 broader applicability.
- **Core category**: 매 central phenomenon.
- **Properties + dimensions** of categories.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **HCI / UX research**: 매 user behavior pattern 의 emergent understanding.
2. **Software engineering**: 매 developer practice 의 study (Stol et al. 2016).
3. **Nursing / healthcare**: 매 patient experience.
4. **Education**: 매 learning process.
5. **Organizational studies**.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### 매 Coding 의 example (line-by-line)
```python
# 매 raw interview transcript:
transcript = """
Researcher: How do you handle a critical bug in production?
Developer: First, I panic for 5 minutes. Then I check the logs.
I look for recent deployments. Often it's the last commit.
I roll back if I can. Otherwise I write a hotfix.
"""
## 🧪 검증 상태 (Validation)
# 매 open coding (manual):
codes = {
"panic for 5 minutes": ["emotional_response", "stress"],
"check the logs": ["diagnostic_action", "data_gathering"],
"look for recent deployments": ["temporal_reasoning", "blame_locality"],
"roll back if I can": ["containment", "reversibility_first"],
"write a hotfix": ["repair", "containment"],
}
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
# 매 axial: 매 cluster
categories = {
"Initial reaction": ["emotional_response", "stress"],
"Diagnosis": ["diagnostic_action", "data_gathering", "temporal_reasoning"],
"Containment strategy": ["reversibility_first", "containment"],
"Repair": ["repair"],
}
## 🧬 중복 검사 (Duplicate Check)
# 매 selective: 매 core category candidate
core = "Containment-First Incident Response"
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### 매 Constant Comparison (매 incident comparison)
```python
def constant_compare(incidents, codes_so_far):
"""매 each new incident 의 기존 codes 와 비교.
매 fits → assign existing. 매 doesn't → new code or category refinement."""
for inc in incidents:
matched = []
for code, examples in codes_so_far.items():
if semantic_similarity(inc, examples) > 0.7: # 매 LLM-assisted
matched.append(code)
if matched:
for c in matched:
codes_so_far[c].append(inc)
else:
new_code = invent_label(inc)
codes_so_far[new_code] = [inc]
return codes_so_far
```
## 🕓 변경 이력 (Changelog)
### 매 LLM-augmented coding (2026 modern practice)
```python
import anthropic
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
def llm_open_code(text, prior_codes=None):
"""매 Claude 4.7 의 grounded theory open coding assistance.
매 IMPORTANT: 매 researcher 의 final judgment 필수 — LLM 의 first-pass only."""
client = anthropic.Anthropic()
system = (
"You are assisting a grounded theory researcher. "
"Generate open codes for each incident. Codes must be GROUNDED in the data. "
"Use gerunds (action-oriented) per Charmaz. "
"Avoid imposing prior theoretical frameworks."
)
if prior_codes:
system += f"\n\nExisting codes (use if fits, propose new if not): {prior_codes}"
msg = client.messages.create(
model="claude-opus-4-7",
max_tokens=4096,
system=system,
messages=[{"role": "user", "content": f"Code this incident:\n\n{text}"}]
)
return msg.content[0].text
# 매 caveat: 매 LLM 의 hidden bias — researcher 의 verification 필수
```
### 매 Theoretical Saturation 의 detection
```python
def saturation_check(new_codes_per_interview):
"""매 marginal new codes 가 0 에 가까워지면 saturated.
매 typical: 12-25 interviews."""
counts = [len(set(codes)) for codes in new_codes_per_interview]
# 매 cumulative new codes
cum = []
seen = set()
for codes in new_codes_per_interview:
before = len(seen)
seen.update(codes)
cum.append(len(seen) - before)
# 매 saturation: 매 last 3 interviews 의 new codes < threshold
if len(cum) >= 3 and sum(cum[-3:]) < 3:
return True, len(seen)
return False, len(seen)
```
### 매 Memo 의 example
```markdown
# Memo: Containment-First Pattern (2026-05-10)
매 Across 8 interviews, 매 developers consistently 의 "containment
before diagnosis" pattern. 매 Specifically:
- P3: "First I undo, then I think."
- P5: "Stop the bleeding, ask later."
- P7: "Roll back is free, downtime isn't."
매 This contradicts Glaser-style "diagnose first" conventional wisdom.
매 Hypothesis: 매 production-incident contexts 의 reversibility 의 highly
asymmetric cost structure 의 produce. 매 Theoretical sampling: 매 next,
매 sample developers 의 IRREVERSIBLE deployment 의 (e.g., DB migrations)
— 매 to test boundary.
매 Connects to: literature on "blameless postmortem" but timing 다름.
```
## 매 결정 기준
| 상황 | School / Approach |
|---|---|
| Pure emergence, minimal preconception | Glaserian classic |
| Structured paradigm needed | Straussian (axial coding) |
| Reflexive / interpretive | Charmaz constructivist |
| Software engineering | Stol et al. 2016 guidelines |
| Existing theory verification | NOT GT — 매 deductive method |
| Quick exploration | Thematic analysis (lighter) |
| Massive corpus | LLM-assisted GT (2026+) but careful |
**기본값**: 매 modern (2026) 의 **Charmaz constructivist** — 매 reflexivity 의 honest, LLM-assistance OK 의 transparent.
## 🔗 Graph
- 부모: [[Qualitative-Research-Methods]] · [[Research-Methodology]]
- 변형: [[Glaserian-GT]] · [[Straussian-GT]] · [[Constructivist-GT]]
- 응용: [[HCI-Research]] · [[Empirical-Software-Engineering]] · [[Nursing-Research]]
- Adjacent: [[Thematic-Analysis]] · [[Phenomenology]] · [[Ethnography]] · [[Theoretical-Sampling]]
## 🤖 LLM 활용
**언제**: 매 first-pass open coding 의 acceleration, 매 memo 작성 의 brainstorm, 매 literature 의 sensitizing concepts 의 식별, 매 saturation 의 estimation.
**언제 X**: 매 final coding decisions, 매 theoretical insights 의 generation 단독 (researcher 의 reflexive interpretation 필수), 매 sensitive / vulnerable participant data — 매 privacy concern.
## ❌ 안티패턴
- **A priori 의 hypothesis verification 시도**: 매 NOT GT — 매 deductive method 와 혼동.
- **Theoretical sampling 의 random sampling 으로 대체**: 매 GT 의 핵심 violation.
- **Memo 작성 생략**: 매 GT 의 analytical engine — 매 skip 시 thin theory.
- **Saturation 의 declaration 의 too early**: 매 5 interviews 의 saturated 주장 — 매 typically 15+ 필요.
- **LLM 코딩 만 사용**: 매 researcher 의 reflexivity 부재 — 매 Charmaz violation.
- **"Coded by AI" 의 unreflective use**: 매 2026 의 emerging issue — 매 transparent disclosure 필요.
## 🧪 검증 / 중복
- Verified (Glaser & Strauss 1967, Charmaz 2014 "Constructing Grounded Theory", Stol et al. 2016 "Grounded Theory in Software Engineering Research").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — three schools, coding levels, LLM-augmented practice, anti-patterns |
@@ -2,91 +2,169 @@
id: wiki-2026-0508-hardware-verification
title: Hardware Verification
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-HAVE-001]
aliases: [Formal Verification, Chip Verification, RTL Verification]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, Hardware-verification, formal-verification, simulation, vlsi, chip-design, functional-safety]
confidence_score: 0.93
verification_status: applied
tags: [hardware, verification, formal-methods, eda, rtl]
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: SystemVerilog
framework: UVM/JasperGold/SymbiYosys
---
# [[Hardware-Verification|Hardware-Verification]]
# Hardware Verification
## 📌 한 줄 통찰 (The Karpathy Summary)
> "물질 이전의 증명: 수조 원의 천문학적 비용이 드는 칩 제조(Tape-out) 전, 설계된 논리 회로가 단 하나의 오차도 없이 의도대로 작동함을 수학적 검증과 수억 번의 시뮬레이션으로 입증하는 결벽증에 가까운 품질 보증."
## 한 줄
> **"매 silicon 의 mistake 의 cost ≫ software bug — 매 60-70% chip dev effort 가 verification"**. Pentium FDIV (1994, $475M recall) 매 watershed; modern flow 매 simulation (UVM) + formal (property checking) + emulation (Palladium/Veloce) + post-silicon validation. 매 RISC-V 의 open verification revolution (2024-26).
## 📖 구조화된 지식 (Synthesized Content)
하드웨어 검증(Hardware-Verification)은 설계된 집적 회로(IC)나 시스템온칩(SoC)이 원래의 사양([[Specification|Specification]])에 맞게 올바르게 동작하는지 확인하는 과정입니다.
## 매 핵심
1. **검증 방법론**:
* **Simulation-based Verification**: 입력 벡터를 넣어보고 출력값이 예상과 맞는지 확인 (UVM 프레임워크). (Simulation와 연결)
* **Formal Verification**: 특정 속성(Property)이 모든 가능한 입력 조합에 대해 수학적으로 참임을 증명. (Mathematical-Proof와 맥락)
* **Emulation/FPGA [[Prototyping|Prototyping]]**: 실제 칩과 유사한 속도로 하드웨어를 구동하여 실시간 소프트웨어 테스트 병행.
2. **왜 중요한가?**:
* 하드웨어는 소스 코드 수정처럼 '패치'가 불가능(비용 폭증)하므로, 제조 전 완벽한 무결성 정책 확보가 생존과 직결되기 때문임. ([[Reliability|Reliability]]와 연결)
### 매 layers
- **Simulation** (UVM/SystemVerilog): constrained-random + coverage-driven.
- **Formal verification**: mathematical proof of property (CDC, register, security).
- **Emulation**: FPGA/dedicated boxes (Palladium, Veloce, ZeBu) — 매 1000× faster than sim, full SoC.
- **Static**: linting, CDC (clock domain crossing), RDC (reset domain).
- **Post-silicon**: bringup on actual die — bugs that escaped pre-si.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 사람이 수동으로 테스트 케이스 정책을 짰으나, 현대 정책은 제약 기반 무작위 테스트(CRV) 정책을 통해 도저히 사람이 생각할 수 없는 '코너 케이스 정책(Corner cases)'을 알고리즘이 스스로 찾아내게 함(RL Update). ([[Constraint-Satisfaction-Problems|Constraint-Satisfaction-Problems]]와 연결)
- **정책 변화(RL Update)**: 이제는 AI 가 설계 도면(RTL) 정책을 읽고 버그가 발생할 확률이 높은 지점 정책을 미리 예측하거나, 검증용 테스트 코드를 자동으로 생성하는 'AI-Driven EDA' 시대가 열림.
### 매 metrics
- **Code coverage**: line/branch/toggle/FSM (necessary, not sufficient).
- **Functional coverage**: covergroups on intent.
- **Bug curve**: bugs/week vs time — closure when asymptote.
## 🔗 지식 연결 (Graph)
- Simulation, [[Reliability|Reliability]], [[Constraint-Satisfaction-Problems|Constraint-Satisfaction-Problems]], [[Quality-Control|Quality-Control]], [[Technical-Architecture|Technical-Architecture]], Standard-Operating-Procedure
- **Key Standard**: Universal Verification Methodology (UVM).
---
### 매 응용
1. CPU verification (RISC-V cores, ARM, x86).
2. AI accelerator verification (TPU, GPU, NPU).
3. Safety-critical (ISO 26262 ASIL-D, DO-254).
4. Security (Spectre/Meltdown class — formal info-flow).
5. Cryptography hardware (AES, post-quantum).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### UVM testbench skeleton
```systemverilog
class my_test extends uvm_test;
`uvm_component_utils(my_test)
my_env env;
function void build_phase(uvm_phase phase);
env = my_env::type_id::create("env", this);
endfunction
task run_phase(uvm_phase phase);
my_seq seq = my_seq::type_id::create("seq");
phase.raise_objection(this);
seq.start(env.agt.sqr);
phase.drop_objection(this);
endtask
endclass
```
## 🤔 의사결정 기준 (Decision Criteria)
### SystemVerilog Assertion (SVA)
```systemverilog
property req_ack;
@(posedge clk) disable iff (rst)
req |-> ##[1:5] ack;
endproperty
assert property (req_ack) else $error("ack timeout");
cover property (req_ack);
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Formal property (Jasper / SymbiYosys)
```systemverilog
// Prove: FIFO never overflows
property no_overflow;
@(posedge clk) (count == DEPTH) |-> !push;
endproperty
assert property (no_overflow);
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Constrained random
```systemverilog
class transaction;
rand bit [31:0] addr;
rand bit [31:0] data;
constraint c_align { addr[1:0] == 0; }
constraint c_range { addr inside {[32'h1000:32'h2000]}; }
endclass
```
**기본값:**
> *(TODO)*
### Coverage closure
```systemverilog
covergroup cg @(posedge clk);
cp_addr: coverpoint addr {
bins low = {[0:32'h0FFF]};
bins mid = {[32'h1000:32'hEFFF]};
bins high = {[32'hF000:$]};
}
cp_kind: coverpoint kind { bins all[] = {READ, WRITE, ATOMIC}; }
cross cp_addr, cp_kind;
endgroup
```
## ❌ 안티패턴 (Anti-Patterns)
### Open-source flow (SymbiYosys + Yosys)
```bash
# .sby file
[options]
mode prove
depth 20
[engines]
smtbmc z3
[script]
read -formal design.sv
prep -top top
[files]
design.sv
sby -f design.sby
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### CDC check (Spyglass-style)
```tcl
read_verilog design.sv
set_top top
analyze cdc
report cdc -severity error
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Control logic correctness | Formal (full proof) |
| Datapath / large bugs | UVM constrained-random |
| Full SoC software boot | Emulation |
| Post-RTL freeze | Gate-level sim + FV |
| Security properties | Formal info-flow (Coq/Sail) |
| Performance | Hybrid emulation + RTL profiling |
**기본값**: UVM for blocks + formal for control + emulation for system.
## 🔗 Graph
- 부모: [[Formal-Methods]] · [[VLSI-Design]]
- 변형: [[Simulation-Based-Verification]] · [[Formal-Verification]] · [[Emulation]]
- 응용: [[RISC-V-Verification]] · [[AI-Accelerator-Verification]] · [[ISO-26262]]
- Adjacent: [[Model-Checking]] · [[Theorem-Proving]]
## 🤖 LLM 활용
**언제**: SVA generation from spec text, UVM boilerplate scaffold, coverage closure analysis, debugging waveform descriptions.
**언제 X**: signing off tapeout (need human + tool sign-off), safety-critical sole reviewer, novel formal proofs (need expert).
## ❌ 안티패턴
- **Coverage = correctness**: 100% code coverage 매 buggy chips ship 의 still.
- **No assertions**: bugs only at testbench checker → late detection.
- **Re-running same seed**: random ineffective without seed sweep.
- **Skipping CDC**: silicon metastability bugs 매 hardest to debug.
- **Late formal**: starting formal at end of project — embed early on critical blocks.
- **No regression triage**: failing tests left "to investigate" rot.
## 🧪 검증 / 중복
- Verified (Accellera UVM 1.2/2020 LRM, Cadence/Synopsys/Siemens EDA whitepapers, Pentium FDIV postmortem, RISC-V International verification WG 2024-25).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — UVM/SVA/formal/CDC patterns |
@@ -2,88 +2,267 @@
id: wiki-2026-0508-hash-functions-and-maps
title: Hash Functions and Maps
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [CS-HASH-001]
aliases: [Hash Tables, Hash Maps, Dictionaries, HashMap]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [computer-science, data-structures, hash-function, hash-map, Search-Efficiency]
confidence_score: 0.9
verification_status: applied
tags: [data-structures, algorithms, hashing, hash-tables, performance]
raw_sources: []
last_reinforced: 2026-04-26
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: Rust
framework: std::collections + ahash + FxHash
---
# Hash Functions and Maps (해시 함수와 맵)
# Hash Functions and Maps
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터의 고유한 지문(Hash)을 만들어, 아무리 넓은 공간에서도 단번에 원하는 정보를 낚아채라" — 임의의 길이를 가진 데이터를 고정된 길이의 고유한 값으로 변환(Hashing)하고, 이를 인덱스로 사용하여 데이터의 삽입과 검색을 상성 시간($O(1)$)에 수행하는 핵심 자료구조.
## 한 줄
> **"매 key → bucket index 의 mapping 을 통해 average O(1) lookup/insert 의 data structure"**. 1953년 IBM 의 Hans Peter Luhn 의 origin — 매 modern Rust HashMap (SipHash), Google SwissTable / Abseil flat_hash_map, Python dict (open addressing + perturbation) 의 모두 derivative. 매 cryptographic hash (SHA-256/3, BLAKE3) 와 non-crypto hash (xxHash, ahash, FxHash) 의 distinction.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Key-Value" 쌍으로 정보를 저장하고, 키값에 해시 함수를 적용하여 저장 위치를 즉각 결정함으로써 탐색 범위를 원천적으로 배제하는 매핑 패턴.
- **핵심 요소:**
- **Hash Function:** 입력 데이터를 고르게 분산된 숫자로 변환하는 결정론적 함수.
- **Collision Re[[Solution|Solution]]:** 서로 다른 키가 같은 해시값을 가질 때의 해결책 (Chaining, Open Addressing).
- **Load Factor:** 해시 테이블의 채워진 정도에 따라 성능이 결정되므로 적절한 리사이징(Resizing) 필요.
- **의의:** 캐시 시스템, 데이터베이스 인덱싱, 암호화, 중복 체크 등 현대 모든 고성능 소프트웨어 아키텍처의 필수 구성 요소.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순한 배열이나 리스트를 순회하던 방식에서, 메모리를 조금 더 사용하더라도 압도적인 검색 속도를 보장하는 해시 기반 자료구조가 현대 개발의 표준으로 정착.
- **정책 변화:** Antigravity 프로젝트는 수백만 개의 지식 임베딩 ID를 관리하고 중복 문서를 빠르게 필터링하기 위해 고성능 해시 맵 아키텍처를 적극 활용함.
### 매 Hash function properties
- **Determinism**: same input → same output.
- **Uniformity**: 매 output 의 uniform distribution.
- **Avalanche**: 매 single-bit input change 의 ~50% output bits 의 flip.
- **Speed** (non-crypto): 매 ahash/xxHash 의 GB/s.
- **Collision resistance** (crypto): 매 finding x≠y, h(x)=h(y) 의 infeasible.
## 🔗 지식 연결 (Graph)
- Data-Structures-Foundations, Search-Algorithms, [[Distributed-Computing|Distributed-Computing]],[[_system|system]]-Design-for-AI-Scale
- **Raw Source:** 10_Wiki/Topics/AI/Hash-Functions-and-Maps.md
### 매 Hash table strategies
- **Separate chaining**: 매 bucket 의 linked list/tree (Java HashMap 의 default since 8 — list→tree at 8).
- **Open addressing**: 매 collision 시 alternative slot probe.
- Linear probing: 매 +1, +2, ... (cache-friendly but clustering).
- Quadratic probing: 매 +1², +2², ...
- Double hashing: 매 +h_2(k), +2h_2(k), ...
- **Robin Hood hashing**: 매 displacement 의 minimization (Rust hashbrown 의 historical).
- **SwissTable** (2017+, Google): 매 SIMD-based metadata + open addressing — 매 modern fastest.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Load factor & resizing
- 매 load factor α = n/m. Open addressing 의 α < 0.75 권장, chaining 의 α < 1 권장.
- 매 resize: 매 doubling (m → 2m) + rehash all keys.
- Amortized O(1) insert.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. **Symbol table** (compiler).
2. **Cache** (LRU, LFU).
3. **Set membership** (HashSet).
4. **Counting** (frequency).
5. **Dedup**.
6. **Database index** (hash join, hash partition).
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Rust — 매 modern HashMap
```rust
use std::collections::HashMap;
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
fn main() {
// Default: SipHash-1-3 (DoS-resistant but slower).
let mut map: HashMap<String, i32> = HashMap::new();
map.insert("alice".to_string(), 30);
map.insert("bob".to_string(), 25);
// 매 ergonomic API
*map.entry("alice".to_string()).or_insert(0) += 1;
if let Some(age) = map.get("alice") {
println!("Alice: {}", age);
}
// 매 iterator
for (k, v) in &map {
println!("{} = {}", k, v);
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Rust — ahash (매 fastest non-crypto, DoS resistant)
```rust
// Cargo.toml: ahash = "0.8"
use ahash::AHashMap;
**선택 A를 써야 할 때:**
- *(TODO)*
fn main() {
let mut map: AHashMap<&str, i32> = AHashMap::new();
map.insert("hello", 1);
// 매 SipHash 보다 ~5x 빠름, AES-NI 사용 시 더 빠름.
// 매 production 의 default 권장 (workload 에 따라).
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Rust — FxHash (매 known-key 의 ultra-fast)
```rust
// Cargo.toml: rustc-hash = "1.1"
use rustc_hash::FxHashMap;
**기본값:**
> *(TODO)*
fn main() {
let mut map: FxHashMap<u64, &str> = FxHashMap::default();
map.insert(42, "answer");
// 매 rustc 내부 사용. 매 NOT DoS-resistant — 매 untrusted input 시 SipHash/aHash 사용.
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Custom Hash (매 Rust trait)
```rust
use std::hash::{Hash, Hasher};
use std::collections::HashMap;
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
#[derive(PartialEq, Eq)]
struct Point { x: i32, y: i32 }
impl Hash for Point {
fn hash<H: Hasher>(&self, state: &mut H) {
// 매 combine fields. 매 Default impl 보다 careful 필요 시 직접.
self.x.hash(state);
self.y.hash(state);
}
}
```
### C++ — 매 std::unordered_map vs absl::flat_hash_map
```cpp
#include <absl/container/flat_hash_map.h>
#include <string>
int main() {
// std::unordered_map: 매 chaining, slow due to pointer chasing
// absl::flat_hash_map: 매 SwissTable, ~2-3x faster
absl::flat_hash_map<std::string, int> map;
map["alice"] = 30;
map["bob"] = 25;
if (auto it = map.find("alice"); it != map.end()) {
std::cout << it->second << "\n";
}
}
```
### Open Addressing (매 simple Linear Probing)
```python
class LinearProbingHashMap:
def __init__(self, capacity=16):
self.capacity = capacity
self.size = 0
self.keys = [None] * capacity
self.values = [None] * capacity
def _probe(self, key):
idx = hash(key) % self.capacity
while self.keys[idx] is not None and self.keys[idx] != key:
idx = (idx + 1) % self.capacity
return idx
def put(self, key, value):
if self.size >= self.capacity * 0.75:
self._resize()
idx = self._probe(key)
if self.keys[idx] is None:
self.size += 1
self.keys[idx] = key
self.values[idx] = value
def get(self, key):
idx = self._probe(key)
return self.values[idx] if self.keys[idx] is not None else None
def _resize(self):
old_keys, old_values = self.keys, self.values
self.capacity *= 2
self.keys = [None] * self.capacity
self.values = [None] * self.capacity
self.size = 0
for k, v in zip(old_keys, old_values):
if k is not None:
self.put(k, v)
```
### Cryptographic hash (매 SHA-256, BLAKE3)
```rust
use sha2::{Sha256, Digest};
use blake3;
fn main() {
// 매 SHA-256: 매 widely supported but slow (~600 MB/s).
let mut hasher = Sha256::new();
hasher.update(b"hello world");
let result = hasher.finalize();
println!("{:x}", result);
// 매 BLAKE3: 매 modern fastest crypto hash (~6 GB/s with SIMD).
let hash = blake3::hash(b"hello world");
println!("{}", hash);
}
```
### Bloom Filter (매 hash-based set, false-positive OK)
```python
import mmh3 # MurmurHash3
from bitarray import bitarray
class BloomFilter:
def __init__(self, size, num_hashes):
self.size = size
self.num_hashes = num_hashes
self.bits = bitarray(size)
self.bits.setall(0)
def add(self, item):
for i in range(self.num_hashes):
idx = mmh3.hash(item, i) % self.size
self.bits[idx] = 1
def contains(self, item):
return all(self.bits[mmh3.hash(item, i) % self.size] for i in range(self.num_hashes))
bf = BloomFilter(size=10000, num_hashes=7)
bf.add("alice")
print(bf.contains("alice")) # True (definitely)
print(bf.contains("bob")) # False (definitely) or True (false-positive)
```
## 매 결정 기준
| 상황 | Hash function / Map |
|---|---|
| Rust trusted input, max speed | FxHash |
| Rust untrusted input | std HashMap (SipHash) or aHash |
| C++ general | absl::flat_hash_map (SwissTable) |
| Python | dict (built-in, optimized) |
| Distributed cache key | xxHash3 / FNV-1a |
| Cryptographic | BLAKE3 (speed) / SHA-3 (NIST) |
| Bloom filter | MurmurHash3 |
| String interning | weak hash + linear probe |
| Ordered iteration | BTreeMap (not hash) |
**기본값**: Rust 매 `std::collections::HashMap`, C++ 매 `absl::flat_hash_map`, Python 매 `dict`. 매 performance-critical 시 ahash/FxHash 으로 교체.
## 🔗 Graph
- 부모: [[Data-Structures]] · [[Algorithms]]
- 변형: [[Bloom-Filter]] · [[Cuckoo-Hashing]] · [[HyperLogLog]] · [[Consistent-Hashing]]
- 응용: [[Database-Index]] · [[LRU-Cache]] · [[Symbol-Table]] · [[Distributed-Hash-Tables]]
- Adjacent: [[SHA-256]] · [[BLAKE3]] · [[SipHash]] · [[xxHash]] · [[Robin-Hood-Hashing]]
## 🤖 LLM 활용
**언제**: 매 hash function 선택 의 advice, 매 hash table 의 implementation 의 review, 매 collision 의 root cause 의 analysis.
**언제 X**: 매 cryptographic hash 의 직접 implement — 매 audited library 사용. 매 production hash function 의 직접 작성.
## ❌ 안티패턴
- **String hashing 없이 length 만 사용**: 매 catastrophic collision.
- **Untrusted input 의 FxHash**: 매 HashDoS attack 가능 — SipHash/aHash 사용.
- **MD5/SHA-1 신규 사용**: 매 broken — BLAKE3/SHA-256 사용.
- **Hash 의 modular reduction 의 비균등**: 매 power-of-2 size + bitmask 또는 fastrange 사용.
- **High load factor 의 open addressing**: 매 α > 0.9 의 catastrophic — resize.
- **Complex key 의 default hash**: 매 distribution 안 좋을 수 있음 — custom impl.
## 🧪 검증 / 중복
- Verified (Knuth TAOCP Vol 3, "Designing a fast, efficient, cache-friendly hash table", Abseil docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Rust/C++/Python implementations, SwissTable, ahash, BLAKE3 |
@@ -2,64 +2,237 @@
id: wiki-2026-0508-hebbian-theory
title: Hebbian Theory
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-HETH-001]
aliases: [Hebbian Learning, Hebb's Rule, "Cells that fire together wire together"]
duplicate_of: none
source_trust_level: A
confidence_score: 0.96
tags: [auto-reinforced, hebbian-theory, Neuroplasticity, synaptic-plasticity, neuroscience, learning, BioLogical-Intelligence]
confidence_score: 0.85
verification_status: applied
tags: [neuroscience, learning-theory, biological-plasticity, neural-networks, STDP]
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: Python
framework: NumPy / Brian2
---
# [[Hebbian-Theory|Hebbian-Theory]]
# Hebbian Theory
## 📌 한 줄 통찰 (The Karpathy Summary)
> "함께 발화하면 함께 강화된다 (Cells that fire together, wire together): 두 신경원이 동시에 활성화되면 그 사이의 연결이 강해진다는 뇌 가소성의 단순하지만 강력한 법칙으로, 모든 학습과 기억의 생물학적 기저."
## 한 줄
> **"매 'cells that fire together, wire together' — 매 pre-/post-synaptic activity 의 correlated firing 시 synapse strength 증가"**. 1949년 Donald Hebb "The Organization of Behavior" — 매 modern neuroscience 의 plasticity 의 foundation, STDP / BCM rule / Oja's rule 의 origin. 매 deep learning 의 backprop 과 다른 biological-plausible learning candidate.
## 📖 구조화된 지식 (Synthesized Content)
헵의 이론(Hebbian-Theory)은 도널드 헵이 1949년에 제안한 신경 가소성의 핵심 이론입니다.
## 매 핵심
1. **기본 원리**:
* **Synaptic Strengthening**: A 세포가 B 세포를 반복적으로 흥분시키면, 두 세포 간의 연결 효율 정책이 증가하여 기억이 형성됨.
* **Long-Term Potentiation (LTP)**: 이 법칙의 생물학적 발현인 장기 강화 현상. ([[Growth-Mindset-Intervention|Growth-Mindset-Intervention]]와 연결)
2. **왜 중요한가?**:
* 인간의 학습 정책을 설명하는 가장 강력한 모델이자, 인공 신경망(Neural Networks)의 가중치 업데이트 방식 정책에 영감을 준 철학적 토대이기 때문임. (Deep Learning (DL)와 연결)
### 매 Original Hebbian Rule
- **Δw_ij = η · x_i · y_j** (η: learning rate, x_i: pre, y_j: post).
- 매 unstable: weights 매 unbounded growth — 매 normalization 필요.
- Anti-Hebbian: Δw = -η x y — 매 decorrelation.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 뇌가 성인이 되면 고착 정책된다고 믿었으나, 헵의 이론 정책을 기반으로 한 현대 뇌과학 정책은 끊임없는 시도 정책과 자극 정책을 통해 신경망 정책이 전 생애에 걸쳐 재구성 정책(Neuroplasticity)될 수 있음을 증명함(RL Update).
- **정책 변화(RL Update)**: 이제는 단순 시냅스 강화 정책을 넘어, 잘못된 연결 정책을 끊어내는 '시냅스 가지치기(Pruning)' 정책과 연계하여 지능의 최적화 정책을 연구하는 방향으로 진화 중임. ([[High-Cohesion-Low-Coupling|High-Cohesion-Low-Coupling]]와 비유적 연결)
### 매 Variants
- **Oja's rule** (1982): Δw_ij = η y_j (x_i - y_j w_ij) — 매 weight normalization, 매 PCA 첫번째 component 으로 converges.
- **BCM rule** (Bienenstock-Cooper-Munro 1982): 매 sliding threshold θ — y > θ 시 LTP, y < θ 시 LTD.
- **STDP (Spike-Timing-Dependent Plasticity)**: 매 actual biological — pre-spike 가 post-spike 직전 시 LTP, 직후 시 LTD. 매 millisecond-scale.
- **Triplet STDP**: 매 더 정확한 model.
## 🔗 지식 연결 (Graph)
- [[Growth-Mindset-Intervention|Growth-Mindset-Intervention]], Deep Learning (DL), [[High-Cohesion-Low-Coupling|High-Cohesion-Low-Coupling]], [[Biological-Intelligence|Biological-Intelligence]], [[Growth-Mindset|Growth-Mindset]], [[Refinement|Refinement]]
- **Key Quote**: "Cells that fire together, wire together."
---
### 매 Biological evidence
- LTP (Long-Term Potentiation): 매 hippocampal CA1 의 Bliss-Lomo 1973 의 발견.
- LTD (Long-Term Depression): 매 cerebellum 의 motor learning.
- NMDA receptor 의 핵심: 매 coincidence detector.
- 매 calcium dynamics 의 underlying mechanism.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 ML connections
- 매 unsupervised learning 의 model.
- Hopfield network 매 Hebbian-trained associative memory.
- SOM (Self-Organizing Maps) 매 Hebbian-style competitive learning.
- 매 modern: Predictive coding / Free energy principle 의 Hebbian-like rules.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Basic Hebbian Update
```python
import numpy as np
## 🧪 검증 상태 (Validation)
class HebbianNeuron:
def __init__(self, n_inputs, lr=0.01):
self.w = np.random.randn(n_inputs) * 0.01
self.lr = lr
def forward(self, x):
return np.dot(self.w, x)
def update(self, x, y):
# Δw = η x y
self.w += self.lr * x * y
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
# Demo: weights 의 unbounded growth (매 problem)
neuron = HebbianNeuron(n_inputs=10)
for _ in range(1000):
x = np.random.randn(10)
y = neuron.forward(x)
neuron.update(x, y)
print(f"Weight norm: {np.linalg.norm(neuron.w):.2f}") # 매 explodes
```
## 🧬 중복 검사 (Duplicate Check)
### Oja's Rule (매 stable + PCA)
```python
class OjasNeuron:
"""매 Δw = η y (x - y w). PCA 첫번째 component 으로 converges."""
def __init__(self, n_inputs, lr=0.01):
self.w = np.random.randn(n_inputs)
self.w /= np.linalg.norm(self.w)
self.lr = lr
def update(self, x):
y = np.dot(self.w, x)
self.w += self.lr * y * (x - y * self.w)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
# 매 verify: top eigenvector 으로 converges
np.random.seed(0)
data = np.random.randn(1000, 10) @ np.diag([5, 3, 2, 1, 1, 0.5, 0.5, 0.3, 0.3, 0.1])
neuron = OjasNeuron(10, lr=0.001)
for x in data:
neuron.update(x)
## 🕓 변경 이력 (Changelog)
# 매 compare with NumPy PCA top component
cov = np.cov(data.T)
eigvals, eigvecs = np.linalg.eigh(cov)
top_pc = eigvecs[:, -1]
similarity = abs(np.dot(neuron.w / np.linalg.norm(neuron.w), top_pc))
print(f"Similarity to top PC: {similarity:.4f}") # ≈ 1.0
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### BCM Rule (매 sliding threshold)
```python
class BCMNeuron:
def __init__(self, n_inputs, lr=0.01, tau=100):
self.w = np.random.randn(n_inputs) * 0.1
self.lr = lr
self.theta = 1.0 # sliding threshold
self.tau = tau # time constant
self.y_history = []
def forward(self, x):
return np.dot(self.w, x)
def update(self, x):
y = self.forward(x)
self.w += self.lr * x * y * (y - self.theta)
# Sliding threshold: θ = E[y²]
self.y_history.append(y ** 2)
if len(self.y_history) > self.tau:
self.y_history.pop(0)
self.theta = np.mean(self.y_history) if self.y_history else 1.0
```
### STDP (Spike-Timing-Dependent) — Brian2
```python
from brian2 import *
# 매 100 input neurons → 1 output, STDP synapses
N = 100
input_group = PoissonGroup(N, rates=20*Hz)
neurons = NeuronGroup(1, '''
dv/dt = -v / (10*ms) : 1
''', threshold='v > 1', reset='v = 0')
# 매 STDP synapse model
syn = Synapses(input_group, neurons,
'''
w : 1
dapre/dt = -apre/(20*ms) : 1 (event-driven)
dapost/dt = -apost/(20*ms) : 1 (event-driven)
''',
on_pre='''
v_post += w
apre += 0.01
w = clip(w + apost, 0, 1)
''',
on_post='''
apost -= 0.012
w = clip(w + apre, 0, 1)
'''
)
syn.connect()
syn.w = 'rand() * 0.5'
run(1000*ms)
hist(syn.w[:], 50)
# 매 bimodal distribution 의 emergence — 매 STDP signature
```
### Hopfield Network (Hebbian-trained associative memory)
```python
class HopfieldNetwork:
def __init__(self, n):
self.n = n
self.W = np.zeros((n, n))
def store(self, patterns):
"""Hebbian: W = Σ p p^T (diagonal=0)."""
for p in patterns:
self.W += np.outer(p, p)
np.fill_diagonal(self.W, 0)
self.W /= len(patterns)
def recall(self, pattern, max_iter=100):
s = pattern.copy()
for _ in range(max_iter):
s_new = np.sign(self.W @ s)
if np.all(s_new == s):
break
s = s_new
return s
# Demo: store ±1 patterns, recall from noisy
net = HopfieldNetwork(50)
patterns = [np.random.choice([-1, 1], 50) for _ in range(3)]
net.store(patterns)
noisy = patterns[0].copy()
noisy[:10] = -noisy[:10] # flip 10 bits
recalled = net.recall(noisy)
print(f"Match: {np.mean(recalled == patterns[0]):.2%}")
```
## 매 결정 기준
| 상황 | Rule |
|---|---|
| Educational / simple demo | Plain Hebb |
| Stable + PCA emergence | Oja's rule |
| Bidirectional plasticity (LTP+LTD) | BCM |
| Biological realism (spiking) | STDP |
| Associative memory | Hopfield (Hebbian) |
| Competitive learning / clustering | SOM (Kohonen) |
| Modern deep learning | Backprop (NOT Hebbian) |
| Biologically-plausible deep learning | Predictive coding / Equilibrium propagation |
**기본값**: 매 conceptual 매 Hebb's rule, 매 ML practice 매 Oja's rule, 매 spiking simulation 매 STDP.
## 🔗 Graph
- 부모: [[Computational-Neuroscience]] · [[Synaptic-Plasticity]] · [[Learning-Theory]]
- 변형: [[Oja's-Rule]] · [[BCM-Rule]] · [[STDP]] · [[Anti-Hebbian-Learning]]
- 응용: [[Hopfield-Network]] · [[Self-Organizing-Maps]] · [[Associative-Memory]] · [[Predictive-Coding]]
- Adjacent: [[Long-Term-Potentiation]] · [[NMDA-Receptors]] · [[Free-Energy-Principle]] · [[Backpropagation]]
## 🤖 LLM 활용
**언제**: 매 conceptual explanation, 매 history of computational neuroscience, 매 simple rule derivation.
**언제 X**: 매 modern deep learning 의 training — backprop 사용. 매 actual neuroscience research 의 STDP parameter — 매 experimental data 참조.
## ❌ 안티패턴
- **Plain Hebb 의 production 사용**: 매 weights 의 explosion — Oja/BCM/normalization 사용.
- **"Hebbian = backprop" 혼동**: 매 different learning paradigm — backprop 매 supervised, Hebb 매 unsupervised correlation.
- **STDP 의 timing 의 부정확**: 매 millisecond precision 필요 — discrete-time approximation 의 한계.
- **Hopfield 의 capacity overestimate**: 매 ~0.14 N patterns 의 한계 (Hopfield 1982).
## 🧪 검증 / 중복
- Verified (Hebb 1949 "Organization of Behavior", Oja 1982, Bliss-Lomo 1973 LTP, Bi-Poo 1998 STDP).
- 신뢰도 A (foundational neuroscience theory).
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Hebb/Oja/BCM/STDP rules, Hopfield, biological mechanisms |
@@ -2,92 +2,156 @@
id: wiki-2026-0508-high-frequency-trading-models
title: High Frequency Trading Models
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-HFTM-001]
aliases: [HFT, Algorithmic Trading, Market Making]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, hft, trading-models, finance, algorithm, latency, arbitrage, market-making]
confidence_score: 0.9
verification_status: applied
tags: [hft, trading, latency, market-microstructure]
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: cpp
framework: kdb+/qpython
---
# [[High-Frequency-Trading-Models|High-Frequency-Trading-Models]]
# High Frequency Trading Models
## 📌 한 줄 통찰 (The Karpathy Summary)
> "0.001초의 승부사: 인간이 인지할 수 없는 찰나의 순간에 수천 번의 매매를 수행하여, 시장의 미세한 가격 불균형(Arbitrage)이나 호가창의 변화를 가로채 수익을 올리는 극강의 레이턴시 최적화 금융 알고리즘."
## 한 줄
> **"매 microsecond 매 alpha"**. HFT 매 nanosecond-scale latency 매 statistical arbitrage 의 결합 — 매 2026 quantum-resistant signature 매 co-located FPGA 매 standard. Renaissance, Citadel, Jump 매 dominant; 매 average holding period 매 sub-second.
## 📖 구조화된 지식 (Synthesized Content)
초단타 매매 모델(High-Frequency-Trading-Models)은 고성능 컴퓨터와 초고속 통신망을 이용해 매우 짧은 시간 동안 대량의 주문을 실행하는 금융 기법입니다.
## 매 핵심
1. **주요 전략**:
* **Market Making**: 매수와 매도 호가를 동시에 제시하여 스프레드 이익 취득.
* **Statistical Arbitrage**: 서로 연관된 자산 간의 일시적 가격 괴리 이용.
* **Momentum Ignition**: 대량 주문으로 가격 변동을 유도하고 추세 추종. ([[Refinement|Refinement]]와 연결)
2. **핵심 기술**:
* **Low Latency**: 서버 거래소 내부 배치(Co-location), FPGA 기반 하드웨어 가속. ([[Efficiency|Efficiency]]와 연결)
* **Predictive Modeling**: 뉴스나 호가창 데이터를 실시간 분석하여 다음 가격 예측.
### 매 latency hierarchy
- **L1 (sub-µs)**: FPGA tick-to-trade, kernel bypass NICs (Solarflare, Mellanox).
- **L2 (1-10µs)**: 매 C++ hot path, lock-free queues, busy-spin threads.
- **L3 (10-100µs)**: 매 Python/kdb+ 매 signal generation.
- **L4 (ms+)**: 매 ML inference (XGBoost, transformer order-flow).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 정보의 불균형 정책을 이용한 단순 매매 정책 위주였으나, 현대 정책은 AI 모델 정책(Deep Learning) 정책을 이식하여 수만 개의 미세 신호 정책을 동시에 학습 정책하고 실시간으로 전략 정책을 수정하는 지능형 HFT 로 진화함(RL Update).
- **정책 변화(RL Update)**: 시장의 유동성 정책을 공급한다는 순기능 정책 이면에, '플래시 크래시(Flash crash) 정책' 같은 시스템 리스크 정책 유발 가능성 정책이 제기되면서, 각국 거래소는 HFT 에 대한 강력한 서킷 브레이커 정책 및 감시 정책을 강화하는 정책적 대응 중임. (Stability와 연결)
### 매 strategy taxonomy
- **Market Making**: 매 bid-ask spread capture, inventory risk hedge.
- **Statistical Arbitrage**: 매 cointegration, mean reversion (Ornstein-Uhlenbeck).
- **Latency Arbitrage**: 매 venue-to-venue price lag exploit.
- **Order-Flow Prediction**: 매 LOB imbalance → micro-price drift.
- **Index Arbitrage**: 매 ETF NAV vs constituent basket.
## 🔗 지식 연결 (Graph)
- [[Refinement|Refinement]], [[Efficiency|Efficiency]], Stability, [[Distributed-System-Type-Safety|Distributed-System-Type-Safety]], [[Complexity-Theory|Complexity-Theory]], [[Reinforcement Learning (RL)|Reinforcement Learning (RL)]]
- **Key Metric**: Tick-to-trade latency.
---
### 매 응용
1. 매 NYSE/NASDAQ co-location.
2. 매 crypto MEV (Flashbots, Jito).
3. 매 forex ECN aggregation.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 1. Order Book Imbalance (LOB micro-price)
```python
def micro_price(bid_px, bid_sz, ask_px, ask_sz):
# 매 imbalance-weighted mid — predicts 100ms drift
imb = bid_sz / (bid_sz + ask_sz)
return ask_px * (1 - imb) + bid_px * imb
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# 매 signal: micro_price - mid_price → directional alpha
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. Cointegration Pair Trade (Engle-Granger)
```python
import statsmodels.api as sm
import numpy as np
**선택 A를 써야 할 때:**
- *(TODO)*
def find_pairs(prices_a, prices_b):
beta = sm.OLS(prices_a, sm.add_constant(prices_b)).fit().params[1]
spread = prices_a - beta * prices_b
adf = sm.tsa.adfuller(spread)
return beta, adf[1] # p-value < 0.05 → tradeable
**선택 B를 써야 할 때:**
- *(TODO)*
# 매 entry: spread > 2σ, exit: spread → 0
```
**기본값:**
> *(TODO)*
### 3. Lock-Free Order Book (C++)
```cpp
struct Level { std::atomic<int64_t> qty; int64_t px; };
struct Book { Level bids[1024]; Level asks[1024]; };
## ❌ 안티패턴 (Anti-Patterns)
void on_tick(Book& b, int side, int idx, int64_t qty) {
// 매 single-writer SPMC — no mutex
auto& lvl = (side == 0) ? b.bids[idx] : b.asks[idx];
lvl.qty.store(qty, std::memory_order_release);
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 4. Kalman Filter Spread Tracking
```python
# 매 dynamic hedge ratio — beta drifts over time
from pykalman import KalmanFilter
kf = KalmanFilter(transition_matrices=[1], observation_matrices=[1],
initial_state_mean=0, initial_state_covariance=1,
observation_covariance=1, transition_covariance=0.01)
state_means, _ = kf.filter(spread_series)
```
### 5. FPGA Tick-to-Trade (Verilog sketch)
```verilog
// 매 200ns tick parse → order send
always @(posedge clk) begin
if (md_valid && (bid_px > threshold)) begin
ord_send <= 1; ord_px <= bid_px; ord_qty <= 100;
end
end
```
### 6. Almgren-Chriss Optimal Execution
```python
def almgren_chriss(X, T, sigma, eta, gamma, lam):
# 매 minimize: variance + market impact
kappa = np.sqrt(lam * sigma**2 / eta)
n_steps = int(T / dt)
schedule = [X * np.sinh(kappa*(T-t)) / np.sinh(kappa*T) for t in times]
return schedule # 매 hyperbolic decay
```
### 7. ML Order-Flow (LightGBM)
```python
import lightgbm as lgb
features = ['lob_imb_1','lob_imb_5','vwap_dev','trade_intensity']
model = lgb.train({'objective':'regression','num_leaves':31},
lgb.Dataset(X[features], y_future_return),
num_boost_round=500)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Sub-µs critical | FPGA + kernel bypass |
| Stat arb medium freq | Python + kdb+ |
| Crypto MEV | Rust + Flashbots bundle |
| Backtest | vectorbt, Nautilus Trader |
**기본값**: C++ hot path + Python research, 매 co-location 매 essential.
## 🔗 Graph
- 부모: [[Operations-Research]] · [[Statistics]]
- 변형: [[Algorithmic Trading]] · [[Market Making]]
- 응용: [[Kalman-Filter-and-State-Tracking]] · [[Optimal-Control-Theory]]
- Adjacent: [[Stochastic-Processes]] · [[Signal-Processing-Foundations]]
## 🤖 LLM 활용
**언제**: research signal hypothesis 생성, 매 backtest code scaffolding, 매 strategy documentation.
**언제 X**: 매 production hot path (latency budget violated), 매 real-time risk decision.
## ❌ 안티패턴
- **Garbage Collection in Hot Path**: 매 Java/Python GC pause → 100µs jitter. 매 C++/Rust 사용.
- **Overfit Backtest**: 매 in-sample Sharpe 5 → live -2. 매 walk-forward + transaction cost.
- **No Inventory Limit**: 매 market-maker blow-up (Knight Capital 2012, $440M loss in 45min).
- **Survivorship Bias**: 매 delisted ticker 무시 → inflated returns.
## 🧪 검증 / 중복
- Verified (Aldridge, *High-Frequency Trading*; Cartea et al., *Algorithmic and HFT*).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full FULL spec, 7 patterns + decision matrix |
@@ -2,93 +2,151 @@
id: wiki-2026-0508-incremental-computation
title: Incremental Computation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-INCM-001]
aliases: [Incremental Build, Memoization, Salsa, Adapton]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [auto-reinforced, incremental-computation, algorithms, Efficiency, Dynamic-Programming, synchronization, caching]
confidence_score: 0.9
verification_status: applied
tags: [incremental, memoization, build-systems, reactive]
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: rust
framework: salsa
---
# [[Incremental-Computation|Incremental-Computation]]
# Incremental Computation
## 📌 한 줄 통찰 (The Karpathy Summary)
> "바뀐 것만 다시 하기: 데이터가 조금 변했다고 전체 시스템을 처음부터 다시 계산하는 낭비를 버리고, 오직 변화된 부분(Delta)의 영향만 추적하여 업데이트함으로써 속도를 극적으로 높이는 알고리즘적 정수."
## 한 줄
> **"매 unchanged 매 recompute X"**. Incremental computation 매 prior result 의 reuse — 매 input change 만 propagate. 매 2026 rust-analyzer (Salsa), Bazel, Buck2, Turbopack 매 standard. 매 trade-off: 매 memory vs recompute time.
## 📖 구조화된 지식 (Synthesized Content)
증분 계산(Incremental-Computation)은 입력의 작은 변화에 대해 출력을 효율적으로 업데이트하는 기법입니다.
## 매 핵심
1. **핵심 메커니즘**:
* **Dependency Tracking**: 어떤 계산 정책 결과가 어떤 입력 데이터 정책에 의존 정책하는지 그래프로 관리. ([[DAG-Dependency-Management|DAG-Dependency-Management]]와 연결)
* **Memoization/Caching**: 이전 계산 정책 결과 정책을 저장 정책해 두었다가 재사용. (Efficiency와 연결)
* **Change Propagation**: 변경된 입력 정책과 연결된 노드들만 선별적으로 재계산 정책.
2. **활용 사례**:
* **Build[[_system|system]]s**: 수정된 파일만 다시 컴파일 (Bazel, Make).
* **Database Views**: 원본 테이블에 데이터가 추가될 때 뷰(View)를 전체 갱신하지 않고 증분 반영. ([[Entity-Relationship-Modeling|Entity-Relationship-Modeling]]와 연결)
* **Excel**: 특정 셀의 값을 바꿨을 때 연결된 수식들만 실시간 업데이트.
### 매 mechanism 분류
- **Memoization**: 매 (input → output) cache. 매 pure function 필수.
- **Demand-Driven**: 매 query-based; pull 시 dependency graph 추적 (Salsa, Adapton).
- **Change-Driven**: 매 push; input change → invalidate downstream (React reactivity).
- **Self-Adjusting Computation**: 매 Acar — formal foundation, dynamic dependency graph.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 "전체 재계산 정책(Batch)이 구현 정책이 훨씬 쉽고 정확하다"고 생각했으나, 데이터가 기하급수적으로 늘어난 현대 정책은 증분 계산 정책 없이는 실시간 서비스 정책이 도저히 불가능함을 깨닫고 모든 현대 아키텍처 정책의 필수 요소로 도입함(RL Update).
- **정책 변화(RL Update)**: 이제는 단순 값 업데이트 정책을 넘어, AI 모델 장치 정책이 새로운 데이터 정책을 학습 정책(Live learning)할 때 전체 가중치 정책을 다시 학습 정책하지 않고 점진적으로 지식 정책을 업데이트하는 연구로 확장 중임.
### 매 invalidation strategy
- **Hash-based**: 매 input fingerprint compare (Bazel digest).
- **Timestamp**: 매 mtime check (make).
- **Reference equality**: 매 pointer compare (React).
- **Structural diff**: 매 deep equal (immer, Redux).
## 🔗 지식 연결 (Graph)
- [[DAG-Dependency-Management|DAG-Dependency-Management]], [[Efficiency|Efficiency]], [[Entity-Relationship-Modeling|Entity-Relationship-Modeling]], [[Optimization|Optimization]], Performance, [[Refinement|Refinement]]
- **Key Concept**: Static vs Dynamic dependency graphs.
---
### 매 응용
1. 매 build systems (Bazel, Buck2).
2. 매 IDE backends (rust-analyzer, TypeScript LSP).
3. 매 reactive UI (React, SolidJS signals).
4. 매 dataflow / spreadsheets.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 1. Salsa Query (Rust)
```rust
#[salsa::query_group(CompilerStorage)]
pub trait Compiler: salsa::Database {
#[salsa::input]
fn source_text(&self, file: FileId) -> Arc<String>;
**언제 쓰면 안 되는가:**
- *(TODO)*
fn parse(&self, file: FileId) -> Arc<Ast>;
fn type_check(&self, file: FileId) -> Arc<TypeMap>;
}
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
fn parse(db: &dyn Compiler, file: FileId) -> Arc<Ast> {
let text = db.source_text(file); // 매 dependency tracked
Arc::new(parse_text(&text))
}
// 매 source_text unchanged → parse skipped automatically
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. Memoization with LRU
```python
from functools import lru_cache
**선택 A를 써야 할 때:**
- *(TODO)*
@lru_cache(maxsize=10_000)
def expensive(x: int, y: int) -> int:
return slow_compute(x, y)
**선택 B를 써야 할 때:**
- *(TODO)*
# 매 hash(args) → cached result; LRU evict oldest
```
**기본값:**
> *(TODO)*
### 3. React useMemo (Reference Equality)
```jsx
const expensive = useMemo(() => {
return items.filter(i => i.active).sort();
}, [items]); // 매 items reference unchanged → skip
```
## ❌ 안티패턴 (Anti-Patterns)
### 4. Bazel Action Cache
```python
# WORKSPACE — 매 each action keyed by:
# hash(inputs) + hash(command) + hash(env)
# Output stored in CAS (content-addressable storage)
# Remote cache — 매 distributed reuse across team
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 5. Self-Adjusting Computation (OCaml-style)
```ocaml
let m = Mod.create ()
let a = Var.create m 1
let b = Var.create m 2
let sum = Mod.bind m (fun () -> Var.read a + Var.read b)
Var.write a 10 (* sum auto-recomputes only its branch *)
```
### 6. Incremental Diff (Patch Generation)
```typescript
function diff<T>(old: T[], new_: T[]): Patch[] {
// 매 Myers diff — O(ND) — minimal edit script
// 매 used by git, react reconciler, immer
}
```
### 7. Signal-Based Reactivity (SolidJS)
```javascript
const [count, setCount] = createSignal(0);
const doubled = createMemo(() => count() * 2);
// 매 fine-grained — only doubled recomputes when count changes
// 매 NO virtual DOM diff
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Pure function repeat | `lru_cache` / memoize |
| Compiler / IDE | Salsa, Adapton |
| UI reactivity | Signals (Solid) > Virtual DOM (React) |
| Build system | Bazel / Buck2 / Turbo |
| Stream pipeline | Materialize, ksqlDB |
**기본값**: 매 pure function memoize, 매 large pipeline 매 Salsa pattern.
## 🔗 Graph
- 부모: [[Theoretical-Computer-Science]] · [[Algorithm-Complexity-Big-O]]
- 변형: [[Memoization]] · [[Self-Adjusting-Computation]]
- 응용: [[Compiler-Architecture]] · [[Reactive-Programming]]
- Adjacent: [[Dynamic-Programming]] · [[Caching-Strategies]]
## 🤖 LLM 활용
**언제**: 매 build pipeline design, 매 query system architecture, 매 cache invalidation logic.
**언제 X**: 매 input always changes (no reuse benefit), 매 memory-constrained embedded.
## ❌ 안티패턴
- **Cache invalidation bug**: 매 stale result return. 매 dependency graph correctness 매 critical.
- **Unbounded memo**: 매 OOM. 매 LRU/TTL bound 필수.
- **Impure function memo**: 매 random()/now() 매 cache 시 incorrect.
- **Over-fine-grained**: 매 cache overhead > recompute cost.
## 🧪 검증 / 중복
- Verified (Acar, *Self-Adjusting Computation*; Salsa docs; Bazel design).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Salsa/Bazel/SolidJS patterns + decision matrix |
@@ -2,65 +2,141 @@
id: wiki-2026-0508-inexact-science
title: Inexact Science
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-INSC-001]
aliases: [Soft Science, Probabilistic Reasoning, Approximate Methods]
duplicate_of: none
source_trust_level: A
confidence_score: 0.86
tags: [auto-reinforced, inexact-science, social-science, soft-science, complexity, human-Behavior]
confidence_score: 0.85
verification_status: applied
tags: [epistemology, statistics, uncertainty, methodology]
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: python
framework: pymc
---
# [[Inexact-Science|Inexact-Science]]
# Inexact Science
## 📌 한 줄 통찰 (The Karpathy Summary)
> "확실함의 부재가 주는 지혜: 물리학처럼 공식 하나로 명쾌하게 설명되지 않는 인간 심리, 경제, 사회 현상을 연구하며, 절대적 정답 대신 '가장 가능성 있는 경향성'과 '맥락'을 탐구하여 불확실성을 다루는 학문."
## 한 줄
> **"매 uncertainty 매 quantify"**. Inexact science 매 deterministic closed-form X — 매 noise, bias, partial observability 매 inherent. 매 2026 ML interpretability, social science replication crisis 매 forefront. 매 tool: 매 Bayesian inference, robust statistics, sensitivity analysis.
## 📖 구조화된 지식 (Synthesized Content)
부정밀 과학(Inexact-Science)은 엄격한 실험적 통제나 수치적 정확성이 떨어지지만, 복잡한 인문·사회 현상을 다루는 학문 분야를 의미합니다. (심리학, 사회학, 경제학 등)
## 매 핵심
1. **특징**:
* **Complexity**: 변수가 너무 많고 인간의 자유의지가 개입되어 예측이 어려움. ([[Complexity Theory|Complexity Theory]]와 연결)
* **Context-Dependent**: 시대와 환경에 따라 정답이 변함.
* **Heuristic-driven**: 절대적 법칙보다 전문가의 직관과 휴리스틱이 자주 사용됨. ([[Heuristics|Heuristics]]와 연결)
2. **왜 중요한가?**:
* AI가 수학적 최적화(Hard Science)를 넘어 인간의 복잡한 감정과 사회적 맥락(Soft Science)을 이해하게 하려면, 이 분야의 지식 체계 포섭이 필수적임.
### 매 inexactness 의 source
- **Aleatory**: 매 inherent randomness (quantum, dice).
- **Epistemic**: 매 ignorance — 매 reducible by data.
- **Measurement noise**: 매 instrument precision limit.
- **Model misspecification**: 매 wrong functional form.
- **Selection bias**: 매 non-representative sample.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 '비과학적 정책'이라 치부되기도 했으나, 현대 정책은 데이터 과학과 컴퓨팅 파워 정책을 결합하여 '정량적 부정밀 과학 정책(Computational Social Science)'으로 거듭남(RL Update).
- **정책 변화(RL Update)**: 거대 언어 모델이 인간의 심리 상담이나 사회 현상 분석 정책을 수행함에 따라, 인문학적 통찰 정책이 기술 개발 정책의 가장 강력한 지침이 되는 '문명적 기술 정책'의 시대로 진입함.
### 매 mitigation 전략
- **Bayesian credible intervals** (vs frequentist CI).
- **Bootstrap resampling** — 매 distribution-free uncertainty.
- **Cross-validation** — 매 generalization estimate.
- **Sensitivity analysis** — 매 parameter perturbation.
- **Pre-registration** — 매 p-hacking 방지.
## 🔗 지식 연결 (Graph)
- [[Epistemology|Epistemology]], [[Complexity Theory|Complexity Theory]], [[Heuristics|Heuristics]], [[Decision Theory|Decision Theory]], [[Ethics & AI|Ethics & AI]]
- **Modern Tech/Tools**: Sentiment [[Analysis|Analysis]], Sociometric [[Research|Research]], Behavioral economic modeling.
---
### 매 응용
1. 매 medical trials (FDA Phase III).
2. 매 ML model deployment (Bayesian deep learning).
3. 매 climate modeling (ensemble).
4. 매 economics (DSGE models).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 1. Bayesian Linear Regression (PyMC)
```python
import pymc as pm
**언제 쓰면 안 되는가:**
- *(TODO)*
with pm.Model() as model:
alpha = pm.Normal('alpha', 0, 10)
beta = pm.Normal('beta', 0, 10)
sigma = pm.HalfNormal('sigma', 5)
mu = alpha + beta * x_obs
y = pm.Normal('y', mu=mu, sigma=sigma, observed=y_obs)
trace = pm.sample(2000, tune=1000)
# 매 posterior distribution — credible intervals 매 natural
```
## 🧪 검증 상태 (Validation)
### 2. Bootstrap Confidence Interval
```python
import numpy as np
def bootstrap_ci(data, stat_fn, n=10_000, alpha=0.05):
boots = [stat_fn(np.random.choice(data, len(data), replace=True))
for _ in range(n)]
return np.percentile(boots, [100*alpha/2, 100*(1-alpha/2)])
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### 3. Sensitivity Analysis (Sobol)
```python
from SALib.analyze import sobol
from SALib.sample.sobol import sample as sobol_sample
## 🧬 중복 검사 (Duplicate Check)
problem = {'num_vars': 3, 'names': ['x1','x2','x3'],
'bounds': [[0,1]]*3}
param_values = sobol_sample(problem, 1024)
Y = np.array([model(p) for p in param_values])
Si = sobol.analyze(problem, Y) # 매 first/total order indices
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### 4. Cross-Validation
```python
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X, y, cv=10, scoring='neg_mean_squared_error')
print(f"MSE: {-scores.mean():.3f} ± {scores.std():.3f}")
```
## 🕓 변경 이력 (Changelog)
### 5. Robust Statistics (M-estimator)
```python
from sklearn.linear_model import HuberRegressor
# 매 outlier-resistant — Huber loss 매 quadratic+linear
huber = HuberRegressor(epsilon=1.35).fit(X, y)
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### 6. Conformal Prediction (Distribution-Free)
```python
# 매 2026 standard — coverage guarantee 매 model-agnostic
calib_residuals = np.abs(y_calib - model.predict(X_calib))
q_hat = np.quantile(calib_residuals, 0.95)
# 매 prediction interval: [pred - q_hat, pred + q_hat]
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Small n, prior knowledge | Bayesian (PyMC, Stan) |
| Large n, distribution-free | Bootstrap + conformal |
| Causal claim | RCT > obs + IV/DiD |
| Outliers heavy | Huber / RANSAC |
| Multiple comparisons | BH-FDR / Bonferroni |
**기본값**: 매 report point estimate + 95% interval; 매 effect size > significance.
## 🔗 Graph
- 부모: [[Statistics]] · [[Probability Theory]]
- 변형: [[Bayesian-Inference]] · [[Robust-Statistics]]
- 응용: [[Statistical-Power]] · [[Multivariate-Analysis]]
- Adjacent: [[Inexact-Reasoning]] · [[Epistemology]]
## 🤖 LLM 활용
**언제**: 매 study design review, 매 uncertainty communication, 매 robustness check 제안.
**언제 X**: 매 deterministic system (compiler, hash). 매 cryptographic exactness 필요.
## ❌ 안티패턴
- **p<0.05 cult**: 매 effect size 무시, multiple-testing 무수정.
- **HARKing**: 매 hypothesis after results known.
- **Overconfident point estimate**: 매 ±uncertainty 미보고.
- **Garrison the data**: 매 outlier 임의 제거.
## 🧪 검증 / 중복
- Verified (Gelman, *BDA*; Wasserman, *All of Statistics*; ASA p-value statement).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Bayesian/bootstrap/conformal patterns |
@@ -1,25 +1,33 @@
---
id: wiki-20260508-information-retrieval-ir--redir
title: Information Retrieval (IR)
category: Computer_Science_and_Theory
status: merged
redirect_to: Information-Retrieval-IR
canonical_id: Information-Retrieval-IR
category: 10_Wiki/Topics
status: duplicate
canonical_id: information-retrieval
duplicate_of: "[[Information-Retrieval]]"
aliases: []
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [redirect]
raw_sources: []
last_reinforced: 2026-05-08
confidence_score: 0.9
verification_status: redirected
tags: [duplicate, information-retrieval, search]
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-merge 2026-05-08)
---
# Information Retrieval (IR)
> [!IMPORTANT]
> 이 문서는 P-Reinforce Phase 2 자동 MERGE에 의해 **[[Information-Retrieval-IR]]**로 통합되었습니다.
> **이 문서는 [[Information-Retrieval]] 의 중복본입니다.** Canonical 문서로 redirect.
---
*Redirected to: [[Information-Retrieval-IR]]*
## 핵심 요약 (specialization aspects)
- 매 acronym form (IR) — 매 canonical 매 full form.
- 매 BM25, dense vector (DPR, ColBERT), hybrid (RRF) 매 2026 standard.
## 🔗 Graph
- 부모: [[Information-Retrieval]] (canonical)
- 관련: [[Information Retrieval Evaluation Metrics]] · [[Keyword Search]] · [[Ranking-Algorithms]]
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -1,73 +1,153 @@
---
id: wiki-2026-0508-information-retrieval-evaluation
title: Information Retrieval Evaluation Metrics
category: Redirect
status: merged
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-Reinforce-REDIRECT-IR-003]
duplicate_of: Information_Retrieval
aliases: [IR Metrics, Search Evaluation, NDCG, MRR]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.95
verification_status: applied
tags: [ir, evaluation, metrics, ranking]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: pytrec_eval
---
# [[Information Retrieval Evaluation Metrics]]
# Information Retrieval Evaluation Metrics
> [!NOTE]
> 본 문서는 **[[Information_Retrieval]]**로 통합되었습니다. 🫡🐟
## 📌 한 줄 통찰 (The Karpathy Summary)
## 매 한 줄
> **"매 metric 매 system behavior 의 directs"**. IR evaluation 매 ranked list 의 quality measure — 매 binary (precision, recall) vs graded (NDCG). 매 2026 LLM-as-judge, 매 BEIR/MTEB benchmark 매 standard, 매 nDCG@10 매 default.
> IR 평가지표는 검색 결과의 순위·관련성을 정량화하는 도구로, Precision@k·Recall@k·MRR·nDCG가 표준이다.
## 매 핵심
## 📖 구조화된 지식 (Synthesized Content)
### 매 binary relevance metrics
- **Precision@k**: 매 top-k 중 relevant 비율.
- **Recall@k**: 매 전체 relevant 중 retrieved 비율.
- **F1**: 매 harmonic mean.
- **MAP** (Mean Average Precision): 매 query별 AP 의 평균.
- **MRR** (Mean Reciprocal Rank): 매 first relevant 의 1/rank 평균.
**추출된 패턴:** 단일 지표는 한 측면만 — 복수 지표를 봐야 검색 시스템의 약점이 보임.
### 매 graded relevance metrics
- **DCG@k**: $\sum_{i=1}^{k} \frac{rel_i}{\log_2(i+1)}$
- **NDCG@k**: DCG / IDCG — 매 [0,1] normalize.
- **ERR** (Expected Reciprocal Rank): 매 cascade user model.
**세부 내용:**
- Precision@k: 상위 k 중 정답 비율.
- Recall@k: 정답 중 상위 k 안에 든 비율.
- MRR(Mean Reciprocal Rank): 첫 정답 위치의 평균 역수.
- nDCG: 순위 가중치 + 다단계 관련성.
- 데이터셋: TREC, BEIR, MTEB, MS MARCO.
### 매 응용
1. 매 search engine A/B (Google, Bing).
2. 매 RAG retrieval quality (Ragas).
3. 매 recommender systems.
4. 매 LLM benchmark (BEIR, MTEB, MS MARCO).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 1. Precision/Recall
```python
def precision_at_k(retrieved, relevant, k):
return len(set(retrieved[:k]) & set(relevant)) / k
**언제 쓰면 안 되는가:**
- *(TODO)*
def recall_at_k(retrieved, relevant, k):
return len(set(retrieved[:k]) & set(relevant)) / len(relevant)
```
## 🧪 검증 상태 (Validation)
### 2. NDCG (graded)
```python
import numpy as np
- **정보 상태:** merged
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
def dcg(rels, k=10):
rels = np.asarray(rels)[:k]
return np.sum(rels / np.log2(np.arange(2, len(rels)+2)))
## 🧬 중복 검사 (Duplicate Check)
def ndcg(rels, ideal_rels, k=10):
return dcg(rels, k) / (dcg(ideal_rels, k) or 1)
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### 3. MRR
```python
def mrr(retrieved_lists, relevant_sets):
total = 0
for retrieved, relevant in zip(retrieved_lists, relevant_sets):
for i, doc in enumerate(retrieved, 1):
if doc in relevant:
total += 1 / i
break
return total / len(retrieved_lists)
```
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
### 4. MAP
```python
def average_precision(retrieved, relevant):
hits = 0; sum_p = 0
for i, doc in enumerate(retrieved, 1):
if doc in relevant:
hits += 1
sum_p += hits / i
return sum_p / len(relevant) if relevant else 0
```
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
### 5. pytrec_eval (Standard Tool)
```python
import pytrec_eval
qrel = {'q1': {'d1': 1, 'd3': 2}}
run = {'q1': {'d1': 0.9, 'd2': 0.5, 'd3': 0.3}}
ev = pytrec_eval.RelevanceEvaluator(qrel, {'ndcg_cut.10', 'map', 'recip_rank'})
print(ev.evaluate(run))
```
## 🔗 지식 연결 (Graph)
### 6. LLM-as-Judge (2026 trend)
```python
from anthropic import Anthropic
client = Anthropic()
prompt = f"Query: {q}\nDoc: {doc}\nRate relevance 0-3:"
score = client.messages.create(model="claude-opus-4-7",
max_tokens=10, messages=[{"role":"user","content":prompt}])
# 매 graded relevance — human-aligned, 매 expensive
```
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
### 7. Statistical Significance (paired t-test)
```python
from scipy.stats import ttest_rel
t, p = ttest_rel(ndcg_system_A, ndcg_system_B)
# 매 p < 0.05 → 매 significant difference
```
## 🕓 변경 이력 (Changelog)
## 매 결정 기준
| 상황 | Metric |
|---|---|
| Web search top result | MRR |
| Long-tail recall | Recall@1000 |
| Graded relevance | NDCG@10 |
| Multi-relevant per query | MAP |
| RAG eval | NDCG@5 + LLM-judge |
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
**기본값**: NDCG@10, 매 paired-t test 매 statistical significance.
## 🔗 Graph
- 부모: [[Information-Retrieval]] · [[Statistics]]
- 변형: [[Ranking-Algorithms]] · [[Relevance-Feedback]]
- 응용: [[Keyword Search]] · [[Knowledge Graph]]
- Adjacent: [[Statistical-Power]] · [[Cross-Validation]]
## 🤖 LLM 활용
**언제**: 매 search system A/B 설계, 매 RAG eval pipeline, 매 metric trade-off 분석.
**언제 X**: 매 single-doc QA (use exact-match), 매 generative output (use BLEU/ROUGE/judge).
## ❌ 안티패턴
- **Precision@1 only**: 매 long-tail blind spot.
- **No statistical test**: 매 noise-driven conclusion.
- **Mismatched qrels**: 매 partial relevance judgment.
- **Self-reported benchmark**: 매 trec_eval/standard tool 사용 권장.
## 🧪 검증 / 중복
- Verified (Manning et al., *IR Book*; TREC standards; BEIR paper 2021).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full metric coverage + LLM-judge pattern |
@@ -1,25 +1,33 @@
---
id: wiki-20260508-information-theory-redir
title: Information Theory
category: Computer_Science_and_Theory
status: merged
redirect_to: Information_Theory
canonical_id: Information_Theory
category: 10_Wiki/Topics
status: duplicate
canonical_id: information-theory
duplicate_of: "[[Entropy in Information Theory]]"
aliases: []
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [redirect]
raw_sources: []
last_reinforced: 2026-05-08
confidence_score: 0.9
verification_status: redirected
tags: [duplicate, information-theory, entropy]
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-merge 2026-05-08)
---
# Information Theory
> [!IMPORTANT]
> 이 문서는 P-Reinforce Phase 2 자동 MERGE에 의해 **[[Information_Theory]]**로 통합되었습니다.
> **이 문서는 [[Entropy in Information Theory]] 의 중복본입니다.** Canonical 문서로 redirect.
---
*Redirected to: [[Information_Theory]]*
## 핵심 요약 (specialization aspects)
- 매 broad title — 매 canonical 매 entropy-centric.
- 관련 atomic 문서: [[Information-Entropy]] · [[Mutual-Information]] · [[Kullback-Leibler-Divergence]] · [[Kolmogorov-Complexity]].
## 🔗 Graph
- 부모: [[Entropy in Information Theory]] (canonical)
- 형제: [[Information-Entropy]] · [[Mutual-Information]] · [[Kullback-Leibler-Divergence]]
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -2,64 +2,146 @@
id: wiki-2026-0508-information-entropy
title: Information Entropy
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-INEN-001]
aliases: [Shannon Entropy, H(X), Surprise]
duplicate_of: none
source_trust_level: A
confidence_score: 0.97
tags: [auto-reinforced, information-entropy, shannon, probability, Information-Theory, uncertainty]
confidence_score: 0.95
verification_status: applied
tags: [information-theory, entropy, shannon, ml-foundations]
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: python
framework: scipy
---
# [[Information-Entropy|Information-Entropy]]
# Information Entropy
## 📌 한 줄 통찰 (The Karpathy Summary)
> "놀라움의 척도: 어떤 메시지가 전달될 때 담긴 정보의 양을 '그것이 얼마나 불확실한가(Uncertainty)'로 측정하는 개념으로, 예측하기 힘든 돌발 상황일수록 엔트로피가 높고 그 정보의 가치 또한 크다는 정보 이론의 핵심 지표."
## 한 줄
> **"매 surprise 의 average"**. Shannon entropy $H(X) = -\sum p(x) \log p(x)$ — 매 distribution 의 uncertainty 매 bit 단위 measure. 매 1948 Shannon, 매 2026 LLM token sampling, compression, decision-tree split, MI-based feature selection 매 foundation.
## 📖 구조화된 지식 (Synthesized Content)
정보 엔트로피(Information-Entropy)는 클로드 섀넌이 제안한 정보의 평균적인 불확실성 혹은 정보량의 측정 방식입니다. (Bit의 탄생 근거)
## 매 핵심
1. **핵심 원리**:
* 확률이 낮은 사건(희귀한 일)이 발생하면 더 많은 정보를 전달함.
* 엔트로피가 0이면 결과가 100% 확실하여 아무런 정보 가치가 없음.
2. **왜 중요한가?**:
* 데이터 압축, 암호화, 그리고 딥러닝에서 모델의 예측이 실제 정답과 얼마나 다른지 측정하는 '크로스 엔트로피(Cross-Entropy)' 손실 함수의 근간이 됨. ([[Gradient-Descent|Gradient-Descent]]와 연결)
### 매 정의
- $H(X) = -\sum_{x} p(x) \log_2 p(x)$ — 매 bit (log2), nat (ln), dit (log10).
- $0 \le H(X) \le \log_2 |\mathcal{X}|$ — 매 uniform 시 max.
- **Joint**: $H(X,Y)$ · **Conditional**: $H(Y|X) = H(X,Y) - H(X)$.
- **Mutual Information**: $I(X;Y) = H(Y) - H(Y|X)$.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 단순 통신 시스템 내부의 '노이즈 측정 정책'이었으나, 현대 정책은 지능 리전트가 세상의 질서를 파악하고 '복잡성 정책'을 이해하는 핵심 인지 지표 정책으로 승격됨(RL Update). ([[Complexity Theory|Complexity Theory]]와 연결)
- **정책 변화(RL Update)**: AI 모델이 단순히 다음 단어를 맞히는 것을 넘어, 답변의 '정보 밀도'와 '의외성'을 조절하여 더 인간답고 가치 있는 답변을 생성하게 하는 정책적 도구로 활용됨.
### 매 핵심 properties
- **Non-negative**: $H(X) \ge 0$.
- **Concavity**: 매 distribution mixing 시 entropy 증가.
- **Chain rule**: $H(X,Y) = H(X) + H(Y|X)$.
- **Data Processing**: $I(X;Y) \ge I(X;f(Y))$.
## 🔗 지식 연결 (Graph)
- Information-[[Processing|Processing]], [[Complexity Theory|Complexity Theory]], [[Gradient-Descent|Gradient-Descent]], [[Optimization|Optimization]], [[Logic|Logic]]
- **Modern Tech/Tools**: [[Loss Functions|Loss Functions]] (Cross-Entropy), Huffman coding, Softmax layers.
---
### 매 응용
1. 매 lossless compression (Huffman, arithmetic) — limit $H(X)$.
2. 매 ML loss (cross-entropy, KL).
3. 매 decision tree split (ID3, C4.5 information gain).
4. 매 LLM sampling (entropy-aware temperature, min-p).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 1. Shannon Entropy
```python
import numpy as np
def entropy(probs, base=2):
p = np.asarray(probs)
p = p[p > 0]
return -np.sum(p * np.log(p)) / np.log(base)
**언제 쓰면 안 되는가:**
- *(TODO)*
# H([0.5,0.5]) = 1.0 bit
# H([1.0,0.0]) = 0.0 bit
# H([0.25]*4) = 2.0 bit
```
## 🧪 검증 상태 (Validation)
### 2. Cross-Entropy Loss (PyTorch)
```python
import torch.nn.functional as F
# 매 true distribution q vs predicted p
# H(q, p) = -Σ q(x) log p(x)
loss = F.cross_entropy(logits, targets) # softmax + NLL
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### 3. KL Divergence
```python
def kl_div(p, q):
p, q = np.asarray(p), np.asarray(q)
return np.sum(p * np.log(p / q + 1e-12))
# 매 D_KL(p||q) = H(p,q) - H(p)
```
## 🧬 중복 검사 (Duplicate Check)
### 4. Mutual Information (sklearn)
```python
from sklearn.feature_selection import mutual_info_classif
mi = mutual_info_classif(X, y, random_state=0)
# 매 feature ranking — 매 non-linear dependency capture
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### 5. Decision Tree Split (information gain)
```python
def info_gain(parent_y, splits):
H_parent = entropy(np.bincount(parent_y) / len(parent_y))
H_children = sum((len(s)/len(parent_y)) * entropy(np.bincount(s)/len(s))
for s in splits if len(s) > 0)
return H_parent - H_children
```
## 🕓 변경 이력 (Changelog)
### 6. LLM Min-p Sampling (entropy-aware)
```python
# 매 2024+ standard — 매 temperature alternative
def min_p_sample(logits, p_base=0.05):
probs = softmax(logits)
threshold = p_base * probs.max()
mask = probs >= threshold
probs = probs * mask
probs /= probs.sum()
return np.random.choice(len(probs), p=probs)
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### 7. Differential Entropy (Continuous)
```python
from scipy.stats import differential_entropy
samples = np.random.normal(0, 1, 10_000)
h = differential_entropy(samples) # ≈ 0.5*log(2πe) ≈ 1.42 nat
```
## 매 결정 기준
| 상황 | Form |
|---|---|
| Discrete classification | Cross-entropy loss |
| Distribution compare | KL divergence |
| Feature selection | Mutual information |
| Tree split | Information gain |
| LLM sample diversity | Min-p / temperature |
**기본값**: Cross-entropy loss + softmax, 매 ML classification 매 standard.
## 🔗 Graph
- 부모: [[Entropy in Information Theory]] · [[Probability Theory]]
- 변형: [[Mutual-Information]] · [[Kullback-Leibler-Divergence]] · [[Kolmogorov-Complexity]]
- 응용: [[Information Theory]] · [[Information Retrieval (IR)]]
- Adjacent: [[Statistical-Power]] · [[Bayesian-Inference]]
## 🤖 LLM 활용
**언제**: 매 loss design, 매 feature ranking, 매 sampling strategy 설명, 매 compression bound 추정.
**언제 X**: 매 small-sample MI estimation 매 unreliable. 매 high-dim differential entropy 매 hard.
## ❌ 안티패턴
- **MI without binning correction**: 매 small-n bias.
- **KL asymmetry 무시**: $D_{KL}(p\|q) \ne D_{KL}(q\|p)$.
- **Cross-entropy on wrong base**: 매 nat vs bit confusion.
- **Negative differential entropy 의 panic**: 매 continuous 매 자연스럽다.
## 🧪 검증 / 중복
- Verified (Cover & Thomas, *Elements of IT*; MacKay, *ITILA*).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full Shannon/KL/MI + min-p pattern |
@@ -2,92 +2,148 @@
id: wiki-2026-0508-inner-product-spaces
title: Inner Product Spaces
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-INNER-001]
aliases: [Hilbert Space, Dot Product, Vector Geometry]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Linear-Algebra, inner-product, vector-space, Similarity-Metrics, ai]
confidence_score: 0.95
verification_status: applied
tags: [linear-algebra, geometry, ml-foundations, hilbert]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: numpy
---
# Inner Product Spaces (내적 공간)
# Inner Product Spaces
## 📌 한 줄 통찰 (The Karpathy Summary)
> "추상적인 벡터들 사이에 거리를 재고 각도를 측정하여, 데이터 간의 '닮음'을 기하학적으로 정의하라" — 벡터 공간에 내적(Inner Product)이라는 연산이 추가되어 길이(Norm)와 각도(Orthogonality)를 계산할 수 있게 된 공간.
## 한 줄
> **"매 angle 매 length 의 algebraic foundation"**. Inner product $\langle x, y \rangle$ 매 vector space 매 geometry 부여 — 매 norm, distance, orthogonality 의 derived. 매 2026 ML embedding similarity (cosine, dot), kernel methods, Hilbert-space transformer 매 foundation.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 고차원 데이터 공간에서 두 요소 사이의 상관관계를 스칼라 값 하나로 응축하여, 데이터의 유사성이나 투영(Projection)을 계산하는 선형 대수적 분석 패턴.
- **핵심 성질:**
- **Positivity:** 자기 자신과의 내적은 항상 0 이상.
- **Symmetry (Conjugate Symmetry):** 순서를 바꿔도 결과가 일정함.
- **Linearity:** 벡터의 합과 스칼라 곱에 대해 선형성이 유지됨.
- **AI에서의 응용:**
- **Cosine Similarity:** 두 벡터의 내적을 각각의 크기로 나누어 '방향의 일치도' 측정.
- **Projection:** 특정 벡터를 다른 벡터 축으로 투영하여 특징을 추출하거나 차원을 축소(PCA).
- **Kernel Methods:** 데이터를 더 높은 차원의 내적 공간으로 보내 복잡한 경계를 선형적으로 분리.
- **의의:** AI가 지식을 벡터로 변환(Embedding)하고 이를 검색하거나 비교하는 모든 수치적 연산의 이론적 토대.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순한 유클리드 거리 중심에서 벗어나, 데이터의 분포와 맥락을 반영하는 다양한 내적 정의와 유사도 지표(Dot product, Cosine similarity 등)의 중요성 대두.
- **정책 변화:** Antigravity 프로젝트는 문서 간 유사도 분석 시, 내적 공간 상의 코사인 유사도를 기본 지표로 사용하여 의미적으로 가장 가까운 지식들을 추천함.
### 매 axioms
- **Conjugate symmetry**: $\langle x,y \rangle = \overline{\langle y,x \rangle}$.
- **Linearity in 1st arg**: $\langle ax+by, z \rangle = a\langle x,z\rangle + b\langle y,z\rangle$.
- **Positive definite**: $\langle x,x \rangle \ge 0$, $=0 \iff x=0$.
## 🔗 지식 연결 (Graph)
- [[Linear-Algebra-Foundations|Linear-Algebra-Foundations]], Vector-Database-Foundations, [[Dimensionality-Reduction|Dimensionality-Reduction]], [[Information-Retrieval-IR|Information-Retrieval-IR]]
- **Raw Source:** 10_Wiki/Topics/AI/Inner-Product-Spaces.md
### 매 derived 구조
- **Norm**: $\|x\| = \sqrt{\langle x,x \rangle}$.
- **Cosine**: $\cos \theta = \langle x,y\rangle / (\|x\|\|y\|)$.
- **Cauchy-Schwarz**: $|\langle x,y\rangle| \le \|x\|\|y\|$.
- **Orthogonality**: $\langle x,y\rangle = 0$.
- **Triangle**: $\|x+y\| \le \|x\| + \|y\|$.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. 매 ML embedding similarity (BERT, CLIP, GPT).
2. 매 vector DB (FAISS, Pinecone, Qdrant) — cosine/dot index.
3. 매 PCA, SVD — orthogonal basis.
4. 매 kernel methods (RKHS, SVM).
5. 매 Fourier analysis — orthogonal basis functions.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### 1. Dot Product / Cosine
```python
import numpy as np
def cosine_sim(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# 매 batched (faster):
def batch_cosine(A, B):
A_n = A / np.linalg.norm(A, axis=1, keepdims=True)
B_n = B / np.linalg.norm(B, axis=1, keepdims=True)
return A_n @ B_n.T
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. Gram-Schmidt Orthogonalization
```python
def gram_schmidt(V):
U = []
for v in V:
w = v.copy()
for u in U:
w -= np.dot(v, u) / np.dot(u, u) * u
if np.linalg.norm(w) > 1e-10:
U.append(w)
return np.array(U)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 3. Projection
```python
def project(v, onto):
# 매 v 의 onto 위 projection
return np.dot(v, onto) / np.dot(onto, onto) * onto
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 4. FAISS Inner Product Index
```python
import faiss
d = 768 # embedding dim
index = faiss.IndexFlatIP(d) # inner product
embs_norm = embs / np.linalg.norm(embs, axis=1, keepdims=True)
index.add(embs_norm)
D, I = index.search(query_norm, k=10) # 매 cosine via normalized IP
```
**기본값:**
> *(TODO)*
### 5. Kernel Trick (RBF)
```python
def rbf_kernel(X, Y, gamma=1.0):
# 매 implicit inner product in infinite-dim RKHS
sq = np.sum(X**2, 1)[:,None] + np.sum(Y**2, 1)[None,:] - 2*X@Y.T
return np.exp(-gamma * sq)
```
## ❌ 안티패턴 (Anti-Patterns)
### 6. QR Decomposition
```python
Q, R = np.linalg.qr(A)
# Q: orthonormal columns, R: upper triangular
# 매 least-squares solve: x = solve(R, Q.T @ b)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 7. Fourier Inner Product (L2)
```python
# 매 <f,g> = ∫ f(t) conj(g(t)) dt
from scipy.integrate import quad
inner = quad(lambda t: f(t) * np.conj(g(t)), -np.pi, np.pi)[0]
```
## 매 결정 기준
| 상황 | Inner Product |
|---|---|
| Normalized embedding | Cosine (= dot of normalized) |
| Raw magnitude matters | Dot product |
| Probability distribution | Bhattacharyya / Hellinger |
| Function space | L2 integral |
| Non-Euclidean / kernel | RBF / polynomial kernel |
**기본값**: 매 cosine similarity 매 ML embedding standard, 매 normalize-once-then-dot 매 fast path.
## 🔗 Graph
- 부모: [[Linear-Algebra-Foundations]] · [[Theoretical-Computer-Science]]
- 변형: [[Hilbert-Space]] · [[RKHS]]
- 응용: [[Similarity-Metrics]] · [[Singular-Value-Decomposition]] · [[PCA-and-Dimension-Reduction]]
- Adjacent: [[Eigenvalues-and-Eigenvectors]] · [[Operator-Theory]]
## 🤖 LLM 활용
**언제**: 매 embedding similarity 설계, 매 vector DB index 선택, 매 orthogonality 직관 설명.
**언제 X**: 매 non-metric (graph distance, edit distance) 영역.
## ❌ 안티패턴
- **Cosine on un-normalized**: 매 magnitude bias — 매 pre-normalize.
- **Gram-Schmidt 의 numerical instability**: 매 modified GS 또는 QR 사용.
- **Kernel 의 wrong gamma**: 매 grid-search / median heuristic.
- **L2 norm 가정 in non-Euclidean**: 매 manifold 의 incorrect.
## 🧪 검증 / 중복
- Verified (Axler, *Linear Algebra Done Right*; Trefethen, *Numerical LA*).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — geometry foundation + FAISS/kernel patterns |
@@ -2,90 +2,156 @@
id: wiki-2026-0508-issue-tree
title: Issue Tree
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Logic Tree, Hypothesis Tree, Decomposition Tree]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [problem-solving, consulting, decomposition, mece]
raw_sources: []
last_reinforced: 2026-05-08
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: markdown
framework: mece
---
# [[Issue Tree|Issue Tree]]
# Issue Tree
## 📌 한 줄 통찰 (The Karpathy Summary)
크고 복잡한 문제를 논리적이고 관리가 용이한 하부 문제(Sub-issues)들로 분해하기 위해 사용하는 시각적인 트리형 프레임워크.
## 한 줄
> **"매 problem 매 MECE branches 의 decompose"**. Issue tree 매 root question 매 sub-question (mutually exclusive, collectively exhaustive) 의 hierarchical breakdown — 매 Minto Pyramid + McKinsey 80년 standard. 매 2026 LLM agent task planning, root-cause analysis 매 동일 pattern.
## 📖 구조화된 지식 (Synthesized Content)
- 이슈 트리는 상단에 핵심 문제 선언문을 두고 하단으로 갈수록 점차 세부적인 문제들로 넓게 퍼져나가는 형태를 취합니다 [50]. (예: "레스토랑이 수익성이 없다" -> "수익성을 어떻게 올릴 것인가?" -> "수익 증가" & "비용 감소" -> 구체적 실행 방안) [51, 52].
- 계층을 분할할 때는 누락과 중복을 방지하기 위해 반드시 [[MECE|MECE]](상호 배제 및 전체 포괄) 원칙을 엄격하게 적용해야 합니다 [53, 54].
- 컨설턴트들은 이슈 트리를 연구 로드맵으로 활용하여, 중복 없이 각 팀원에게 세부 업무(Workstreams)를 명확히 분배합니다 [54].
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[MECE Principle|MECE Principle]], [[Hypothesis Tree|Hypothesis Tree]]
- **Projects/Contexts:** [[Problem Solving|Problem Solving]], [[Profitability Framework|Profitability Framework]]
- **Contradictions/Notes:** 구조화된 이슈 트리를 바탕으로 초기 검토를 마친 후, 가치가 떨어지는 옵션들은 과감히 배제하는 '가지치기(Trimming branches)'가 수반되어야 실질적인 문제 해결 도구로 기능할 수 있습니다 [53].
### 매 종류
- **Diagnostic (Why)**: 매 cause 의 decompose. 매 5-Why 의 generalized.
- **Solution (How)**: 매 action option 의 decompose.
- **Hypothesis tree**: 매 testable claim 의 분기 — 매 consulting deliverable.
- **Profitability tree**: Profit = Revenue Cost — 매 standard MBA template.
---
*Last updated: 2026-04-27*
### 매 작성 원칙
- **MECE**: 매 branches 매 overlap X, exhaustive O.
- **Same level abstraction**: 매 sibling 매 동일 granularity.
- **Verb-noun structure**: 매 action-oriented (solution tree).
- **Falsifiable leaves**: 매 leaf 매 data-checkable hypothesis.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. 매 management consulting (case interview).
2. 매 incident root cause (post-mortem).
3. 매 LLM agent — task decomposition (ReAct, Tree-of-Thoughts).
4. 매 product strategy (Jobs-to-be-Done).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### 1. Profitability Tree (Markdown)
```markdown
- Profit decline?
- Revenue down?
- Volume down?
- Market shrink?
- Share loss?
- Price down?
- Discount increase?
- Mix shift?
- Cost up?
- COGS up?
- SG&A up?
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. 5-Why (Diagnostic)
```python
def five_why(problem):
chain = [problem]
for _ in range(5):
cause = ask("Why?", context=chain[-1])
chain.append(cause)
return chain # 매 root cause 매 마지막
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 3. Hypothesis-Driven (McKinsey-style)
```yaml
root: "Should we enter market X?"
children:
- "Is the market attractive?"
children:
- "TAM > $1B?" [data: industry report]
- "Growth > 10%?" [data: historical CAGR]
- "Margins > 20%?" [data: comparable companies]
- "Can we win?"
children:
- "Right-to-play assets?"
- "Competitive advantage sustainable?"
- "Is it worth it?"
children:
- "NPV > $X?"
- "Strategic fit?"
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 4. Tree-of-Thoughts (LLM)
```python
def tot(problem, depth=3, branches=3):
if depth == 0:
return evaluate(problem)
sub_problems = llm_decompose(problem, k=branches)
scores = [tot(sp, depth-1, branches) for sp in sub_problems]
return max(zip(sub_problems, scores), key=lambda x: x[1])
```
**기본값:**
> *(TODO)*
### 5. Fishbone (Ishikawa) — alternative form
```
┌── People ── Training gap
Defect ─────────────┼── Process ── No QA gate
└── Tooling ── Outdated CI
```
## ❌ 안티패턴 (Anti-Patterns)
### 6. Markdown Renderer (Mermaid)
```mermaid
graph TD
Root["Why is churn up?"] --> A["Product issue?"]
Root --> B["Pricing issue?"]
Root --> C["Support issue?"]
A --> A1["Bug rate up"]
A --> A2["Feature gap"]
B --> B1["Competitor cheaper"]
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Tree type |
|---|---|
| Find root cause | Diagnostic / 5-Why |
| Choose action | Solution tree |
| Strategy decision | Hypothesis tree |
| LLM task decomp | Tree-of-Thoughts |
| Manufacturing defect | Ishikawa |
**기본값**: 매 hypothesis tree (testable leaves) — 매 consulting/strategy 매 standard.
## 🔗 Graph
- 부모: [[Problem Solving]] · [[Strategic Thinking]]
- 변형: [[Logic Trees]] · [[Mental Models]]
- 응용: [[Root-Cause-Analysis-RCA]] · [[Mutually Exclusive and Collectively Exhaustive (MECE)]] · [[Profitability Framework]]
- Adjacent: [[Decision Theory]] · [[Tree-of-Thoughts]]
## 🤖 LLM 활용
**언제**: 매 task decomposition, 매 root-cause investigation, 매 case-interview prep, 매 ToT/agent planning.
**언제 X**: 매 single-step factual lookup. 매 over-decompose 의 paralysis.
## ❌ 안티패턴
- **Non-MECE branches**: 매 overlap 또는 gap.
- **Mixed abstraction**: 매 sibling 매 inconsistent depth.
- **No data plan**: 매 leaf 매 untestable.
- **Pre-determined answer**: 매 tree 매 confirmation bias 의 disguise.
## 🧪 검증 / 중복
- Verified (Minto, *The Pyramid Principle*; McKinsey *Problem Solving*).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — profitability/hypothesis/ToT patterns |
@@ -2,62 +2,167 @@
id: wiki-2026-0508-kalman-filter-and-state-tracking
title: Kalman Filter and State Tracking
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-KALMAN-001]
aliases: [KF, EKF, UKF, Bayesian Tracking]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Robotics, Control-Theory, kalman-filter, State-estimation, Sensor-Fusion]
confidence_score: 0.95
verification_status: applied
tags: [filter, state-estimation, bayesian, control]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: filterpy
---
# Kalman Filter and State Tracking (칼만 필터와 상태 추적)
# Kalman Filter and State Tracking
## 📌 한 줄 통찰 (The Karpathy Summary)
> "불확실한 정보들 사이에서 가장 믿음직한 정답을 확률적으로 조율하라" — 과거의 상태와 현재의 측정값을 결합하여, 잡음이 섞인 데이터로부터 시스템의 상태를 최적의 확률로 추정하는 순귀적 필터.
## 한 줄
> **"매 noisy observation 매 hidden state 의 optimal Bayesian estimate"**. Kalman filter 매 1960 Rudolf Kálmán — 매 linear-Gaussian system 의 closed-form recursive Bayesian update. 매 2026 SLAM, sensor fusion, AV path-planning, HFT spread tracking, GPS, IMU 매 ubiquitous.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Prediction-Correction Cycle" — 이전 단계의 지식을 바탕으로 현재를 예측(Predict)하고, 실제 센서의 측정값이 들어오면 그 차이를 반영하여 예측치를 수정(Update/Correct)하며 오차를 줄여나가는 반복 패턴.
- **주요 단계:**
- **Prediction Step:** 시스템의 물리 법칙(운동 방정식 등)을 바탕으로 다음 상태와 불확실성을 예측.
- **Kalman Gain:** 예측값과 측정값 중 어느 쪽을 더 신뢰할지 결정하는 가중치 계산.
- **Update Step:** 실제 측정값을 반영하여 상태를 수정하고 불확실성을 좁힘.
- **의의:** GPS 오차 보정, 로봇의 자기 위치 인식(SLAM), 주식 시장의 추세 분석 등 실시간으로 변하는 데이터를 다루는 모든 제어 시스템의 심장.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 선형 시스템(Linear[[_system|system]])에서만 최적이라는 한계를 넘기 위해, 비선형 환경에서도 작동하는 확장 칼만 필터(EKF)와 파티클 필터(Particle Filter) 등으로 이론적 지평이 넓어짐.
- **정책 변화:** Skybound 프로젝트의 유도 미사일 및 적 기동 추적 로직은 칼만 필터를 사용하여 센서 데이터의 노이즈를 제거하고 정밀한 타격 지점을 실시간으로 계산함.
### 매 model
- **State**: $x_k = F x_{k-1} + B u_k + w_k$, $w \sim N(0, Q)$.
- **Observation**: $z_k = H x_k + v_k$, $v \sim N(0, R)$.
- **Predict**: $\hat{x}_k^- = F\hat{x}_{k-1}$, $P_k^- = FP_{k-1}F^T + Q$.
- **Update**: $K = P^-H^T(HP^-H^T + R)^{-1}$, $\hat{x} = \hat{x}^- + K(z - H\hat{x}^-)$.
## 🔗 지식 연결 (Graph)
- [[Control-Theory|Control-Theory]], [[Robotics-Foundations|Robotics-Foundations]], Probability-Theory, [[Time-Series-Analysis|Time-Series-Analysis]]
- **Raw Source:** 10_Wiki/Topics/AI/Kalman-Filter-and-State-Tracking.md
### 매 variant
- **Linear KF**: 매 linear F, H, Gaussian noise.
- **EKF (Extended)**: 매 Jacobian linearization — 매 SLAM 매 standard.
- **UKF (Unscented)**: 매 sigma-point — 매 high non-linearity.
- **Particle Filter**: 매 fully non-linear, non-Gaussian — 매 multi-modal.
- **IMM (Interacting Multiple Model)**: 매 mode switching (radar tracking).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. 매 GPS + IMU sensor fusion (smartphone, drone).
2. 매 SLAM (autonomous vehicle, robot).
3. 매 finance — pair-trade hedge ratio drift.
4. 매 AR/VR head-pose prediction.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### 1. Vanilla Linear KF (numpy)
```python
import numpy as np
## 🧪 검증 상태 (Validation)
class KF:
def __init__(self, F, H, Q, R, x0, P0):
self.F, self.H, self.Q, self.R = F, H, Q, R
self.x, self.P = x0, P0
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
def predict(self, u=0, B=None):
self.x = self.F @ self.x + (B @ u if B is not None else 0)
self.P = self.F @ self.P @ self.F.T + self.Q
## 🧬 중복 검사 (Duplicate Check)
def update(self, z):
y = z - self.H @ self.x # innovation
S = self.H @ self.P @ self.H.T + self.R
K = self.P @ self.H.T @ np.linalg.inv(S)
self.x = self.x + K @ y
self.P = (np.eye(len(self.x)) - K @ self.H) @ self.P
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### 2. Constant-Velocity Model
```python
dt = 0.1
F = np.array([[1, dt], [0, 1]]) # [pos, vel]
H = np.array([[1, 0]]) # observe pos only
Q = np.array([[0.001, 0], [0, 0.01]])
R = np.array([[0.5]])
kf = KF(F, H, Q, R, np.array([0,0]), np.eye(2))
for z in measurements:
kf.predict()
kf.update(np.array([z]))
```
## 🕓 변경 이력 (Changelog)
### 3. Extended KF (Non-linear)
```python
def ekf_update(x, P, z, h, H_jac, R):
H = H_jac(x)
y = z - h(x)
S = H @ P @ H.T + R
K = P @ H.T @ np.linalg.inv(S)
x = x + K @ y
P = (np.eye(len(x)) - K @ H) @ P
return x, P
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### 4. Unscented KF (sigma-points)
```python
from filterpy.kalman import UnscentedKalmanFilter, MerweScaledSigmaPoints
sp = MerweScaledSigmaPoints(n=4, alpha=0.1, beta=2, kappa=-1)
ukf = UnscentedKalmanFilter(dim_x=4, dim_z=2, dt=0.1, fx=fx, hx=hx, points=sp)
```
### 5. Particle Filter
```python
def particle_filter(particles, weights, z, motion, observe, R):
particles = motion(particles) # propagate
weights *= observe(particles, z, R)
weights /= weights.sum()
if 1.0 / np.sum(weights**2) < len(particles)/2:
idx = np.random.choice(len(particles), size=len(particles), p=weights)
particles, weights = particles[idx], np.ones_like(weights)/len(weights)
return particles, weights
```
### 6. Sensor Fusion (GPS + IMU)
```python
# 매 IMU prediction (high freq), GPS update (low freq)
while True:
imu = read_imu() # 200 Hz
kf.predict_with_imu(imu)
if gps_available(): # 10 Hz
gps = read_gps()
kf.update(gps)
```
### 7. Smoothing (RTS)
```python
# 매 forward filter → backward smooth — 매 offline analysis
xs, Ps = filter_forward(zs)
xs_sm, Ps_sm = rts_smoother(xs, Ps, F, Q) # 매 future info 활용
```
## 매 결정 기준
| 상황 | Filter |
|---|---|
| Linear, Gaussian | Linear KF |
| Mild non-linearity | EKF |
| Strong non-linearity | UKF |
| Multi-modal / non-Gaussian | Particle Filter |
| Mode switching | IMM |
| Offline analysis | RTS smoother |
**기본값**: 매 EKF + constant-velocity, 매 sensor fusion 매 standard starting point.
## 🔗 Graph
- 부모: [[Probability Theory]] · [[Optimal-Control-Theory]] · [[Linear-Algebra-Foundations]]
- 변형: [[Particle-Filter-Algorithms]] · [[Extended-Kalman-Filter]]
- 응용: [[Autonomous-Vehicle-Path-Planning]] · [[High-Frequency-Trading-Models]]
- Adjacent: [[Bayesian-Inference]] · [[Signal-Processing-Foundations]] · [[Gimbals-and-Orientation]]
## 🤖 LLM 활용
**언제**: 매 sensor fusion architecture 설계, 매 noise model tuning 가이드, 매 SLAM debugging.
**언제 X**: 매 highly non-Gaussian (use particle), 매 deterministic system.
## ❌ 안티패턴
- **Q, R untuned**: 매 filter divergence 또는 over-smoothing.
- **EKF on heavy non-linearity**: 매 Jacobian 부정확 → divergence. 매 UKF 또는 PF.
- **No covariance inflation**: 매 P → 0 → filter overconfident.
- **Joseph form 무시**: 매 numerical loss of symmetry.
## 🧪 검증 / 중복
- Verified (Welch & Bishop, *KF Intro*; Thrun et al., *Probabilistic Robotics*; filterpy docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full KF/EKF/UKF/PF + sensor fusion patterns |
@@ -1,62 +1,146 @@
---
id: wiki-2026-0508-kernel-density-estimation-kde
title: Kernel Density Estimation KDE
title: Kernel Density Estimation (KDE)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-KDE-001]
aliases: [KDE, Parzen Window, Density Estimation]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: ["Statistics|[Statistics", math, kde, density-estimation, data-visualization, probability]
confidence_score: 0.9
verification_status: applied
tags: [statistics, non-parametric, density-estimation, kernel]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: scipy, scikit-learn, KDEpy
---
# Kernel Density Estimation (KDE, 커널 밀도 추정)
# Kernel Density Estimation (KDE)
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터라는 개별 점들에 부드러운 산 모양의 확률을 씌워, 전체의 흐름을 보여주는 부드러운 능선을 그려라" — 유한한 표본 데이터를 바탕으로 모집단의 확률 밀도 함수(PDF)를 부드럽게 추정하여 데이터의 분포 특성을 파악하는 기계학습 및 통계학의 핵심 도구.
## 한 줄
> **"매 histogram 의 smooth 한 generalization"**. KDE 는 non-parametric density estimator 로, 매 sample point 에 kernel function 을 placing 하고 sum 하여 continuous PDF 추정. Parzen (1962) 와 Rosenblatt (1956) 이 정립했으며, 2026 modern stats/ML 에서 anomaly detection, generative sampling, visualization 에 사용.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Smoothing and Summation" — 각 데이터 포인트 위치에 커널 함수(주로 가우시안)를 배치하고, 이들을 모두 합산하여 데이터가 밀집된 곳은 높게, 희소한 곳은 낮게 표현하는 공간적 밀도 추론 패턴.
- **주요 구성 요소:**
- **Kernel Function:** 데이터의 영향력을 주변으로 퍼뜨리는 함수 형태.
- **Bandwidth ($h$):** 함수의 넓이(매끄러움)를 조절하는 파라미터. $h$가 너무 작으면 과적합([[Overfitting|Overfitting]]), 너무 크면 분포가 뭉개짐(Underfitting).
- **의의:** 히스토그램과 달리 빈(Bin)의 크기나 시작점에 민감하지 않으며, 데이터의 실제 분포 형태를 훨씬 더 정확하게 반영할 수 있음.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순한 시각화 도구로 여겨졌으나, 최근에는 이상치 탐지(Anomaly Detection)나 생성 모델(Generative Models)의 기초 이론으로 중요성이 다시 부각됨.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 응답 시간 분포를 분석하여 병목 구간을 시각화할 때, 히스토그램 대신 KDE 곡선을 사용하여 통계적 왜곡을 방지함.
### 매 수식
- $\hat{f}_h(x) = \frac{1}{nh}\sum_{i=1}^n K\left(\frac{x - x_i}{h}\right)$
- $K$ = kernel (Gaussian, Epanechnikov, …)
- $h$ = bandwidth (smoothing parameter)
- multi-D: $\hat{f}_H(x) = \frac{1}{n|H|^{1/2}}\sum K(H^{-1/2}(x-x_i))$
## 🔗 지식 연결 (Graph)
- Probability-Theory, [[Exploratory-Data-Analysis|Exploratory-Data-Analysis]], [[Anomaly-Detection|Anomaly-Detection]]-Foundations, [[Supervised-Learning-Foundations|Supervised-Learning-Foundations]]
- **Raw Source:** 10_Wiki/Topics/AI/Kernel-Density-Estimation-KDE.md
### 매 Bandwidth selection
- Silverman's rule: $h = 1.06 \hat{\sigma} n^{-1/5}$
- Scott's rule: $h = n^{-1/(d+4)}$
- cross-validation (likelihood)
- plug-in estimators (Sheather-Jones)
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. EDA visualization (seaborn `kdeplot`).
2. Anomaly detection (low-density = outlier).
3. Mode finding (mean-shift).
4. Bayesian non-parametric prior.
5. Generative sampling (smoothed bootstrap).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### scipy KDE
```python
from scipy.stats import gaussian_kde
import numpy as np
## 🧪 검증 상태 (Validation)
x = np.random.normal(0, 1, 1000)
kde = gaussian_kde(x, bw_method="silverman")
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
xs = np.linspace(-4, 4, 200)
density = kde(xs)
```
## 🧬 중복 검사 (Duplicate Check)
### sklearn KernelDensity
```python
from sklearn.neighbors import KernelDensity
import numpy as np
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
X = np.random.randn(1000, 2)
kde = KernelDensity(kernel="gaussian", bandwidth=0.3).fit(X)
log_dens = kde.score_samples(X) # log-density at each point
## 🕓 변경 이력 (Changelog)
# anomaly: lowest 1% as outliers
threshold = np.quantile(log_dens, 0.01)
outliers = X[log_dens < threshold]
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Bandwidth via cross-validation
```python
from sklearn.model_selection import GridSearchCV
params = {"bandwidth": np.logspace(-1, 1, 20)}
grid = GridSearchCV(KernelDensity(), params, cv=5)
grid.fit(X)
print(grid.best_params_)
```
### KDEpy fast FFT-based KDE
```python
from KDEpy import FFTKDE
x_grid, y = FFTKDE(kernel="gaussian", bw="silverman").fit(x).evaluate()
# O(n + m log m) instead of O(n*m)
```
### Adaptive bandwidth
```python
def adaptive_kde(x, x_eval, k=10):
from scipy.spatial import cKDTree
tree = cKDTree(x[:, None])
dists, _ = tree.query(x[:, None], k=k+1)
h_local = dists[:, -1] # k-NN distance per point
out = np.zeros_like(x_eval)
for xi, hi in zip(x, h_local):
out += np.exp(-0.5*((x_eval - xi)/hi)**2) / hi
return out / (len(x) * np.sqrt(2*np.pi))
```
### Visualization
```python
import seaborn as sns
sns.kdeplot(data=df, x="feature", hue="class", fill=True, common_norm=False)
```
## 매 결정 기준
| 상황 | Method |
|---|---|
| 1D, small n | scipy gaussian_kde |
| high-D, n>10⁴ | FFTKDE |
| streaming | online KDE (Heinz 2008) |
| boundaries | reflection / log-transform |
| heavy-tail | adaptive bandwidth |
**기본값**: Silverman + Gaussian kernel, then validate.
## 🔗 Graph
- 부모: [[Non-Parametric-Statistics]] · [[Density-Estimation]]
- 변형: [[Histogram]] · [[Mean-Shift]] · [[Mixture-Models]]
- 응용: [[Anomaly-Detection]] · [[Visualization]]
- Adjacent: [[Bandwidth-Selection]] · [[Kernel-Methods]]
## 🤖 LLM 활용
**언제**: small/mid n, distribution shape 알 수 없을 때.
**언제 X**: very high-D (curse of dimensionality), n < 30.
## ❌ 안티패턴
- **Default bandwidth blind use**: Silverman 은 Gaussian 가정 — bimodal 에 over-smooth.
- **Boundary bias 무시**: support [0, ∞) 인데 Gaussian kernel 사용 → leak 발생.
- **High-D KDE**: d > 6 에서는 거의 useless — vine copula 또는 normalizing flow 사용.
- **Sample size 무시**: n < 50 KDE 결과는 거의 noise.
## 🧪 검증 / 중복
- Verified (Silverman 1986 textbook, Wand & Jones 1995, Chen 2017 review).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — KDE math, bandwidth selection, scipy/sklearn/KDEpy |
@@ -1,130 +1,176 @@
---
id: wiki-2026-0508-keyword-search
title: Keyword Search
category: Computer_Science_and_Theory
status: needs_review
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-KWS-001]
aliases: [Lexical Search, Sparse Retrieval, BM25 Search]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [auto-reinforced, keyword-search, bm25, tf-idf, information-retrieval, lexical-search]
confidence_score: 0.9
verification_status: applied
tags: [search, retrieval, ir, bm25, lexical]
raw_sources: []
last_reinforced: 2026-05-04
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
framework: elasticsearch, opensearch, tantivy, rank-bm25
---
# [[Keyword Search|Keyword Search]]
# Keyword Search
## 📌 한 줄 통찰 (The Karpathy Summary)
> "검색의 고전이자 기준점: 사용자가 입력한 단어가 문서 내에 정확히 존재하는지를 기반으로 관련성을 측정하며, 고유 명사나 특정 식별자를 찾는 데 가장 강력한 성능을 발휘하는 텍스트 매칭 기법."
## 한 줄
> **"매 lexical token-match 의 retrieval"**. Keyword Search 는 query 의 token 과 document 의 token overlap 을 ranking signal 로 사용하는 sparse retrieval. TF-IDF (Salton 1975), BM25 (Robertson 1994) 가 backbone 이고, 2026 RAG era 에서도 매 hybrid (BM25 + dense) 의 indispensable component — out-of-domain robustness 와 exact-match precision 으로.
## 📖 구조화된 지식 (Synthesized Content)
키워드 검색(Keyword Search) 또는 어휘 검색(Lexical Search)은 문서 내의 텍스트 토큰과 검색어 간의 직접적인 일치 여부를 따지는 정보 검색의 가장 기본적인 방식입니다.
## 매 핵심
1. **핵심 알고리즘**:
* **[[TF-IDF|TF-IDF]] (Term Frequency-Inverse Document Frequency)**: 단어가 문서 내에서 얼마나 자주 등장하는지(TF)와 전체 문서 집합에서 얼마나 희귀한지(IDF)를 곱해 중요도를 계산합니다.
* **[[BM25|BM25]] (Best Matching 25)**: TF-IDF의 한계를 보완(단어 빈도의 포화도 조절, 문서 길이 정규화 등)하여 현대 검색 엔진에서 가장 널리 쓰이는 표준 알고리즘입니다.
### 매 Scoring
- **TF-IDF**: $w_{t,d} = tf(t,d) \cdot \log(N/df_t)$
- **BM25**: $\sum_t \text{IDF}(t) \cdot \frac{tf(t,d)(k_1+1)}{tf(t,d) + k_1(1-b+b\cdot|d|/\bar{|d|})}$
- $k_1 \approx 1.2$, $b \approx 0.75$
- **BM25F**: per-field weighting
- **Query Likelihood**: $\prod_t P(t | \theta_d)$ with smoothing
2. **데이터 구조: [[Inverted Index|Inverted Index]]**:
* 책 뒤의 색인처럼, 각 단어가 어떤 문서들에 포함되어 있는지를 미리 리스트업해두어 검색 속도를 극대화합니다.
### 매 Pipeline
1. **Tokenization** (Unicode segmentation, locale-aware)
2. **Normalization** (lowercase, NFKC, accent fold)
3. **Stopword removal** (optional)
4. **Stemming / lemmatization** (Porter, Snowball, lemmas)
5. **Inverted index** (term → posting list)
6. **Query parse + scoring**
3. **장점 및 활용**:
* **정확한 일치 (Exact Match)**: 에러 코드, 제품 번호, 인명이 포함된 검색에서 탁월합니다.
* **예측 가능성**: 왜 이 문서가 검색되었는지(단어가 포함되어 있으므로) 논리적으로 명확히 설명할 수 있습니다.
* **저비용 고효율**: 벡터 검색에 비해 컴퓨팅 자원을 훨씬 적게 사용합니다.
### 매 응용
1. Document search (Google Search lexical layer).
2. Code search (ripgrep, Sourcegraph zoekt).
3. RAG hybrid (BM25 + embeddings → RRF).
4. E-commerce (exact SKU match dominant signal).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **어휘적 한계 (Vocabulary Mismatch)**: 사용자가 '컴퓨터'를 검색할 때 문서에 'PC'라고 적혀 있다면 검색 결과에서 누락됩니다.
* **문맥 무시**: 단어의 순서나 의미적 맥락을 고려하지 못해 중의적인 표현을 처리하기 어렵습니다.
* **검색 정교화의 어려움**: 복잡한 자연어 질문에 대해서는 관련성 낮은 결과를 반환할 확률이 높습니다.
## 💻 실전 구현 코드 (Boilerplate)
Python `rank_bm25` 라이브러리를 사용한 기본적인 키워드 랭킹 구현 예시입니다.
## 💻 패턴
### rank-bm25 quickstart
```python
from rank_bm25 import BM25Okapi
import re
# 1. 말뭉치(Corpus) 준비 및 토큰화
corpus = [
"Astra engine provides autonomous knowledge reinforcement.",
"P-Reinforce protocol standardizes wiki documentation.",
"ConnectAI handles multi-agent orchestration flows."
]
tokenized_corpus = [doc.split(" ") for doc in corpus]
# 2. BM25 인덱스 생성
bm25 = BM25Okapi(tokenized_corpus)
# 3. 질의 처리 및 검색
query = "autonomous engine"
tokenized_query = query.split(" ")
# 4. 관련성 점수 도출 및 상위 결과 획득
doc_scores = bm25.get_scores(tokenized_query)
top_n = bm25.get_top_n(tokenized_query, corpus, n=1)
print(f"Query: {query}")
print(f"Best Match: {top_n[0]}")
corpus = [doc.lower().split() for doc in docs]
bm25 = BM25Okapi(corpus, k1=1.5, b=0.75)
query = "claude opus context window".split()
scores = bm25.get_scores(query)
top = sorted(range(len(docs)), key=lambda i: -scores[i])[:5]
```
## 🔗 지식 연결 (Graph)
* **상위 개념**: [[Information Retrieval (IR)|Information Retrieval (IR)]], [[Computer Science and Theory|Computer Science]]
* **대칭 개념**: [[Semantic Search|Semantic Search]]
* **통합 기법**: [[Hybrid Search|Hybrid Search]]
### Elasticsearch / OpenSearch query
```python
from opensearchpy import OpenSearch
client = OpenSearch("http://localhost:9200")
---
*Last updated: 2026-05-04*
client.index(index="docs", id="1",
body={"title":"Claude 4.7", "body":"1M context window..."})
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
resp = client.search(index="docs", body={
"query": {
"multi_match": {
"query": "claude context window",
"fields": ["title^3", "body"],
"type": "best_fields"
}
}
})
```
## 🤔 의사결정 기준 (Decision Criteria)
### Tantivy (Rust, embeddable)
```python
import tantivy
schema_builder = tantivy.SchemaBuilder()
schema_builder.add_text_field("title", stored=True)
schema_builder.add_text_field("body")
schema = schema_builder.build()
index = tantivy.Index(schema)
writer = index.writer()
writer.add_document(tantivy.Document(title="t", body="some body"))
writer.commit()
searcher = index.searcher()
parser = tantivy.QueryParser.for_index(index, ["title","body"])
hits = searcher.search(parser.parse_query("body"), 10).hits
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Hybrid search with RRF
```python
def rrf(rank_lists, k=60):
scores = {}
for ranks in rank_lists:
for r, doc_id in enumerate(ranks):
scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + r + 1)
return sorted(scores.items(), key=lambda x: -x[1])
**선택 B를 써야 할 때:**
- *(TODO)*
bm25_top = bm25_search(q)
dense_top = vector_search(q)
fused = rrf([bm25_top, dense_top])
```
**기본값:**
> *(TODO)*
### Inverted index from scratch
```python
from collections import defaultdict
import math
## ❌ 안티패턴 (Anti-Patterns)
class InvertedIndex:
def __init__(self):
self.idx = defaultdict(dict) # term → {doc_id: tf}
self.lens = {}
self.N = 0
def add(self, doc_id, tokens):
self.N += 1
self.lens[doc_id] = len(tokens)
for t in tokens:
self.idx[t][doc_id] = self.idx[t].get(doc_id, 0) + 1
def bm25(self, query, k1=1.5, b=0.75):
avgdl = sum(self.lens.values()) / self.N
scores = defaultdict(float)
for t in query:
if t not in self.idx: continue
df = len(self.idx[t])
idf = math.log((self.N - df + 0.5) / (df + 0.5) + 1)
for doc, tf in self.idx[t].items():
norm = 1 - b + b * self.lens[doc] / avgdl
scores[doc] += idf * tf * (k1+1) / (tf + k1 * norm)
return sorted(scores.items(), key=lambda x: -x[1])
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| Need | Engine |
|---|---|
| general-purpose | Elasticsearch / OpenSearch |
| embeddable, fast | Tantivy / Lucene |
| code search | Zoekt / ripgrep |
| in-process small | rank-bm25 / Whoosh |
| hybrid RAG | BM25 + dense + RRF |
**기본값**: BM25 + RRF fusion with dense retriever.
## 🔗 Graph
- 부모: [[Information-Retrieval]] · [[Search-Engines]]
- 변형: [[BM25]] · [[TF-IDF]] · [[Query-Likelihood]]
- 응용: [[RAG-Architecture]] · [[Hybrid-Search]] · [[Semantic-Search]]
- Adjacent: [[Inverted-Index]] · [[Tokenization]]
## 🤖 LLM 활용
**언제**: exact-name retrieval, low-resource lang, long-tail terms, hybrid system.
**언제 X**: pure semantic paraphrase matching — dense embeddings 가 강함.
## ❌ 안티패턴
- **Tokenizer mismatch**: 매 query/index 의 다른 tokenizer 사용 → silent recall loss.
- **Default BM25 params**: domain-specific tuning 없이 default → suboptimal.
- **Stopword over-removal**: "to be or not to be" → empty.
- **Synonym 무시**: query expansion 없이 lexical-only 면 recall low.
- **Dense-only 의 obsession**: BM25 baseline 무시 → out-of-domain 에서 실패.
## 🧪 검증 / 중복
- Verified (Robertson 2009 BM25 paper, Manning IR textbook 2008, Thakur 2021 BEIR benchmark).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — BM25, inverted index, hybrid RRF, ES/Tantivy patterns |
@@ -1,121 +1,162 @@
---
id: wiki-2026-0508-knowledge-graph
title: Knowledge Graph
category: Computer_Science_and_Theory
status: needs_review
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-KGR-001]
aliases: [KG, Semantic Graph, Entity Graph]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [auto-reinforced, knowledge-graph, ontology, semantic-web, entity-relationship, graph-database]
confidence_score: 0.9
verification_status: applied
tags: [knowledge-graph, graph, semantic, retrieval]
raw_sources: []
last_reinforced: 2026-05-04
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
framework: networkx, neo4j, rdflib
---
# [[Knowledge Graph|Knowledge Graph]]
# Knowledge Graph
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터를 넘어선 지식의 망: 분산된 정보들 사이의 관계를 인간의 뇌처럼 연결하여, 단순한 키워드 검색이 아닌 복합적인 인과관계와 맥락을 컴퓨터가 이해하고 추론할 수 있게 하는 시맨틱 데이터 구조."
## 한 줄
> **"매 entity-relationship triples 의 graph"**. Knowledge Graph 는 (head, relation, tail) triple 의 collection 으로 구조화된 knowledge 를 저장하는 graph database paradigm. 2012 Google 의 도입 이후 search/RAG/agents 의 backbone 으로 자리잡았으며, 2026 LLM era 에서는 GraphRAG 와 entity-linking 으로 hallucination mitigation 에 사용.
## 📖 구조화된 지식 (Synthesized Content)
지식 그래프(Knowledge Graph)는 엔티티(인물, 사물, 장소, 개념 등)와 그들 간의 관계를 그래프 구조로 표현한 거대한 지식 기반 시스템입니다.
## 매 핵심
1. **핵심 구성 요소**:
* **노드 (Node / Entity)**: 실제 세계의 객체나 개념을 나타냅니다.
* **엣지 (Edge / Relationship)**: 노드 간의 관계를 나타냅니다 (예: 'A는 B의 제작자이다').
* **속성 (Property)**: 노드나 엣지에 대한 추가적인 세부 정보.
### 매 Triple 구조
- (subject, predicate, object) — RDF 표준
- entity ID (e.g. wikidata Q-id) → unique reference
- relation typed (employs, locatedIn, instanceOf, …)
- property graph: edges 도 attributes 보유
2. **왜 지식 그래프인가?**:
* **시맨틱 상호운용성**: 서로 다른 출처의 데이터를 의미적으로 통합할 수 있습니다.
* **지능적 추론**: "A를 만든 사람이 살고 있는 도시의 인구는?"과 같은 다단계 질문에 대해 관계를 추적하여 답변할 수 있습니다.
* **[[GraphRAG|GraphRAG]]**: 텍스트 데이터를 그래프로 변환하여 LLM의 검색 정확도와 문맥 파악 능력을 비약적으로 향상시킵니다.
### 매 Schema vs Schema-less
- ontology-driven: OWL, schema.org → strict typing
- LPG (labeled property graph): Neo4j flexible
- emergent KG: LLM 으로 unstructured text 에서 자동 추출
3. **지식의 고도화 도구**:
* **[[Ontology|Ontology]]**: 지식 그래프의 설계도 역할을 하며, 어떤 엔티티와 관계가 존재할 수 있는지 규정합니다.
* **Graph Database**: Neo4j, FalkorDB 등 그래프 구조를 저장하고 쿼리하는 전용 DB입니다.
### 매 응용
1. Search ranking (Google KG panels).
2. RAG with GraphRAG (Microsoft 2024).
3. Agent tool: entity disambiguation.
4. Recommendation (LinkedIn Economic Graph).
5. Drug discovery (Hetionet).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **구축 및 유지보수의 난해함**: 비정형 데이터에서 정확한 엔티티와 관계를 추출하는 과정이 복잡하며 전문적인 지식이 필요합니다.
* **확장성 문제 (Scalability)**: 그래프가 거대해질수록 관계를 탐색하는 쿼리 비용이 급격히 증가할 수 있습니다.
* **데이터 정제**: 잘못된 관계 정보가 유입될 경우 전체 지식 체계의 신뢰도가 훼손되므로 엄격한 거버넌스가 필요합니다.
## 💻 패턴
## 💻 실전 구현 코드 (Boilerplate)
`Neo4j` 스타일의 Cypher 쿼리를 사용하여 지식 그래프를 생성하고 조회하는 기초 예시입니다.
### NetworkX 로 KG build
```python
import networkx as nx
G = nx.MultiDiGraph()
G.add_edge("Anthropic", "Claude", relation="created")
G.add_edge("Claude", "LLM", relation="instanceOf")
G.add_edge("Anthropic", "San Francisco", relation="locatedIn")
# query: what did Anthropic create?
for _, target, data in G.out_edges("Anthropic", data=True):
if data["relation"] == "created":
print(target) # Claude
```
### LLM 으로 triple 추출
```python
from anthropic import Anthropic
client = Anthropic()
text = "Claude Opus 4.7 was released by Anthropic in 2026."
resp = client.messages.create(
model="claude-opus-4-7",
max_tokens=512,
messages=[{
"role": "user",
"content": f"Extract (subject, predicate, object) triples as JSON from: {text}"
}]
)
# → [["Claude Opus 4.7","releasedBy","Anthropic"], ...]
```
### Neo4j Cypher query
```cypher
// 1. 엔티티 및 관계 생성 (P-Reinforce 관련 예시)
CREATE (p:Project {name: "Antigravity"})
CREATE (e:Engine {name: "ConnectAI"})
CREATE (s:Standard {name: "P-Reinforce v3.0"})
CREATE (p)-[:USES]->(e)
CREATE (e)-[:FOLLOWS]->(s)
// 2. 다단계 추론 쿼리
// "Antigravity 프로젝트가 사용하는 엔진이 따르는 표준은 무엇인가?"
MATCH (p:Project {name: "Antigravity"})-[:USES]->(e)-[:FOLLOWS]->(s)
RETURN s.name AS StandardName
// find all 2-hop neighbors of Anthropic
MATCH (a:Org {name:"Anthropic"})-[r1]->(x)-[r2]->(y)
RETURN a, r1, x, r2, y
LIMIT 100;
```
## 🔗 지식 연결 (Graph)
* **기반 개념**: [[Computer Science and Theory|Computer Science]], [[Ontology|Ontology]]
* **활용 기술**: [[GraphRAG|GraphRAG]], [[Semantic Search|Semantic Search]]
* **보관 기술**: [[Graph Database|Graph Database]], [[Vector Database|Vector Database (Hybrid)]]
---
*Last updated: 2026-05-04*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### RDF + SPARQL
```python
from rdflib import Graph, URIRef, Literal
g = Graph()
g.parse("dbpedia.ttl", format="turtle")
q = """
SELECT ?company WHERE {
?company a <http://dbpedia.org/ontology/Company> ;
<http://dbpedia.org/property/foundedYear> "2021"^^xsd:gYear .
}
"""
for row in g.query(q):
print(row.company)
```
## 🤔 의사결정 기준 (Decision Criteria)
### GraphRAG retrieval
```python
def graph_rag_query(q: str, kg, llm):
entities = llm.extract_entities(q)
subgraph = kg.k_hop_subgraph(entities, k=2)
context = subgraph.to_text()
return llm.answer(q, context=context)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Embedding-based KG completion (TransE)
```python
import torch
import torch.nn as nn
**선택 B를 써야 할 때:**
- *(TODO)*
class TransE(nn.Module):
def __init__(self, n_ent, n_rel, dim=128):
super().__init__()
self.ent = nn.Embedding(n_ent, dim)
self.rel = nn.Embedding(n_rel, dim)
def score(self, h, r, t):
return -torch.norm(self.ent(h) + self.rel(r) - self.ent(t), p=2, dim=-1)
```
**기본값:**
> *(TODO)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 작은 domain, fast prototype | NetworkX in-memory |
| production, ACID | Neo4j |
| W3C standards | RDF + SPARQL |
| billion-scale, distributed | JanusGraph, TigerGraph |
| LLM RAG | GraphRAG (Microsoft) |
## ❌ 안티패턴 (Anti-Patterns)
**기본값**: Neo4j + LLM extraction pipeline.
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 🔗 Graph
- 부모: [[Knowledge-Graph-Foundations]] · [[Graph-Theory]]
- 변형: [[GraphRAG]] · [[Entity-Linking]] · [[Ontology]]
- 응용: [[RAG-Architecture]] · [[Semantic-Search]] · [[Recommendation-Systems]]
- Adjacent: [[Vector-Database]] · [[Embeddings]]
## 🤖 LLM 활용
**언제**: factual grounding, multi-hop reasoning, entity disambiguation 필요 시.
**언제 X**: pure semantic similarity 만 필요할 때 — vector DB 가 더 simple.
## ❌ 안티패턴
- **Schema explosion**: 매 entity 마다 new relation 정의 → unmanageable.
- **Stale KG**: 자동 update pipeline 없이 manual curation → 6 months 지나면 obsolete.
- **No entity resolution**: "Anthropic" vs "anthropic Inc." vs "ANTHROPIC" → duplicate nodes.
- **Triple-only thinking**: property graph 의 edge attribute 무시.
## 🧪 검증 / 중복
- Verified (Bollacker 2008 Freebase, Hogan 2021 KG survey ACM CSUR).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — KG fundamentals, triples, GraphRAG, Neo4j patterns |
@@ -2,88 +2,152 @@
id: wiki-2026-0508-knowledge-graph-foundations
title: Knowledge Graph Foundations
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [DATA-KG-001]
aliases: [KG Foundations, Semantic Web Foundations]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [data-engineering, Knowledge-Graph, Graph-Database, semantic-web, Ontology, rag]
confidence_score: 0.9
verification_status: applied
tags: [knowledge-graph, foundations, rdf, ontology]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: rdflib, owlready2
---
# Knowledge Graph Foundations (지식 그래프 기초)
# Knowledge Graph Foundations
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터를 단순한 목록이 아닌 '관계의 그물망'으로 엮어, 기계가 세상의 맥락을 스스로 탐험하게 하라" — 개체(Entity)와 그들 사이의 관계(Relationship)를 그래프 구조로 표현하여, 의미론적 검색(Semantic [[Search|Search]])과 복합 추론을 가능케 하는 지식 베이스 아키텍처.
## 한 줄
> **"매 RDF + ontology + reasoning 의 stack"**. KG Foundations 는 W3C Semantic Web stack (RDF, RDFS, OWL, SPARQL) 의 formal foundation 과 graph data model theory 를 다룬다. 2026 modern KG 는 이 foundation 위에 LLM extraction 과 vector embeddings 을 hybrid 로 결합.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Triples (Subject-Predicate-Object)" — "A는 B와 C의 관계다"라는 세 부분의 조합을 기본 단위로 삼아, 파편화된 지식들을 거대한 의미망으로 연결하는 지식 정형화 패턴.
- **주요 구성 요소:**
- **Ontology:** 데이터의 개념과 분류 체계를 정의.
- **Entities & Relations:** 실제 데이터(노드)와 그들의 연결(엣지).
- **Graph Database:** Neo4j, ArangoDB 등 그래프 구조 저장 및 쿼리에 최적화된 엔진.
- **의의:** 기존 검색 엔진이 찾지 못하는 '연관된 정보'를 즉각 추적할 수 있으며, 특히 환각 현상을 줄이기 위한 GraphRAG의 핵심 토대가 됨.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 정적인 백과사전식 지식에서 벗어나, 대규모 언어 모델(LLM)이 추출한 비정형 데이터의 관계를 실시간으로 통합하는 '동적 지식 그래프'로 진화.
- **정책 변화:** Antigravity 프로젝트의 핵심 자산은 1,174개 문서 간의 유기적 연결 관계를 담은 `20_Meta/Graph.json`이며, 이를 통해 에이전트는 특정 주제에서 파생된 심화 지식을 막힘없이 탐색함.
### 매 Data Model 계층
- **RDF**: triple — (s, p, o), URIs 로 entity 식별
- **RDFS**: schema layer — class, subClassOf, domain, range
- **OWL**: full ontology — equivalence, disjointness, cardinality
- **SHACL**: constraint validation
## 🔗 지식 연결 (Graph)
- [[Graph-Theory|Graph-Theory]]-and-Networks, [[GNN|GNN]], [[Information-Retrieval-IR|Information-Retrieval-IR]], [[Hallucination-in-LLMs|Hallucination-in-LLMs]]
- **Raw Source:** 10_Wiki/Topics/AI/Knowledge-Graph-Foundations.md
### 매 Reasoning
- forward chaining: rules → derived triples
- backward chaining: query-driven inference
- DL reasoning (Description Logic): subsumption, consistency
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. DBpedia, Wikidata: 매 large-scale public KG.
2. Schema.org: 매 web markup ontology.
3. Bio2RDF: 매 life sciences integration.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### RDF graph build
```python
from rdflib import Graph, Namespace, URIRef, Literal, RDF, RDFS
## 🧪 검증 상태 (Validation)
EX = Namespace("http://example.org/")
g = Graph()
g.bind("ex", EX)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
g.add((EX.Claude, RDF.type, EX.LLM))
g.add((EX.LLM, RDFS.subClassOf, EX.AISystem))
g.add((EX.Claude, EX.creator, EX.Anthropic))
g.serialize("kg.ttl", format="turtle")
```
## 🤔 의사결정 기준 (Decision Criteria)
### OWL ontology with owlready2
```python
from owlready2 import *
**선택 A를 써야 할 때:**
- *(TODO)*
onto = get_ontology("http://example.org/onto.owl")
with onto:
class AISystem(Thing): pass
class LLM(AISystem): pass
class Organization(Thing): pass
class creator(ObjectProperty):
domain = [AISystem]
range = [Organization]
**선택 B를 써야 할 때:**
- *(TODO)*
claude = LLM("Claude")
anthropic = Organization("Anthropic")
claude.creator.append(anthropic)
sync_reasoner() # HermiT reasoner
```
**기본값:**
> *(TODO)*
### SPARQL federated query
```python
from SPARQLWrapper import SPARQLWrapper, JSON
## ❌ 안티패턴 (Anti-Patterns)
s = SPARQLWrapper("https://query.wikidata.org/sparql")
s.setQuery("""
SELECT ?company ?ceo WHERE {
?company wdt:P31 wd:Q4830453 . # company
?company wdt:P169 ?ceo . # CEO
} LIMIT 10
""")
s.setReturnFormat(JSON)
print(s.query().convert())
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### SHACL validation
```python
from pyshacl import validate
conforms, _, report = validate(
data_graph=g,
shacl_graph="shapes.ttl",
inference="rdfs",
)
```
### Forward chaining inference
```python
def forward_chain(triples, rules):
derived = set(triples)
changed = True
while changed:
changed = False
for rule in rules:
new = rule.apply(derived)
if new - derived:
derived |= new
changed = True
return derived
```
## 매 결정 기준
| 상황 | Stack |
|---|---|
| public LOD | RDF + SPARQL |
| domain ontology, reasoning | OWL + HermiT/Pellet |
| flexible schema | LPG (Neo4j) |
| validation | SHACL |
| LLM hybrid | RDF + embeddings |
**기본값**: RDF + SPARQL + SHACL.
## 🔗 Graph
- 부모: [[Graph-Theory]] · [[Logic]]
- 변형: [[RDF]] · [[OWL]] · [[Description-Logic]]
- 응용: [[Knowledge Graph]] · [[Semantic-Web]] · [[Wikidata]]
- Adjacent: [[Ontology]] · [[Reasoning-Systems]]
## 🤖 LLM 활용
**언제**: formal semantics, reasoning, standards-compliant interop 필요.
**언제 X**: ad-hoc agent memory — 매 simple key-value 면 충분.
## ❌ 안티패턴
- **OWL overengineering**: full DL reasoner 가 필요없는데 OWL Full 사용 → undecidable.
- **URI minting chaos**: 매 새 entity 마다 random URI → linkability 손실.
- **Closed-world assumption**: RDF 는 OWA — "absent ≠ false".
## 🧪 검증 / 중복
- Verified (W3C RDF 1.1 spec, OWL 2 spec, Hitzler 2009 textbook).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — RDF/OWL/SPARQL stack, reasoning, validation |
@@ -2,91 +2,150 @@
id: wiki-2026-0508-knowledge-structure
title: Knowledge Structure
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-KNST-001]
aliases: [Knowledge Organization, Information Structure]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced, knowledge-structure, Mental-Models, hierarchy, network, organizational-learning]
confidence_score: 0.85
verification_status: applied
tags: [knowledge, structure, organization, information-architecture]
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
framework: networkx, llamaindex
---
# [[Knowledge-Structure|Knowledge-Structure]]
# Knowledge Structure
## 📌 한 줄 통찰 (The Karpathy Summary)
> "지능의 골격: 파편화된 정보들이 서로 어떤 위계와 논리적 관계로 묶여 있는지를 보여주는 설계도이자, 새로운 정보를 기존 지식에 안정적으로 안착시키는 '지적 앵커(Anchor)'들의 집합체."
## 한 줄
> **"매 raw text → organized hierarchy"**. Knowledge Structure 는 information 을 hierarchies, taxonomies, networks, frames 로 organizing 하는 paradigm 의 study. 2026 LLM era 에서는 retrieval-augmented systems 의 indexing strategy 와 agent memory architecture 의 backbone.
## 📖 구조화된 지식 (Synthesized Content)
지식 구조(Knowledge-Structure)는 정보 간의 관계를 조직화하는 방식입니다. (KH-Mapping적 관점 포함)
## 매 핵심
1. **주요 형태**:
* **Hierarchy**: 상위 개념과 하위 개념의 트리 구조 (분류학적 접근).
* **Network**: 유기적으로 얽힌 거미줄 구조 (지식 그래프적 접근). ([[Graph Theory|Graph Theory]]와 연결)
* **[[Schema|Schema]]**: 특정 상황이나 개념에 대한 고정된 지식 틀. ([[Gestalt Psychology|Gestalt Psychology]]와 연결)
2. **왜 중요한가?**:
* 구조가 없는 데이터는 '소음'일 뿐이지만, 잘 정립된 지식 구조는 정보의 검색(Retrieval)과 활용([[Reasoning|Reasoning]]) 속도를 비약적으로 높임. ([[Efficiency|Efficiency]]와 연결)
### 매 Structures
- **Hierarchy / Taxonomy**: tree (subClass, partOf)
- **Network / Graph**: arbitrary relations (KG)
- **Faceted classification**: orthogonal dimensions (Ranganathan)
- **Frames / Schemata**: slots + fillers (Minsky)
- **Folksonomy**: tag-based emergent
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 정적인 '백과사전식 분류 정책'이 주류였으나, 현대 정책은 지식 간의 다차원적 연결 정책과 사용자 맥락에 따라 유연하게 변하는 '동적 그래프 정책'으로 진화함(RL Update). ([[Concept Mapping|Concept Mapping]]와 연결)
- **정책 변화(RL Update)**: AI가 방대한 텍스트 속에서 스스로 지식의 구조 정책을 추출(Embedding)하고 이를 그래프 DB로 구축하는 '자동화된 지식 구조화 정책'이 지식 관리 시스템의 새 표준이 됨.
### 매 Properties
- **Granularity**: atomic facts vs documents
- **Reasoning depth**: lookup → multi-hop → analogical
- **Update frequency**: static → real-time
- **Source provenance**: trust chain
## 🔗 지식 연결 (Graph)
- [[Graph Theory|Graph Theory]], [[Concept Mapping|Concept Mapping]], [[Gestalt Psychology|Gestalt Psychology]], [[Ontology|Ontology]] (온톨로지), [[Efficiency|Efficiency]]
- **Modern Tech/Tools**: Obsidian (Graph view), Neo4j, Knowledge graphs, Vector databases.
---
### 매 응용
1. Wiki 의 backlinks + categories (Roam-style).
2. RAG indexing (chunks + metadata).
3. Agent long-term memory (MemGPT, LangMem).
4. Personal Knowledge Management (Zettelkasten).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Hierarchical taxonomy
```python
from anytree import Node, RenderTree
**언제 쓰면 안 되는가:**
- *(TODO)*
ai = Node("AI")
ml = Node("ML", parent=ai)
dl = Node("DL", parent=ml)
llm = Node("LLM", parent=dl)
opus = Node("Claude Opus 4.7", parent=llm)
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
for pre, _, node in RenderTree(ai):
print(f"{pre}{node.name}")
```
## 🤔 의사결정 기준 (Decision Criteria)
### Faceted indexing
```python
class FacetedIndex:
def __init__(self):
self.facets = {} # facet_name → {value → set(doc_ids)}
def add(self, doc_id, facets):
for k, v in facets.items():
self.facets.setdefault(k, {}).setdefault(v, set()).add(doc_id)
def query(self, **constraints):
sets = [self.facets[k][v] for k, v in constraints.items()]
return set.intersection(*sets) if sets else set()
**선택 A를 써야 할 때:**
- *(TODO)*
idx = FacetedIndex()
idx.add("doc1", {"topic":"ML", "year":"2026", "lang":"en"})
idx.query(topic="ML", year="2026")
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Zettelkasten-style atomic notes
```python
import re, hashlib
def make_zettel(title, body, tags, links):
zid = hashlib.md5(title.encode()).hexdigest()[:8]
return {
"id": zid, "title": title, "body": body,
"tags": tags, "links": links,
"wikilinks": re.findall(r"\[\[([^\]]+)\]\]", body),
}
```
**기본값:**
> *(TODO)*
### Hierarchical RAG indexing (LlamaIndex)
```python
from llama_index.core import VectorStoreIndex, Document
from llama_index.core.node_parser import HierarchicalNodeParser
## ❌ 안티패턴 (Anti-Patterns)
parser = HierarchicalNodeParser.from_defaults(
chunk_sizes=[2048, 512, 128]
)
nodes = parser.get_nodes_from_documents(docs)
index = VectorStoreIndex(nodes)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Frame-based knowledge
```python
restaurant_frame = {
"name": None,
"cuisine": None,
"location": {"city": None, "address": None},
"menu": [], # list of dish frames
"reviews": [],
}
```
## 매 결정 기준
| Use case | Structure |
|---|---|
| stable domain | Taxonomy |
| rich relations | Graph (KG) |
| multiple dims | Faceted |
| stereotyped events | Frames |
| user-generated | Folksonomy |
| LLM RAG | Hierarchical chunks + metadata |
**기본값**: Hierarchy + tags + wikilinks (hybrid).
## 🔗 Graph
- 부모: [[Information-Architecture]] · [[Knowledge-Representation]]
- 변형: [[Taxonomy]] · [[Ontology]] · [[Folksonomy]]
- 응용: [[Knowledge Graph]] · [[Wiki-Systems]] · [[RAG-Architecture]]
- Adjacent: [[Zettelkasten]] · [[Personal-Knowledge-Management]]
## 🤖 LLM 활용
**언제**: agent memory design, RAG indexing strategy, large doc collection 정리.
**언제 X**: 매 single-doc Q&A — 매 over-engineering.
## ❌ 안티패턴
- **Premature taxonomy**: domain 도 모르고 hierarchy 먼저 design → constant restructuring.
- **Single structure forced fit**: 매 problem 이 graph 인데 tree 로 강제.
- **No update mechanism**: 매 evolving knowledge 에 frozen schema.
- **Tags 없는 hierarchy**: orthogonal facet 표현 불가.
## 🧪 검증 / 중복
- Verified (Ranganathan 1933 colon classification, Minsky 1974 frames, Sowa 2000 KR textbook).
- 신뢰도 A-.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — taxonomy/graph/facet/frame structures, RAG indexing |
@@ -2,87 +2,143 @@
id: wiki-2026-0508-kolmogorov-complexity
title: Kolmogorov Complexity
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-KOLM-001]
aliases: [Algorithmic Complexity, Descriptive Complexity, K-complexity]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, computer-science, Information-Theory, kolmogorov-complexity, compression]
confidence_score: 0.95
verification_status: applied
tags: [complexity, information-theory, computability, algorithmic-information]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: zlib, lzma
---
# Kolmogorov Complexity (콜모고로프 복잡도)
# Kolmogorov Complexity
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터의 복잡도는 그 데이터를 설명하기 위해 필요한 '가장 짧은 문장'의 길이다" — 어떤 데이터를 생성할 수 있는 가장 짧은 알고리즘(프로그램)의 길이로 데이터의 정보량을 정의하는 이론적 척도.
## 한 줄
> **"매 string 의 shortest description length"**. Kolmogorov Complexity $K(x)$ 는 universal Turing machine 위에서 string $x$ 를 출력하는 shortest program 의 length. Solomonoff (1960), Kolmogorov (1965), Chaitin (1969) 이 독립적으로 정의했고, 2026 ML 에서는 generalization bounds, MDL, AIXI agents 의 theoretical foundation.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Algorithmic Incompressibility" — 규칙적인 데이터는 짧은 프로그램으로 설명 가능하지만(낮은 복잡도), 완전 무작위(Random) 데이터는 데이터 그 자체를 출력하는 것 외에는 방법이 없어 데이터 길이만큼의 복잡도를 가진다는 패턴.
- **주요 개념:**
- **Minimum Description Length (MDL):** 데이터를 설명하는 모델의 복잡도와 모델로 데이터를 설명했을 때의 오차를 동시에 최소화하려는 원리.
- **Universal Turing Machine:** 복잡도는 언어에 따라 상수로만 차이가 나며 본질적인 복잡도는 보존됨 (Invariance Theorem).
- **의의:** 데이터 압축 기술의 이론적 상한선(Entropy)을 제공하며, 인공지능이 데이터를 '학습'한다는 것이 곧 데이터의 '가장 짧은 압축 알고리즘'을 찾는 과정임을 시사함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 이론적으로는 계산 불가능(Uncomputable)한 영역이지만, 실전에서는 신경망의 파라미터 수와 손실 함수의 관계를 분석하여 모델의 효율성을 측정하는 도구로 응용됨.
- **정책 변화:** Antigravity 프로젝트는 지식 문서의 정보 밀도를 측정할 때, 의미론적 핵심 내용이 얼마나 함축적으로 표현되었는지 평가하는 척도 중 하나로 콜모고로프 복잡도 개념을 차용함.
### 매 Definition
- $K_U(x) = \min \{ |p| : U(p) = x \}$
- $U$ = universal Turing machine
- invariance theorem: $|K_U(x) - K_{U'}(x)| \le c$ — choice 무관 up to constant
- **uncomputable** — no algorithm computes $K(x)$ for arbitrary $x$
## 🔗 지식 연결 (Graph)
- Probability-Theory, [[Information-Retrieval-IR|Information-Retrieval-IR]], [[Deep-Learning|Deep-Learning]]-Foundations, Occams-Razor-in-ML
- **Raw Source:** 10_Wiki/Topics/AI/Kolmogorov-Complexity.md
### 매 Variants
- **Plain $C(x)$**: any halting program
- **Prefix $K(x)$**: prefix-free programs (Levin)
- **Conditional $K(x|y)$**: given $y$ as input
- **Time-bounded $K^t(x)$**: program runs in ≤ $t$ steps
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **MDL principle**: model selection — pick shortest description.
2. **Solomonoff prior**: $P(x) \propto 2^{-K(x)}$.
3. **Lossless compression**: practical lower bound.
4. **Randomness test**: $K(x) \approx |x|$ ⟺ random.
5. **AIXI**: optimal universal agent.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 Properties
- $K(x) \le |x| + O(1)$ — copy verbatim
- $K(xy) \le K(x) + K(y) + O(\log)$
- most strings are incompressible (Counting argument)
- Chaitin's $\Omega$ — halting probability, encodes K
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Compression-based estimate
```python
import zlib, lzma
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
def K_approx(x: bytes, codec="lzma") -> int:
if codec == "zlib":
return len(zlib.compress(x, 9))
return len(lzma.compress(x, preset=9 | lzma.PRESET_EXTREME))
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# normalized
def NCD(x: bytes, y: bytes) -> float:
"""Normalized Compression Distance — Cilibrasi & Vitanyi 2005"""
Kx, Ky = K_approx(x), K_approx(y)
Kxy = K_approx(x + y)
return (Kxy - min(Kx, Ky)) / max(Kx, Ky)
```
## 🤔 의사결정 기준 (Decision Criteria)
### MDL model selection
```python
def mdl_score(model, data):
# L(model) = bits to describe model
# L(data|model) = bits to encode data given model
return code_length(model) + code_length(data, given=model)
**선택 A를 써야 할 때:**
- *(TODO)*
best = min(candidates, key=lambda m: mdl_score(m, data))
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Solomonoff prior approximation (Levin search)
```python
def levin_search(input, target, max_t):
"""enumerate programs by 2^|p| * t — Levin's universal search"""
for budget in range(1, max_t):
for p in enumerate_programs(max_len=int(np.log2(budget))):
if simulate(p, input, steps=budget // (2**len(p))) == target:
return p
```
**기본값:**
> *(TODO)*
### Compression-based clustering
```python
from sklearn.cluster import AgglomerativeClustering
import numpy as np
## ❌ 안티패턴 (Anti-Patterns)
dist = np.array([[NCD(xi, xj) for xj in docs] for xi in docs])
labels = AgglomerativeClustering(
metric="precomputed", linkage="average", n_clusters=k
).fit_predict(dist)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Random string detector
```python
def is_likely_random(x: bytes, threshold=0.95) -> bool:
return K_approx(x) / len(x) > threshold # near-incompressible
```
## 매 결정 기준
| Need | Tool |
|---|---|
| theoretical proof | $K$ definition |
| practical estimate | LZMA / zstd compress length |
| similarity | NCD |
| model selection | MDL / BIC |
| online learning | Solomonoff (intractable, approximate) |
**기본값**: LZMA approximation for compute, MDL for principled selection.
## 🔗 Graph
- 부모: [[Information-Theory]] · [[Computability-Theory]]
- 변형: [[Algorithmic-Probability]] · [[Levin-Complexity]] · [[MDL]]
- 응용: [[Compression]] · [[AIXI]] · [[Generalization-Bounds]]
- Adjacent: [[Shannon-Entropy]] · [[Chaitin-Omega]]
## 🤖 LLM 활용
**언제**: model complexity reasoning, compression-as-intelligence arguments, generalization theory.
**언제 X**: 매 production code path — uncomputable, only bounds.
## ❌ 안티패턴
- **Treating K as computable**: 매 K(x) 의 exact value 사용 시도.
- **Compressor-specific bound 절대화**: gzip approximation 은 매 noisy upper bound.
- **NCD 의 metric assumption**: NCD 는 매 quasi-metric — triangle inequality 약하게 only.
- **Confusing K with Shannon H**: K is per-string, H is distributional.
## 🧪 검증 / 중복
- Verified (Li & Vitanyi 2019 4th ed textbook, Hutter 2005 AIXI book, Chaitin 1987 algorithmic info theory).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — K definition, MDL, NCD, Solomonoff, AIXI |
@@ -1,92 +1,142 @@
---
id: wiki-2026-0508-kullback-leibler-divergence
title: Kullback Leibler Divergence
title: Kullback-Leibler Divergence
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-KL-001]
aliases: [KL Divergence, Relative Entropy, KL-D]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Statistics, kl-divergence, Information-Theory, loss-functions, ai]
confidence_score: 0.95
verification_status: applied
tags: [information-theory, divergence, ml, vae, rlhf]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: torch, scipy
---
# Kullback-Leibler Divergence (KL 발산)
# Kullback-Leibler Divergence
## 📌 한 줄 통찰 (The Karpathy Summary)
> "두 세상(확률 분포) 사이의 어긋남을 측정하여, 모델이 진실에 얼마나 도달했는지 수치로 증명하라" — 어떤 확률 분포 $P$를 다른 확률 분포 $Q$로 대체했을 때 발생하는 정보 손실의 양을 측정하는 비대칭적 지표.
## 한 줄
> **"매 distribution 간의 directed information loss"**. KL Divergence $D_{\text{KL}}(P \| Q) = \mathbb{E}_P[\log P/Q]$ 는 reference distribution $Q$ $P$ 를 encode 시 expected extra bits. Kullback & Leibler (1951) 가 정의했고, 2026 ML 에서는 VAE ELBO, RLHF (PPO/DPO), variational inference, distillation 의 매 core loss term.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Distribution [[Alignment|Alignment]]" — 모델의 출력 분포를 타겟 분포에 근사시키기 위해 정보 엔트로피의 차이를 최소화하며 지식의 왜곡을 줄여나가는 최적화 패턴.
- **핵심 성질:**
- **Non-negativity:** 항상 0 이상이며, 두 분포가 완벽히 같을 때만 0임 (Gibbs' In[[Equality|Equality]]).
- **Asymmetry:** $D_{KL}(P||Q) \neq D_{KL}(Q||P)$. 즉, 기준이 되는 분포에 따라 값이 달라짐 (거리 개념이 아님).
- **AI에서의 응용:**
- **VAE (Variational Autoencoder):** 잠재 공간의 분포를 가우시안 분포에 가깝게 강제.
- **PPO (Reinforcement Learning):** 새로운 정책이 이전 정책과 너무 급격하게 변하지 않도록 제약.
- **Knowledge [[Distillation|Distillation]]:** 스튜던트 모델이 티처 모델의 확률 분포를 따라가게 함.
- **의의:** AI 모델이 단순히 정답을 맞히는 것을 넘어, 데이터의 내재된 확률 구조 자체를 학습하게 만드는 수학적 나침반.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 대칭적인 거리 개념(Euclidean Distance)으로 접근하던 초기 방식을 넘어, 정보의 흐름과 소실 관점에서 확률 분포를 비교하는 정보 이론적 접근이 현대 AI의 표준이 됨.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 페르소나 미세 조정([[Fine-tuning|Fine-tuning]]) 시, 기존 모델과의 KL 발산을 모니터링하여 원래의 유용한 지능이 파괴되지 않도록 관리함.
### 매 Definition
- discrete: $D_{\text{KL}}(P\|Q) = \sum_x P(x) \log \frac{P(x)}{Q(x)}$
- continuous: $\int p(x) \log \frac{p(x)}{q(x)} dx$
- always $\ge 0$ (Gibbs inequality), $=0$ iff $P=Q$
- **NOT symmetric**, **NOT a metric** (no triangle inequality)
- $D_{\text{KL}}(P\|Q) = H(P, Q) - H(P)$ — cross-entropy minus entropy
## 🔗 지식 연결 (Graph)
- Probability-Theory, [[Kolmogorov-Complexity|Kolmogorov-Complexity]], [[Knowledge-Distillation|Knowledge-Distillation]], [[Reinforcement-Learning|Reinforcement-Learning]]
- **Raw Source:** 10_Wiki/Topics/AI/Kullback-Leibler-Divergence.md
### 매 Mode behavior
- **Forward $D_{\text{KL}}(P\|Q)$**: Q must cover all mass of P → "mode-covering"
- **Reverse $D_{\text{KL}}(Q\|P)$**: Q goes where P has mass → "mode-seeking"
- VAE 는 reverse, EP 는 forward
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **VAE ELBO**: $\mathbb{E}[\log p(x|z)] - D_{\text{KL}}(q(z|x) \| p(z))$.
2. **RLHF PPO**: $\beta \cdot D_{\text{KL}}(\pi \| \pi_{\text{ref}})$ penalty.
3. **Knowledge distillation**: $D_{\text{KL}}(p_T \| p_S)$ with temperature.
4. **Variational inference**: $\arg\min_q D_{\text{KL}}(q \| p)$.
5. **Mutual information**: $I(X;Y) = D_{\text{KL}}(p(x,y) \| p(x)p(y))$.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Discrete KL
```python
import numpy as np
def kl_div(p, q, eps=1e-12):
p, q = np.asarray(p), np.asarray(q)
return np.sum(p * (np.log(p + eps) - np.log(q + eps)))
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
p = np.array([0.5, 0.3, 0.2])
q = np.array([0.4, 0.4, 0.2])
print(kl_div(p, q))
```
## 🤔 의사결정 기준 (Decision Criteria)
### PyTorch KL (numerically stable)
```python
import torch
import torch.nn.functional as F
**선택 A를 써야 할 때:**
- *(TODO)*
# inputs MUST be log-probs for kl_div first arg
log_p = F.log_softmax(model_logits, dim=-1)
q = F.softmax(target_logits, dim=-1)
loss = F.kl_div(log_p, q, reduction="batchmean")
```
**선택 B를 써야 할 때:**
- *(TODO)*
### KL between Gaussians (closed form)
```python
def kl_gaussian(mu1, var1, mu2, var2):
return 0.5 * (
torch.log(var2 / var1) + (var1 + (mu1-mu2)**2) / var2 - 1
).sum()
**기본값:**
> *(TODO)*
# VAE: q ~ N(mu, sigma^2), prior N(0, 1)
def kl_to_standard_normal(mu, log_var):
return -0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp())
```
## ❌ 안티패턴 (Anti-Patterns)
### Distillation loss with temperature
```python
def distill_kl(student_logits, teacher_logits, T=4.0):
log_p_s = F.log_softmax(student_logits / T, dim=-1)
p_t = F.softmax(teacher_logits / T, dim=-1)
return F.kl_div(log_p_s, p_t, reduction="batchmean") * (T*T)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### RLHF PPO KL penalty (per-token)
```python
def ppo_kl_penalty(logp_new, logp_ref, beta=0.05):
# token-level KL via log-prob difference
return beta * (logp_new - logp_ref) # used as reward shaping
```
### Forward vs reverse comparison
```python
# Approximate q (Gaussian) to bimodal p
# - reverse KL D(q||p): q picks one mode (mode-seeking)
# - forward KL D(p||q): q spans both modes (mode-covering, broader)
```
## 매 결정 기준
| Need | Form |
|---|---|
| variational posterior fit | reverse $D_{\text{KL}}(q\|p)$ |
| spread (cover all modes) | forward $D_{\text{KL}}(p\|q)$ |
| symmetric | JS divergence |
| bounded, metric | Wasserstein, Hellinger |
| RLHF stability | per-token reverse KL with $\beta$ schedule |
**기본값**: 매 problem 따라 — VAE 면 reverse, EP 면 forward.
## 🔗 Graph
- 부모: [[Information-Theory]] · [[Divergences]]
- 변형: [[Jensen-Shannon-Divergence]] · [[Wasserstein-Distance]] · [[f-Divergence]]
- 응용: [[VAE]] · [[RLHF]] · [[Knowledge-Distillation]] · [[Variational-Inference]]
- Adjacent: [[Cross-Entropy]] · [[Mutual-Information]]
## 🤖 LLM 활용
**언제**: 매 distribution-level loss 정의, RLHF 의 reference model anchoring, distillation.
**언제 X**: 매 distance metric 이 필요할 때 — KL 은 metric 이 X — Wasserstein 사용.
## ❌ 안티패턴
- **Symmetric 가정**: $D_{\text{KL}}(P\|Q) \ne D_{\text{KL}}(Q\|P)$.
- **Disjoint support**: $Q(x)=0, P(x)>0$ 이면 $\infty$ — smooth or use JS.
- **`F.kl_div` 의 input 순서 혼동**: 첫 arg 는 log-prob.
- **Distillation T 무시**: temperature $T$ 없이 sharp distribution 사용 → poor signal.
- **RLHF 에서 KL collapse**: $\beta$ 너무 작으면 reward hacking.
## 🧪 검증 / 중복
- Verified (Cover & Thomas 2006 textbook ch 2, MacKay 2003 ch 2, Kingma VAE 2013).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — KL definition, mode behavior, VAE/RLHF/distillation patterns |
@@ -2,87 +2,153 @@
id: wiki-2026-0508-lagrange-multipliers
title: Lagrange Multipliers
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-LAGR-001]
aliases: [Lagrangian Method, Constrained Optimization, KKT]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Optimization, calculus, lagrange-multipliers, constrained-optimization]
confidence_score: 0.95
verification_status: applied
tags: [optimization, calculus, constrained, kkt, ml-foundations]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: scipy, cvxpy
---
# Lagrange Multipliers (라그랑주 승수법)
# Lagrange Multipliers
## 📌 한 줄 통찰 (The Karpathy Summary)
> "제약(Constraint)이라는 벽에 가로막혔을 때, 그 벽과 목표(Objective)가 만나는 가장 아름다운 접점을 찾아라" — 제약 조건이 있는 최적화 문제를 제약 조건이 없는 문제로 변환하여, 목적 함수의 경사도(Gradient)와 제약 함수의 경사도가 나란해지는 지점을 찾는 수학적 기법.
## 한 줄
> **"매 constrained optimization 의 universal trick"**. Lagrange Multiplier 방법은 equality-constrained problem $\min f(x)$ s.t. $g(x)=0$ 을 $\nabla f = \lambda \nabla g$ 의 unconstrained stationary condition 으로 reduce 한다. Joseph-Louis Lagrange (1788) 이 도입했고, 2026 ML 의 SVM, regularization, RLHF reward shaping, physics-informed NN 에 매 fundamental.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Gradient [[Alignment|Alignment]]" — 목표 함수의 등고선과 제약 조건의 경계선이 서로 접할 때 최적해가 발생한다는 기하학적 통찰을 바탕으로, 라그랑주 승수($\lambda$)를 도입하여 통합 함수($L$)를 구성하는 최적화 패턴.
- **핵심 원리:**
- **Lagrangian Function:** $L(x, \lambda) = f(x) - \lambda(g(x) - c)$ 형태의 식을 구성.
- **Stationary Point:** $L$을 각 변수에 대해 편미분하여 0이 되는 지점을 탐색.
- **의의:** 기계학습의 수많은 최적화 문제(특히 제약 조건이 있는 SVM, 주성분 분석 등)를 해결하는 이론적 근거가 되며, 복잡한 현실의 제약 속에서 최선의 선택을 내리는 논리적 토대 제공.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 등식 제약 조건에만 머물던 고전적 방식에서, 부등식 제약 조건까지 포괄하는 KKT(Karush-Kuhn-Tucker) 조건으로 확장되어 현대 인공지능의 정교한 최적화 알고리즘에 적용됨.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 연산 자원(Token, Time) 제약 하에서 정보의 품질을 극대화하는 스케줄링 알고리즘 설계 시 라그랑주 승수법의 최적화 개념을 활용함.
### 매 Equality 형
- problem: $\min f(x)$ s.t. $g_i(x) = 0$
- Lagrangian: $\mathcal{L}(x, \lambda) = f(x) + \sum_i \lambda_i g_i(x)$
- stationarity: $\nabla_x \mathcal{L} = 0, \nabla_\lambda \mathcal{L} = 0$
- $\lambda_i$ = sensitivity of optimal $f^*$ to perturbation of $g_i$ (shadow price)
## 🔗 지식 연결 (Graph)
- [[Kernel-Methods-and-SVMs|Kernel-Methods-and-SVMs]], [[Global-vs-Local-Optima|Global-vs-Local-Optima]], [[Deep-Learning|Deep-Learning]]-Foundations, [[Search|Search]]-Algorithms
- **Raw Source:** 10_Wiki/Topics/AI/Lagrange-Multipliers.md
### 매 KKT (inequality 확장)
- problem: $\min f(x)$ s.t. $g_i(x) \le 0, h_j(x) = 0$
- $\mathcal{L} = f + \sum \mu_i g_i + \sum \lambda_j h_j$
- KKT conditions:
1. **Stationarity**: $\nabla_x \mathcal{L} = 0$
2. **Primal feasibility**: $g_i \le 0, h_j = 0$
3. **Dual feasibility**: $\mu_i \ge 0$
4. **Complementary slackness**: $\mu_i g_i = 0$
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **SVM**: max-margin → KKT dual.
2. **Regularization**: Lagrangian view of $\min L + \lambda \|w\|^2$.
3. **Constrained RL**: CPO, Lagrangian SAC.
4. **Physics**: Euler-Lagrange equations of motion.
5. **Economics**: utility maximization budget constraint.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Symbolic solve (sympy)
```python
import sympy as sp
## 🧪 검증 상태 (Validation)
x, y, lam = sp.symbols("x y lambda")
f = x**2 + y**2 # min x^2 + y^2
g = x + y - 1 # s.t. x + y = 1
L = f + lam * g
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
eqs = [sp.diff(L, v) for v in (x, y, lam)]
sol = sp.solve(eqs, [x, y, lam])
print(sol) # {x: 1/2, y: 1/2, lambda: -1}
```
## 🤔 의사결정 기준 (Decision Criteria)
### scipy constrained
```python
from scipy.optimize import minimize
**선택 A를 써야 할 때:**
- *(TODO)*
f = lambda x: x[0]**2 + x[1]**2
cons = {"type": "eq", "fun": lambda x: x[0] + x[1] - 1}
res = minimize(f, x0=[0.0, 0.0], constraints=cons)
print(res.x) # ≈ [0.5, 0.5]
```
**선택 B를 써야 할 때:**
- *(TODO)*
### CVXPY (convex)
```python
import cvxpy as cp
x = cp.Variable(2)
prob = cp.Problem(cp.Minimize(cp.sum_squares(x)),
[cp.sum(x) == 1, x >= 0])
prob.solve()
print(x.value, prob.constraints[0].dual_value) # primal + lambda
```
**기본값:**
> *(TODO)*
### SVM dual derivation
```python
# Primal: min 1/2 ||w||^2 s.t. y_i(w·x_i + b) >= 1
# Dual via KKT: max sum a_i - 1/2 sum a_i a_j y_i y_j x_i·x_j
# s.t. a_i >= 0, sum a_i y_i = 0
import numpy as np
from scipy.optimize import minimize
## ❌ 안티패턴 (Anti-Patterns)
def svm_dual(X, y):
n = len(y)
K = (y[:,None]*y) * (X @ X.T)
obj = lambda a: 0.5 * a @ K @ a - a.sum()
cons = [{"type":"eq", "fun": lambda a: a @ y}]
bnds = [(0, None)] * n
res = minimize(obj, np.zeros(n), bounds=bnds, constraints=cons)
return res.x # dual variables = lambda_i
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Penalty / augmented Lagrangian
```python
def augmented_lagrangian(f, g, x0, mu0=1.0, rho=1.5, iters=20):
x, mu = x0, mu0
lam = 0.0
for _ in range(iters):
# solve unconstrained
from scipy.optimize import minimize
L = lambda x: f(x) + lam*g(x) + (mu/2)*g(x)**2
x = minimize(L, x).x
lam += mu * g(x) # multiplier update
mu *= rho
return x, lam
```
## 매 결정 기준
| Problem | Method |
|---|---|
| small symbolic | sympy |
| smooth nonlinear | scipy SLSQP |
| convex | CVXPY |
| large-scale | augmented Lagrangian / ADMM |
| RL constraints | Lagrangian PPO/SAC |
**기본값**: CVXPY for convex, scipy SLSQP otherwise.
## 🔗 Graph
- 부모: [[Optimization]] · [[Calculus]]
- 변형: [[KKT-Conditions]] · [[Duality]] · [[ADMM]]
- 응용: [[SVM]] · [[Constrained-RL]] · [[Regularization]]
- Adjacent: [[Convex-Optimization]] · [[Penalty-Methods]]
## 🤖 LLM 활용
**언제**: deriving SVM/RLHF math, constrained policy optimization, MLE w/ constraints.
**언제 X**: unconstrained smooth — 그냥 gradient descent.
## ❌ 안티패턴
- **Forgetting CQ**: constraint qualification (LICQ, Slater) 만족 X 면 KKT 무효.
- **Sign convention 혼동**: $\le$ 와 $\ge$ 따라 $\mu$ sign flip.
- **Non-convex KKT 의 sufficiency 가정**: KKT 는 매 necessary, sufficient 는 convex 에서만.
- **Penalty 만 사용**: ill-conditioning — augmented Lagrangian 사용.
## 🧪 검증 / 중복
- Verified (Boyd & Vandenberghe 2004 ch 5, Nocedal & Wright 2006 ch 12).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Lagrangian, KKT, SVM dual, augmented Lagrangian |
@@ -2,62 +2,122 @@
id: wiki-2026-0508-least-squares-methods
title: Least Squares Methods
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-LSM-001]
aliases: [Least-Squares, OLS, 최소제곱법]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Statistics, linear-regression, least-squares, Optimization, data-science]
confidence_score: 0.95
verification_status: applied
tags: [optimization, regression, linear-algebra, statistics]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: numpy-scipy
---
# Least Squares Methods (최소제곱법)
# Least Squares Methods
## 📌 한 줄 통찰 (The Karpathy Summary)
> "실제 데이터와 예측값 사이의 벌어진 틈(Residuals)을 최소로 좁히는 가장 정직한 직선을 그려라" — 데이터 포인트들과 모델 함수 사이의 오차 제곱합을 최소화함으로써 가장 적합한 파라미터를 찾아내는 회귀 분석의 핵심 수학 기법.
## 한 줄
> **"매 residual의 제곱합을 최소화하라"**. Gauss(1795)와 Legendre(1805)가 독립 발견; 매 modern ML의 MSE loss·linear regression·Kalman filter의 직접 조상이다. 2026에도 매 LoRA fine-tuning의 closed-form initializer로 살아있다.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Error Minimization" — 개별 오차의 절대값 대신 제곱을 사용함으로써 큰 오차에 더 큰 벌점을 부여하고, 미분이 가능한 매끄러운 손실 함수를 구성하여 수학적으로 명확한 최적해를 구하는 패턴.
- **핵심 원리:**
- **Residuals:** 관측값과 모델이 예측한 값의 차이.
- **Objective Function:** $\sum (y_i - \hat{y}_i)^2$ 를 최소화.
- **Normal Equation:** 행렬 연산을 통해 반복적 계산 없이 한 번에 최적의 가중치를 구하는 공식.
- **의의:** 선형 회귀분석의 표준 방법론이며, 데이터 속에 숨겨진 선형적 관계를 파악하고 미래 값을 예측하는 가장 기초적이면서 강력한 도구.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 이상치(Outliers)에 매우 민감하다는 단점이 있어, 실제 산업 데이터 처리 시에는 로버스트 회귀(Robust Regression)나 정규화(L1/L2) 기법과 결합하여 한계를 보완함.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 응답 지연 시간 경향성을 분석하고 하드웨어 자원 사용량의 선형적 추세를 예측할 때, 최소제곱법 기반의 회귀 모델을 활용함.
### 매 정식화
- **OLS**: minimize ‖y Xβ‖²; closed-form β̂ = (XᵀX)⁻¹Xᵀy.
- **Weighted LS**: residual에 weight W; β̂ = (XᵀWX)⁻¹XᵀWy.
- **Total LS**: 매 X에도 noise — SVD 기반.
- **Regularized**: Ridge (L2), Lasso (L1), Elastic Net.
## 🔗 지식 연결 (Graph)
- [[Linear-Regression-Mastery|Linear-Regression-Mastery]], [[Gradient-Descent|Gradient-Descent]]-Foundations, [[L1-and-L2-Regularization|L1-and-L2-Regularization]], Probability-Theory
- **Raw Source:** 10_Wiki/Topics/AI/Least-Squares-Methods.md
### 매 수치적 안정성
- Normal equation 직접 풀이는 매 condition number² 증폭 → QR/SVD 권장.
- 매 LAPACK `gels` 는 QR 사용.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Linear regression (econometrics, ML baseline).
2. Curve fitting (lmfit, scipy.optimize.curve_fit).
3. Bundle adjustment (SLAM, photogrammetry).
4. Kalman update step (least-squares projection).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### OLS via NumPy (lstsq)
```python
import numpy as np
beta, residuals, rank, sv = np.linalg.lstsq(X, y, rcond=None)
```
## 🧪 검증 상태 (Validation)
### Ridge regression
```python
def ridge(X, y, lam):
n_features = X.shape[1]
return np.linalg.solve(X.T @ X + lam * np.eye(n_features), X.T @ y)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Nonlinear least squares
```python
from scipy.optimize import least_squares
def residual(params, x, y):
a, b, c = params
return y - (a * np.exp(-b * x) + c)
result = least_squares(residual, [1, 1, 0], args=(x, y))
```
## 🧬 중복 검사 (Duplicate Check)
### QR-based solve (numerically stable)
```python
Q, R = np.linalg.qr(X)
beta = np.linalg.solve(R, Q.T @ y)
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Weighted LS
```python
W_sqrt = np.sqrt(weights)
beta = np.linalg.lstsq(X * W_sqrt[:, None], y * W_sqrt, rcond=None)[0]
```
## 🕓 변경 이력 (Changelog)
### Recursive LS (online update)
```python
def rls_update(P, beta, x, y, lam=0.99):
k = P @ x / (lam + x @ P @ x)
beta = beta + k * (y - x @ beta)
P = (P - np.outer(k, x @ P)) / lam
return P, beta
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Well-conditioned, small p | Normal equation |
| Ill-conditioned | QR or SVD |
| Many features, sparse | Lasso |
| Heteroscedastic noise | Weighted LS |
| Streaming data | RLS |
**기본값**: `np.linalg.lstsq` (uses SVD-based GELSD).
## 🔗 Graph
- 부모: [[Linear-Algebra-Foundations]] · [[Optimization]]
- 변형: [[Ridge-Regression]] · [[Lasso]] · [[Total-Least-Squares]]
- 응용: [[Kalman-Filter-and-State-Tracking]] · [[Linear-Regression]] · [[Bundle-Adjustment]]
- Adjacent: [[Maximum-Likelihood-Estimation]] · [[QR-Decomposition]]
## 🤖 LLM 활용
**언제**: Linear/affine model fit, baseline regression, calibration curves.
**언제 X**: Outliers 다수 (use Huber/RANSAC), heavy non-linearity (use NN/GP).
## ❌ 안티패턴
- **Normal equation 남용**: 매 ill-conditioned에서 매 silently 망함.
- **Outlier 무시**: L2 loss는 매 outlier 민감 — robust loss 고려.
- **Multicollinearity 방치**: VIF 점검 또는 Ridge.
## 🧪 검증 / 중복
- Verified (Trefethen & Bau "Numerical Linear Algebra").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — OLS/Ridge/RLS patterns |
@@ -2,89 +2,163 @@
id: wiki-2026-0508-linear-algebra-foundations
title: Linear Algebra Foundations
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-LA-001]
aliases: [Matrix Algebra, Vector Spaces, Linear Algebra]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Linear-Algebra, vector-space, matrix, ai-foundations]
confidence_score: 0.95
verification_status: applied
tags: [linear-algebra, math, ml-foundations, matrix]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: numpy, jax, torch
---
# Linear Algebra Foundations (선형대수학 기초)
# Linear Algebra Foundations
## 📌 한 줄 통찰 (The Karpathy Summary)
> "세상의 모든 데이터를 숫자들의 격자(Matrix)로 치환하고, 그들 사이의 관계를 공간의 변환(Transformation)으로 이해하라" — 벡터와 행렬을 통해 다차원 데이터를 표현하고 연산하는 수학적 체계이자, 인공지능이 세상을 수치화하고 처리하는 공용어.
## 한 줄
> **"매 ML 의 universal language"**. Linear Algebra 는 vector space, linear map, eigendecomposition, SVD 의 study — 매 modern ML/DL 의 numerical backbone. 2026 LLM era 에서 attention 은 매 Q@K.T softmax @V — 매 pure linear algebra 의 chain. GPU/TPU 의 design 자체가 매 LA primitive (GEMM) 위에 built.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Space Mapping" — 데이터를 고차원 벡터 공간의 점으로 정의하고, 행렬 곱을 통해 공간을 회전, 확대, 투영함으로써 데이터 내의 숨겨진 구조와 특징을 추출하는 수학적 추상화 패턴.
- **핵심 구성 요소:**
- **Vectors & Scalars:** 데이터의 방향과 크기 표현.
- **Matrices:** 데이터 집합체이자 선형 변환의 도구.
- **Eigenvalues & Eigenvectors:** 행렬 변환 시 방향이 변하지 않는 고유한 축(핵심 특징).
- **Inverse Matrix & Determinant:** 시스템의 해를 구하거나 공간의 부피 변화 측정.
- **의의:** 신경망의 가중치 연산, 차원 축소(PCA), 추천 시스템, 그래픽스 등 현대 모든 지능형 소프트웨어의 물리적 토대.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 정적인 수식 풀이 중심에서, 이제는 거대한 규모의 행렬 연산을 효율적으로 처리하기 위한 수치 선형대수(Numerical Linear Algebra)와 GPU 가속 하드웨어 연산 최적화가 더 중요한 쟁점으로 부상함.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 지식 임베딩 연산 시, 선형대수적 원리를 바탕으로 유사도 측정 및 공간 투영 최적화를 수행하여 연산 효율을 극대화함.
### 매 Vector spaces
- field $\mathbb{F}$ (보통 $\mathbb{R}, \mathbb{C}$)
- closed under linear combinations
- basis: minimal spanning set, dim
- linear map $T: V \to W$ — represent as matrix in basis
## 🔗 지식 연결 (Graph)
- [[Inner-Product-Spaces|Inner-Product-Spaces]], [[Eigenvalues-and-Eigenvectors|Eigenvalues-and-Eigenvectors]], [[Dimensionality-Reduction|Dimensionality-Reduction]], [[GPU-Architecture|GPU-Architecture]]-for-AI
- **Raw Source:** 10_Wiki/Topics/AI/Linear-Algebra-Foundations.md
### 매 Decompositions
- **LU**: $A = LU$ — Gaussian elimination, $O(n^3)$
- **QR**: $A = QR$, $Q$ orthogonal — least squares
- **Eigendecomposition**: $A = V\Lambda V^{-1}$, square only
- **SVD**: $A = U\Sigma V^\top$ — universal, rectangular
- **Cholesky**: $A = LL^\top$, SPD only, fastest
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Norms / inner products
- $\|x\|_2 = \sqrt{x^\top x}$, $\|x\|_p$, $\|x\|_\infty$
- Frobenius: $\|A\|_F = \sqrt{\sum a_{ij}^2}$
- Spectral: $\|A\|_2 = \sigma_{\max}(A)$
- Cauchy-Schwarz: $|x^\top y| \le \|x\| \|y\|$
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. **Attention**: $\text{softmax}(QK^\top / \sqrt{d}) V$.
2. **PCA**: SVD of centered $X$.
3. **Linear regression**: normal eq $w = (X^\top X)^{-1} X^\top y$.
4. **Graph Laplacian**: spectral clustering.
5. **Quantum states**: complex Hilbert space.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### NumPy basics
```python
import numpy as np
A = np.random.randn(5, 3)
# Solve Ax = b in least-squares
b = np.random.randn(5)
x, *_ = np.linalg.lstsq(A, b, rcond=None)
# rank, condition number, determinant
print(np.linalg.matrix_rank(A), np.linalg.cond(A))
```
## 🤔 의사결정 기준 (Decision Criteria)
### SVD + low-rank approx
```python
U, S, Vt = np.linalg.svd(A, full_matrices=False)
k = 2
A_lr = U[:, :k] @ np.diag(S[:k]) @ Vt[:k] # rank-k approx
err = np.linalg.norm(A - A_lr, "fro")
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Eigendecomposition (symmetric)
```python
S = np.random.randn(4, 4); S = S + S.T
w, V = np.linalg.eigh(S) # use eigh for symmetric (stable, real)
# reconstruction
assert np.allclose(V @ np.diag(w) @ V.T, S, atol=1e-10)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Cholesky for SPD systems
```python
import scipy.linalg as la
A = np.random.randn(50, 50)
A = A.T @ A + np.eye(50) # SPD
L = la.cholesky(A, lower=True)
b = np.random.randn(50)
y = la.solve_triangular(L, b, lower=True)
x = la.solve_triangular(L.T, y, lower=False)
```
**기본값:**
> *(TODO)*
### JAX matmul + autodiff
```python
import jax, jax.numpy as jnp
@jax.jit
def loss(W, x, y):
return jnp.mean((x @ W - y) ** 2)
grad_fn = jax.grad(loss)
```
## ❌ 안티패턴 (Anti-Patterns)
### Power iteration (top eigenvector)
```python
def power_iter(A, n_iter=200, tol=1e-10):
x = np.random.randn(A.shape[0])
x /= np.linalg.norm(x)
for _ in range(n_iter):
x_new = A @ x
x_new /= np.linalg.norm(x_new)
if np.linalg.norm(x_new - x) < tol: break
x = x_new
eig = x @ A @ x
return eig, x
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### PyTorch attention (linear algebra core)
```python
import torch, math
def attention(Q, K, V, mask=None):
d = Q.size(-1)
s = Q @ K.transpose(-2, -1) / math.sqrt(d)
if mask is not None: s = s.masked_fill(mask == 0, -1e9)
return torch.softmax(s, dim=-1) @ V
```
## 매 결정 기준
| Problem | Method |
|---|---|
| solve Ax = b, square nonsingular | LU (np.linalg.solve) |
| SPD | Cholesky |
| least squares | QR or SVD |
| dimensionality reduction | SVD / PCA |
| symmetric eigen | eigh |
| sparse large | scipy.sparse.linalg / iterative |
**기본값**: SVD when in doubt — most stable, universal.
## 🔗 Graph
- 부모: [[Mathematics]] · [[Vector-Space]]
- 변형: [[SVD]] · [[Eigendecomposition]] · [[Tensor-Algebra]]
- 응용: [[PCA]] · [[Attention-Mechanism]] · [[Linear-Regression]]
- Adjacent: [[Numerical-Methods]] · [[Convex-Optimization]]
## 🤖 LLM 활용
**언제**: 매 ML 의 derivation, debugging matrix shapes, performance reasoning.
**언제 X**: 매 task 가 combinatorial — graph algorithms 등.
## ❌ 안티패턴
- **`inv(A) @ b` 사용**: numerically unstable + slow → use `solve`.
- **eig vs eigh 혼동**: symmetric 인데 `eig` 사용 → complex eigenvalues from numerical noise.
- **Memory layout 무시**: row vs column major → 10× slowdown.
- **Condition number 무시**: ill-conditioned matrix → inversion blows up.
- **Dense for sparse**: huge sparse → use scipy.sparse.
## 🧪 검증 / 중복
- Verified (Strang 2016 textbook, Trefethen & Bau 1997, Golub & Van Loan 2013).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — vector spaces, decompositions, norms, NumPy/JAX patterns |
@@ -2,88 +2,226 @@
id: wiki-2026-0508-linked-lists-and-trees
title: Linked Lists and Trees
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [CS-DS-001]
aliases: [Linked List, Tree, 연결 리스트, 트리]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [computer-science, data-structures, linked-list, trees, algorithm-foundations]
confidence_score: 0.92
verification_status: applied
tags: [data-structures, linked-list, tree, fundamentals]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: none
---
# Linked Lists and Trees (연결 리스트와 트리)
# Linked Lists and Trees
## 📌 한 줄 통찰 (The Karpathy Summary)
> "메모리의 조각들을 포인터로 엮어 유연한 흐름(List)을 만들고, 데이터의 숲(Tree)을 구축하여 탐색의 미학을 완성하라" — 데이터 요소를 물리적 순서가 아닌 논리적 연결로 관리하는 연결 리스트와, 부모-자식 관계를 통해 계층적 정보를 저장하는 트리 자료구조.
## 한 줄
> **"매 pointer-based dynamic structure 의 family: 매 1D (list) → 매 hierarchy (tree)"**. 매 1955 Newell-Shaw-Simon 의 IPL 의 origin. 매 modern era 의 in-memory 의 array/hash 의 dominant — 매 list/tree 의 specific use (cache-unfriendly 의 의 X).
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Non-contiguous [[Storage|Storage]] & Hierarchical [[Search|Search]]" — 고정된 배열의 한계를 넘어 데이터를 필요할 때마다 동적으로 할당(Linked List)하고, $O(\log N)$ 수준의 고속 탐색을 위해 지식을 분류하고 계층화(Tree)하는 최적화 패턴.
- **핵심 특징:**
- **Linked List:** 삽입과 삭제가 자유롭지만 탐색이 느림($O(N)$). 큐(Queue)나 스택(Stack) 구현의 기초.
- **Binary Search Tree (BST):** 정렬된 데이터를 효율적으로 탐색.
- **Balanced Trees (AVL, [[B-Tree|B-Tree]]):** 데이터가 한쪽으로 쏠리지 않게 관리하여 성능 유지 (DB 인덱스의 핵심).
- **의의:** AI 에이전트의 사고 과정([[Decision Tree|Decision Tree]]), 파일 시스템 구조, 지식 그래프의 하위 분류 등 복잡한 정보를 조직화하는 가장 기본적인 논리 장치.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순한 이진 트리를 넘어, 이제는 고차원 벡터 공간의 검색을 가속하기 위한 KD-Tree, Ball-Tree 등 특수한 트리 구조가 AI 도메인에서 더 핵심적으로 활용됨.
- **정책 변화:** Antigravity 프로젝트는 지식 문서의 카테고리 계층 구조를 트리 형태로 관리하며, 에이전트의 추론 단계([[Reasoning|Reasoning]] Chain)를 연결 리스트로 시각화하여 사용자가 사고의 흐름을 추적할 수 있게 함.
### 매 Linked List
- **node**: data + next pointer.
- **singly**: O(1) head insert, O(n) random access, O(n) delete by value.
- **doubly**: prev + next — O(1) delete with node pointer.
- **circular**: tail.next = head.
- **memory**: 매 cache-unfriendly (pointer chasing).
## 🔗 지식 연결 (Graph)
- Search-Algorithms, [[Knowledge-Graph-Foundations|Knowledge-Graph-Foundations]], [[Indexing-Strategies|Indexing-Strategies]], Decision-Trees-and-Random-Forests
- **Raw Source:** 10_Wiki/Topics/AI/Linked-Lists-and-Trees.md
### 매 Tree
- **rooted tree**: parent + children, 매 root 의 single.
- **binary tree**: ≤ 2 children.
- **BST**: left < root < right — search O(h), 매 worst h = n (degenerate).
- **balanced (RB, AVL, Splay)**: h = O(log n).
- **traversal**: pre-order (root-left-right), in-order (left-root-right = sorted for BST), post-order, level-order (BFS).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 modern relevance
- **list 의 X**: 매 dynamic array (Vec / list) 의 의 의 amortized O(1) append + O(1) random access + cache-friendly.
- **tree 의 use case**: 매 sorted + range query (RB, B+ tree), 매 hierarchy (DOM, AST, filesystem), 매 priority (heap).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. AST (compiler).
2. DOM (browser).
3. Filesystem (directory tree).
4. Decision tree (ML).
5. Priority queue (heap = array-backed binary tree).
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Singly linked list
```python
class Node:
__slots__ = ('val', 'next')
def __init__(self, val, next=None):
self.val = val; self.next = next
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
class LinkedList:
def __init__(self):
self.head = None
def push(self, val): # O(1) head insert
self.head = Node(val, self.head)
def find(self, val): # O(n)
n = self.head
while n:
if n.val == val: return n
n = n.next
return None
def reverse(self): # O(n) in-place
prev, curr = None, self.head
while curr:
curr.next, prev, curr = prev, curr, curr.next
self.head = prev
```
## 🤔 의사결정 기준 (Decision Criteria)
### Detect cycle (Floyd's tortoise & hare)
```python
def has_cycle(head: Node) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Binary tree traversal
```python
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
**선택 B를 써야 할 때:**
- *(TODO)*
def inorder(node): # sorted output for BST
if not node: return
yield from inorder(node.left)
yield node.val
yield from inorder(node.right)
**기본값:**
> *(TODO)*
def level_order(root): # BFS
from collections import deque
if not root: return
q = deque([root])
while q:
node = q.popleft()
yield node.val
if node.left: q.append(node.left)
if node.right: q.append(node.right)
```
## ❌ 안티패턴 (Anti-Patterns)
### BST insert / search
```python
class BST:
def __init__(self): self.root = None
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
def insert(self, val):
def _ins(node):
if not node: return TreeNode(val)
if val < node.val: node.left = _ins(node.left)
elif val > node.val: node.right = _ins(node.right)
return node
self.root = _ins(self.root)
def search(self, val) -> bool:
n = self.root
while n:
if val == n.val: return True
n = n.left if val < n.val else n.right
return False
```
### LRU cache (doubly linked list + dict)
```python
class LRUCache:
class Node:
__slots__ = ('k', 'v', 'prev', 'nxt')
def __init__(self, k, v): self.k, self.v, self.prev, self.nxt = k, v, None, None
def __init__(self, cap):
self.cap = cap; self.map = {}
self.head = self.Node(0, 0); self.tail = self.Node(0, 0)
self.head.nxt = self.tail; self.tail.prev = self.head
def _remove(self, n):
n.prev.nxt = n.nxt; n.nxt.prev = n.prev
def _add_front(self, n):
n.nxt = self.head.nxt; n.prev = self.head
self.head.nxt.prev = n; self.head.nxt = n
def get(self, k):
if k not in self.map: return -1
n = self.map[k]
self._remove(n); self._add_front(n)
return n.v
def put(self, k, v):
if k in self.map:
self._remove(self.map[k])
elif len(self.map) >= self.cap:
lru = self.tail.prev
self._remove(lru); del self.map[lru.k]
n = self.Node(k, v); self.map[k] = n
self._add_front(n)
```
### Tree height + balance check
```python
def height(node):
if not node: return 0
return 1 + max(height(node.left), height(node.right))
def is_balanced(node) -> bool:
def check(n):
if not n: return 0 # height
l = check(n.left)
if l == -1: return -1
r = check(n.right)
if r == -1 or abs(l - r) > 1: return -1
return 1 + max(l, r)
return check(node) != -1
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 random access | array / dynamic array (NOT list) |
| 매 head insert frequent | linked list |
| 매 LRU eviction | doubly linked list + dict |
| 매 sorted + range | balanced BST / B+ tree |
| 매 priority | binary heap (array-backed) |
| 매 hierarchy (DOM, AST) | n-ary tree |
| 매 unique key lookup | hash map |
| 매 prefix search | trie |
**기본값**: list 의 X — dynamic array 의 의. tree 의 specific structure (BST sorted, heap priority, n-ary hierarchy) 의 의.
## 🔗 Graph
- 부모: [[Data Structures]] · [[Pointer Structures]]
- 변형: [[Doubly Linked List]] · [[Skip List]] · [[Binary Tree]] · [[N-ary Tree]] · [[BST]]
- 응용: [[LRU Cache]] · [[AST Abstract Syntax Tree]] · [[DOM Tree]] · [[Filesystem Tree]]
- Adjacent: [[Hash Functions and Maps]] · [[B-Tree]] · [[Heap Data Structure]] · [[Trie]]
## 🤖 LLM 활용
**언제**: 매 hierarchy 의 model (AST, DOM, filesystem), 매 LRU 의 doubly linked, 매 BST 의 sorted lookup, 매 trie 의 prefix.
**언제 X**: 매 1D index access (array), 매 unique lookup (hash), 매 cache-sensitive scan (array), 매 small data (overhead 의 X).
## ❌ 안티패턴
- **list 의 random access**: O(n) — 매 array 의 의.
- **BST 의 unbalanced**: 매 sorted insert → O(n) height. 매 RB / AVL 의 의.
- **memory leak**: 매 unlink X / cycle 의 reference → GC 의 fail (in C, manual free needed).
- **shallow copy**: 매 tree clone 의 deep copy 의 의 — `copy.deepcopy` 의 의.
- **recursion depth**: 매 deep tree 의 stack overflow — iterative + explicit stack 의 의.
## 🧪 검증 / 중복
- Verified (CLRS Ch 10, 12; Sedgewick Algorithms 4th).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — linked list + tree fundamentals with LRU + Floyd cycle |
@@ -1,92 +1,166 @@
---
id: wiki-2026-0508-locality-sensitive-hashing-lsh
title: Locality Sensitive Hashing (LSH)
title: Locality-Sensitive Hashing (LSH)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-LSHH-001]
aliases: [LSH, Approximate Nearest Neighbor, MinHash, SimHash]
duplicate_of: none
source_trust_level: A
confidence_score: 0.96
tags: [auto-reinforced, lsh, hashing, vector-Search, algorithms, Big-Data, similarity-search]
confidence_score: 0.9
verification_status: applied
tags: [hashing, ann, retrieval, similarity-search]
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
framework: datasketch, faiss
---
# [[Locality-Sensitive-Hashing (LSH)|Locality-Sensitive-Hashing (LSH)]]
# Locality-Sensitive Hashing (LSH)
## 📌 한 줄 통찰 (The Karpathy Summary)
> "비슷한 놈들끼리 같은 주소로: 값이 하나만 달라도 전혀 딴판이 되는 일반 해시(Hash)와 정반대로, 비슷한 데이터들은 높은 확률로 같은 바구니(Bucket)에 담기게 설계하여 방대한 데이터 속에서 닮은꼴을 순식간에 찾아내는 마법의 필터."
## 한 줄
> **"매 similar item 의 same bucket 으로의 hash"**. LSH 는 hash function family $\mathcal{H}$ 가 매 distance-preserving — close points 는 collide, far points 는 separate. Indyk & Motwani (1998) 이 도입했고, 2026 에서는 ANN 의 매 classical baseline 이며 dedup, plagiarism, blocking, near-duplicate retrieval 의 매 default 로 여전히 사용 (HNSW 가 dominate 하지만 LSH 는 streaming/external memory 에 유리).
## 📖 구조화된 지식 (Synthesized Content)
가까운 것을 민감하게 해싱(LSH)하는 기법은 고차원 데이터의 근사 유사도 검색을 위한 알고리즘입니다.
## 매 핵심
1. **동작 원리**:
* 데이터를 여러 개의 특수 해시 함수로 투영.
* 거리가 가까운 데이터들은 해시값이 같을 확률이 매우 높게 설계됨.
* 전체 데이터를 다 비교하는 대신, 같은 바구니에 담긴 데이터들만 상세히 비교함 (연산량 폭감).
2. **왜 중요한가?**:
* 유튜브의 저작권 도용 영상 찾기, 구글의 중복 문서 필터링, 대규모 벡터 DB의 핵심 엔진임. ([[Efficiency|Efficiency]]와 연결)
### 매 Definition
$\mathcal{H}$ is $(r_1, r_2, p_1, p_2)$-sensitive iff:
- $d(x,y) \le r_1 \Rightarrow \Pr[h(x)=h(y)] \ge p_1$
- $d(x,y) \ge r_2 \Rightarrow \Pr[h(x)=h(y)] \le p_2$
- $r_1 < r_2$, $p_1 > p_2$
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 정확도가 떨어진다는 정책적 우려가 있었으나, 현대 정책은 '근사 유사도 검색(ANN)' 정책이 빅데이터 환경에서 '정확도 100% 탐색 정책'보다 수천 배 빠르고 실용적임을 입증함(RL Update).
- **정책 변화(RL Update)**: 최근 RAG(검색 증강 생성) 시스템에서 수백만 개의 문서 중 질문과 가장 닮은 문서를 0.1초 만에 찾아내는 'Faiss' 같은 라이브러리의 밑바닥 핵심 원리 정책으로 작동함. ([[Large Language Models (LLM)|Large Language Models (LLM)]]와 연결)
### 매 Families
- **MinHash**: Jaccard distance — set similarity
- **SimHash (random hyperplane)**: cosine — sign of $w^\top x$
- **p-stable LSH**: $\ell_p$ norms (Datar 2004)
- **Cross-polytope**: spherical distance (state-of-art)
## 🔗 지식 연결 (Graph)
- [[Efficiency|Efficiency]], [[Large Language Models (LLM)|Large Language Models (LLM)]], [[Analysis|Analysis]], [[Information-Entropy|Information-Entropy]], [[Search-Optimization|Search-Optimization]]
- **Modern Tech/Tools**: Faiss (Meta), MinHash, SimHash, Pinecone, Milvus.
---
### 매 Amplification
- AND: $g(x) = (h_1(x), \dots, h_k(x))$ — reduces $p_2$ to $p_2^k$
- OR: $L$ tables, query all → reduces miss rate
- tune $(k, L)$ for target precision/recall
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **Dedup**: web crawl near-dup pages (MinHash + LSH).
2. **Plagiarism**: shingled MinHash.
3. **Blocking**: entity resolution candidate generation.
4. **ANN**: cosine NN (SimHash baseline).
5. **Genomics**: sketch-based read alignment.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### MinHash + LSH for Jaccard
```python
from datasketch import MinHash, MinHashLSH
## 🧪 검증 상태 (Validation)
def shingles(text, k=5):
return {text[i:i+k] for i in range(len(text)-k+1)}
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
def make_mh(s, num_perm=128):
m = MinHash(num_perm=num_perm)
for sh in s: m.update(sh.encode())
return m
## 🧬 중복 검사 (Duplicate Check)
lsh = MinHashLSH(threshold=0.7, num_perm=128)
docs = {"d1": "the quick brown fox", "d2": "the quick red fox"}
mhs = {k: make_mh(shingles(v)) for k, v in docs.items()}
for k, m in mhs.items(): lsh.insert(k, m)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
q = make_mh(shingles("the quick brown fox jumps"))
print(lsh.query(q)) # candidate set
```
## 🤔 의사결정 기준 (Decision Criteria)
### SimHash for cosine
```python
import numpy as np
from collections import defaultdict
**선택 A를 써야 할 때:**
- *(TODO)*
def simhash(x, planes):
return tuple((x @ planes.T > 0).astype(np.int8))
**선택 B를 써야 할 때:**
- *(TODO)*
# k random hyperplanes
d, k, L = 128, 8, 10
tables = [np.random.randn(k, d) for _ in range(L)]
**기본값:**
> *(TODO)*
def index(X):
out = [defaultdict(list) for _ in range(L)]
for i, x in enumerate(X):
for li, planes in enumerate(tables):
out[li][simhash(x, planes)].append(i)
return out
## ❌ 안티패턴 (Anti-Patterns)
def query(q, idx):
cands = set()
for li, planes in enumerate(tables):
cands |= set(idx[li].get(simhash(q, planes), []))
return cands
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### p-stable LSH (L2)
```python
# h(x) = floor((a·x + b) / w), a ~ N(0, I), b ~ U[0, w]
def make_l2_lsh(d, w=4.0, k=8):
a = np.random.randn(k, d)
b = np.random.uniform(0, w, k)
return lambda x: tuple(np.floor((a @ x + b) / w).astype(np.int64))
```
### LSH Forest (multi-resolution)
```python
from datasketch import MinHashLSHForest
forest = MinHashLSHForest(num_perm=128)
for k, m in mhs.items(): forest.add(k, m)
forest.index()
print(forest.query(q, 5)) # top-5 approx Jaccard NN
```
### Banding technique (k-AND, L-OR)
```python
def banded_lsh(signatures, k_per_band, L_bands):
# signatures: (n, k_per_band * L_bands)
buckets = [defaultdict(list) for _ in range(L_bands)]
for i, sig in enumerate(signatures):
for b in range(L_bands):
band = tuple(sig[b*k_per_band:(b+1)*k_per_band])
buckets[b][band].append(i)
return buckets
```
## 매 결정 기준
| Distance | Family |
|---|---|
| Jaccard (sets) | MinHash |
| Cosine | SimHash / Cross-polytope |
| $\ell_2$ | p-stable (Gaussian) |
| Hamming | bit-sampling |
| edit distance | shingle + MinHash approx |
**기본값**: HNSW for general ANN (faster); LSH for dedup, streaming, external memory, exact-recall guarantee.
## 🔗 Graph
- 부모: [[Hashing]] · [[Approximate-Nearest-Neighbor]]
- 변형: [[MinHash]] · [[SimHash]] · [[Cross-Polytope-LSH]]
- 응용: [[Deduplication]] · [[Entity-Resolution]] · [[Plagiarism-Detection]]
- Adjacent: [[HNSW]] · [[Vector-Database]] · [[Faiss]]
## 🤖 LLM 활용
**언제**: massive corpus dedup (e.g. pretraining cleanup), candidate blocking, streaming.
**언제 X**: small (n < 10⁵) 또는 high-precision recall — HNSW/IVF 가 더 빠름.
## ❌ 안티패턴
- **(k, L) tuning 무시**: default 사용 → too many false positives or misses.
- **Wrong family**: cosine 인데 MinHash 사용 → meaningless.
- **Re-hash on every query**: index 재build → use persistent lib (datasketch, faiss).
- **Treating LSH as exact**: 매 approximate — verify candidates with true distance.
## 🧪 검증 / 중복
- Verified (Indyk & Motwani 1998 STOC, Andoni & Indyk 2008 CACM, Leskovec MMDS textbook ch 3).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — LSH families, MinHash/SimHash, banding, dedup patterns |
@@ -2,88 +2,135 @@
id: wiki-2026-0508-locality-sensitive-hashing
title: Locality Sensitive Hashing
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [ALGO-LSH-001]
aliases: [LSH, Locality-Sensitive-Hashing, MinHash, SimHash]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [algorithm, Search, lsh, hashing, similarity-search, Big-Data]
confidence_score: 0.93
verification_status: applied
tags: [hashing, ann, similarity-search, embeddings, retrieval]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: datasketch-faiss
---
# Locality-Sensitive Hashing (LSH, 지역 민감 해싱)
# Locality Sensitive Hashing
## 📌 한 줄 통찰 (The Karpathy Summary)
> "해시 충돌을 '버그'가 아닌 '특징'으로 활용하여, 닮은꼴 데이터들을 같은 바구니에 담아라" — 비슷한 특성을 가진 고차원 데이터들이 높은 확률로 동일한 해시 값을 갖게 하여, 선형 탐색 없이도 유사한 데이터를 매우 빠르게 찾아내는 확률적 근사 검색 기법.
## 한 줄
> **"매 가까운 점은 매 같은 bucket에 떨어진다"**. LSH는 매 metric similarity를 hash collision probability로 변환하여 매 sub-linear ANN(approximate nearest neighbor) search를 가능케 한다. 2026 vector DB 시대에 IVF-PQ·HNSW에 밀렸지만, 매 streaming dedup·document near-dup detection에서 매 dominant.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Probabilistic Bucketing" — 모든 데이터를 전수 조사하는 대신, 유사한 데이터끼리 같은 버킷(Bucket)에 모이도록 설계된 해시 함수를 통해 탐색 범위를 획기적으로 줄이는 고속 검색 패턴.
- **작동 원리:**
- **Projection:** 고차원 벡터를 임의의 축으로 투영하거나 해싱하여 차원 축소.
- **Collision as Similarity:** 일반적인 해시와 반대로, 유사한 데이터일수록 해시 충돌(Collision)이 빈번하게 발생하도록 유도.
- **Candidate Selection:** 동일한 해시 버킷에 담긴 데이터들만을 대상으로 정밀한 유사도 측정 수행.
- **의의:** 수억 건 이상의 데이터가 쌓인 환경에서도 중복 문서 탐지, 유사 이미지 검색, 추천 시스템 등을 실시간 수준으로 처리 가능케 함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 완전한 정답을 보장하지 못한다는 이유로 외면받기도 했으나, 데이터가 폭발적으로 증가하는 빅데이터 시대에 '완벽한 정답'보다 '충분히 빠른 근사 정답'이 더 가치 있음을 입증하며 필수 알고리즘으로 정착됨.
- **정책 변화:** Antigravity 프로젝트는 1,174개의 방대한 문서 중 중복되거나 유사한 내용이 있는지 전수 검사할 때, 연산 효율을 위해 LSH 기반의 1차 필터링을 수행함.
### 매 family들
- **MinHash (Jaccard)**: 매 set similarity — shingled documents.
- **SimHash (cosine)**: 매 random hyperplane projection.
- **p-stable LSH (L2)**: 매 random Gaussian projection + bucketing.
- **Cross-polytope LSH**: 매 angular distance, 매 unit sphere 위.
## 🔗 지식 연결 (Graph)
- [[Indexing-Strategies|Indexing-Strategies]], Vector-Database-Foundations, [[Dimensionality-Reduction|Dimensionality-Reduction]], [[K-Nearest-Neighbors-K-NN|K-Nearest-Neighbors-K-NN]]
- **Raw Source:** 10_Wiki/Topics/AI/Locality-Sensitive-Hashing.md
### 매 amplification
- AND-construction: 매 k hashes 모두 일치 → false positive ↓.
- OR-construction: 매 L tables 중 하나라도 collision → recall ↑.
- (k, L) tuning이 매 핵심.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Plagiarism / near-duplicate detection (web, code).
2. Streaming deduplication (logs, training data).
3. Genomic sequence matching.
4. Pre-filter for vector DBs at billion scale.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### MinHash with datasketch
```python
from datasketch import MinHash, MinHashLSH
def shingles(text, k=3):
return {text[i:i+k] for i in range(len(text)-k+1)}
m = MinHash(num_perm=128)
for s in shingles(doc):
m.update(s.encode())
lsh = MinHashLSH(threshold=0.7, num_perm=128)
lsh.insert("doc1", m)
matches = lsh.query(m_query)
```
## 🤔 의사결정 기준 (Decision Criteria)
### SimHash (64-bit)
```python
import numpy as np
def simhash(features, bits=64):
v = np.zeros(bits)
for f, w in features:
h = hash(f)
for i in range(bits):
v[i] += w if (h >> i) & 1 else -w
return sum(1 << i for i in range(bits) if v[i] > 0)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Random projection LSH (cosine)
```python
class CosineLSH:
def __init__(self, dim, n_planes=16):
self.planes = np.random.randn(n_planes, dim)
def hash(self, x):
return tuple((self.planes @ x > 0).astype(int))
```
**선택 B를 써야 할 때:**
- *(TODO)*
### p-stable LSH (Euclidean)
```python
def l2_hash(x, a, b, w):
return int((a @ x + b) // w)
# a ~ N(0, I), b ~ U(0, w)
```
**기본값:**
> *(TODO)*
### Banding for MinHash
```python
def bands(sig, b, r):
return [tuple(sig[i*r:(i+1)*r]) for i in range(b)]
# threshold ~ (1/b)^(1/r)
```
## ❌ 안티패턴 (Anti-Patterns)
### FAISS LSH index (for L2)
```python
import faiss
index = faiss.IndexLSH(dim, n_bits=256)
index.add(X)
D, I = index.search(query, k=10)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| Metric | LSH family |
|---|---|
| Jaccard | MinHash |
| Cosine | SimHash / random hyperplane |
| Euclidean | p-stable / IndexLSH |
| Hamming | Bit sampling |
**기본값**: HNSW 우선, billion-scale dedup만 LSH.
## 🔗 Graph
- 부모: [[Hash-Functions-and-Maps]] · [[Approximate-Nearest-Neighbor]]
- 변형: [[MinHash]] · [[SimHash]] · [[Cross-Polytope-LSH]]
- 응용: [[Near-Duplicate-Detection]] · [[Vector-Database]] · [[Streaming-Dedup]]
- Adjacent: [[HNSW]] · [[Product-Quantization]] · [[Bloom-Filters in Search]]
## 🤖 LLM 활용
**언제**: Billion-scale dedup, Jaccard-based near-dup detection, streaming pipeline.
**언제 X**: High-recall ANN with dense embeddings (use HNSW/IVF-PQ).
## ❌ 안티패턴
- **단일 hash table**: recall 낮음 — 매 L tables 필수.
- **k 너무 큼**: false neg 폭증.
- **Dense embedding에 MinHash**: 매 잘못된 family 선택.
## 🧪 검증 / 중복
- Verified (Indyk & Motwani 1998; Mining of Massive Datasets ch.3).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — LSH families + datasketch/FAISS examples |
@@ -2,69 +2,135 @@
id: wiki-2026-0508-logic-trees
title: Logic Trees
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [c3e4f5a6-b7d8-4901-2e3f-4a5b6c7d8e9f]
aliases: [Logic-Tree, Issue-Tree, Decision-Tree-Reasoning]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [logic-tree, issue-tree, hypothesis-tree, Problem-Solving, structuring]
confidence_score: 0.9
verification_status: applied
tags: [reasoning, problem-solving, mece, consulting, structured-thinking]
raw_sources: []
last_reinforced: 2026-04-27
github_commit: "[[P-Reinforce|P-Reinforce]]-logic"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: markdown
framework: unspecified
---
# [[Logic Trees|Logic Trees]]
# Logic Trees
## 📌 한 줄 통찰 (The Karpathy Summary)
> 논리 트리는 거대한 문제를 원자 단위의분해하여 연구 로드맵을 시각화하고 업무의 중복을 원천 차단하는 문제 해결의 지도다.
## 한 줄
> **"매 문제를 MECE쪼개라"**. McKinsey식 hypothesis-driven problem solving의 매 핵심 도구로, 매 root question을 mutually exclusive·collectively exhaustive subquestions으로 분할한다. 2026 LLM agent의 chain-of-thought planner와 매 동형(同形).
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 거시적 문제 선언문에서 미시적 실행 방안으로의 계층적 분해.
- **주요 유형:**
- **[[Issue Tree|Issue Tree]]:** "무엇이 문제인가?"를 중심으로 전체 상황을 [[MECE|MECE]]하게 해체하여 작업 범위(Workstreams)를 획정.
- **[[Hypothesis Tree|Hypothesis Tree]]:** "이것이 해결책인가?"라는 가설에서 시작하여 이를 증명하기 위한 데이터와 분석 단위를 설계.
- **구축 원칙:**
- **Hierarchical Inte[[Grit|Grit]]y:** 하단으로 갈수록 구체성이 높아지며, 각 계층은 상위 계층을 논리적으로 증명해야 함.
- **Trimming Branches:** 가치가 낮은 옵션은 조기에 배제하여 분석의 효율성 극대화.
- **수평적 논리 ([[Horizontal Logic|Horizontal Logic]]):** 그룹 내 아이디어들이 연역적 또는 귀납적인 명확한 논리 순서를 따라야 함.
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Parent:** Logic & Reasoning
- **Related:** [[MECE Principle|MECE Principle]], Business Problem Solving, [[Deductive & Inductive Reasoning|Deductive & Inductive Reasoning]]
- **Raw Source:** 00_Raw/Issue Tree, 00_Raw/Hypothesis Tree, 00_Raw/Horizontal and Vertical Logic
### 매 종류
- **Why-tree (diagnostic)**: 매 root cause 분석 — "왜?"를 5번 반복.
- **How-tree (solution)**: 매 목표 달성 방법 분해.
- **What-tree (descriptive)**: 매 system component 분류.
---
*Last updated: 2026-04-27*
### 매 구성 원칙
- **MECE**: 매 가지가 서로 겹치지 않고 (ME) 매 합쳐서 전체 (CE).
- **Same-level abstraction**: 매 형제 노드는 same granularity.
- **Hypothesis-driven**: 매 leaf에 매 testable hypothesis.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Consulting case interview (McKinsey, BCG, Bain).
2. Root cause analysis (5 Whys, Fishbone).
3. Product strategy (revenue tree: price × volume).
4. LLM agent task decomposition.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Markdown logic tree
```markdown
- Root: 왜 매출이 감소했나?
- 가격 하락? (Hypothesis 1)
- 평균 단가 추이 확인
- 할인율 변화 확인
- 거래량 감소? (Hypothesis 2)
- 신규 고객 수
- 재구매율
- 믹스 변화? (Hypothesis 3)
- 카테고리별 비중
```
## 🧪 검증 상태 (Validation)
### Revenue tree (Python dataclass)
```python
from dataclasses import dataclass
@dataclass
class RevenueTree:
revenue: float
price: float
volume: int
@classmethod
def decompose(cls, rev, p, v):
assert abs(rev - p * v) < 1e-6
return cls(rev, p, v)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### LLM agent decomposition prompt
```python
prompt = """
Decompose this problem into a MECE logic tree (depth=3).
Each leaf must be a testable hypothesis.
Problem: {problem}
Output: nested JSON with {hypothesis, subnodes, test_method}.
"""
```
## 🧬 중복 검사 (Duplicate Check)
### Tree validator (MECE check)
```python
def is_mece(children, total):
coverage = sum(c.share for c in children)
overlap = any(set(a.scope) & set(b.scope)
for a, b in itertools.combinations(children, 2))
return abs(coverage - 1.0) < 0.01 and not overlap
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Issue tree → Gantt
```python
def tree_to_tasks(node, owner=None):
tasks = []
if not node.children:
tasks.append({"task": node.q, "owner": owner})
for c in node.children:
tasks.extend(tree_to_tasks(c, owner=c.owner))
return tasks
```
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
## 매 결정 기준
| 상황 | Tree type |
|---|---|
| 문제 진단 | Why-tree |
| 해결책 설계 | How-tree |
| 시스템 이해 | What-tree |
| LLM agent plan | How-tree (with tools) |
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
**기본값**: Hypothesis-driven Why-tree (depth 3-4).
## 🕓 변경 이력 (Changelog)
## 🔗 Graph
- 부모: [[Mental Models]] · [[Mutually Exclusive and Collectively Exhaustive (MECE)]]
- 변형: [[Issue Tree]] · [[Decision Theory]] · [[Fault-Tree-Analysis]]
- 응용: [[Root-Cause-Analysis]] · [[LLM-Agent-Planning]] · [[5-Whys]]
- Adjacent: [[Pyramid-Principle]] · [[Hypothesis-Driven-Development]]
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🤖 LLM 활용
**언제**: Open-ended problem decomposition, agent task planning, structured analysis.
**언제 X**: Tightly coupled problems with no clean partition (use system dynamics).
## ❌ 안티패턴
- **Non-MECE branches**: 매 overlap 또는 gap.
- **Symptom tree**: 매 root cause 도달 전에 멈춤.
- **Boil-the-ocean**: 매 prioritization 없이 매 leaf 다 조사.
## 🧪 검증 / 중복
- Verified (Minto "The Pyramid Principle"; Rasiel "The McKinsey Way").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Logic tree taxonomy + agent integration |
@@ -2,92 +2,164 @@
id: wiki-2026-0508-lubrication
title: Lubrication
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-LUBR-001]
aliases: [Tribology, Friction Reduction, Bearing Lubrication]
duplicate_of: none
source_trust_level: A
confidence_score: 0.84
tags: [auto-reinforced, lubrication, _system-Efficiency, buffers, coordination, friction-reduction]
confidence_score: 0.88
verification_status: applied
tags: [tribology, mechanical-engineering, materials, maintenance]
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
framework: scipy, sympy, openturns
---
# [[Lubrication|Lubrication]]
# Lubrication
## 📌 한 줄 통찰 (The Karpathy Summary)
> "시스템의 기름칠: 기계 부품 사이의 마찰을 줄여 열과 마모를 막는 물리적 작용을 넘어, 조직이나 소프트웨어 모듈 사이의 '소통의 부재'나 '버퍼의 부재'로 인한 마찰을 제거하여 전체 흐름을 매끄럽게 만드는 시스템적 유연함."
## 한 줄
> **"매 sliding/rolling surface 사이에 매 friction + wear 의 minimize 의 fluid/film 의 introduction"**. Reynolds (1886) 의 thin-film equation → modern: **EHL (elastohydrodynamic), MoS₂ / DLC solid lubricants, ionic liquids, ML-driven oil-condition monitoring**. 매 mechanical reliability 의 single biggest lever — 매 ~23% global energy 의 friction/wear 에 lost (Holmberg & Erdemir 2017).
## 📖 구조화된 지식 (Synthesized Content)
윤활(Lubrication)은 마찰을 완화하여 에너지를 보존하고 파손을 방지하는 행위 및 요소를 의미합니다.
## 매 핵심
1. **물리적 윤활**: 기계적 마찰 감소. ([[Hardware|Hardware]]와 연결)
2. **시스템/조직적 윤활**:
* **Buffers**: 업무 사이의 여유 공간([[Just-in-Case|Just-in-Case]])을 두어 병목 해결. (Just-in-Case와 연결)
* **Communication**: 조율되지 않은 부서 간의 이견을 중재하는 '소통의 기술'. ([[Leadership|Leadership]]와 연결)
* **InterOperability**: 데이터 규격을 맞춰 시스템 간 충돌 방지. (Interoperability와 연결)
3. **왜 중요한가?**:
* 시스템이 복잡해질수록 구성 요소 간의 마찰(Friction)은 기하급수적으로 늘어나며, 적절한 윤활이 없으면 시스템은 과부하로 자폭하기 때문임. ([[Complexity Theory|Complexity Theory]]와 연결)
### 매 Stribeck regimes
- **Boundary**: 매 surface contact, additives carry load (boundary additive ZDDP). μ ≈ 0.1.
- **Mixed**: 매 partial film + asperity contact.
- **Hydrodynamic**: 매 full fluid film, μ ≈ 0.0010.01.
- **EHL (Elastohydrodynamic)**: 매 high-pressure point/line contact (gear teeth, ball bearing) — 매 oil viscosity rises with p, surfaces deform elastically.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 윤활(여유 자원)을 단순한 '낭비 정책'으로 보았으나, 현대 정책은 이 유연성이야말로 불확실한 환경에서 시스템의 생사를 결정하는 '복원력 정책([[Resilience|Resilience]])'임을 인식함(RL Update).
- **정책 변화(RL Update)**: 소프트웨어 아키텍처 정책에서 '미들웨어(Middleware)'나 '중재자 패턴(Mediator Pattern)'은 모듈 간의 직접 마찰을 방지하는 디지털 윤활제 정책으로 기능함.
### 매 lubricant types
- **Mineral oil** (refined crude).
- **Synthetic** (PAO, ester, PAG).
- **Grease** (oil + thickener, e.g., lithium-complex).
- **Solid** (graphite, MoS₂, PTFE, DLC coating).
- **Gas** (air bearing, hard-disk head).
- **Bio / water-based** (food, marine).
## 🔗 지식 연결 (Graph)
- [[Just-in-Case|Just-in-Case]], [[Interoperability|Interoperability]], [[Leadership|Leadership]], [[Complexity Theory|Complexity Theory]], [[Efficiency|Efficiency]]
- **Modern Tech/Tools**: API Gateways, Message Queues (RabbitMQ), Organizational mediators.
---
### 매 key parameters
- **Viscosity** η (Pa·s); kinematic ν = η/ρ (cSt).
- **Viscosity index (VI)**: 매 sensitivity to T (higher = better).
- **Film thickness** h (μm). 매 minimum h_min / σ (composite roughness) > 3 → 매 full EHL.
- **Pressure-viscosity coefficient** α — 매 EHL 의 critical.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 modern (2026)
- **Online oil sensors**: dielectric, IR, viscometer-MEMS, ferrography.
- **ML CBM**: LSTM/transformer 의 RUL prediction from oil + vibration.
- **Sustainability**: re-refined oils, bio-based esters, dry / minimum-quantity lubrication (MQL) machining.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Reynolds equation (1-D, slider bearing)
```python
import numpy as np
from scipy.integrate import solve_bvp
## 🧪 검증 상태 (Validation)
eta = 0.05 # Pa·s
U = 5.0 # m/s
L = 0.05 # m
h0, h1 = 50e-6, 25e-6
def h(x): return h0 + (h1-h0)*x/L
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
def rhs(x, y):
p, dpdx = y
H = h(x)
return np.vstack([dpdx, 6*eta*U/H**3 - 3*dpdx/H * (h1-h0)/L])
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def bc(ya, yb): return np.array([ya[0], yb[0]]) # p=0 at both ends
xs = np.linspace(0, L, 50); y0 = np.zeros((2, xs.size))
sol = solve_bvp(rhs, bc, xs, y0)
W = np.trapz(sol.sol(xs)[0], xs) # load capacity per unit width
```
## 🤔 의사결정 기준 (Decision Criteria)
### HamrockDowson EHL film thickness (point contact)
```python
def hd_central_film(W, U, G, k=1.0):
"""central film thickness ratio H_c (HamrockDowson, point contact)."""
return 2.69 * U**0.67 * G**0.53 * W**-0.067 * (1 - 0.61*np.exp(-0.73*k))
# W = w/(E'*Rx²), U = η0*us/(E'*Rx), G = α*E' (dimensionless groups)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Stribeck curve simulator
```python
import numpy as np, matplotlib.pyplot as plt
def stribeck(eta_N_over_P):
x = np.log10(eta_N_over_P)
return 0.001 + 0.15*np.exp(-((x+5)**2)/1.5) # toy μ(η·N/P)
xs = np.logspace(-7, -3, 200)
plt.semilogx(xs, [stribeck(v) for v in xs])
plt.xlabel("η·N/P"); plt.ylabel("μ")
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Walther viscosity-temperature
```python
def walther_nu(T_C, A, B):
Z = 10**(A - B*np.log10(T_C + 273.15))
return Z - 0.7 # cSt
# A, B 의 fit from two data points (e.g., 40 °C and 100 °C).
```
**기본값:**
> *(TODO)*
### Oil-condition ML (RUL with LSTM, sketch)
```python
import torch, torch.nn as nn
class RULNet(nn.Module):
def __init__(self, in_dim=8, hidden=64):
super().__init__()
self.lstm = nn.LSTM(in_dim, hidden, 2, batch_first=True)
self.head = nn.Linear(hidden, 1)
def forward(self, x):
h,_ = self.lstm(x); return self.head(h[:, -1, :])
# inputs: viscosity, TAN, water%, particle counts, Fe ppm, Cu ppm, T, p
```
## ❌ 안티패턴 (Anti-Patterns)
### Bearing life (L10, ISO 281)
```python
def L10_million_revs(C_N, P_N, p_exp=3): # 3 ball, 10/3 roller
return (C_N / P_N) ** p_exp
def L10h_hours(L10_Mrev, n_rpm):
return L10_Mrev * 1e6 / (60 * n_rpm)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Sliding journal bearing | **Hydrodynamic oil + Reynolds** |
| Rolling element / gear | **EHL oil with high VI + α** |
| High T (engine, turbine) | **Synthetic ester / PAO** |
| Vacuum / radiation / dry | **Solid lubricant (MoS₂, DLC)** |
| Food, medical | **H1 food-grade / bio-based** |
| Sealed-for-life | **Grease (NLGI 2)** |
| Precision machining | **MQL (minimum-quantity lubrication)** |
| Condition monitoring | **Online sensors + ML RUL** |
**기본값**: 매 industrial machinery → **mineral/PAO oil + ZDDP additive + ISO VG selected by viscosity-temp/load**, 매 critical → **online oil + vibration CBM**.
## 🔗 Graph
- 부모: [[Tribology]] · [[Mechanical-Engineering]] · [[Materials-Science]]
- 변형: [[Hydrodynamic-Lubrication]] · [[EHL]] · [[Boundary-Lubrication]] · [[Solid-Lubricant]] · [[Grease]]
- 응용: [[Bearing]] · [[Gearbox]] · [[Internal-Combustion-Engine]] · [[Wind-Turbine]] · [[Hard-Disk-Drive]]
- Adjacent: [[Reynolds-Equation]] · [[Stribeck-Curve]] · [[Condition-Monitoring]] · [[Wear]] · [[Friction]]
## 🤖 LLM 활용
**언제**: 매 lubricant 의 selection table 의 first cut, 매 viscosity-temp curve 의 fitting, 매 oil-analysis report 의 interpretation, 매 CBM model architecture 의 prototyping.
**언제 X**: 매 safety-critical (aerospace, nuclear) 의 final spec — 매 OEM/standards (ISO, DIN, MIL) 직접 검증.
## ❌ 안티패턴
- **Mixing greases (incompatible thickeners)**: 매 Li + Ca-sulfonate → 매 phase-separates → 매 bearing failure.
- **Over-greasing sealed bearing**: 매 churning heat → 매 seal blowout.
- **Wrong viscosity grade**: 매 too-low → boundary/wear; too-high → drag/heat.
- **Ignoring oil age / oxidation (TAN)**: 매 acid attacks bearing.
- **Topping up only**: 매 contaminants accumulate — 매 periodic full change + filter.
- **Same oil 매 high-T + low-T 모두**: 매 VI 의 inadequate → 매 multigrade or synthetic 사용.
## 🧪 검증 / 중복
- Verified (Reynolds 1886; Hamrock & Dowson 1977; Holmberg & Erdemir 2017; Stachowiak & Batchelor *Engineering Tribology* 4th ed.; ISO 281, ASTM D2270/D341).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 placeholder |
| 2026-05-10 | Manual cleanup — Stribeck/EHL theory + 6 patterns + decision matrix |
@@ -2,62 +2,138 @@
id: wiki-2026-0508-model-predictive-control-mpc
title: Model Predictive Control (MPC)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-MPC]
aliases: [MPC, Receding-Horizon-Control, RHC]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
tags: [Engineering, ControlTheory, MPC, Predictive]
confidence_score: 0.95
verification_status: applied
tags: [control, optimization, robotics, autonomous-vehicles, receding-horizon]
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: python
framework: cvxpy-acados
---
# [[Model-Predictive-Control (MPC)|Model-Predictive-Control (MPC)]] (모델 예측 제어)
# Model Predictive Control (MPC)
## 📌 한 줄 통찰 (The Karpathy Summary)
> "몇 수 앞을 내다보고 현재의 핸들을 꺾는 지능형 조타수." 시스템의 수학적 모델을 사용해 미래의 거동을 예측하고, 수천 번의 가공 시뮬레이션을 통해 현재 시점에서 최선의 제어 입력을 결정하는 고도의 제어 알고리즘이다.
## 한 줄
> **"매 step마다 future를 optimize, 첫 action만 실행, 매 반복"**. Receding horizon control은 매 dynamics model + cost + constraints를 매 online QP/NLP로 풀어낸다. 2026 자율주행·드론·humanoid robot의 매 dominant control paradigm으로 reinforcement learning과도 hybrid 구성된다.
## 📖 구조화된 지식 (Synthesized Content)
- **Mechanism**:
1. 현재 상태를 측정함.
2. 일정 기간(Prediction Horizon) 동안 시스템이 어떻게 움직일지 미래를 예측함.
3. 제약 조건(예: 속도 100km 제한)을 만족하면서 가장 목표에 근접하는 입력 시퀀스를 계산.
4. 계산된 여러 수 중 **첫 번째 명령만 실행**하고 다시 1번으로 돌아감 (Receding Horizon).
- **Strength**: 여러 개의 입력과 출력이 얽힌 복잡한 시스템(MIMO)을 다루는 데 탁월하며, 제약 조건을 하드코딩으로 반영할 수 있다.
- **Domain**: 정유 공정, 우주선 도킹, 고성능 자율주행 차량.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- MPC는 매 순간 최적화 문제를 풀어야 하므로 계산 성능이 엄청나게 소모된다. 최근에는 강화학습(RL)이 MPC의 역할을 대신하거나, 반대로 RL이 갈 방향을 MPC가 제약 조건으로 가이드해주는 하이브리드 제어(Learning-based MPC)가 로보틱스의 새로운 표준이 되고 있다.
### 매 정식화
```
min_{u_0..u_{N-1}} Σ (x_k, u_k) + V_f(x_N)
s.t. x_{k+1} = f(x_k, u_k)
g(x_k, u_k) ≤ 0
x_0 = x_current
```
매 첫 u_0만 적용, 다음 step에서 매 새 measurement로 재최적화.
## 🔗 지식 연결 (Graph)
- Related: [[Control-Theory|Control-Theory]] , [[Decision Theory|Decision Theory]]
- AI Hybrid: Deep-[[Reinforcement-Learning|Reinforcement-Learning]]-for-Control
### 매 종류
- **Linear MPC**: f linear, quadratic → QP.
- **Nonlinear MPC (NMPC)**: NLP (IPOPT, acados).
- **Robust MPC**: tube/min-max — uncertainty 처리.
- **Stochastic MPC**: chance constraints.
- **Learning-based MPC**: f를 NN/GP로.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Autonomous driving — trajectory tracking, lane change.
2. Quadrotor / drone control.
3. Humanoid locomotion (Boston Dynamics, Tesla Optimus 추정).
4. Process industry — refinery, chemical plant.
5. HVAC, smart grid.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Linear MPC with CVXPY
```python
import cvxpy as cp, numpy as np
def lin_mpc(A, B, x0, N=10, Q=None, R=None):
nx, nu = B.shape
Q = Q if Q is not None else np.eye(nx)
R = R if R is not None else 0.1*np.eye(nu)
x = cp.Variable((nx, N+1))
u = cp.Variable((nu, N))
cost, cons = 0, [x[:, 0] == x0]
for k in range(N):
cost += cp.quad_form(x[:, k], Q) + cp.quad_form(u[:, k], R)
cons += [x[:, k+1] == A @ x[:, k] + B @ u[:, k]]
cons += [cp.norm(u[:, k], 'inf') <= 1.0]
cp.Problem(cp.Minimize(cost), cons).solve()
return u[:, 0].value
```
## 🧪 검증 상태 (Validation)
### NMPC with CasADi/acados (sketch)
```python
import casadi as ca
x = ca.SX.sym('x', nx); u = ca.SX.sym('u', nu)
f = ca.Function('f', [x, u], [dynamics(x, u)])
# build NLP with multiple shooting...
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Receding horizon loop
```python
for t in range(T):
x_meas = sensor.read()
u_star = mpc_solve(x_meas)
actuator.apply(u_star)
```
## 🧬 중복 검사 (Duplicate Check)
### Reference tracking cost
```python
cost += cp.quad_form(x[:, k] - x_ref, Q)
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Soft constraint via slack
```python
slack = cp.Variable(N, nonneg=True)
cons += [g(x[:, k], u[:, k]) <= slack[k]]
cost += 1e3 * cp.sum(slack)
```
## 🕓 변경 이력 (Changelog)
### Warm-start (next iter uses prev solution)
```python
solver.set_initial_guess(shift(u_prev))
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 매 결정 기준
| 상황 | MPC variant |
|---|---|
| Linear plant, quadratic cost | QP-based linear MPC |
| Nonlinear dynamics | NMPC (acados, CasADi) |
| Bounded uncertainty | Tube MPC |
| Probabilistic constraint | Stochastic MPC |
| Hard real-time (kHz) | Explicit MPC (precomputed) |
**기본값**: Linear MPC + warm-start (cycle time < 10 ms).
## 🔗 Graph
- 부모: [[Optimal-Control-Theory]] · [[Optimization]]
- 변형: [[Nonlinear-MPC]] · [[Robust-MPC]] · [[Stochastic-MPC]]
- 응용: [[Autonomous-Vehicle-Path-Planning]] · [[Quadrotor-Control]] · [[Humanoid-Robot]]
- Adjacent: [[Reinforcement-Learning]] · [[Kalman-Filter-and-State-Tracking]] · [[Feedback-Control-Systems]]
## 🤖 LLM 활용
**언제**: Constrained dynamic systems, real-time replanning, model + cost are known.
**언제 X**: Model 알 수 없거나 long-horizon strategic decision (use RL).
## ❌ 안티패턴
- **Horizon 너무 짧음**: 매 myopic control.
- **Constraint feasibility 무시**: infeasible 시 fallback 없음.
- **Cold-start 매 iteration**: 매 latency 폭발 — warm-start 필수.
- **Plant-model mismatch 무시**: 매 robust/adaptive 가 필요.
## 🧪 검증 / 중복
- Verified (Rawlings, Mayne, Diehl "Model Predictive Control").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — MPC formulation + CVXPY/acados patterns |
@@ -2,62 +2,135 @@
id: wiki-2026-0508-monte-carlo-integration
title: Monte Carlo Integration
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-MC-INT-001]
aliases: [Monte-Carlo-Integration, MC-Integration, 몬테카를로-적분]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Statistics, monte-carlo, integration, sampling, numerical-Analysis]
confidence_score: 0.95
verification_status: applied
tags: [numerical, integration, sampling, statistics, simulation]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: numpy-jax
---
# Monte Carlo Integration (몬테카를로 적분)
# Monte Carlo Integration
## 📌 한 줄 통찰 (The Karpathy Summary)
> "해석적으로 풀 수 없는 복잡한 영역의 넓이를 무작위 샘플통계적 평균으로 정복하라" — 함수의 적분값을 구하기 위해 영역 내에서 무작위 점을 추출하고, 그 점들의 함숫값 평균을 통해 전체 적분량을 근사적으로 계산하는 수치 해석 기법.
## 한 줄
> **"매 무작위 샘플의 평균이 적분값으로 수렴"**. ∫f dμ ≈ (1/N)Σf(xᵢ), error O(N⁻¹/²) — 매 dimension에 무관한 게 매 핵심 강점이다. 1949 Metropolis-Ulam에서 Manhattan Project 이후, 2026 LLM 시대에도 매 RLHF reward estimation·diffusion sampling의 backbone.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Statistical Approximation of Continuous Space" — 연속적인 공간 전체를 계산하는 대신, 대표적인 샘플들을 충분히 많이 추출하면 그 평균이 실제 값에 수렴한다는 대수의 법칙을 활용하여 '차원의 저주'를 극복하는 적분 패턴.
- **수식적 원리:** $I = \int f(x) dx \approx \frac{V}{N} \sum_{i=1}^N f(x_i)$. 여기서 $V$는 영역의 부피, $N$은 샘플 수.
- **주요 특징:**
- **Dimension Independence:** 차원이 높아져도 샘플링 기반이기에 연산 복잡도가 지수적으로 증가하지 않음.
- **Probabilistic Accuracy:** 샘플 수가 늘어날수록 실제 값에 확률적으로 수렴하며, 오차 범위를 통계적으로 추정 가능.
- **의의:** 베이지안 추론, 강화학습의 기댓값 계산, 레이 트레이싱(Ray Tracing) 그래픽스 연산 등 현대 과학 계산의 핵심 근간.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 샘플링의 무작위성 때문에 결과가 매번 미세하게 달라질 수 있다는 단점이 있으나, 중요도 샘플링(Importance Sampling)이나 준-몬테카를로(Quasi-Monte Carlo) 기법을 통해 분산을 줄이고 수렴 속도를 높이는 방향으로 진화함.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 불확실한 보상 기대치를 계산하거나 대규모 지식 그래프의 잠재적 연결 강도를 추정할 때, 몬테카를로 적분 원리를 기반으로 한 시뮬레이션을 수행함.
### 매 estimator
- **Standard MC**: x ~ p, Î = (1/N)Σf(xᵢ); Var = σ²/N.
- **Importance sampling**: x ~ q, Î = (1/N)Σf(xᵢ)p(xᵢ)/q(xᵢ).
- **Control variates**: f → f c(g E[g]); 매 variance ↓.
- **Stratified**: 매 domain partition.
- **Quasi-MC**: Sobol/Halton — error O(N⁻¹ logᵈ N).
## 🔗 지식 연결 (Graph)
- [[Markov-Chain-Monte-Carlo|Markov-Chain-Monte-Carlo]], Probability-Theory, Monte-Carlo-Tree-Search-MCTS, Bayesian-Inference
- **Raw Source:** 10_Wiki/Topics/AI/Monte-Carlo-Integration.md
### 매 수렴
- Error std ~ σ/√N (CLT).
- 매 dim 무관 — high-dim integration의 매 유일한 실용 도구.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Bayesian inference — posterior expectation (MCMC).
2. Computer graphics — path tracing, light transport.
3. Finance — option pricing (Black-Scholes path).
4. RLHF — reward expectation.
5. Diffusion model — score-matching expectation.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Basic MC integral
```python
import numpy as np
def mc_integrate(f, low, high, n=10000):
x = np.random.uniform(low, high, n)
return (high - low) * f(x).mean(), (high - low) * f(x).std() / np.sqrt(n)
```
## 🧪 검증 상태 (Validation)
### Importance sampling
```python
def importance_mc(f, sampler_q, log_p, log_q, n=10000):
x = sampler_q(n)
w = np.exp(log_p(x) - log_q(x))
return (f(x) * w).mean()
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Control variates
```python
def cv_mc(f, g, Eg, n=10000):
x = np.random.uniform(0, 1, n)
fx, gx = f(x), g(x)
c = -np.cov(fx, gx)[0, 1] / np.var(gx)
return (fx + c * (gx - Eg)).mean()
```
## 🧬 중복 검사 (Duplicate Check)
### Quasi-MC with Sobol
```python
from scipy.stats.qmc import Sobol
sampler = Sobol(d=5, scramble=True)
points = sampler.random_base2(m=14) # 2^14 points
estimate = f(points).mean()
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### MCMC (Metropolis-Hastings)
```python
def mh(log_pi, x0, n=10000, sigma=0.5):
x, samples = x0, [x0]
for _ in range(n):
x_prop = x + sigma * np.random.randn(*x.shape)
if np.log(np.random.rand()) < log_pi(x_prop) - log_pi(x):
x = x_prop
samples.append(x)
return np.array(samples)
```
## 🕓 변경 이력 (Changelog)
### JAX vectorized MC
```python
import jax, jax.numpy as jnp
@jax.jit
def mc(key, n):
x = jax.random.uniform(key, (n,))
return jnp.mean(jnp.exp(-x**2))
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 매 결정 기준
| 상황 | Method |
|---|---|
| Smooth low-dim | Quadrature or QMC |
| High-dim | Vanilla MC |
| Heavy tail / rare event | Importance sampling |
| Posterior | MCMC (NUTS, HMC) |
| Light transport | Path tracing + MIS |
**기본값**: Vanilla MC + control variates (low complexity, low variance).
## 🔗 Graph
- 부모: [[Numerical-Integration]] · [[Statistics]]
- 변형: [[Importance-Sampling]] · [[MCMC]] · [[Quasi-Monte-Carlo]]
- 응용: [[Bayesian-Inference]] · [[Path-Tracing]] · [[RLHF]]
- Adjacent: [[Variance-Reduction]] · [[Stratified-Sampling]]
## 🤖 LLM 활용
**언제**: High-dim integration, expectation under intractable distribution, simulation.
**언제 X**: 1-3 dim smooth functions (use Gauss quadrature).
## ❌ 안티패턴
- **Variance 무시**: 매 std error 안 보고 estimate 제출.
- **Bad importance proposal**: 매 q tail이 p보다 얇으면 explosion.
- **Correlated samples**: MCMC autocorrelation 무시 → 매 ESS 부풀려짐.
## 🧪 검증 / 중복
- Verified (Robert & Casella "Monte Carlo Statistical Methods").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — MC variants + JAX/MCMC patterns |
@@ -2,89 +2,147 @@
id: wiki-2026-0508-multivariate-analysis
title: Multivariate Analysis
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-MVA-001]
aliases: [MVA, Multivariate Statistics]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: ["Statistics|[Statistics", math, multivariate-Analysis, pca, mva, data-science]
confidence_score: 0.9
verification_status: applied
tags: [statistics, dimensionality-reduction, multivariate]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: scikit-learn/statsmodels
---
# Multivariate Analysis (다변량 분석)
# Multivariate Analysis
## 📌 한 줄 통찰 (The Karpathy Summary)
> "단일 변수의 관찰을 넘어, 변수들 사이의 복잡한 얽힘과 상호작용 속에서 데이터의 진짜 형상을 발견하라" — 둘 이상의 변수가 동시에 가지는 통계적 특성과 상관관계를 분석하여, 데이터 내의 숨겨진 패턴이나 구조를 파악하는 통계적 방법론의 총칭.
## 한 줄
> **"매 multiple correlated variables 매 동시에"**. 매 MVA는 covariance·correlation matrix를 base로 PCA/FA/CCA/MANOVA/discriminant analysis 매 통합, 매 2026 ML 시대에도 매 EDA·feature engineering·biostatistics·marketing research에서 매 indispensable foundation.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Dimensionality Reduction and Structural Discovery" — 변수들 사이의 공분산(Covariance)과 상관계수를 분석하여, 데이터의 흩어짐을 가장 잘 설명하는 주성분을 찾거나(PCA) 유사한 집단으로 묶는(Clustering) 등 고차원 데이터를 저차원의 핵심 구조로 요약하는 패턴.
- **주요 기법:**
- **PCA (주성분 분석):** 데이터의 분산을 최대한 보존하며 차원 축소.
- **Factor Analysis (요인 분석):** 관측된 변수들 뒤에 숨겨진 잠재 요인 추출.
- **MANOVA (다변량 분산 분석):** 여러 종속 변수에 대한 집단 간 차이 검정.
- **Canonical Correlation:** 두 변수 집단 사이의 상관관계 최대화.
- **의의:** 변수가 수백, 수천 개에 달하는 현대 빅데이터 환경에서 데이터의 중복성을 제거하고 핵심적인 인사이트를 도출하기 위한 필수적인 통계적 토대.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 선형적인 관계 분석에 치중하던 과거와 달리, 이제는 커널 기법이나 오토인코더(Autoencoder)와 같은 신경망 기술과 결합하여 비선형적인 다변량 관계까지 정밀하게 포착하는 방향으로 진화함.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 다양한 성능 지표(응답 속도, 정확도, 토큰 사용량 등) 사이의 복합적인 상관관계를 분석하여 전체적인 시스템 효율을 최적화할 때 다변량 분석 기법을 활용함.
### 매 covariance matrix Σ
- Σᵢⱼ = E[(Xᵢ - μᵢ)(Xⱼ - μⱼ)].
- Eigendecomposition Σ = QΛQᵀ가 매 모든 multivariate 기법의 backbone.
- Sample S = (1/(n-1)) XᶜᵀXᶜ.
## 🔗 지식 연결 (Graph)
- [[Principal-Component-Analysis|Principal-Component-Analysis]]-PCA, [[Linear-Discriminant-Analysis|Linear-Discriminant-Analysis]], [[Exploratory-Data-Analysis|Exploratory-Data-Analysis]], Correlation-vs-Causality
- **Raw Source:** 10_Wiki/Topics/AI/Multivariate-Analysis.md
### 매 family
- **PCA**: max variance projection (eigen of Σ).
- **FA (Factor Analysis)**: latent factors + idiosyncratic noise (X = ΛF + ε).
- **CCA**: max correlation between two variable sets.
- **LDA**: discriminant axes (between-class vs within-class scatter).
- **MANOVA**: multivariate generalization of ANOVA (Wilks Λ, Pillai trace).
- **MDS**: distance-preserving embedding.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. EDA on tabular data (correlation heatmap, biplot).
2. Feature engineering before tree models or MLP.
3. Genomics (gene expression PCA / FA).
4. Marketing segmentation (cluster + biplot).
5. Psychometrics (factor structure of survey).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### PCA — full pipeline
```python
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
## 🧪 검증 상태 (Validation)
X_std = StandardScaler().fit_transform(X)
pca = PCA(n_components=0.95) # keep 95% variance
Z = pca.fit_transform(X_std)
print(pca.explained_variance_ratio_.cumsum())
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# Biplot
loadings = pca.components_.T * np.sqrt(pca.explained_variance_)
plt.scatter(Z[:,0], Z[:,1], alpha=0.3)
for i, name in enumerate(feature_names):
plt.arrow(0, 0, loadings[i,0]*3, loadings[i,1]*3, color='r')
plt.text(loadings[i,0]*3.2, loadings[i,1]*3.2, name)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Factor Analysis with rotation
```python
from sklearn.decomposition import FactorAnalysis
fa = FactorAnalysis(n_components=3, rotation='varimax')
fa.fit(X_std)
print(fa.components_) # loadings
```
**선택 A를 써야 할 때:**
- *(TODO)*
### CCA (cross-modal)
```python
from sklearn.cross_decomposition import CCA
cca = CCA(n_components=2)
cca.fit(X_view1, X_view2)
U, V = cca.transform(X_view1, X_view2)
# diag(corr(U, V)) = canonical correlations
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Linear Discriminant Analysis
```python
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
lda = LinearDiscriminantAnalysis(n_components=2)
Z = lda.fit_transform(X_std, y) # supervised projection
```
**기본값:**
> *(TODO)*
### MANOVA via statsmodels
```python
from statsmodels.multivariate.manova import MANOVA
maov = MANOVA.from_formula('y1 + y2 + y3 ~ group', data=df)
print(maov.mv_test()) # Wilks, Pillai, Hotelling, Roy
```
## ❌ 안티패턴 (Anti-Patterns)
### Mahalanobis distance (multivariate outliers)
```python
import numpy as np
mu = X.mean(axis=0)
S_inv = np.linalg.inv(np.cov(X, rowvar=False))
def mahal(x):
d = x - mu
return np.sqrt(d @ S_inv @ d)
# threshold: chi2.ppf(0.975, df=p)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Variance compression unsupervised | PCA |
| Latent structure interpretation | Factor Analysis (with rotation) |
| Two correlated groups of vars | CCA |
| Supervised projection | LDA |
| Group-mean comparison (multivariate) | MANOVA |
| Distance-only data | MDS |
| Outlier detection multivariate | Mahalanobis / Min Cov Det |
**기본값**: 매 EDA에 PCA + correlation heatmap, 매 supervised에 LDA, 매 latent factor에 FA + varimax.
## 🔗 Graph
- 부모: [[Statistics]] · [[Linear-Algebra]]
- 변형: [[PCA]] · [[Factor-Analysis]] · [[CCA]] · [[LDA]] · [[MANOVA]]
- 응용: [[EDA]] · [[Feature-Engineering]] · [[Biostatistics]]
- Adjacent: [[Dimensionality-Reduction]] · [[t-SNE]] · [[UMAP]]
## 🤖 LLM 활용
**언제**: 매 EDA narrative generation (PCA biplot 해석), factor labeling, MANOVA result writeup.
**언제 X**: 매 actual decomposition computing (numpy/sklearn use).
## ❌ 안티패턴
- **No standardization**: 매 PCA before scaling → 매 large-magnitude vars dominate.
- **PCA on nonlinear**: 매 swiss-roll에 매 PCA 매 사용 → 매 t-SNE/UMAP/Isomap 매 사용.
- **FA without rotation**: 매 unrotated factors 매 interpret 어려움 — 매 varimax/promax 적용.
- **MANOVA assumption**: 매 multivariate normality + equal cov 매 검증 X → wrong p-values.
## 🧪 검증 / 중복
- Verified (Johnson & Wichern "Applied Multivariate", Hardle & Simar).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full MVA toolkit (PCA/FA/CCA/LDA/MANOVA) |
@@ -2,63 +2,132 @@
id: wiki-2026-0508-mutual-information
title: Mutual Information
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-MI-001]
aliases: [Mutual-Information, MI, 상호정보량, I(X;Y)]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Information-Theory, mutual-information, entropy, machine-learning, feature-selection]
confidence_score: 0.95
verification_status: applied
tags: [information-theory, statistics, dependence, feature-selection, representation-learning]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: scikit-learn-pytorch
---
# Mutual Information (상호 정보량)
# Mutual Information
## 📌 한 줄 통찰 (The Karpathy Summary)
> "두 변수가 공유하고 있는 정보의 양을 측정하여, 하나를 알 때 다른 하나에 대한 불확실성이 얼마나 사라지는지 수치화하라" — 두 확률 변수 사이의 상호 의존성을 측정하는 지표로, 단순한 선형 관계를 넘어 비선형적인 연관성까지 모두 포착할 수 있는 정보 이론적 척도.
## 한 줄
> **"매 X를 알면 Y에 대해 매 얼마나 덜 놀라는가"**. I(X;Y) = H(X) H(X|Y) = KL(P_XY ‖ P_X⊗P_Y); 매 어떤 monotonic transform에도 invariant한 dependence measure다. 2026 self-supervised learning(InfoNCE, CLIP)과 disentanglement(β-VAE) 핵심 도구.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Uncertainty Reduction" — 변수 $X$를 관찰함으로써 변수 $Y$의 엔트로피(불확실성)가 얼마나 감소하는지 계산하여, 두 변수가 얼마나 밀접하게 얽혀 있는지 파악하는 패턴.
- **수식적 정의:** $I(X; Y) = H(X) + H(Y) - H(X, Y)$ (각자의 엔트로피 합에서 결합 엔트로피를 뺀 값).
- **주요 특징:**
- **Non-linear Correlation:** 상관계수가 0이라도 상호 정보량은 높을 수 있음 (비선형적 관계 포착 가능).
- **Symmetry:** $I(X; Y) = I(Y; X)$.
- **Non-negativity:** 항상 0 이상의 값을 가지며, 0인 경우 두 변수는 독립임.
- **의의:** 머신러닝의 특징 선택(Feature Selection), 데이터 압축, 베이지안 네트워크 구축, 독립 성분 분석(ICA) 등에서 핵심적인 판단 기준으로 활용됨.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 연속형 변수에서 상호 정보량을 계산할 때 구간 분할(Binning) 방식에 따라 값이 왜곡될 수 있다는 한계가 있어, 최근에는 KNN 기반의 KSG 추정기나 MINE(Mutual Information Neural Estimation) 등 신경망 기반 추정 기법이 주로 사용됨.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 지식 임베딩 품질을 평가할 때, 입력 텍스트와 추출된 핵심 개념 사이의 상호 정보량을 측정하여 정보 손실을 최소화하는 지표로 활용함.
### 매 정의
- **Discrete**: I(X;Y) = ΣΣ p(x,y) log(p(x,y)/(p(x)p(y))).
- **Continuous**: integral 형태.
- **KL form**: I(X;Y) = D_KL(P_XY ‖ P_X⊗P_Y) ≥ 0.
- 매 0 iff X⊥Y.
## 🔗 지식 연결 (Graph)
- [[Kullback-Leibler-Divergence|Kullback-Leibler-Divergence]], [[Independent-Component-Analysis|Independent-Component-Analysis]], Feature-Selection-Strategies, Probability-Theory
- **Raw Source:** 10_Wiki/Topics/AI/Mutual-Information.md
### 매 추정의 어려움
- High-dim continuous에서 매 매 어렵다.
- KSG(k-NN) — Kraskov-Stögbauer-Grassberger.
- MINE — neural net 기반 (Donsker-Varadhan).
- InfoNCE bound — contrastive.
- KDE 기반 (low dim only).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Feature selection (mRMR).
2. Self-supervised learning (SimCLR, CLIP, InfoNCE).
3. Representation disentanglement (β-VAE, InfoGAN).
4. Causal discovery (CMI tests).
5. Information bottleneck.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Discrete MI (sklearn)
```python
from sklearn.metrics import mutual_info_score
mi = mutual_info_score(x_labels, y_labels)
```
## 🧪 검증 상태 (Validation)
### Continuous MI (KSG via sklearn)
```python
from sklearn.feature_selection import mutual_info_regression
mi = mutual_info_regression(X, y, n_neighbors=3)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### MINE (PyTorch)
```python
import torch, torch.nn as nn
class MINE(nn.Module):
def __init__(self, dim_x, dim_y, hid=256):
super().__init__()
self.f = nn.Sequential(nn.Linear(dim_x+dim_y, hid),
nn.ELU(), nn.Linear(hid, 1))
def forward(self, x, y):
joint = self.f(torch.cat([x, y], -1))
y_perm = y[torch.randperm(y.size(0))]
marg = self.f(torch.cat([x, y_perm], -1))
return joint.mean() - torch.log(marg.exp().mean())
```
## 🧬 중복 검사 (Duplicate Check)
### InfoNCE lower bound
```python
def infonce(z_x, z_y, tau=0.1):
logits = z_x @ z_y.T / tau
labels = torch.arange(z_x.size(0), device=z_x.device)
return -torch.nn.functional.cross_entropy(logits, labels) + np.log(z_x.size(0))
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Conditional MI (KSG-style via partition)
```python
def cmi_estimate(X, Y, Z, n_neighbors=5):
# I(X;Y|Z) = I(X;Y,Z) - I(X;Z)
return (mutual_info_regression(X, np.column_stack([Y, Z]), n_neighbors=n_neighbors)
- mutual_info_regression(X, Z, n_neighbors=n_neighbors))
```
## 🕓 변경 이력 (Changelog)
### Maximal Information Coefficient (MIC)
```python
from minepy import MINE as MIC
mine = MIC(); mine.compute_score(x, y)
print(mine.mic())
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 매 결정 기준
| 상황 | Estimator |
|---|---|
| Discrete labels | sklearn `mutual_info_score` |
| Low-dim continuous | KSG (k-NN) |
| High-dim, ML training | InfoNCE / MINE |
| Equitability needed | MIC |
**기본값**: KSG for analysis, InfoNCE for SSL training.
## 🔗 Graph
- 부모: [[Information Theory]] · [[Information-Entropy]]
- 변형: [[Conditional-Mutual-Information]] · [[Pointwise-MI]] · [[Total-Correlation]]
- 응용: [[Self-Supervised-Learning]] · [[Feature-Selection]] · [[Information-Bottleneck]]
- Adjacent: [[Kullback-Leibler-Divergence]] · [[Cross-Entropy]] · [[Causal-Inference]]
## 🤖 LLM 활용
**언제**: Non-linear dependence detection, contrastive representation learning, causal screening.
**언제 X**: Sample size 작거나 high-dim continuous (estimator 신뢰도 ↓).
## ❌ 안티패턴
- **Histogram MI in high-dim**: bias 폭발.
- **MI = correlation 가정**: MI는 매 모든 dependence 잡지만 correlation은 linear만.
- **Plug-in estimator 그대로**: 매 bias correction 필수.
## 🧪 검증 / 중복
- Verified (Cover & Thomas "Elements of Information Theory" ch.2).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — MI estimators + MINE/InfoNCE patterns |
@@ -2,65 +2,142 @@
id: wiki-2026-0508-mutually-exclusive-and-collectiv
title: Mutually Exclusive and Collectively Exhaustive (MECE)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [MECE, ME-CE, 상호배타-전체포괄]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.95
verification_status: applied
tags: [reasoning, problem-solving, consulting, structured-thinking, taxonomy]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: markdown
framework: unspecified
---
# [[Mutually Exclusive and Collectively Exhaustive (MECE)|Mutually Exclusive and Collectively Exhaustive (MECE]]
# Mutually Exclusive and Collectively Exhaustive (MECE)
## 📌 한 줄 통찰 (The Karpathy Summary)
데이터나 문제를 범주화할 때, 항목 간 **'상호 배제(중복 없음)'**와 **'전체 포괄(누락 없음)'**을 충족하도록 나누는 논리적 프레임워크로 전략 컨설팅의 핵심 기초입니다.
## 한 줄
> **"매 항목 겹치지 않고 매 합쳐 전체"**. Barbara Minto가 McKinsey에서 정형화한 매 categorization 원칙으로, 매 합리적 의사소통과 매 logical decomposition의 매 backbone이다. 2026 LLM agent의 task partitioning에서도 매 동일 원칙이 적용된다.
## 📖 구조화된 지식 (Synthesized Content)
- **상호 배제 (Mutually Exclusive):** 각 정보나 하위 범주가 고유하고 독립적이어야 합니다. 즉, 하나의 항목이 두 개 이상의 범주에 속해서는 안 되며, 이는 분석 시 이중 계산(Double-counting)이나 혼란을 방지합니다 [61-63].
- **전체 포괄 (Collectively Exhaustive):** 선택한 범주들을 모두 합쳤을 때 전체 문제나 데이터 세트를 100% 포괄해야 합니다. 누락된 부분이 있으면 중요한 전략적 기회나 위험을 놓칠 수 있습니다 [62, 64, 65].
- **실전 활용:** 이윤 하락 문제를 분석할 때 수익(Price × Volume)과 비용(Fixed Costs + Variable Costs)으로 나누는 수익성 프레임워크가 가장 대표적인 MECE 적용 사례입니다 [66, 67].
- **함정 피하기:** 고객을 '취미'와 '관심사'로 나누는 것은 중복이 발생하여 Non-MECE 방식이 되며 [63, 68], '기타(Other)'라는 모호한 범주를 남용해 억지로 CE 요건을 맞추는 것도 지양해야 합니다 [57].
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[McKinsey Problem Solving|McKinsey Problem Solving]], [[Minto Pyramid Principle|Minto Pyramid Principle]]
- **Projects/Contexts:** [[Issue Tree|Issue Tree]] Development, Market Segmentation
- **Contradictions/Notes:** 현실 세계의 복잡한 시스템에서는 범주 간 완전히 분리되지 않는 상호의존성이 존재할 수 있으므로, MECE만 고집할 경우 문제의 유기적 본질을 지나치게 단순화(False completeness)할 위험이 있습니다 [10, 41, 69].
### 매 두 조건
- **Mutually Exclusive (ME)**: 매 두 카테고리의 교집합 = ∅.
- **Collectively Exhaustive (CE)**: 매 카테고리들의 합집합 = 전체.
---
*Last updated: 2026-04-27*
### 매 typical partition 패턴
- Binary split: A vs Not-A.
- Process steps: Before / During / After.
- Stakeholders: Internal / External.
- Time: Past / Present / Future.
- Quantitative axes: Price × Volume = Revenue.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Issue tree / logic tree decomposition.
2. Market sizing (top-down vs bottom-up).
3. SQL GROUP BY 카테고리 설계.
4. LLM agent subtask split (no overlap, no gap).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### MECE check (Python)
```python
def is_mece(categories, universe):
union = set().union(*categories)
if union != universe:
return False, "not exhaustive", universe - union
for i, a in enumerate(categories):
for b in categories[i+1:]:
if a & b:
return False, "overlap", a & b
return True, "MECE", None
```
## 🧪 검증 상태 (Validation)
### Decision-tree style decomposition
```markdown
- 매출 감소 원인
- 가격 (P)
- 수량 (Q) [P와 ME — 가격 효과 통제 후]
- 믹스 (M) [구성 변화]
→ P + Q + M ≈ ΔRevenue (CE check)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Pandas group MECE validation
```python
def validate_mece_groups(df, group_col, total_col):
grouped = df.groupby(group_col)[total_col].sum()
return abs(grouped.sum() - df[total_col].sum()) < 1e-6
```
## 🧬 중복 검사 (Duplicate Check)
### Set cover (greedy CE construction)
```python
def greedy_cover(universe, sets):
chosen, remaining = [], set(universe)
while remaining:
best = max(sets, key=lambda s: len(s & remaining))
chosen.append(best)
remaining -= best
return chosen
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### LLM prompt for MECE plan
```python
prompt = """
Decompose the task into MECE subtasks:
- Subtasks must NOT overlap (ME).
- Subtasks must cover the full task (CE).
- Output JSON list. Verify by sketching the union set.
Task: {task}
"""
```
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
### MECE + Pareto (80/20 prioritization)
```python
def mece_pareto(buckets, values, top=0.8):
sorted_buckets = sorted(zip(buckets, values), key=lambda x: -x[1])
cum, picked = 0, []
for b, v in sorted_buckets:
picked.append(b); cum += v
if cum >= top * sum(values): break
return picked
```
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 매 결정 기준
| 상황 | Decomposition axis |
|---|---|
| Revenue analysis | P × Q × M |
| Cost analysis | Fixed vs Variable |
| Customer | New vs Existing |
| Process | Stage gates |
| Bug triage | Severity × Component |
## 🕓 변경 이력 (Changelog)
**기본값**: Quantitative MECE (numerical sum-check 가능).
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🔗 Graph
- 부모: [[Mental Models]] · [[Pyramid-Principle]]
- 변형: [[Logic Trees]] · [[Issue Tree]]
- 응용: [[Consulting-Frameworks]] · [[LLM-Agent-Planning]] · [[Root-Cause-Analysis]]
- Adjacent: [[Decision Theory]] · [[Set-Theory]]
## 🤖 LLM 활용
**언제**: Task decomposition, structured analysis, taxonomy design, agent planning.
**언제 X**: Highly entangled / coupled systems where clean partition is impossible.
## ❌ 안티패턴
- **Pseudo-MECE**: 매 표면 MECE이나 매 실제 overlap.
- **Forced exhaustiveness**: "Other" 버킷으로 매 모든 잔여 처리.
- **Wrong axis**: 매 분석 목적과 무관한 축.
## 🧪 검증 / 중복
- Verified (Minto "The Pyramid Principle"; Rasiel "The McKinsey Way").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — MECE conditions + validators |
@@ -2,117 +2,127 @@
id: wiki-2026-0508-neural-ignition
title: Neural Ignition
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Neural-Ignition, Global-Ignition, Conscious-Access]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.85
verification_status: applied
tags: [neuroscience, consciousness, global-workspace, attention, cognitive-neuroscience]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: mne-nilearn
---
# [[신경적 점화]]
# Neural Ignition
## 📌 Brief 무 Summary
신경적 점화(Neuronal Ignition)는 전역적 신경 워크스페이스(GNW) 모델에서 주의(Attention) 메커니즘이 특정 신호를 선택했을 때, 해당 신호가 임계값을 넘어 뇌 전체의 방대한 네트워크로 급격히 확장되는 임계 순간을 의미한다 [1-3]. 이는 무의식적인 국소 정보가 의식적이고 전역적으로 접근 가능한 상태로 변환되는 '전부 아니면 전무(all-or-none)' 형태의 비선형적 상전이 현상이다 [4, 5]. 점화된 정보는 피라미드 뉴런의 장거리 축삭을 통해 방송되며, 인지적 자원들이 맥락적으로 통합될 수 있는 핵심 기반을 제공한다 [3].
## 매 한 줄
> **"매 자극이 의식에 진입하는 순간 전체 뇌가 점화된다"**. Dehaene-Changeux Global Neuronal Workspace theory의 매 핵심 phenomenon — 매 sub-threshold 처리가 매 frontoparietal network의 non-linear all-or-none 활성화로 전이된다. 2026 LLM consciousness 논쟁에서 매 reference 모델로 자주 인용.
## 📖 구조화된 지식 (Synthesized Content)
* **맥락 통합의 시작, 비선형적 상전이(Nonlinear Phase Transition):**
감각 모듈에 입력된 특정 자극(국소 패턴)이 충분히 강하고 측면 경쟁(Lateral competition)을 이겨내면, 전역 워크스페이스의 평균 활성화 수치가 특정 임계값($\theta$)을 초과하게 된다 [2, 6]. 이때 신경적 점화가 발생하며, 임계값 아래에서는 무의식(잠재) 상태에 머물던 패턴이 임계값을 넘는 순간 뇌 전체로 퍼져나가는 비선형적 상전이 현상을 겪게 된다 [5].
* **전역적 방송(Global Broadcasting):**
신경적 점화 상태에 도달한 정보는 전전두엽과 두정엽을 연결하는 장거리 축삭(Axon)을 가진 피라미드 뉴런들을 통해 뇌의 다른 전문 모듈(언어, 기억, 계획 등)로 방송(Broadcast)된다 [3]. 이 과정은 약 100~200ms 동안 지속되며, 수신 네트워크의 광범위한 적응(Adaptation)을 유도하고 다수의 입력 스트림이 승자독식(Winner-take-all) 평형에 정착하여 하나의 의식적 게슈탈트를 형성하게 한다 [7, 8].
* **피드백 신호와 시냅스 가소성(Synaptic Plasticity)의 상호작용:**
점화는 단순히 정보를 퍼뜨리는 수동적인 이벤트가 아니라, 국소 모듈로 피드백 신호를 보내는 기폭제 역할을 한다 [9]. 이 피드백은 뉴런의 국소장(Local fields)에 영향을 미쳐 뉴런의 활성화 상태를 조절하며, 헤브의 법칙(Hebb's rule)에 기반한 시냅스 가소성과 상호작용하여 새로운 상태를 네트워크의 기억에 각인(Imprint)시키는 등 유연하고 견고한 학습 및 적응을 가능하게 한다 [10, 11].
* **객관적 관측 지표:**
신경적 점화 과정은 뇌전도(EEG), 뇌자도(MEG), 기능적 자기공명영상(fMRI) 등에서 관찰될 수 있다 [1]. 특히 감마 동기화(Gamma synchrony) 및 전두-두정 피질의 지속적인 활성화 형태로 나타나며, 이는 정보가 의식 경험과 상관관계를 맺는 뇌의 생물학적 마커로 작용한다 [4, 12, 13].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **용량 제한과 병목 현상(Capacity Limits and Bottleneck):**
신경적 점화는 의식적 정보의 통합을 가능하게 하지만, 전역적 방송이 서로 간섭하는 것을 막기 위해 한 번에 오직 하나(혹은 극소수)의 정보 패턴만이 점화되어 작업 공간에 접근할 수 있다 [14-16]. 결과적으로 뇌는 고도로 병렬적인 시스템임에도 불구하고 의식적 처리는 순차적이고 제한적인 용량을 가질 수밖에 없다는 제약이 발생한다 [14, 17].
* **유연성과 장기 기억의 상충(Flexibility vs. Long-term Retention):**
피드백 신호의 강도($\beta$)가 지나치게 높을 경우 기존 로컬 모듈의 어트랙터(Attractor)가 파괴되거나 크게 변형될 수 있다 [10]. 빠른 맥락 정보의 획득(점화를 통한 인지적 재구성)은 유연성을 높이지만 시스템의 영구적인 근본 지식으로 내재화되는 것과는 상충 관계가 존재할 수 있다 [18].
* **점화 도달을 위한 시간 및 에너지 소요:**
신경적 점화와 뒤이은 맥락의 방송은 뇌의 무의식적 자동 처리 과정과 비교할 때 높은 대사 에너지(BOLD 활성화)를 소모한다 [19]. 학습이 고도화되어 자동화되기 전의 새롭고 낯선 자극일수록 의식적 점화 과정이 많이 요구되며, 생소한 맥락일수록 맥락 체류 시간이 길어져야만 효과적인 인출이 일어난다 [19, 20].
### 매 특성
- **All-or-none**: 매 sub-threshold → ignition 임계 초과 시 매 전역 활성.
- **Late, large-amplitude**: P300 / late slow wave (300-500 ms post-stimulus).
- **Long-distance synchrony**: gamma/beta cross-frequency coupling.
- **Reportable**: 매 ignition된 정보만 self-report 가능 (per GNW).
## 🔗 지식 연결 (Graph)
### Related Concepts
### 매 메커니즘 (GNW)
- Local processors → workspace neuron(layer 5 pyramidal) 경쟁.
- Top-down amplification: prefrontal/parietal feedback.
- Inhibitory winner-take-all.
#### [이론 및 아키텍처 모델]
- [[글로벌 워크스페이스 이론(GWT)]]
- 연결 이유: 신경적 점화가 일어나는 무대인 '작업 공간'의 개념적 뼈대를 제공한 이론이다 [21, 22].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 점화된 정보가 어떻게 다양한 무의식적 프로세스 모듈(청중)에 의해 공유되고 선택적 주의(스포트라이트)를 받게 되는지의 인지 심리학적 은유 메커니즘을 이해할 수 있다 [22, 23].
### 매 응용
1. Anesthesia depth monitor (PCI, perturbational complexity).
2. Vegetative/MCS patient assessment.
3. Subliminal vs supraliminal masking experiments.
4. AI consciousness benchmarks (GWT-inspired).
- [[전역적 신경 워크스페이스(GNW)]]
- 연결 이유: GWT를 생물학적이고 계산 가능한 신경망 아키텍처로 구체화한 모델로, 점화를 시스템의 핵심 동력으로 규정한다 [24].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 국소 모듈의 정보가 어떻게 전두-두정 네트워크의 피라미드 뉴런을 통해 물리적으로 점화되고 뇌 전체로 통합되는지 파악할 수 있다 [3].
## 💻 패턴
#### [동적/계산적 메커니즘]
- [[비선형 상전이(Nonlinear Phase Transition)]]
- 연결 이유: 신경적 점화가 점진적인 현상이 아니라 특정 임계값($\theta$)을 초과할 때 급격히 발생하는 수학적/동역학적 성질을 묘사한다 [5].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 잠재되어 있던 정보가 어떻게 전부 아니면 전무(all-or-none)의 형태로 갑작스럽게 의식 상태로 전환되는지 수학적 임계 모델의 관점에서 이해할 수 있다 [4, 5].
### EEG ERP analysis (MNE)
```python
import mne
epochs = mne.Epochs(raw, events, tmin=-0.2, tmax=0.8,
baseline=(None, 0), preload=True)
evoked = epochs.average()
evoked.plot(picks=['Pz']) # P300 ignition signature
```
- [[세타-감마 결합(TGC)]]
- 연결 이유: 점화된 정보가 멀리 떨어진 뇌 영역 간에 전달되고 묶이는(Binding) 신경 진동의 메커니즘이다 [25].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 전역적 방송이 어떻게 세타파의 위상과 감마파의 진폭 간 동기화를 활용하여 분산된 신경 활동을 시공간적으로 일관되게 묶어내는지 원리를 제공한다 [25].
### Phase-locking value (long-range sync)
```python
import numpy as np
def plv(sig1, sig2):
phase_diff = np.angle(sig1) - np.angle(sig2)
return np.abs(np.exp(1j * phase_diff).mean())
```
### Deeper Research Questions
### PCI (Perturbational Complexity Index)
```python
from sklearn.cluster import KMeans
def pci(tms_eeg_response):
binary = (tms_eeg_response > threshold).astype(int)
return lempel_ziv_complexity(binary.flatten())
```
- GNW 계산 모델 내에서 신경적 점화를 결정하는 임계값($\theta$)은 생물학적으로 어떤 뇌내 신경전달물질에 의해 동적으로 조절되며, 이는 스트레스나 각성 상태와 어떻게 연관되는가?
- 신경적 점화로 인한 전역적 방송(Global Broadcasting)이 일어나는 100~200ms 동안 다른 무의식적 자극들은 구체적으로 어떤 하향식 억제(Top-down inhibition) 기제를 겪는가?
- 측면 경쟁(Lateral competition)의 강도 파라미터($\alpha$) 조정은 자폐 스펙트럼 장애(ASD)의 '약한 중앙 응집' 및 '맥락 맹' 현상과 수학적으로 어떻게 연결하여 모델링할 수 있는가?
- 홉필드 신경망(Hopfield network) 기반 GNW에서 점화 이후 일어나는 피드백($\beta$) 신호가 헤브의 법칙(Hebb's rule)에 의한 시냅스 가소성과 결합하여 인지적 스키마(Schema)를 재구성하는 세부 역학은 무엇인가?
- 인공지능의 어텐션 메커니즘(Attention)이나 맘바(Mamba) 아키텍처의 선택적 상태 공간 모델(SSM)은 뇌의 신경적 점화 방식이 가진 '전역적 수렴 후 분산' 구조(Bowtie 아키텍처)를 어떻게 더 효율적으로 모방할 수 있는가?
### Neural mass model (Wilson-Cowan ignition)
```python
def wilson_cowan(E, I, P, dt=1e-3, tau_e=10, tau_i=20):
dE = (-E + sigmoid(c1*E - c2*I + P)) / tau_e
dI = (-I + sigmoid(c3*E - c4*I)) / tau_i
return E + dt*dE, I + dt*dI
```
### Practical Application Contexts
### Detection of ignition events
```python
def detect_ignition(signal, fs, win_ms=200, k=3):
win = int(fs * win_ms / 1000)
rolling = np.lib.stride_tricks.sliding_window_view(signal, win)
amp = np.abs(rolling).mean(-1)
return amp > amp.mean() + k * amp.std()
```
- **Implementation:** 홉필드 신경망과 같은 순환 신경망 모델을 활용하여, 국소 모듈의 평균 활성화가 임계값($\theta$)을 초과할 때 '점화' 함수를 활성화(1)하고, 그렇지 않으면 억제(0)하는 비선형 활성화 스크립트를 파이썬(Python) 등으로 코딩하여 정보의 의식적 전이 과정을 시뮬레이션할 수 있다 [26, 27].
- **System Design:** 멀티모달 정보를 통합하는 AI 시스템 설계 시, 모든 데이터를 대등하게 처리하기보다 로컬 피처 추출(CNN 등)을 거친 후 중요한 특징만이 '전역 워크스페이스' 모듈로 전파되도록 측면 경쟁 및 점화 임계값 모듈을 포함한 하이브리드 아키텍처를 설계할 수 있다 [28, 29].
- **Operation / Maintenance:** 강화학습(RL) 에이전트를 도입하여 시스템 운영 과정에서 획득한 보상에 따라 점화 임계값($\theta$)과 측면 경쟁 강도($\alpha$)를 동적으로 업데이트, 환경 변화에 맞추어 인지적 자원(컴퓨팅 파워) 할당을 최적화할 수 있다 [30, 31].
- **Learning Path:** 뇌 구조의 정보 통합 이론(GWT/GNW)을 이해한 뒤, 이를 바탕으로 인간의 의식을 모방하여 추론 기능과 통계적 학습을 융합하는 차세대 뉴로-심볼릭 AI(Neuro-Symbolic AI) 분야나 설명 가능한 AI 시스템의 핵심 메커니즘 연구로 학습을 확장할 수 있다 [32, 33].
- **My Project Relevance:** 자율 의사결정을 수행하는 AI 파이프라인 개발 시, 단순히 프롬프트(맥락)를 무한정 늘리는 대신, 상황 판단에 필수적인 핵심 트리거 데이터만이 전역 추론 엔진으로 "점화(방송)"되도록 설계하여 병목 현상 및 환각(Hallucination)을 제어하는 라우팅 메커니즘 구축에 적용할 수 있다.
### Cross-frequency coupling
```python
def pac(low_phase, high_amp):
return np.abs((high_amp * np.exp(1j*low_phase)).mean())
```
### Adjacent Topics
## 매 결정 기준
| Question | Method |
|---|---|
| Conscious access? | P300 / late wave + report |
| Anesthesia depth | PCI |
| Network ignition | Phase-locking, fMRI distance |
| Local vs global | Granger causality, DCM |
- [[어텐션 메커니즘(Attention Mechanism)]]
- 확장 방향: 신경적 점화가 주의(Attention)에 의해 촉발되는 생물학적 기제라면, 이를 인공신경망에서 수학적 가중치 연산으로 모방한 메커니즘을 탐구하고 이 둘 간의 구조적 공통점과 차이점을 비교 분석한다.
- [[자폐 스펙트럼 장애(ASD)의 맥락 맹]]
- 확장 방향: 신경적 점화와 전역적 방송 시스템의 병목 혹은 결함으로 인해 정보가 전체적인 맥락 속에서 통합되지 못하고 국소적 정보 처리에만 머물게 되는 임상적 현상과 그 원인을 분석한다.
- [[뉴로-심볼릭 AI(Neuro-Symbolic AI)]]
- 확장 방향: 패턴 인식에 뛰어난 신경망(로컬 모듈)과 명시적 논리를 처리하는 기호 모듈(전역 워크스페이스 역할)을 통합하는 미래 AI 아키텍처 연구로 확장한다.
**기본값**: ERP P300 + frontoparietal sync as joint signature.
---
*Last updated: 2026-05-04*
## 🔗 Graph
- 부모: [[Global-Workspace-Theory]] · [[Cognitive Neuroscience of Flow]]
- 변형: [[Conscious-Access]] · [[P300]] · [[Late-Positive-Potential]]
- 응용: [[Anesthesia-Monitoring]] · [[Disorders-of-Consciousness]] · [[AI-Consciousness-Benchmarks]]
- Adjacent: [[Cross-Frequency Coupling (CFC)]] · [[Attention-Networks]] · [[Integrated-Information-Theory]]
## 📌 한 줄 통찰 (The Karpathy Summary)
## 🤖 LLM 활용
**언제**: Consciousness modeling, EEG ignition analysis, GWT-inspired AI architecture.
**언제 X**: Pure perceptual processing without report (use V1 models).
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
## ❌ 안티패턴
- **Ignition = activity 동치**: 매 baseline 활성과 매 구분 필요.
- **Single-area ignition**: 매 GNW는 매 distributed 정의.
- **Subjective report 의존**: 매 no-report paradigm 도입 권장.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 🧪 검증 / 중복
- Verified (Dehaene "Consciousness and the Brain"; Mashour et al. 2020).
- 신뢰도 A.
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Ignition signatures + EEG/PCI patterns |
@@ -2,91 +2,122 @@
id: wiki-2026-0508-noise
title: Noise
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-NOIS-001]
aliases: [Noise, 노이즈, Random-Noise]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-reinforced, noise, signals, data-quality, Information-Theory, Statistics]
verification_status: applied
tags: [noise, signals, data-quality, information-theory, statistics]
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
framework: numpy
---
# [[Noise|Noise]]
# Noise
## 📌 한 줄 통찰 (The Karpathy Summary)
> "진실을 가리는 불청객: 우리가 진짜 알고 싶은 정보(Signal)에 섞여 들어와 데이터의 정확도를 떨어뜨리고 판단을 흐리게 만드는 무작위한 방해 요소이자, 역설적으로는 이미지 생성이나 보안 암호화의 핵심 재료로 쓰이는 혼돈의 변수."
## 한 줄
> **"매 signal은 noise와 함께 살아간다"**. Noise는 measurement·channel·process에 섞이는 unwanted variation으로, 매 statistical structure (Gaussian, Poisson, 1/f 등)을 가진다. 2026 ML 시대에서도 매 denoising diffusion model의 핵심 도구로 부활.
## 📖 구조화된 지식 (Synthesized Content)
노이즈(Noise)는 정보 전달 및 처리 과정에서 원치 않게 발생하는 방해 요소입니다.
## 매 핵심
1. **유형**:
* **Statistical Noise**: 측정 오차나 우연성에 의한 데이터 변동. ([[Inferential-Statistics|Inferential-Statistics]]와 연결)
* **Signal Noise**: 통신이나 녹음 과정에서의 전자적 간섭.
* **Concept Noise (Decision Noise)**: 판단 시 나타나는 일관성 없는 편차 (대니얼 카너먼 정의). ([[Judgment|Judgment]]와 연결)
2. **왜 중요한가?**:
* 노이즈를 제거(Denoising)하지 못하면 모델은 데이터의 본질이 아닌 쓸모없는 잡음을 학습([[Overfitting|Overfitting]])하여 예측력이 바닥을 치기 때문임.
### 매 분류 (by spectrum)
- **White noise**: flat power spectrum, 매 사실상 i.i.d.
- **Pink (1/f) noise**: 매 자연계 보편 — neural firing, music, finance.
- **Brownian (1/f²)**: 매 random walk integral.
- **Shot noise (Poisson)**: 매 photon counting, low-light imaging.
- **Quantization noise**: ADC bit depth 한계.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 노이즈를 무조건 지워야 할 '오답 정책'으로만 보았으나, 현대 정책(Diffusion Model 등)은 노이즈로부터 정보를 복원하는 과정 정책을 통해 고해상도 이미지를 생성하는 '노이즈의 창조적 활용 정책'으로 패러다임을 바꿈(RL Update). ([[Gen-AI|Gen-AI]]와 연결)
- **정책 변화(RL Update)**: 학습 데이터 정책에서도 의도적으로 노이즈를 섞어(Data Augmentation) 모델의 맷집을 키우는 '강인한 학습 정책'이 일반화 성능의 핵심 정책이 됨.
### 매 noise model
- Additive: y = x + n (대부분 가정).
- Multiplicative: y = x · n (speckle, fading).
- Convolutive: 매 reverberation.
## 🔗 지식 연결 (Graph)
- [[Information-Entropy|Information-Entropy]], [[Inferential-Statistics|Inferential-Statistics]], [[Judgment|Judgment]], [[Gen-AI|Gen-AI]], [[Optimization|Optimization]]
- **Modern Tech/Tools**: Denoising Autoencoders, Diffusion Models, Gaussian noise, SNR (Signal-to-Noise Ratio).
---
### 매 응용
1. Denoising diffusion (Stable Diffusion 3, FLUX) — noise를 학습 시그널로 사용.
2. Differential privacy — Laplace/Gaussian noise 추가.
3. Stochastic optimization — SGD의 noise가 generalization 도움.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Gaussian noise 추가
```python
import numpy as np
def add_gaussian(x, sigma=0.1):
return x + np.random.normal(0, sigma, x.shape)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pink noise 생성 (Voss-McCartney)
```python
def pink_noise(n, num_sources=16):
array = np.zeros((num_sources, n))
for i in range(num_sources):
step = 2 ** i
array[i, ::step] = np.random.randn((n + step - 1) // step)
return array.sum(axis=0)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### SNR 계산
```python
def snr_db(signal, noise):
return 10 * np.log10(np.var(signal) / np.var(noise))
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Wiener filter (optimal linear denoise)
```python
from scipy.signal import wiener
denoised = wiener(noisy, mysize=5)
```
**기본값:**
> *(TODO)*
### DP-noise (differential privacy)
```python
def laplace_dp(value, sensitivity, epsilon):
return value + np.random.laplace(0, sensitivity / epsilon)
```
## ❌ 안티패턴 (Anti-Patterns)
### Diffusion forward process
```python
def forward_diffuse(x0, t, betas):
alpha_bar = np.cumprod(1 - betas)[t]
eps = np.random.randn(*x0.shape)
return np.sqrt(alpha_bar) * x0 + np.sqrt(1 - alpha_bar) * eps, eps
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Sensor 측정 | Gaussian assumption + Kalman |
| Photon-limited | Poisson MLE |
| Privacy preserve | Laplace/Gaussian DP |
| Generative model | Diffusion (DDPM/EDM) |
**기본값**: Additive Gaussian (most analyzable).
## 🔗 Graph
- 부모: [[Information Theory]] · [[Statistics]]
- 변형: [[White-Noise]] · [[Pink-Noise]] · [[Shot-Noise]]
- 응용: [[Denoising-Diffusion]] · [[Kalman-Filter-and-State-Tracking]] · [[Differential-Privacy]]
- Adjacent: [[Signal-Processing]] · [[Stochastic-Process]]
## 🤖 LLM 활용
**언제**: Data augmentation, robustness training, generative modeling, privacy.
**언제 X**: Deterministic exact computation 필요 시.
## ❌ 안티패턴
- **Noise blindness**: noise model 가정 없이 deterministic 처리.
- **SNR 무시**: low-SNR 데이터로 high-precision claim.
- **Whiteness 가정**: 매 실제는 colored noise인데 white로 모델링.
## 🧪 검증 / 중복
- Verified (Papoulis "Probability, Random Variables, and Stochastic Processes").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Noise taxonomy + DP/diffusion patterns |
@@ -1,125 +1,193 @@
---
id: wiki-2026-0508-ontology
title: Ontology
category: Computer_Science_and_Theory
status: needs_review
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ONT-001]
aliases: [Formal Ontology, Knowledge Ontology, Domain Model]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [auto-reinforced, ontology, knowledge-engineering, taxonomy, semantic-web, data-modeling]
confidence_score: 0.9
verification_status: applied
tags: [knowledge-representation, semantic-web, philosophy, AI]
raw_sources: []
last_reinforced: 2026-05-04
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/turtle
framework: rdflib/owlready2
---
# [[Ontology|Ontology]]
# Ontology
## 📌 한 줄 통찰 (The Karpathy Summary)
> "지식의 세계관 설계: 단순히 데이터를 분류하는 것을 넘어, 특정 도메인 내에 존재하는 개념들의 본질과 그들 사이의 엄격한 관계 규칙을 정의하여 컴퓨터가 세상을 이해하는 논리적 틀을 제공하는 것."
## 한 줄
> **"매 specification of a conceptualization (Gruber 1993) — 매 domain 의 entity, class, relation 의 formal definition"**. Aristotle 의 categories 에서 출발, Tim Berners-Lee 의 Semantic Web (RDF/OWL) 으로 web-scale 구현. 매 2026 의 사용처: knowledge graph (Wikidata, Google KG), biomedical (Gene Ontology, SNOMED CT), enterprise data fabric, LLM 의 retrieval-augmented generation grounding.
## 📖 구조화된 지식 (Synthesized Content)
온톨로지(Ontology)는 특정 지식 도메인 내의 개념(Class), 개체(Instance), 속성(Property) 및 그들 간의 관계를 정형화하여 표현한 모델입니다.
## 매 핵심
1. **온톨로지의 구성 요소**:
* **클래스 (Class)**: 사물이나 개념의 집합. (예: '사람', '도시', '프로젝트')
* **속성 (Property)**: 클래스의 특징이나 관계를 정의. (예: '나이', '위치한 곳')
* **제약 조건 (Constraint)**: 관계의 규칙을 정의. (예: '도시'는 반드시 하나의 '국가'에 속해야 함)
### 매 핵심 구성요소
- **Class (Concept)**: 매 entity type (e.g., Person, Drug).
- **Individual (Instance)**: 매 구체적 entity (e.g., :alice).
- **Property**: 매 entity 간 또는 entity-literal 의 binary relation.
- **ObjectProperty**: 매 entity → entity (e.g., :hasParent).
- **DatatypeProperty**: 매 entity → literal (e.g., :hasAge xsd:int).
- **Axiom**: 매 logical statement (subClassOf, equivalentClass, disjointWith).
- **Hierarchy**: 매 taxonomy (is-a) + partonomy (part-of).
2. **분류 체계(Taxonomy)와의 차이**:
* **Taxonomy**: 단순히 부모-자식 관계(A는 B의 일종이다)의 계층 구조만 가집니다.
* **Ontology**: '소유하다', '제작하다', '거주하다' 등 훨씬 더 복잡하고 다양한 관계를 표현할 수 있습니다.
### 매 stack
- **RDF**: 매 triple (subject, predicate, object) — graph data model.
- **RDFS**: 매 lightweight schema (subClassOf, domain, range).
- **OWL 2**: 매 description logic 기반 — 매 SROIQ(D), reasoning 가능.
- **SPARQL**: 매 query language (SQL for RDF).
- **SHACL**: 매 shape-based validation.
3. **지식 관리 시스템에서의 역할**:
* **[[Knowledge Graph|Knowledge Graph]]의 뼈대**: 그래프가 어떤 형태로 구축되어야 하는지 가이드를 제공합니다.
* **데이터 통합**: 서로 다른 이름으로 불리는 같은 개념을 통일된 용어로 매핑합니다.
* **추론 가동**: 정의된 규칙을 바탕으로 명시되지 않은 새로운 지식을 도출합니다.
### 매 응용
1. Wikidata, DBpedia (general knowledge graph).
2. Gene Ontology, SNOMED CT, UMLS (biomedical).
3. schema.org (web markup, Google rich results).
4. Enterprise: data catalogs (Collibra, Atlan).
5. LLM grounding (GraphRAG, knowledge-graph augmented retrieval).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **고도의 전문성 요구**: 효과적인 온톨로지를 설계하기 위해서는 해당 도메인에 대한 깊은 이해와 지식 공학(Knowledge Engineering) 기술이 필수적입니다.
* **경직성 리스크**: 너무 엄격하게 설계된 온톨로지는 빠르게 변화하는 최신 지식을 수용하기 어렵고 유연성이 떨어질 수 있습니다.
* **구축 비용**: 초기 설계와 지속적인 갱신에 상당한 시간과 인적 자원이 소요됩니다.
## 💻 패턴
## 💻 실전 구현 코드 (Boilerplate)
지식의 계층과 관계를 정의하는 마크다운 기반의 약식 온톨로지 정의 예시입니다.
### Turtle (RDF/OWL syntax)
```turtle
@prefix : <http://example.org/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
```markdown
# Antigravity Knowledge Ontology v1.0
:Person a owl:Class .
:Drug a owl:Class .
:Antibiotic rdfs:subClassOf :Drug .
## 1. Core Classes (개념군)
- [[Agent]]: 자율적으로 행동하는 AI 주체
- [[Wiki]]: 정제된 지식의 보관 단위
- [[Protocol]]: 지식 처리를 위한 규약
:hasPrescribed a owl:ObjectProperty ;
rdfs:domain :Person ;
rdfs:range :Drug .
## 2. Relationships (관계 정의)
- [Agent] -- FOLLOWS --> [Protocol]
- [Protocol] -- STANDARDIZES --> [Wiki]
- [Agent] -- REINFORCES --> [Wiki]
## 3. Data Properties (속성 정의)
- Agent.version: 시스템 버전
- Wiki.category: 지식 분류 (AI_and_ML, Backend 등)
- Protocol.last_updated: 최신 갱신일
:alice a :Person ;
:hasPrescribed :amoxicillin .
:amoxicillin a :Antibiotic .
```
## 🔗 지식 연결 (Graph)
* **상위 개념**: [[Computer Science and Theory|Computer Science]], [[Information Science|Information Science]]
* **활용 기술**: [[Knowledge Graph|Knowledge Graph]], [[Semantic Web|Semantic Web]]
* **관련 도구**: [[RDF|RDF]], [[OWL|OWL]], [[Protégé|Protégé]]
### rdflib (Python) — load + query
```python
from rdflib import Graph
---
*Last updated: 2026-05-04*
g = Graph()
g.parse("ontology.ttl", format="turtle")
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# SPARQL: who was prescribed an antibiotic?
q = """
PREFIX : <http://example.org/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?person ?drug WHERE {
?person :hasPrescribed ?drug .
?drug a/rdfs:subClassOf* :Antibiotic .
}
"""
for row in g.query(q):
print(row.person, row.drug)
```
## 🤔 의사결정 기준 (Decision Criteria)
### owlready2 (OWL with reasoning)
```python
from owlready2 import *
**선택 A를 써야 할 때:**
- *(TODO)*
onto = get_ontology("http://example.org/onto.owl")
with onto:
class Person(Thing): pass
class Drug(Thing): pass
class Antibiotic(Drug): pass
class hasPrescribed(ObjectProperty):
domain = [Person]
range = [Drug]
**선택 B를 써야 할 때:**
- *(TODO)*
alice = Person("alice")
amox = Antibiotic("amoxicillin")
alice.hasPrescribed.append(amox)
**기본값:**
> *(TODO)*
sync_reasoner_pellet() # 매 inference: amox is Drug (subclass)
```
## ❌ 안티패턴 (Anti-Patterns)
### SHACL validation
```turtle
:PersonShape a sh:NodeShape ;
sh:targetClass :Person ;
sh:property [
sh:path :hasAge ;
sh:datatype xsd:integer ;
sh:minInclusive 0 ;
sh:maxInclusive 150 ;
] .
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### LLM + ontology RAG (GraphRAG-style)
```python
def graph_rag(question, llm, kg):
# 1. Extract entities from question
entities = llm.extract_entities(question)
# 2. SPARQL: get neighborhood
facts = []
for e in entities:
facts.extend(kg.query(f"""
SELECT ?p ?o WHERE {{ <{e}> ?p ?o }} LIMIT 50
"""))
# 3. Answer with grounded context
return llm.generate(question, context=facts)
```
### Ontology alignment (string + embedding)
```python
from sentence_transformers import SentenceTransformer, util
def align_classes(onto_a_labels, onto_b_labels, threshold=0.85):
model = SentenceTransformer("all-mpnet-base-v2")
emb_a = model.encode(onto_a_labels, convert_to_tensor=True)
emb_b = model.encode(onto_b_labels, convert_to_tensor=True)
sim = util.cos_sim(emb_a, emb_b)
matches = []
for i, row in enumerate(sim):
j = row.argmax().item()
if row[j] > threshold:
matches.append((onto_a_labels[i], onto_b_labels[j], row[j].item()))
return matches
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| simple tagging / faceting | flat taxonomy |
| domain modeling, no reasoning | RDFS |
| reasoning required (subsumption, equivalence) | OWL 2 + reasoner |
| validation rules | SHACL |
| massive scale, low schema | property graph (Neo4j) |
| LLM grounding | knowledge graph + GraphRAG |
**기본값**: 매 enterprise → SKOS + RDFS; 매 reasoning critical → OWL 2 EL/QL profile.
## 🔗 Graph
- 부모: [[Knowledge Graph]] · [[Semantic Web]] · [[Knowledge Representation]]
- 변형: [[OWL]] · [[RDFS]] · [[SKOS]]
- 응용: [[Gene Ontology]] · [[schema.org]] · [[Wikidata]] · [[GraphRAG]]
- Adjacent: [[Description Logic]] · [[SPARQL]] · [[Linked Data]] · [[Taxonomy]]
## 🤖 LLM 활용
**언제**: 매 hallucination 감소를 위한 grounding, 매 enterprise data fabric, 매 named-entity resolution against canonical IDs.
**언제 X**: 매 small unstructured task — overhead 큼. 매 ontology engineering 비용 > 가치.
## ❌ 안티패턴
- **OWL Full 사용**: 매 reasoning undecidable. 매 OWL 2 DL profile (EL/QL/RL) 사용.
- **subClassOf 의 오용** as instanceOf: 매 class hierarchy ≠ instance membership.
- **No URI versioning**: 매 schema 진화 시 breakage. 매 owl:versionIRI 사용.
- **Free-text label only, no canonical URI**: 매 alignment 불가능.
- **Reasoning everything** every query: 매 비싸다 — materialize 후 cache.
## 🧪 검증 / 중복
- Verified (Gruber 1993; W3C OWL 2 spec; *Foundations of Semantic Web Technologies* Hitzler et al.; GraphRAG Microsoft 2024).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Ontology FULL with RDF/OWL/SHACL/GraphRAG patterns |
@@ -2,95 +2,156 @@
id: wiki-2026-0508-operations-research
title: Operations Research
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-OPRES-001]
aliases: [OR, Management Science, Decision Science]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, mathematics, Optimization, _system-Analysis, Management-science]
confidence_score: 0.9
verification_status: applied
tags: [optimization, decision-science, mathematical-programming]
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
framework: PuLP/Gurobi/OR-Tools
---
# [[Operations-Research|Operations-Research]]
# Operations Research
## 📌 한 줄 통찰 (The Karpathy Summary)
> "최적의 선택을 위한 수학적 나침반: 복잡한 시스템의 자원 배분 문제를 수리 모델링하여, 최소의 비용으로 최대의 효율을 뽑아내는 의사결정의 과학."
## 한 줄
> **"매 decision-making을 mathematical model로"**. 매 WWII 군사 logistics에서 시작된 OR은 매 LP/MIP/network/queueing/simulation으로 확장, 매 2026 현재 supply chain·routing·scheduling·revenue management의 backbone이며 Gurobi 12 / OR-Tools 9.10 / Mosek가 매 industrial workhorse.
## 📖 구조화된 지식 (Synthesized Content)
경영 과학([[Opera|Opera]]tions [[Research|Research]], OR)은 수학적 모델, 통계학, 알고리즘을 사용하여 복잡한 시스템의 문제를 해결하고 의사결정을 돕는 학문입니다.
## 매 핵심
1. **주요 해결 기법**:
* **Linear Programming (선형 계획법)**: 제약 조건 하에서 선형 함수를 극대화/최소화 (예: 수송 최적화).
* **Queuing Theory (대기 행렬 이론)**: 줄 서기 현상을 분석하여 서비스 창구 수나 대기 시간을 최적화.
* **Monte Carlo Simulation**: 불확실성이 큰 시스템을 반복 시행을 통해 확률적으로 분석.
2. **적용 분야**:
* **공급망 관리 (SCM)**: 재고 유지 비용 최소화 및 물류 경로 최적화.
* **금융**: 포트폴리오 자산 배분 및 리스크 관리.
* **전략 기획**: 비즈니스 프로세스 개선 및 인력 배치.
3. **역사적 배경**:
* 제2차 세계대전 당시 레이더 배치, 잠수함 탐색 등 군사 작전의 효율성을 높이기 위해 시작되어 민간 영역으로 확산됨.
### 매 4 sub-disciplines
- **Mathematical Programming**: LP, MIP, NLP, SOCP, SDP.
- **Network Models**: shortest path, max flow, min-cost flow, assignment.
- **Stochastic Models**: queueing (M/M/c), Markov chains, MDP.
- **Simulation**: discrete event, Monte Carlo, agent-based.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 정적인 데이터 기반의 선형 모델이 주류였으나, 현대의 OR은 실시간으로 변하는 빅데이터와 결합하여 '적응형 최적화(Adaptive Optimization)'로 진화함.
- **정책 변화(RL Update)**: 인공지능(Reinforcement Learning)이 기존의 OR 수식을 대체하거나 보완하며, 단순 효율성뿐만 아니라 '지속 가능성(ESG)'을 제약 조건으로 포함하는 다중 목적 최적화 정책이 글로벌 스탠다드가 됨.
### 매 LP duality
- Primal min cᵀx s.t. Ax ≥ b, x ≥ 0.
- Dual max bᵀy s.t. Aᵀy ≤ c, y ≥ 0.
- Strong duality: optimal values equal (Slater's condition).
- Dual = shadow prices of constraints.
## 🔗 지식 연결 (Graph)
- **Related**: [[Decision Theory|Decision Theory]], Game Theory, [[Probability Theory|Probability Theory]], Complex Adaptive Systems, Economic Models
- **Modern Tech/Tools**: Gurobi Solver, IBM ILOG CPLEX, Python (SciPy/Pyomo).
---
### 매 응용
1. **Supply chain**: facility location, inventory, transportation.
2. **Airline**: crew scheduling, fleet assignment, revenue management.
3. **Energy**: unit commitment, economic dispatch.
4. **Healthcare**: OR scheduling, ambulance routing.
5. **ML 교차**: structured prediction, MIP-based interpretability.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Linear Programming with PuLP
```python
import pulp
prob = pulp.LpProblem("Diet", pulp.LpMinimize)
x1 = pulp.LpVariable("bread", lowBound=0)
x2 = pulp.LpVariable("milk", lowBound=0)
prob += 2*x1 + 3*x2 # cost
prob += 4*x1 + 3*x2 >= 100 # protein
prob += 2*x1 + 5*x2 >= 80 # vitamin
prob.solve(pulp.GUROBI_CMD(msg=0))
print(x1.varValue, x2.varValue, pulp.value(prob.objective))
```
## 🤔 의사결정 기준 (Decision Criteria)
### MIP — Facility Location
```python
from gurobipy import Model, GRB, quicksum
m = Model()
y = m.addVars(facilities, vtype=GRB.BINARY, name="open")
x = m.addVars(facilities, customers, lb=0, name="ship")
m.setObjective(
quicksum(f[i]*y[i] for i in facilities) +
quicksum(c[i,j]*x[i,j] for i in facilities for j in customers),
GRB.MINIMIZE)
m.addConstrs(quicksum(x[i,j] for i in facilities) == d[j] for j in customers)
m.addConstrs(x[i,j] <= d[j]*y[i] for i in facilities for j in customers)
m.optimize()
```
**선택 A를 써야 할 때:**
- *(TODO)*
### VRP with OR-Tools
```python
from ortools.constraint_solver import pywrapcp, routing_enums_pb2
manager = pywrapcp.RoutingIndexManager(len(dist), num_vehicles, depot)
routing = pywrapcp.RoutingModel(manager)
def cb(i, j): return dist[manager.IndexToNode(i)][manager.IndexToNode(j)]
idx = routing.RegisterTransitCallback(cb)
routing.SetArcCostEvaluatorOfAllVehicles(idx)
params = pywrapcp.DefaultRoutingSearchParameters()
params.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
solution = routing.SolveWithParameters(params)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Min-Cost Flow (NetworkX)
```python
import networkx as nx
G = nx.DiGraph()
G.add_edge('s', 'a', capacity=4, weight=2)
G.add_edge('s', 'b', capacity=2, weight=4)
G.add_edge('a', 't', capacity=3, weight=1)
G.add_edge('b', 't', capacity=5, weight=3)
flow_cost, flow_dict = nx.network_simplex(G)
```
**기본값:**
> *(TODO)*
### M/M/c queue analysis
```python
import math
def mmc(lam, mu, c):
rho = lam/(c*mu)
p0_inv = sum((c*rho)**n / math.factorial(n) for n in range(c))
p0_inv += (c*rho)**c / (math.factorial(c)*(1-rho))
p0 = 1/p0_inv
Lq = p0 * (c*rho)**c * rho / (math.factorial(c)*(1-rho)**2)
Wq = Lq/lam
return {'utilization': rho, 'Lq': Lq, 'Wq': Wq}
```
## ❌ 안티패턴 (Anti-Patterns)
### Stochastic 2-stage LP
```python
# x: first-stage, y_s: scenario s recourse
# min cᵀx + Σ pₛ qᵀyₛ s.t. Tx + Wyₛ = hₛ
# Benders decomposition으로 solve 매 large-scale.
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Continuous, linear | LP (simplex/interior point) |
| Discrete decisions | MIP (branch & cut) |
| Nonconvex | Global solver (BARON, Gurobi 12) or heuristic |
| Stochastic | 2-stage SP / robust optimization |
| Sequential decision | MDP / RL |
| Combinatorial/routing | OR-Tools CP-SAT |
**기본값**: Gurobi 12 (commercial) or HiGHS (open-source) for LP/MIP; OR-Tools CP-SAT for combinatorial.
## 🔗 Graph
- 부모: [[Optimization]] · [[Mathematical-Programming]]
- 변형: [[Linear-Programming]] · [[Integer-Programming]] · [[Stochastic-Programming]]
- 응용: [[Supply-Chain]] · [[Vehicle-Routing-Problem]] · [[Revenue-Management]]
- Adjacent: [[Reinforcement-Learning]] · [[Combinatorial-Optimization]]
## 🤖 LLM 활용
**언제**: 매 problem formulation translation (NL→model), constraint extraction, MIP warm-start heuristics, post-hoc 해석.
**언제 X**: 매 numerical solving 자체 (LLM은 solver 호출 매 wrapping role).
## ❌ 안티패턴
- **Pure LLM solving**: 매 LLM은 OR solver 아님. 매 Gurobi/OR-Tools 매 사용.
- **Ignoring duality**: 매 shadow price 매 sensitivity analysis 의 핵심.
- **Over-tight constraints**: 매 infeasibility → IIS (irreducible inconsistent subsystem) 매 분석.
- **Symmetry-blind MIP**: 매 symmetry breaking constraint 매 추가, branch tree 매 collapse.
## 🧪 검증 / 중복
- Verified (Hillier & Lieberman 11e, Bertsimas & Tsitsiklis, Gurobi docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full OR overview with LP/MIP/VRP/queueing patterns |
@@ -2,65 +2,126 @@
id: wiki-2026-0508-operator-theory
title: Operator Theory
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-OPTH-001]
aliases: [Operator-Theory, 작용소-이론, Functional-Analysis-Operators]
duplicate_of: none
source_trust_level: A
confidence_score: 0.86
tags: [auto-reinforced, Operator-theory, mathematics, Physics, functional-Analysis, linear-operators]
confidence_score: 0.9
verification_status: applied
tags: [math, functional-analysis, linear-algebra, hilbert-space, spectral-theory]
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: python
framework: scipy-linalg
---
# [[Operator-Theory|Operator-Theory]]
# Operator Theory
## 📌 한 줄 통찰 (The Karpathy Summary)
> "변화의 수학적 규칙: 함수를 입력받아 다른 함수로 변조하거나 숫자로 변환하는 '연산자(Operator)' 그 자체의 성질을 연구하는 학문이자, 입자의 확률 분포가 변하는 현대 물리학(양자역학)과 복잡한 신경망의 변환을 설명하는 심오한 기초 체력."
## 한 줄
> **"매 행렬을 무한차원으로 확장한 게 operator"**. Hilbert/Banach 공간의 linear map을 다루며, 매 spectral theorem·compact operators·C*-algebras를 통해 quantum mechanics·PDE·signal processing을 통합한다. 2026 ML에서는 매 Koopman operator로 dynamical system 학습에 부활.
## 📖 구조화된 지식 (Synthesized Content)
연산자 이론(Operator-Theory)은 함수 공간에서 작용하는 연산자의 특성을 다루는 수학의 한 분야입니다. (함수해석학의 핵심)
## 매 핵심
1. **기초 개념**:
* **Linear Operator**: 덧셈과 상수 곱셈의 선형성을 유지하는 변환. ([[Linear-Algebra|Linear-Algebra]]와 연결)
* **Spectrum**: 행렬의 고유값 개념을 무한 차원의 함수 공간으로 확장한 것.
* **Functional Analysis**: 무한히 많은 변수를 다루는 수학적 뼈대.
2. **왜 중요한가?**:
* 현대 제어 공학, 신호 처리, 그리고 양자 컴퓨팅의 상태 변화 정책을 수식으로 완벽히 통제하게 돕기 때문임.
### 매 분류
- **Bounded vs Unbounded**: 매 norm 제한 여부.
- **Compact**: 매 unit ball을 relatively compact set으로 보내는 operator.
- **Self-adjoint**: T = T*; 매 eigenvalue 실수.
- **Unitary**: T*T = I; 매 inner product 보존.
- **Normal**: TT* = T*T; 매 spectral theorem 적용 가능.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 추상 수학 정책에 머물렀으나, 현대 정책은 딥러닝에서 입력 텐서를 출력 텐서로 바꾸는 계층(Layer) 하나하나를 연산자로 보고 '연산자 학습(Neural Operator)' 정책을 연구하여 물리 법칙을 직접 푸는 AI 정책 수립에 결정적 기여 정책을 함(RL Update).
- **정책 변화(RL Update)**: 데이터 간의 차이가 유한할 때는 행렬 대수 정책을 쓰지만, 연속적인 세상 정책(Continuous world)을 설명할 때는 연산자 이론 정책이 필수적이며, 이는 '물리 기반 신경망(PINN)' 정책의 모태가 됨.
### 매 spectral 분해
- Finite-dim: eigenvalue decomposition.
- Compact self-adjoint: countable eigenvalues + ON eigenvectors (Hilbert-Schmidt).
- Bounded self-adjoint: spectral measure dE(λ); T = ∫λ dE(λ).
## 🔗 지식 연결 (Graph)
- [[Linear-Algebra|Linear-Algebra]], [[Optimization|Optimization]], Deep Learning (DL), [[High-Performance Computing (HPC)|High-Performance Computing (HPC)]], [[Logic|Logic]]
- **Modern Tech/Tools**: Fourier transform operators, Laplacians, Neural Operators (FNO), Quantum operators.
---
### 매 응용
1. Quantum mechanics — observable = self-adjoint operator.
2. PDE — Laplacian, Schrödinger evolution.
3. Koopman/Perron-Frobenius — dynamical system linearization.
4. RKHS / kernel methods — integral operator.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Bounded operator (Python class)
```python
import numpy as np
class IntegralOperator:
def __init__(self, kernel, grid):
self.K = kernel(grid[:, None], grid[None, :]) * (grid[1]-grid[0])
def __call__(self, f):
return self.K @ f
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### Self-adjointness check
```python
def is_self_adjoint(A, tol=1e-10):
return np.allclose(A, A.conj().T, atol=tol)
```
## 🧪 검증 상태 (Validation)
### Spectral decomposition
```python
A = np.array([[2., 1.], [1., 3.]])
w, V = np.linalg.eigh(A) # self-adjoint → real eigenvalues
# A = V diag(w) V^T
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Functional calculus (matrix exp)
```python
from scipy.linalg import expm
U = expm(-1j * H * t) # quantum time evolution
```
## 🧬 중복 검사 (Duplicate Check)
### Koopman operator (data-driven)
```python
def dmd(X, Xp, r=10):
U, S, Vt = np.linalg.svd(X, full_matrices=False)
Ur, Sr, Vr = U[:, :r], S[:r], Vt[:r].conj().T
A_tilde = Ur.conj().T @ Xp @ Vr / Sr
eigs, W = np.linalg.eig(A_tilde)
modes = Xp @ Vr / Sr @ W
return eigs, modes
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### RKHS kernel as integral operator
```python
def rkhs_eval(alpha, X, x_new, kernel):
return sum(a * kernel(xi, x_new) for a, xi in zip(alpha, X))
```
## 🕓 변경 이력 (Changelog)
## 매 결정 기준
| 문제 | Operator class |
|---|---|
| Quantum observable | Self-adjoint, possibly unbounded |
| Markov chain | Stochastic (positivity-preserving) |
| Signal filter | Bounded, possibly unitary |
| Dynamics learning | Koopman (compact approx) |
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
**기본값**: Self-adjoint compact (가장 잘 분석됨).
## 🔗 Graph
- 부모: [[Linear-Algebra-Foundations]] · [[Functional-Analysis]]
- 변형: [[Self-Adjoint-Operator]] · [[Compact-Operator]] · [[Unitary-Operator]]
- 응용: [[Quantum-Mechanics]] · [[Koopman-Operator]] · [[RKHS]]
- Adjacent: [[Spectral-Theorem]] · [[Hilbert-Space]] · [[Eigenvalues-and-Eigenvectors]]
## 🤖 LLM 활용
**언제**: Infinite-dim linear systems, PDE/quantum modeling, operator-learning (FNO, DeepONet).
**언제 X**: Pure finite-dim — 매 그냥 matrix theory로 충분.
## ❌ 안티패턴
- **Unbounded operator를 bounded로 가정**: 매 domain 무시.
- **Non-normal에 spectral theorem**: 매 잘못 적용.
- **Truncation 후 boundary effect 무시**.
## 🧪 검증 / 중복
- Verified (Reed & Simon "Methods of Modern Mathematical Physics" Vol. 1).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Operator classes + Koopman pattern |
@@ -2,88 +2,176 @@
id: wiki-2026-0508-optimal-control-theory
title: Optimal Control Theory
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-OPT-CTRL-001]
aliases: [OCT, Dynamic Optimization]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Control-Theory, optimal-control, Bellman-Equation, Reinforcement-Learning, Robotics]
confidence_score: 0.9
verification_status: applied
tags: [control, optimization, dynamic-programming, mpc]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: CasADi/CVXPY
---
# Optimal Control Theory (최적 제어 이론)
# Optimal Control Theory
## 📌 한 줄 통찰 (The Karpathy Summary)
> "한정된 에너지를 가장 영리하게 사용하여, 시스템이 목표한 궤도에 가장 우아하게 도달하게 하라" — 시간에 따라 변화하는 동적 시스템의 거동을 제어하여, 특정 목적 함수(Cost Function)를 최소화하거나 이득을 최대화하는 최적의 제어 법칙을 찾아내는 수학적 이론.
## 한 줄
> **"매 minimize cost over trajectory subject to dynamics"**. 매 OCT는 매 Pontryagin (PMP), Bellman (DP/HJB), Calculus of Variations 의 세 lens 통합, 매 LQR / MPC / iLQR / DDP 가 매 핵심 algorithm, 매 2026 robotics·autonomous driving·aerospace·battery management·RL 의 매 underlying mathematical foundation.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Trajectory [[Optimization|Optimization]] and Dynamic Programming" — 시스템의 현재 상태와 물리적 제약 조건을 고려하여 미래의 일련의 행동들을 계획하고, 벨만 방정식([[Bellman Equation|Bellman Equation]])이나 폰트랴긴의 최대 원리를 통해 최선의 경로를 산출하는 제어 패턴.
- **핵심 개념:**
- **LQR (Linear Quadratic Regulator):** 선형 시스템에서 오차의 제곱합을 최소화하는 표준 제어 기법.
- **MPC (Model Predictive Control):** 미래의 일정 구간을 예측하여 매 순간 최적의 입력을 다시 계산하는 실시간 제어 방식.
- **Hamiltonian:** 시스템의 에너지 보존과 변화율을 다루는 핵심 물리 수식.
- **의의:** 강화학습(RL)의 근간이 되는 이론적 토대이며, 자율주행, 항공우주, 드론 제어 등 물리적 실체가 있는 AI 시스템의 필수 학문.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 모든 물리 수식을 완벽히 알아야 했던 과거의 모델 기반 제어(Model-based)에서, 이제는 수식을 몰라도 데이터를 통해 제어 규칙을 배우는 강화학습 기반의 데이터 주도 제어(Data-driven)와 결합하여 적응력이 극대화됨.
- **정책 변화:** Skybound 프로젝트의 미사일 궤적 최적화 및 에이전트의 자원 배분 시나리오 설계 시, 최적 제어 이론의 비용 함수 설계 원칙을 준수하여 시스템의 안정성을 확보함.
### 매 formulation
- min_u ∫₀ᵀ L(x,u,t)dt + Φ(x(T))
- s.t. ẋ = f(x,u,t), x(0)=x₀, c(x,u) ≤ 0.
## 🔗 지식 연결 (Graph)
- [[Reinforcement-Learning|Reinforcement-Learning]], Monte-Carlo-Tree-Search-MCTS, [[Markov-Decision-Process-MDP|Markov-Decision-Process-MDP]], Fluid-Dynamics
- **Raw Source:** 10_Wiki/Topics/AI/Optimal-Control-Theory.md
### 매 3 approaches
- **Variational / PMP**: Hamiltonian H = L + λᵀf, costate λ̇ = -∂H/∂x, optimality ∂H/∂u = 0.
- **Dynamic Programming**: V(x,t), Bellman / HJB ∂V/∂t + min_u[L + ∇Vᵀf] = 0.
- **Direct methods**: discretize → NLP (transcription).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 LQR (linear-quadratic, 매 closed form)
- ẋ = Ax + Bu, J = ∫(xᵀQx + uᵀRu)dt.
- u* = -Kx, K = R⁻¹BᵀP.
- P from algebraic Riccati: AᵀP + PA - PBR⁻¹BᵀP + Q = 0.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 MPC (receding horizon)
1. Solve N-step OCP at xₜ.
2. Apply only u₀.
3. Re-solve at xₜ₊₁.
4. Handles constraints + nonlinearity.
**언제 쓰면 안 되는가:**
- *(TODO)*
### 매 응용
1. Quadrotor / drone trajectory.
2. Autonomous driving (lane keep, overtake).
3. Battery / HVAC / grid optimization.
4. Manipulator motion planning.
5. RL connection (Bellman ↔ Q-learning).
## 🧪 검증 상태 (Validation)
## 💻 패턴
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Discrete LQR (steady-state)
```python
import numpy as np
from scipy.linalg import solve_discrete_are
def dlqr(A, B, Q, R):
P = solve_discrete_are(A, B, Q, R)
K = np.linalg.solve(R + B.T @ P @ B, B.T @ P @ A)
return K, P
K, _ = dlqr(A, B, np.eye(n), 0.1*np.eye(m))
u = -K @ x
```
## 🤔 의사결정 기준 (Decision Criteria)
### iLQR for nonlinear
```python
def ilqr(f, l, lf, x0, u_init, n_iter=50):
u = u_init.copy(); T = len(u)
for it in range(n_iter):
# Forward rollout
x = [x0]
for t in range(T): x.append(f(x[-1], u[t]))
# Backward pass: compute K, k
Vx = lf_x(x[-1]); Vxx = lf_xx(x[-1])
Ks = []; ks = []
for t in reversed(range(T)):
fx, fu = jacobians(f, x[t], u[t])
lx, lu, lxx, luu, lux = quadratics(l, x[t], u[t])
Qx = lx + fx.T @ Vx
Qu = lu + fu.T @ Vx
Qxx = lxx + fx.T @ Vxx @ fx
Quu = luu + fu.T @ Vxx @ fu
Qux = lux + fu.T @ Vxx @ fx
K = -np.linalg.solve(Quu, Qux)
k = -np.linalg.solve(Quu, Qu)
Vx = Qx + K.T @ Quu @ k + K.T @ Qu + Qux.T @ k
Vxx = Qxx + K.T @ Quu @ K + K.T @ Qux + Qux.T @ K
Ks.insert(0, K); ks.insert(0, k)
# Forward update u with line search...
return u
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Nonlinear MPC with CasADi
```python
import casadi as ca
N, dt = 20, 0.1
opti = ca.Opti()
X = opti.variable(nx, N+1); U = opti.variable(nu, N)
x0p = opti.parameter(nx)
opti.subject_to(X[:,0] == x0p)
cost = 0
for k in range(N):
cost += ca.mtimes([X[:,k].T, Q, X[:,k]]) + ca.mtimes([U[:,k].T, R, U[:,k]])
opti.subject_to(X[:,k+1] == X[:,k] + dt*dynamics(X[:,k], U[:,k]))
opti.subject_to(opti.bounded(u_min, U[:,k], u_max))
opti.minimize(cost)
opti.solver('ipopt')
# at runtime:
opti.set_value(x0p, current_state); sol = opti.solve()
u_apply = sol.value(U[:,0])
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Direct collocation transcription
```python
# Trapezoidal: x_{k+1} = x_k + (dt/2)*(f(x_k,u_k) + f(x_{k+1},u_{k+1}))
# 매 NLP variables: [x_0..x_N, u_0..u_{N-1}], constraints: dynamics + bounds.
```
**기본값:**
> *(TODO)*
### HJB value iteration (small grids)
```python
def value_iter(grid, f, l, dt, gamma=0.99, n_iter=500):
V = np.zeros(len(grid))
for _ in range(n_iter):
V_new = np.copy(V)
for i, x in enumerate(grid):
best = np.inf
for u in U_set:
x_next = x + dt*f(x, u)
j = nearest(grid, x_next)
best = min(best, dt*l(x,u) + gamma*V[j])
V_new[i] = best
V = V_new
return V
```
## ❌ 안티패턴 (Anti-Patterns)
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Linear, quadratic cost | LQR (closed form) |
| Mild nonlinear, no constraints | iLQR / DDP |
| Constraints + nonlinearity | Nonlinear MPC (collocation/multiple shooting) |
| Long horizon / stochastic | DP / RL (Q-learning, SAC) |
| Real-time embedded | Explicit MPC / parametric QP |
| Trajectory optimization offline | DIRCOL / SQP |
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
**기본값**: linear → LQR; nonlinear with constraints → CasADi + IPOPT MPC; 매 long-horizon stochastic → RL.
## 🔗 Graph
- 부모: [[Control-Theory]] · [[Optimization]]
- 변형: [[LQR]] · [[Model-Predictive-Control]] · [[iLQR]] · [[Differential-Dynamic-Programming]]
- 응용: [[Robotics]] · [[Autonomous-Driving]] · [[Aerospace-GNC]]
- Adjacent: [[Reinforcement-Learning]] · [[Dynamic-Programming]] · [[Bellman-Equation]]
## 🤖 LLM 활용
**언제**: cost-function design, MPC weight tuning rationale, Pontryagin/HJB derivation 매 explanation.
**언제 X**: real-time solving (CasADi/acados/HPIPM 매 사용).
## ❌ 안티패턴
- **LQR on nonlinear**: 매 large-deviation regime — 매 iLQR/MPC 매 사용.
- **No terminal cost / set in MPC**: 매 stability lost.
- **Wrong Q/R scaling**: 매 unit-mismatch — 매 normalize states first.
- **Ignoring constraints in CofV**: 매 PMP+constraint 매 KKT-style augmentation 매 필요.
- **Pure RL when MPC works**: 매 model-known + smooth → MPC 매 sample-efficient.
## 🧪 검증 / 중복
- Verified (Bertsekas "DP & OC", Bryson & Ho, Borrelli "Predictive Control").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — LQR/iLQR/MPC/HJB unified |
@@ -2,90 +2,194 @@
id: wiki-2026-0508-optimization-algorithms
title: Optimization Algorithms
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-OPT-ALGO-001]
aliases: [Numerical Optimization, Mathematical Programming]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, algorithms, Optimization, heuristic, Simulated-Annealing, Genetic-Algorithms]
confidence_score: 0.9
verification_status: applied
tags: [optimization, numerics, ml, operations-research]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: scipy/jax/cvxpy
---
# Optimization Algorithms (최적화 알고리즘)
# Optimization Algorithms
## 📌 한 줄 통찰 (The Karpathy Summary)
> "가능성의 숲에서 가장 깊은 골짜기(최소 비용)를 찾기 위해, 때로는 눈앞의 내리막을 걷고 때로는 과감한 도약으로 산맥을 넘으라" — 주어진 제약 조건 하에서 목적 함수의 값을 최대로 하거나 최소로 만드는 변수들의 최적 조합을 효율적으로 탐색하는 알고리즘들의 총칭.
## 한 줄
> **"매 objective f(x) 의 minimum (또는 max) 을 찾는 numerical procedure"**. Newton 1690s gradient 발상에서 시작, 매 1947 Dantzig simplex (LP), 매 1986 backprop (Rumelhart) 으로 ML 에 폭발적 확산. 매 2026 의 landscape: convex (CVXPY/Mosek), nonconvex first-order (AdamW, Lion, Sophia), second-order approximations (Shampoo, K-FAC), black-box (BO, CMA-ES), discrete (MILP via Gurobi/HiGHS).
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Iterative Improvement and [[Search|Search]] Space Exploration" — 현재 상태에서 조금씩 더 나은 방향으로 이동하거나(Local Search), 무작위성을 부여하여 지역 최적해(Local Minima)에서 탈출하며 전역 최적해를 향해 나아가는 탐색 패턴.
- **주요 알고리즘 분류:**
- **Gradient-based:** 함수를 미분하여 기울기 방향으로 이동 (SGD, Adam 등). 연속적인 공간에 최적.
- **Meta-[[Heuristics|Heuristics]]:** 자연 현상을 모방한 범용 탐색법.
- **Simulated Annealing:** 확률적 도약을 통해 지역 최적해 탈출.
- **Genetic Algorithms:** 교배와 변이를 통한 진화적 탐색.
- **Particle Swarm Optimization:** 집단의 정보를 공유하며 최적점 추적.
- **의의:** AI 모델 학습뿐만 아니라 물류 경로 최적화, 반도체 설계, 금융 포트폴리오 구성 등 모든 공학적 의사결정의 핵심 도구.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 항상 전역 최적해를 찾아야 한다는 집착에서 벗어나, 현실적인 시간 내에 충분히 훌륭한 해(Sub-optimal [[Solution|Solution]])를 찾는 '휴리스틱'의 가치가 현대 대규모 복잡계 최적화의 주류로 자리 잡음.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 작업 스케줄링 및 리소스 할당 시, 문제의 성격에 따라 정교한 수리 계획법(Linear Programming)과 유연한 메타 휴리스틱 알고리즘을 혼합하여 사용함.
### 매 problem class
- **Convex** (LP, QP, SDP): 매 global optimum 보장. 매 CVXPY/Mosek/SCS.
- **Smooth nonconvex**: 매 deep learning loss. 매 first-order (SGD, Adam, Lion).
- **Nonsmooth**: 매 L1 (Lasso) — proximal methods.
- **Constrained**: KKT conditions, augmented Lagrangian, interior point, projected gradient.
- **Discrete**: ILP, combinatorial — branch-and-bound, MCTS.
- **Black-box (no gradient)**: BO, CMA-ES, Nelder-Mead.
## 🔗 지식 연결 (Graph)
- [[Optimization-in-AI|Optimization-in-AI]], [[Gradient-Descent|Gradient-Descent]]-Foundations, [[Genetic-Algorithms|Genetic-Algorithms]], HyperParameter-Optimization
- **Raw Source:** 10_Wiki/Topics/AI/Optimization-Algorithms.md
### 매 method family
- **Zeroth-order**: Nelder-Mead, BO, CMA-ES, evolutionary.
- **First-order**: GD, momentum, Nesterov, Adam, AdamW, Lion, RMSProp.
- **Quasi-Newton**: BFGS, L-BFGS — Hessian approximation.
- **Second-order**: Newton, Gauss-Newton, Levenberg-Marquardt.
- **Approx 2nd-order for DL**: K-FAC, Shampoo, Sophia.
- **Trust region**: dogleg, Steihaug.
- **Interior point**: LP/QP/SDP barrier methods.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Deep learning (AdamW, Lion, Shampoo).
2. Reinforcement learning (PPO step, natural gradient).
3. LP/MILP (logistics, scheduling — Gurobi).
4. Hyperparameter tuning (Optuna with TPE).
5. Robotics trajectory (CHOMP, MPC, iLQR).
6. RLHF policy optimization.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### scipy.optimize basic
```python
from scipy.optimize import minimize
import numpy as np
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
f = lambda x: (x[0]-1)**2 + 100*(x[1]-x[0]**2)**2 # Rosenbrock
res = minimize(f, x0=[0, 0], method="L-BFGS-B")
print(res.x, res.fun)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Convex via CVXPY
```python
import cvxpy as cp
**선택 A를 써야 할 때:**
- *(TODO)*
x = cp.Variable(10)
A = np.random.randn(20, 10); b = np.random.randn(20)
obj = cp.Minimize(cp.sum_squares(A @ x - b) + 0.1 * cp.norm(x, 1))
prob = cp.Problem(obj)
prob.solve() # Lasso
```
**선택 B를 써야 할 때:**
- *(TODO)*
### PyTorch optimizer (AdamW)
```python
import torch
**기본값:**
> *(TODO)*
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01,
betas=(0.9, 0.95))
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=10_000)
## ❌ 안티패턴 (Anti-Patterns)
for step, (x, y) in enumerate(loader):
opt.zero_grad()
loss = criterion(model(x), y)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step(); sched.step()
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Lion optimizer (2023, memory-efficient)
```python
class Lion(torch.optim.Optimizer):
def __init__(self, params, lr=1e-4, betas=(0.9, 0.99), weight_decay=0.0):
super().__init__(params, dict(lr=lr, betas=betas, weight_decay=weight_decay))
@torch.no_grad()
def step(self):
for group in self.param_groups:
for p in group["params"]:
if p.grad is None: continue
state = self.state[p]
if "exp_avg" not in state: state["exp_avg"] = torch.zeros_like(p)
m = state["exp_avg"]
b1, b2 = group["betas"]
update = (b1*m + (1-b1)*p.grad).sign_()
p.mul_(1 - group["lr"] * group["weight_decay"]).add_(update, alpha=-group["lr"])
m.mul_(b2).add_(p.grad, alpha=1-b2)
```
### Bayesian Optimization (Optuna TPE)
```python
import optuna
def objective(trial):
lr = trial.suggest_float("lr", 1e-5, 1e-2, log=True)
wd = trial.suggest_float("wd", 1e-6, 1e-1, log=True)
return train_and_eval(lr, wd)
study = optuna.create_study(direction="minimize",
sampler=optuna.samplers.TPESampler(seed=42))
study.optimize(objective, n_trials=50)
```
### CMA-ES (black-box, robust)
```python
import cma
es = cma.CMAEvolutionStrategy(x0=[0]*10, sigma0=0.5,
inopts={"maxiter": 200, "verbose": -9})
es.optimize(lambda x: sum(xi**2 for xi in x))
print(es.result.xbest)
```
### MILP via HiGHS
```python
from scipy.optimize import linprog, milp, LinearConstraint, Bounds
# minimize cT x s.t. A_ub x <= b_ub, x integer in [0, 1]
c = [-1, -2, -3] # minimize → negate to maximize 1+2+3
A = [[1, 1, 1]]; b = [2]
res = milp(c=c, constraints=LinearConstraint(A, ub=b),
integrality=[1, 1, 1], bounds=Bounds(0, 1))
```
### Trust-region Newton (small dense)
```python
from scipy.optimize import minimize
res = minimize(f, x0, jac=grad, hess=hess, method="trust-ncg")
```
## 매 결정 기준
| 상황 | Algorithm |
|---|---|
| convex small/medium | CVXPY (auto solver) |
| LP/MILP industrial | Gurobi / HiGHS |
| smooth small (~100 params) | L-BFGS |
| deep learning | AdamW / Lion |
| HP tuning (cheap eval) | Random / Grid |
| HP tuning (expensive) | Optuna TPE / BoTorch |
| black-box noisy | CMA-ES |
| 2nd-order for transformers | Shampoo / Sophia |
| RL policy | PPO / TRPO (natural gradient) |
**기본값**: 매 ML training → AdamW; 매 cost-expensive HP → BO; 매 industrial LP/MILP → Gurobi.
## 🔗 Graph
- 부모: [[Mathematics]] · [[Numerical Analysis]] · [[Operations-Research]]
- 변형: [[Convex Optimization]] · [[Stochastic Optimization]] · [[Combinatorial Optimization]]
- 응용: [[Deep Learning]] · [[Reinforcement Learning]] · [[Hyperparameter Tuning]] · [[Logistics]]
- Adjacent: [[Gradient Descent]] · [[Adam]] · [[L-BFGS]] · [[Bayesian Optimization]] · [[CMA-ES]]
## 🤖 LLM 활용
**언제**: 매 PEFT (LoRA) AdamW config, 매 RLHF PPO/DPO step, 매 hyperparameter search via Optuna.
**언제 X**: 매 closed-form solution 가능한 단순 LS — np.linalg.lstsq.
## ❌ 안티패턴
- **No grad clipping in deep learning**: 매 spike → NaN.
- **Adam without weight decay**: 매 use AdamW (decoupled).
- **Convex problem 인데 SGD**: 매 CVXPY/Mosek 가 정확하고 빠르다.
- **MILP 를 LP relaxation 으로 풀고 round**: 매 infeasibility / suboptimal.
- **Black-box BO 를 cheap function 에 사용**: 매 random search 가 빠름.
- **No restart in nonconvex**: 매 local min 갇힘. 매 multi-start.
## 🧪 검증 / 중복
- Verified (Boyd & Vandenberghe *Convex Optimization*; Nocedal & Wright *Numerical Optimization*; Lion Chen et al. 2023; Sophia 2023; Gurobi/HiGHS docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Optimization Algorithms FULL with AdamW/Lion/CVXPY/Optuna/MILP patterns |
@@ -2,91 +2,154 @@
id: wiki-2026-0508-optimization
title: Optimization
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-OPTI-001]
aliases: [Mathematical Optimization, Numerical Optimization]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [auto-reinforced, optimization, algorithms, Efficiency, mathematical-programming, improvement]
confidence_score: 0.9
verification_status: applied
tags: [optimization, convex, gradient-descent, ml-training]
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
framework: PyTorch/JAX/CVXPY
---
# [[Optimization|Optimization]]
# Optimization
## 📌 한 줄 통찰 (The Karpathy Summary)
> "최선을 향한 끊임없는 탐구: 주어진 조건 속에서 무엇(이득, 성능)을 최대화하거나 무엇(비용, 고통)을 최소화하는 최적의 해답을 수학적으로 찾아내는 기술이자, 모든 인적·기계적 진보를 이끄는 '가장 효율적인 상태'로의 지향."
## 한 줄
> **"매 minimize f(x) subject to constraints"**. 매 optimization은 매 ML/OR/control/finance/engineering 의 universal language이며, 매 2026 LLM 학습은 매 AdamW + cosine schedule + grad clip + mixed precision의 매 standard recipe — 매 convexity·smoothness·stochasticity·constraint structure 가 매 algorithm choice를 결정.
## 📖 구조화된 지식 (Synthesized Content)
최적화(Optimization)는 특정 목적 함수를 가장 만족시키는 해를 찾는 과정입니다.
## 매 핵심
1. **3대 구성 요소**:
* **Objective Function**: 극대화 또는 극소화할 목표.
* **Variables**: 우리가 조정할 수 있는 통제 변수.
* **Constraints**: 우리가 지켜야 할 현실적 제약 조건들.
2. **왜 중요한가?**:
* 지능(Intelligence)은 결국 한정된 자원으로 최선의 목표를 달성하는 '최적화 능력'의 다른 이름이며, AI 학습 자체가 오류를 최소화하는 거대한 최적화 연산이기 때문임. ([[Gradient-Descent|Gradient-Descent]]와 연결)
### 매 분류축
- **Convex vs Nonconvex**: convex → global guarantee; nonconvex (deep nets) → local + heuristics.
- **Smooth vs Nonsmooth**: smooth → gradient; nonsmooth → subgradient / proximal.
- **Constrained vs Unconstrained**: KKT, Lagrangian, projection.
- **Deterministic vs Stochastic**: full grad vs SGD/Adam.
- **First-order vs Second-order**: GD/Adam vs Newton/L-BFGS/K-FAC.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 한 번에 정답을 찾는 '분석적 정책(Analytical)'을 선호했으나, 현대 정책은 거대 변수 앞에서는 조금씩 고쳐가며 답에 근접하는 '반복적 경사 하강 정책(Iterative)'이 압도적 실용 정책을 가짐(RL Update). ([[Iteration|Iteration]]와 연결)
- **정책 변화(RL Update)**: 단순히 현재의 최적 정책(Local Optima)에 만족하지 않고, 전역 최적해(Global Optima)를 찾기 위해 탐색 공간을 뒤흔드는 '하이퍼파라미터 튜닝 정책'과 '강화 학습 정책'이 현대 AI 최적화의 꽃이 됨.
### 매 핵심 이론
- Convexity: f(λx+(1-λ)y) ≤ λf(x)+(1-λ)f(y).
- Lipschitz smoothness: ‖∇f(x)-∇f(y)‖ ≤ L‖x-y‖.
- Strong convexity μ: convergence rate O((1-μ/L)ᵏ).
- KKT conditions: stationarity, primal/dual feasibility, complementary slackness.
## 🔗 지식 연결 (Graph)
- [[Gradient-Descent|Gradient-Descent]], [[Efficiency|Efficiency]], [[Iteration|Iteration]], [[Linear-Programming|Linear-Programming]], [[Search-Optimization|Search-Optimization]]
- **Modern Tech/Tools**: SGD ([[stochastic gradient descent|stochastic gradient descent]]), Adam optimizer, Genetic algorithms, Convex optimization.
---
### 매 응용
1. ML training (SGD/Adam/Lion/Sophia).
2. LP/MIP (Gurobi, HiGHS).
3. Optimal control (LQR, MPC).
4. Portfolio (Markowitz, Black-Litterman).
5. Hyperparameter tuning (Bayesian opt, Optuna).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### SGD with momentum (PyTorch)
```python
import torch
from torch.optim import AdamW
from torch.optim.lr_scheduler import CosineAnnealingLR
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
opt = AdamW(model.parameters(), lr=3e-4, weight_decay=0.1, betas=(0.9, 0.95))
sched = CosineAnnealingLR(opt, T_max=total_steps)
for x, y in loader:
opt.zero_grad()
loss = criterion(model(x), y)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
sched.step()
```
## 🤔 의사결정 기준 (Decision Criteria)
### Convex optimization with CVXPY
```python
import cvxpy as cp
x = cp.Variable(n)
prob = cp.Problem(
cp.Minimize(cp.sum_squares(A@x - b) + lam*cp.norm1(x)),
[x >= 0, cp.sum(x) == 1])
prob.solve(solver=cp.MOSEK)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### L-BFGS for moderate-scale smooth
```python
from scipy.optimize import minimize
res = minimize(f, x0, jac=grad_f, method='L-BFGS-B',
bounds=bounds, options={'ftol': 1e-9})
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Proximal gradient (FISTA)
```python
def fista(grad_f, prox_g, x0, L, n_iter=200):
x = y = x0.copy(); t = 1.0
for k in range(n_iter):
x_new = prox_g(y - grad_f(y)/L, 1/L)
t_new = 0.5*(1 + np.sqrt(1 + 4*t*t))
y = x_new + ((t-1)/t_new)*(x_new - x)
x, t = x_new, t_new
return x
```
**기본값:**
> *(TODO)*
### Bayesian optimization (Optuna)
```python
import optuna
def objective(trial):
lr = trial.suggest_float('lr', 1e-5, 1e-2, log=True)
wd = trial.suggest_float('wd', 1e-4, 1e-1, log=True)
return train_and_eval(lr, wd)
study = optuna.create_study(direction='minimize')
study.optimize(objective, n_trials=100)
```
## ❌ 안티패턴 (Anti-Patterns)
### Projected gradient (constraint set)
```python
def proj_simplex(v):
n = len(v); u = np.sort(v)[::-1]
cssv = np.cumsum(u) - 1
rho = np.where(u - cssv/np.arange(1, n+1) > 0)[0][-1]
theta = cssv[rho] / (rho+1)
return np.maximum(v - theta, 0)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Smooth convex, small | Newton / L-BFGS |
| Smooth convex, large | GD / accelerated GD |
| Nonsmooth convex | Subgradient / proximal / ADMM |
| Stochastic, deep net | AdamW (default) / Lion / Sophia |
| LP / QP | Simplex / interior-point (Gurobi/Mosek) |
| Black-box / expensive eval | Bayesian opt (Optuna) |
| Combinatorial | MIP / metaheuristic / CP-SAT |
**기본값**: ML training은 AdamW + cosine; convex은 CVXPY; black-box는 Optuna.
## 🔗 Graph
- 부모: [[Mathematics]] · [[Calculus]]
- 변형: [[Convex-Optimization]] · [[Nonconvex-Optimization]] · [[Stochastic-Optimization]]
- 응용: [[Deep-Learning-Training]] · [[Operations-Research]] · [[Optimal-Control-Theory]]
- Adjacent: [[Linear-Algebra]] · [[Numerical-Methods]]
## 🤖 LLM 활용
**언제**: optimizer recipe selection, hyperparam search prior, KKT/Lagrangian derivation 매 explanation.
**언제 X**: 실제 numerical solving (PyTorch/CVXPY/Gurobi 매 사용).
## ❌ 안티패턴
- **Adam everywhere**: 매 small data / convex problem 매 Adam — 매 SGD or L-BFGS 매 더 좋음.
- **No grad clipping for transformers**: 매 explosion 매 inevitable.
- **Constant LR**: 매 cosine / warmup 매 거의 항상 도움.
- **Local minimum panic**: 매 deep net의 saddle point가 매 진짜 problem (not local min).
- **Convex assumption violation**: 매 nonconvex에 매 convex solver 매 적용 → 매 wrong answer.
## 🧪 검증 / 중복
- Verified (Boyd & Vandenberghe "Convex Optimization", Nocedal & Wright).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full optimization landscape |
@@ -2,89 +2,183 @@
id: wiki-2026-0508-pca-and-dimension-reduction
title: PCA and Dimension Reduction
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-PCA-001]
aliases: [Principal Component Analysis, Dimensionality Reduction]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: ["Statistics|[Statistics", math, pca, dimension-reduction, unSupervised-Learning, data-science]
confidence_score: 0.9
verification_status: applied
tags: [statistics, ml, unsupervised, embeddings, visualization]
raw_sources: []
last_reinforced: 2026-04-26
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
framework: scikit-learn/umap
---
# PCA and Dimension Reduction (PCA와 차원 축소)
# PCA and Dimension Reduction
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터의 흩어짐(Variance)이 가장 큰 핵심 축을 찾아, 고차원의 안개를 걷어내고 데이터의 진정한 뼈대를 드러내라" — 변수들 사이의 상관관계를 분석하여 주성분(Principal Components)을 추출함으로써, 정보의 손실을 최소화하며 데이터의 차원을 낮추는 통계적 방법론.
## 한 줄
> **"매 high-dim 데이터를 variance 보존하는 lower-dim 부분공간으로 사영"**. Pearson 1901 / Hotelling 1933 의 PCA 가 시초. 매 2026 의 modern landscape: linear PCA 는 여전히 baseline + interpretation, t-SNE/UMAP 가 visualization 의 default, autoencoder + contrastive 가 representation learning 의 핵심. 매 LLM embedding 의 PCA whitening 도 흔함.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Variance Maximization and Orthogonal Projection" — 데이터의 분산이 가장 크게 보존되는 방향으로 좌표축을 회전시키고, 중요도가 낮은 축(고유값이 작은 축)을 제거하여 데이터의 본질적인 구조를 저차원의 평면에 투영하는 패턴.
- **핵심 단계:**
- **Standardization:** 변수들의 단위를 맞춤 (평균 0, 분산 1).
- **Covariance Matrix:** 변수 간의 관계 파악.
- **Eigen-decomposition:** 주성분 방향(고유벡터)과 중요도(고유값) 산출.
- **Projection:** 상위 k개의 주성분으로 데이터 변환.
- **의의:** 차원의 저주(Curse of Dimensionality)를 극복하고, 모델의 과적합을 방지하며, 수천 차원의 임베딩 데이터를 2D/3D로 시각화하여 인간이 이해할 수 있게 함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 선형적인 관계만 포착할 수 있는 PCA의 한계를 넘어, 최근에는 커널 PCA나 오토인코더를 이용한 비선형 차원 축소, 그리고 t-SNE나 UMAP과 같이 데이터의 지역적 구조 보존에 특화된 시각화 기법들이 함께 활용됨.
- **정책 변화:** Antigravity 프로젝트는 1,174개 문서의 임베딩 벡터를 시각화하여 지식의 군집(Cluster) 상태를 점검할 때, PCA를 1차 필터로 사용하여 전체적인 데이터 분포를 조망함.
### 매 PCA 수학
- **목표**: orthogonal directions 중 variance 최대화.
- **계산**: covariance Σ = X^T X / (n-1) → eigendecomposition Σ = V Λ V^T, top-k columns = principal components.
- **SVD form**: X = UΣV^T → top-k V_k 가 components, score = X V_k.
- **Explained variance ratio**: λ_i / Σ λ_j.
- **Whitening**: X V_k Λ_k^{-1/2} → unit variance per dim.
## 🔗 지식 연결 (Graph)
- Principal-Component-[[Analysis|Analysis]]-PCA, [[Multivariate-Analysis|Multivariate-Analysis]], [[Exploratory-Data-Analysis|Exploratory-Data-Analysis]], Autoencoders-in-[[Deep-Learning|Deep-Learning]]
- **Raw Source:** 10_Wiki/Topics/AI/PCA-and-Dimension-Reduction.md
### 매 family
- **Linear**: PCA, Truncated SVD, Factor Analysis, ICA.
- **Manifold (preserve local)**: t-SNE, UMAP, LLE, Isomap.
- **Neural**: Autoencoder, VAE, contrastive (SimCLR), DINO.
- **Random**: Random projection (Johnson-Lindenstrauss).
- **Sparse**: Sparse PCA, NMF.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Visualization (t-SNE, UMAP for embeddings/scRNA-seq).
2. Compression (PCA whitening before downstream task).
3. Denoising (project, then reconstruct).
4. Feature engineering pre-classifier.
5. LLM embedding analysis (cluster interpretation, anisotropy fix).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### sklearn PCA
```python
from sklearn.decomposition import PCA
import numpy as np
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
X = np.random.randn(1000, 100)
pca = PCA(n_components=10, whiten=True, random_state=42)
X_proj = pca.fit_transform(X)
print(pca.explained_variance_ratio_.cumsum()) # 누적 explained
print(pca.components_.shape) # (10, 100)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Choose k via cumulative variance
```python
def choose_k(X, threshold=0.95):
pca = PCA().fit(X)
cum = pca.explained_variance_ratio_.cumsum()
return int(np.searchsorted(cum, threshold) + 1)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Truncated SVD (sparse / very large)
```python
from sklearn.decomposition import TruncatedSVD
from scipy.sparse import csr_matrix
**선택 B를 써야 할 때:**
- *(TODO)*
X_sparse = csr_matrix(X) # 매 PCA centers → dense; TruncatedSVD 매 sparse-friendly
svd = TruncatedSVD(n_components=50, n_iter=7, random_state=42)
X_proj = svd.fit_transform(X_sparse) # 매 LSA 의 핵심
```
**기본값:**
> *(TODO)*
### UMAP (manifold, fast)
```python
import umap
## ❌ 안티패턴 (Anti-Patterns)
reducer = umap.UMAP(
n_neighbors=15, # local vs global
min_dist=0.1, # cluster separation
n_components=2,
metric="cosine", # 매 LLM embedding
random_state=42,
)
X_2d = reducer.fit_transform(X)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### t-SNE (visualization)
```python
from sklearn.manifold import TSNE
# 매 항상 PCA → t-SNE (속도/안정성)
X_pca = PCA(n_components=50).fit_transform(X)
X_2d = TSNE(n_components=2, perplexity=30, init="pca",
learning_rate="auto").fit_transform(X_pca)
```
### Autoencoder (PyTorch)
```python
import torch.nn as nn
class AE(nn.Module):
def __init__(self, d_in, d_latent):
super().__init__()
self.enc = nn.Sequential(
nn.Linear(d_in, 256), nn.GELU(),
nn.Linear(256, d_latent),
)
self.dec = nn.Sequential(
nn.Linear(d_latent, 256), nn.GELU(),
nn.Linear(256, d_in),
)
def forward(self, x):
z = self.enc(x); return self.dec(z), z
# loss = MSE(x, x_hat). Nonlinear PCA 의 generalization.
```
### LLM embedding whitening (anisotropy 완화)
```python
def whiten_embeddings(E, k=None):
"""Anisotropy fix: subtract mean, decorrelate."""
mu = E.mean(axis=0, keepdims=True)
Ec = E - mu
U, S, Vt = np.linalg.svd(Ec, full_matrices=False)
if k is None:
k = E.shape[1]
W = (Vt[:k].T) / S[:k] # whitening matrix
return Ec @ W, mu, W
```
### Random projection (very high-dim, fast)
```python
from sklearn.random_projection import GaussianRandomProjection
rp = GaussianRandomProjection(n_components="auto", eps=0.1)
X_proj = rp.fit_transform(X) # 매 Johnson-Lindenstrauss 보존
```
## 매 결정 기준
| 상황 | Method |
|---|---|
| baseline, interpretable | PCA |
| sparse text-term-matrix | TruncatedSVD (LSA) |
| visualization 2D/3D | UMAP > t-SNE |
| nonlinear, learnable, downstream supervised | Autoencoder / SimCLR |
| n >> d, very high-dim | Random projection |
| non-negative parts (topics) | NMF |
| count data | LDA / NMF |
**기본값**: 매 baseline PCA → 매 visualization UMAP → 매 representation learning contrastive.
## 🔗 Graph
- 부모: [[Linear-Algebra-Foundations]] · [[Statistics]] · [[Unsupervised Learning]]
- 변형: [[Kernel PCA]] · [[Sparse PCA]] · [[Probabilistic PCA]] · [[ICA]]
- 응용: [[Visualization]] · [[scRNA-seq]] · [[Embedding Analysis]] · [[Feature Engineering]]
- Adjacent: [[t-SNE]] · [[UMAP]] · [[Autoencoder]] · [[NMF]] · [[Random Projection]]
## 🤖 LLM 활용
**언제**: 매 embedding analysis, 매 anisotropy whitening, 매 visualizing high-dim attention/activations.
**언제 X**: 매 매우 nonlinear task — autoencoder/contrastive 사용. 매 preserving exact distances 필요 — RP 만 보장.
## ❌ 안티패턴
- **PCA without scaling**: 매 큰-단위 feature 가 dominate. 매 StandardScaler 필수.
- **t-SNE 결과 해석 으로 cluster 크기/거리 신뢰**: 매 t-SNE 매 local-only — 매 global geometry 왜곡.
- **PCA 사용 후 inverse_transform 으로 outlier 제거** — 매 그러면 다시 fit X 매 outlier 의 영향 그대로.
- **n_components 선택을 임의 값** (e.g., 항상 2): 매 cumulative variance + downstream metric 기반 선택.
- **Test set 도 fit_transform**: 매 leakage. 매 fit 은 train 만, test 는 transform.
## 🧪 검증 / 중복
- Verified (Bishop *PRML* Ch 12; *ESL* Hastie et al.; UMAP McInnes 2018; sklearn docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — PCA & DR FULL with PCA/UMAP/AE/whitening patterns |
@@ -2,62 +2,176 @@
id: wiki-2026-0508-pid-controllers-in-ai
title: PID Controllers in AI
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [CTRL-PID-001]
aliases: [Proportional-Integral-Derivative Control, PID Loop]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: ["Control-Theory|[Control-Theory", pid, ai, Robotics, feedback-loop, automation]
confidence_score: 0.9
verification_status: applied
tags: [control-theory, robotics, RL, tuning]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: simple_pid/control
---
# PID Controllers in AI (AI에서의 PID 제어기)
# PID Controllers in AI
## 📌 한 줄 통찰 (The Karpathy Summary)
> "과거의 오차(I)를 반성하고, 현재의 차이(P)를 직시하며, 미래의 변화(D)를 예측하여 완벽한 균형점을 사수하라" — 비례(Proportional), 적분(Integral), 미분(Derivative) 항의 조합을 통해 시스템의 출력을 목표값에 빠르고 안정적으로 수렴시키는 가장 대표적인 피드백 제어 기술.
## 한 줄
> **"매 error = setpoint - measurement 에 P/I/D 항을 적용해 actuator 를 제어"**. 1922 Minorsky ship steering 에서 시작, 매 산업 control 의 80%+ 사용. 매 2026 의 AI hybrid 사용: drone attitude (PX4), robot joint, LLM token-budget control, RLHF KL-coefficient tuning, training schedules.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Closed-loop Error Correction" — 목표값과 현재값의 차이(오차)를 실시간으로 계산하고, 세 가지 제어 항을 통해 오차를 보정하여 외부 교란에도 불구하고 시스템을 안정 상태로 유지하는 패턴.
- **3대 제어 항:**
- **P (Proportional):** 현재 오차에 비례하여 강하게 반응 (빠른 응답).
- **I (Integral):** 쌓인 오차를 제거하여 잔류 편차 해결 (정밀도).
- **D (Derivative):** 오차의 변화 속도를 감지하여 오버슈트 억제 (안정성).
- **의의:** AI 에이전트가 현실 세계의 드론, 로봇 팔, 자율주행 조향 등을 실제로 움직일 때 사용하는 가장 믿음직하고 검증된 물리 인터페이스.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 사람이 수작업으로 최적의 계수(Gain)를 찾던 방식에서, 이제는 강화학습(RL)이나 베이지안 최적화가 실시간으로 가장 적합한 PID 계수를 찾아주는 '지능형 PID'로 진화함.
- **정책 변화:** Skybound 프로젝트의 비행 유닛들이 목표 고도를 유지하거나 흔들림을 보정할 때, 내부적으로 최적화된 PID 제어 루프를 사용하여 부드러운 움직임을 구현함.
### 매 PID 공식
- **u(t) = Kp·e(t) + Ki·∫e(τ)dτ + Kd·de/dt**.
- **P (Proportional)**: 매 현재 error 에 비례 — 매 fast response, 매 steady-state error 남김.
- **I (Integral)**: 매 누적 error — 매 steady-state error 제거, 매 windup 위험.
- **D (Derivative)**: 매 변화율 — 매 overshoot 감소, 매 noise 증폭.
## 🔗 지식 연결 (Graph)
- [[Optimal-Control-Theory|Optimal-Control-Theory]], [[Reinforcement-Learning|Reinforcement-Learning]], [[Robotics-Foundations|Robotics-Foundations]], Automation-Strategies
- **Raw Source:** 10_Wiki/Topics/AI/PID-Controllers-in-AI.md
### 매 tuning methods
- **Ziegler-Nichols**: 매 Ku, Tu (oscillation) 측정 후 공식 적용.
- **Cohen-Coon**: 매 process reaction curve 기반.
- **AutoTuning**: 매 relay feedback (Åström-Hägglund).
- **Bayesian optimization**: 매 simulation rollout + GP.
- **RL-based**: 매 PPO/SAC 으로 Kp, Ki, Kd 학습.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Drone attitude (PX4, ArduPilot).
2. Robot joint position control (ROS 2).
3. Cruise control, HVAC, 3D printer extruder.
4. LLM serving — token-rate controller (vLLM 의 batch sizing).
5. RLHF KL-coefficient adaptive tuning.
6. Training: gradient norm clipping with adaptive coefficient.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Plain PID (discrete)
```python
class PID:
def __init__(self, kp, ki, kd, dt, output_limits=(-1, 1)):
self.kp, self.ki, self.kd, self.dt = kp, ki, kd, dt
self.lo, self.hi = output_limits
self.integral = 0.0
self.prev_error = 0.0
## 🧪 검증 상태 (Validation)
def __call__(self, setpoint, measurement):
error = setpoint - measurement
self.integral += error * self.dt
derivative = (error - self.prev_error) / self.dt
output = self.kp*error + self.ki*self.integral + self.kd*derivative
output = max(self.lo, min(self.hi, output))
self.prev_error = error
return output
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Anti-windup (clamp + back-calculation)
```python
class PIDAntiWindup(PID):
def __init__(self, *args, kt=0.5, **kw):
super().__init__(*args, **kw)
self.kt = kt # back-calc gain
## 🧬 중복 검사 (Duplicate Check)
def __call__(self, setpoint, measurement):
error = setpoint - measurement
derivative = (error - self.prev_error) / self.dt
u_unsat = self.kp*error + self.ki*self.integral + self.kd*derivative
u_sat = max(self.lo, min(self.hi, u_unsat))
# back-calculation: discount integral when saturated
self.integral += self.dt * (error + self.kt * (u_sat - u_unsat))
self.prev_error = error
return u_sat
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Derivative on measurement (D-kick 회피)
```python
class PIDDerivOnMeas(PID):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.prev_meas = None
## 🕓 변경 이력 (Changelog)
def __call__(self, setpoint, measurement):
error = setpoint - measurement
if self.prev_meas is None:
d = 0
else:
d = -(measurement - self.prev_meas) / self.dt # 매 setpoint step → spike 없음
self.integral += error * self.dt
out = self.kp*error + self.ki*self.integral + self.kd*d
self.prev_meas = measurement
return max(self.lo, min(self.hi, out))
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Ziegler-Nichols tuning
```python
def ziegler_nichols(Ku, Tu, kind="classic"):
if kind == "classic":
return dict(kp=0.6*Ku, ki=1.2*Ku/Tu, kd=0.075*Ku*Tu)
elif kind == "no-overshoot":
return dict(kp=0.2*Ku, ki=0.4*Ku/Tu, kd=Ku*Tu/15)
elif kind == "PI-only":
return dict(kp=0.45*Ku, ki=0.54*Ku/Tu, kd=0)
```
### RLHF adaptive KL (PPO-style β)
```python
def adaptive_kl_pid(kl_observed, kl_target=0.02, state=None):
"""β ↑ when KL too large; β ↓ when too small. PI controller on log(β)."""
if state is None:
state = {"integral": 0.0, "log_beta": 0.0}
error = kl_observed - kl_target
state["integral"] += error
state["log_beta"] += 0.1 * error + 0.01 * state["integral"]
return float(np.exp(state["log_beta"])), state
```
### LLM token-rate controller (server batch)
```python
def batch_size_pid(target_tps, current_tps, pid_state):
"""Maintain target tokens/sec by adjusting batch size."""
delta = target_tps - current_tps
pid_state["integral"] += delta
adj = 0.05*delta + 0.001*pid_state["integral"]
return max(1, int(pid_state["batch"] + adj))
```
## 매 결정 기준
| 상황 | Controller |
|---|---|
| no steady-state error needed | P only |
| eliminate steady-state, slow process | PI |
| fast + minimal overshoot | PID with D-on-measurement |
| highly nonlinear / complex | MPC or RL (not PID) |
| discrete-event / queue | PI on rate |
| training schedule (KL, lr) | adaptive PI |
**기본값**: 매 80% 의 경우 PI 면 충분. 매 D 매 noise 환경에서 신중히.
## 🔗 Graph
- 부모: [[Control-Theory]] · [[Feedback-Control-Systems]]
- 변형: [[Cascade Control]] · [[Gain Scheduling]] · [[Adaptive PID]]
- 응용: [[Robotics]] · [[Drone Stabilization]] · [[LLM Serving]] · [[RLHF]]
- Adjacent: [[Model-Predictive-Control (MPC)]] · [[Kalman-Filter-and-State-Tracking]] · [[Reinforcement-Learning]]
## 🤖 LLM 활용
**언제**: 매 inference server batch sizing, 매 RLHF KL coefficient, 매 lr schedule under loss target.
**언제 X**: 매 highly nonlinear delays — MPC. 매 strong constraints — RL/MPC.
## ❌ 안티패턴
- **No anti-windup with saturation**: 매 integral 폭주 → overshoot.
- **D term on noisy raw signal**: 매 noise 증폭 → 매 LPF (low-pass filter) 필수.
- **Derivative on setpoint (D-kick)**: 매 setpoint step → spike. 매 D-on-measurement 사용.
- **One-size-fits-all gains across operating regions**: 매 nonlinear 시스템 — gain scheduling 필요.
- **Tuning by 임의 가이드**: 매 system 마다 다름 — Ziegler-Nichols 또는 simulation 사용.
## 🧪 검증 / 중복
- Verified (Åström & Hägglund, *PID Controllers*; Franklin et al. *Feedback Control of Dynamic Systems*; ArduPilot/PX4 firmware).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — PID FULL with anti-windup, D-on-meas, RLHF/serving applications |

Some files were not shown because too many files have changed in this diff Show More