[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
+155 -91
View File
@@ -2,116 +2,180 @@
id: wiki-2026-0508-graph-theory
title: Graph Theory
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [그래프 이론, Graphs]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-consolidated, technical-documentation]
confidence_score: 0.9
verification_status: applied
tags: [algorithms, graphs, cs]
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: python
framework: networkx
---
# [[Graph Theory|Graph Theory]]
# Graph Theory
## 📌 한 줄 통찰 (The Karpathy Summary)
> "관계의 수학적 지도: 개별 존재(Node)와 그들 사이의 연결(Edge)만을 추출하여 세상의 복잡한 네트워크 구조를 추상화하고, 그 안에서 경로를 찾거나 핵심 요소를 식별하며 구조적 특성을 분석하는 현대 문명의 연결학."
## 한 줄
> **"매 vertex + edge 의 abstraction 으로 매 거의 모든 관계를 model"**. 매 Euler (1736 Königsberg) 부터 매 modern Graph Neural Network (2026 GraphSAGE, GAT, Graph Transformer) 까지 — 매 search engine PageRank, social network, dependency graph, GNN, knowledge graph 의 foundation.
---
## 매 핵심
> "세상의 모든 존재를 점(Node)으로, 그들의 관계를 선(Edge)으로 연결하여 복잡계의 지도를 그려라" — 개체들 간의 상호작용과 연결 구조를 수학적으로 모델링하여, 네트워크의 특성과 정보의 흐름을 분석하는 학문적 토대.
### 매 representations
- **Adjacency matrix**: O(V²) space, O(1) edge query — 매 dense graph.
- **Adjacency list**: O(V+E) space — 매 sparse 일반.
- **Edge list**: 매 streaming / disk-based.
- **CSR (Compressed Sparse Row)**: 매 cache-friendly, GNN framework 의 표준.
## 📖 구조화된 지식 (Synthesized Content)
그래프 이론(Graph Theory)은 점(Vertex)과 선(Edge)으로 이루어진 수학적 구조인 그래프를 연구하는 학문입니다. (오일러의 '쾨니히스베르크 다리 문제'에서 기원)
### 매 핵심 algorithm
- **BFS** O(V+E) — 매 unweighted shortest path, level order.
- **DFS** O(V+E) — 매 cycle detection, topo sort, SCC.
- **Dijkstra** O((V+E) log V) — 매 non-negative weighted shortest path.
- **Bellman-Ford** O(VE) — 매 negative weight allowed.
- **Floyd-Warshall** O(V³) — 매 all-pairs.
- **Union-Find** ~ O(α(V)) — 매 connectivity, Kruskal MST.
- **Topological sort** — 매 DAG ordering.
- **PageRank** — 매 power iteration on stochastic matrix.
1. **핵심 지표**:
* **Degree**: 한 노드에 연결된 선의 개수.
* **Centrality**: 시스템 내에서 특정 노드가 얼마나 중요한지(영향력)를 측정.
* **Cycle**: 경로가 다시 시작점으로 돌아오는 순환 구조.
2. **왜 중요한가?**:
* SNS 친구 관계, 인터넷 도메인 연결, 전력망 아키텍처, 지식 베이스의 상호 참조 등 현대 사회의 모든 연결 구조를 이해하는 기초임. (이 Wiki의 Graph View와 연결)
### 매 응용
1. Routing / map — 매 OSRM, Valhalla, Google Maps.
2. Dependency resolution — npm, cargo, Bazel.
3. GNN — 매 fraud detection, drug discovery, recommendation (Pinterest PinSage).
4. Knowledge graph — 매 RAG / LLM grounding.
---
## 💻 패턴
- **추출된 패턴:** 개별 요소의 특성보다 요소들 사이의 '연결 방식(Connectivity)'이 시스템 전체의 성격(중요도, 전파 속도, 강건성 등)을 결정한다는 관계 중심의 분석 패턴.
- **핵심 개념:**
- **Nodes & Edges:** 데이터를 나타내는 정점과 관계를 나타내는 간선.
- **Degree:** 특정 노드에 연결된 간선의 수 (중요도 지표).
- **Shortest Path:** 두 노드 사이의 최단 거리 (효율성 지표).
- **Centrality:** 네트워크 내에서 특정 노드가 차지하는 영향력 (PageRank 등).
- **Clustering:** 노드들이 얼마나 밀집하여 그룹을 형성하는지 측정.
- **의의:** 소셜 네트워크 분석, 전력망 설계, 신약 개발은 물론, 현대 AI의 지식 그래프(Knowledge Graph)와 GNN의 핵심 이론적 근거.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 정적인 연결 구조 분석 정책에 머물렀으나, 현대 정책은 실시간으로 노드가 추가되고 연결이 변하는 '동적 그래프 정책'과 그래프 상에서 학습하는 'GNN(Graph Neural Networks) 정책'으로 진화함(RL Update).
- **정책 변화(RL Update)**: 단순 텍스트 학습을 넘어, 방대한 지식 그래프 정책을 결합하여 AI의 답변 정확도를 높이는 '지식 그래프 융합 AI 정책'이 차세대 지능의 핵심이 됨. (RAG와 연결)
---
- **과거 데이터와의 충돌:** 정적인 관계망 분석에서 벗어나, 시간에 따라 노드와 엣지가 생성/소멸하는 동적 네트워크(Dynamic Networks) 분석으로 진화.
- **정책 변화:** Antigravity 프로젝트는 1,174개의 지식 문서 간의 상관관계를 그래프 이론적 관점에서 상시 분석하며, 지식의 고립(Island)을 방지하고 핵심 연결 노드를 자동으로 추천함.
## 🔗 지식 연결 (Graph)
- [[Distributed-Systems|Distributed-Systems]], [[Analysis|Analysis]], [[Complexity Theory|Complexity Theory]], [[Technical-Architecture|Technical-Architecture]], [[Internet of Things (IoT)|Internet of Things (IoT)]]
- **Modern Tech/Tools**: Neo4j, NetworkX, Gephi, GraphQL, DGL (Graph Deep Learning).
---
---
- [[GNN|GNN]], [[Geometric-Deep-Learning|Geometric-Deep-Learning]], [[Knowledge-Graph-Foundations|Knowledge-Graph-Foundations]], [[Search|Search]]-Algorithms
- **Raw Source:** 10_Wiki/Topics/AI/Graph-Theory.md
## 🤖 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
### Adjacency list (Python)
```python
from collections import defaultdict
g: dict[int, list[int]] = defaultdict(list)
for u, v in edges:
g[u].append(v); g[v].append(u)
```
## 🤔 의사결정 기준 (Decision Criteria)
### BFS shortest path
```python
from collections import deque
def bfs(g, s, t):
q = deque([(s, 0)]); seen = {s}
while q:
u, d = q.popleft()
if u == t: return d
for v in g[u]:
if v not in seen: seen.add(v); q.append((v, d+1))
return -1
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Dijkstra (heap)
```python
import heapq
def dijkstra(g, s):
dist = {s: 0}; pq = [(0, s)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]: continue
for v, w in g[u]:
nd = d + w
if nd < dist.get(v, float("inf")):
dist[v] = nd; heapq.heappush(pq, (nd, v))
return dist
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Topological sort (Kahn)
```python
from collections import deque
def topo(n, edges):
g = [[] for _ in range(n)]; indeg = [0]*n
for u, v in edges: g[u].append(v); indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0); out = []
while q:
u = q.popleft(); out.append(u)
for v in g[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
return out if len(out) == n else None # cycle
```
**기본값:**
> *(TODO)*
### Union-Find (path compression + rank)
```python
class DSU:
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)
### NetworkX (Python prototyping)
```python
import networkx as nx
G = nx.DiGraph(); G.add_weighted_edges_from([("a","b",1), ("b","c",2)])
print(nx.shortest_path(G, "a", "c", weight="weight"))
print(nx.pagerank(G, alpha=0.85))
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### GNN (PyTorch Geometric)
```python
import torch
from torch_geometric.nn import GCNConv
class GCN(torch.nn.Module):
def __init__(self, d_in, d_h, d_out):
super().__init__()
self.c1 = GCNConv(d_in, d_h); self.c2 = GCNConv(d_h, d_out)
def forward(self, x, edge_index):
x = self.c1(x, edge_index).relu()
return self.c2(x, edge_index)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Unweighted shortest | BFS |
| Non-negative weighted | Dijkstra |
| Negative weight | Bellman-Ford / Johnson |
| All-pairs, dense, V<500 | Floyd-Warshall |
| MST | Kruskal (DSU) / Prim (heap) |
| DAG scheduling | Topological sort |
| Cycle / SCC | DFS + Tarjan / Kosaraju |
| Massive web graph | Pregel-style (GraphX, Giraph) |
| Learning on graph | GNN (PyG, DGL) |
**기본값**: prototype 은 NetworkX, production 은 graph-tool / igraph / 직접 CSR.
## 🔗 Graph
- 부모: [[Algorithms]] · [[Discrete Mathematics]]
- 변형: [[Directed Graph]] · [[Weighted Graph]] · [[Bipartite Graph]] · [[DAG]]
- 응용: [[Shortest Path]] · [[MST]] · [[PageRank]] · [[GNN]] · [[Knowledge Graph]]
- Adjacent: [[Trees]] · [[Network Flow]] · [[Matching]] · [[Graph Coloring]]
## 🤖 LLM 활용
**언제**: 매 problem 을 graph 로 model 가능한지 reasoning, 매 algorithm 선택.
**언제 X**: 매 V, E 가 매우 작은 brute-force 충분 case — 매 over-engineering.
## ❌ 안티패턴
- **Adjacency matrix on sparse**: 매 V=10⁶ 에 V² 메모리 폭발.
- **Recursive DFS on deep graph (Python)**: 매 stack overflow — iterative.
- **Dijkstra with negative edges**: 매 wrong answer — Bellman-Ford.
- **Re-running BFS from each node for diameter**: 매 BFS×V — multi-source / approx 사용.
- **Forgetting visited set**: 매 BFS/DFS 무한 loop.
## 🧪 검증 / 중복
- Verified (CLRS *Introduction to Algorithms* 4th ed., Sedgewick *Algorithms* 4ed, NetworkX docs, PyG 2.5).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — graph algorithms + GNN 응용 정리 |