Delete emergence_engine.py
Browse files- emergence_engine.py +0 -1081
emergence_engine.py
DELETED
|
@@ -1,1081 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
emergence_engine.py — MAIA 창발성 발현 엔진 v1.0
|
| 3 |
-
특허 제7호: 다차원 가능성 공간 탐색 및 창발적 조합 생성 엔진
|
| 4 |
-
|
| 5 |
-
[독립항 1] 5단계 창발적 조합 생성 방법:
|
| 6 |
-
(a) 브루트포스 전수 탐색 + 스코어링
|
| 7 |
-
(b) 볼츠만 분포 기반 확률적 샘플링 (온도 파라미터 T)
|
| 8 |
-
(c) 지식그래프 연결 탐색 (미발견 경로)
|
| 9 |
-
(d) 교차 융합 보너스 매트릭스
|
| 10 |
-
(e) 창발성 임계점 판정
|
| 11 |
-
|
| 12 |
-
[종속항 3] 엔트로피 기반 다양성 보장
|
| 13 |
-
[종속항 4] 다중 도메인 적용
|
| 14 |
-
|
| 15 |
-
(주) 비드래프트 / AETHER Proto-AGI
|
| 16 |
-
"""
|
| 17 |
-
|
| 18 |
-
import math
|
| 19 |
-
import logging
|
| 20 |
-
import hashlib
|
| 21 |
-
import time
|
| 22 |
-
from typing import List, Dict, Any, Tuple, Optional, Set
|
| 23 |
-
from dataclasses import dataclass, field
|
| 24 |
-
from itertools import combinations, product
|
| 25 |
-
from collections import Counter, defaultdict
|
| 26 |
-
|
| 27 |
-
import numpy as np
|
| 28 |
-
|
| 29 |
-
# ── 상수 ──
|
| 30 |
-
DEFAULT_TEMPERATURE = 1.0 # 볼츠만 분포 기본 온도
|
| 31 |
-
MIN_EMERGENCE_THRESHOLD = 0.65 # 창발성 임계점 기본값
|
| 32 |
-
MIN_ENTROPY = 1.5 # 최소 엔트로피 (비트)
|
| 33 |
-
MAX_BRUTE_FORCE_COMBOS = 50000 # 전수 탐색 최대 조합 수
|
| 34 |
-
DEFAULT_SAMPLE_SIZE = 100 # 기본 샘플링 크기
|
| 35 |
-
|
| 36 |
-
LAYER_ORDER = ["INPUT", "TRANSFORMATION", "CONTROL", "FABRICATION", "CONTEXT", "VALUE"]
|
| 37 |
-
|
| 38 |
-
logger = logging.getLogger(__name__)
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 42 |
-
# 1. 데이터 구조
|
| 43 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 44 |
-
|
| 45 |
-
@dataclass
|
| 46 |
-
class IdeaVector:
|
| 47 |
-
"""가능성 공간 내 아이디어 벡터"""
|
| 48 |
-
item_name: str
|
| 49 |
-
category: str
|
| 50 |
-
layer: str
|
| 51 |
-
layer_index: int
|
| 52 |
-
position: np.ndarray # N차원 좌표
|
| 53 |
-
relevance_score: float = 0.0
|
| 54 |
-
metadata: Dict[str, Any] = field(default_factory=dict)
|
| 55 |
-
|
| 56 |
-
@property
|
| 57 |
-
def id(self) -> str:
|
| 58 |
-
return hashlib.md5(f"{self.layer}:{self.category}:{self.item_name}".encode()).hexdigest()[:8]
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
@dataclass
|
| 62 |
-
class Combination:
|
| 63 |
-
"""아이디어 조합 (2개 이상 아이디어의 융합)"""
|
| 64 |
-
items: List[IdeaVector]
|
| 65 |
-
score: float = 0.0
|
| 66 |
-
fusion_bonus: float = 0.0
|
| 67 |
-
complexity: float = 0.0
|
| 68 |
-
is_emergent: bool = False
|
| 69 |
-
emergence_level: str = "LOW"
|
| 70 |
-
novelty_score: float = 0.0
|
| 71 |
-
graph_paths: List[List[str]] = field(default_factory=list)
|
| 72 |
-
metadata: Dict[str, Any] = field(default_factory=dict)
|
| 73 |
-
|
| 74 |
-
@property
|
| 75 |
-
def layers_involved(self) -> Set[str]:
|
| 76 |
-
return set(item.layer for item in self.items)
|
| 77 |
-
|
| 78 |
-
@property
|
| 79 |
-
def n_layers(self) -> int:
|
| 80 |
-
return len(self.layers_involved)
|
| 81 |
-
|
| 82 |
-
@property
|
| 83 |
-
def description(self) -> str:
|
| 84 |
-
parts = [f"[{item.layer}] {item.category} > {item.item_name}" for item in self.items]
|
| 85 |
-
return " ⊕ ".join(parts)
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
@dataclass
|
| 89 |
-
class EmergenceResult:
|
| 90 |
-
"""창발성 판정 결과"""
|
| 91 |
-
complexity: float
|
| 92 |
-
threshold: float
|
| 93 |
-
is_emergent: bool
|
| 94 |
-
emergence_level: str # HIGH, MODERATE, LOW
|
| 95 |
-
confidence: float # 0.0 ~ 1.0
|
| 96 |
-
contributing_factors: Dict[str, float] = field(default_factory=dict)
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 100 |
-
# 2. [독립항 전제] N차원 가능성 공간 (Possibility Space)
|
| 101 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 102 |
-
|
| 103 |
-
class PossibilitySpace:
|
| 104 |
-
"""N차원(N≥5) 가능성 공간
|
| 105 |
-
|
| 106 |
-
각 차원은 기술 레이어(INPUT, TRANSFORMATION, CONTROL, FABRICATION, CONTEXT, VALUE)에 대응.
|
| 107 |
-
아이디어는 N차원 벡터로 공간에 배치되며, 레이어 소속 정도를 연속 좌표로 표현.
|
| 108 |
-
"""
|
| 109 |
-
|
| 110 |
-
def __init__(self, dimensions: List[str] = None):
|
| 111 |
-
self.dimensions = dimensions or LAYER_ORDER
|
| 112 |
-
self.n_dims = len(self.dimensions)
|
| 113 |
-
assert self.n_dims >= 5, f"가능성 공간은 최소 5차원이어야 합니다 (현재: {self.n_dims})"
|
| 114 |
-
self.ideas: List[IdeaVector] = []
|
| 115 |
-
self._dim_index = {d: i for i, d in enumerate(self.dimensions)}
|
| 116 |
-
logger.info(f"✅ 가능성 공간 초기화: {self.n_dims}차원 {self.dimensions}")
|
| 117 |
-
|
| 118 |
-
def place_idea(self, item_name: str, category: str, layer: str,
|
| 119 |
-
relevance_score: float = 0.5, cross_layer_affinity: Dict[str, float] = None) -> IdeaVector:
|
| 120 |
-
"""아이디어를 N차원 공간에 배치
|
| 121 |
-
|
| 122 |
-
주(primary) 레이어에 높은 좌표, 교차 친화도에 따라 다른 차원에도 분산 배치.
|
| 123 |
-
이를 통해 "순수 INPUT" 아이디어와 "INPUT+CONTROL 융합" 아이디어의 위치가 구별됨.
|
| 124 |
-
"""
|
| 125 |
-
position = np.zeros(self.n_dims)
|
| 126 |
-
primary_idx = self._dim_index.get(layer, 0)
|
| 127 |
-
position[primary_idx] = relevance_score
|
| 128 |
-
|
| 129 |
-
# 교차 레이어 친화도 반영 (부(secondary) 차원에 분산)
|
| 130 |
-
if cross_layer_affinity:
|
| 131 |
-
for other_layer, affinity in cross_layer_affinity.items():
|
| 132 |
-
if other_layer in self._dim_index:
|
| 133 |
-
idx = self._dim_index[other_layer]
|
| 134 |
-
position[idx] = max(position[idx], affinity * 0.5)
|
| 135 |
-
|
| 136 |
-
# L2 정규화 (단위 초구면에 배치)
|
| 137 |
-
norm = np.linalg.norm(position)
|
| 138 |
-
if norm > 0:
|
| 139 |
-
position = position / norm
|
| 140 |
-
|
| 141 |
-
idea = IdeaVector(
|
| 142 |
-
item_name=item_name, category=category, layer=layer,
|
| 143 |
-
layer_index=primary_idx, position=position,
|
| 144 |
-
relevance_score=relevance_score
|
| 145 |
-
)
|
| 146 |
-
self.ideas.append(idea)
|
| 147 |
-
return idea
|
| 148 |
-
|
| 149 |
-
def place_from_categories(self, categories, relevance_scores: Dict):
|
| 150 |
-
"""categories.py의 카테고리/관련성 스코어로부터 대량 배치"""
|
| 151 |
-
count = 0
|
| 152 |
-
for cat in categories:
|
| 153 |
-
cat_name = cat.name_ko if hasattr(cat, 'name_ko') else str(cat)
|
| 154 |
-
layer = getattr(cat, 'layer', 'TRANSFORMATION')
|
| 155 |
-
cat_data = relevance_scores.get(cat_name, {})
|
| 156 |
-
cat_score = cat_data.get("category_score", 0.5)
|
| 157 |
-
item_scores = cat_data.get("items", {})
|
| 158 |
-
|
| 159 |
-
items = cat.items if hasattr(cat, 'items') and cat.items else []
|
| 160 |
-
for item in items:
|
| 161 |
-
item_key = item.get('name', str(item)) if isinstance(item, dict) else str(item)
|
| 162 |
-
item_score = item_scores.get(item_key, 0.5)
|
| 163 |
-
combined = (cat_score + item_score) / 2
|
| 164 |
-
self.place_idea(item_key, cat_name, layer, relevance_score=combined)
|
| 165 |
-
count += 1
|
| 166 |
-
|
| 167 |
-
logger.info(f"✅ 가능성 공간 배치 완료: {count}개 아이디어 → {self.n_dims}차원 공간")
|
| 168 |
-
return count
|
| 169 |
-
|
| 170 |
-
def distance(self, idea_a: IdeaVector, idea_b: IdeaVector) -> float:
|
| 171 |
-
"""두 아이디어 간 유클리드 거리 (멀수록 이종 결합)"""
|
| 172 |
-
return float(np.linalg.norm(idea_a.position - idea_b.position))
|
| 173 |
-
|
| 174 |
-
def cosine_similarity(self, idea_a: IdeaVector, idea_b: IdeaVector) -> float:
|
| 175 |
-
"""두 아이디어 간 코사인 유사도"""
|
| 176 |
-
dot = np.dot(idea_a.position, idea_b.position)
|
| 177 |
-
norm_a = np.linalg.norm(idea_a.position)
|
| 178 |
-
norm_b = np.linalg.norm(idea_b.position)
|
| 179 |
-
if norm_a == 0 or norm_b == 0:
|
| 180 |
-
return 0.0
|
| 181 |
-
return float(dot / (norm_a * norm_b))
|
| 182 |
-
|
| 183 |
-
def get_ideas_by_layer(self, layer: str) -> List[IdeaVector]:
|
| 184 |
-
return [idea for idea in self.ideas if idea.layer == layer]
|
| 185 |
-
|
| 186 |
-
@property
|
| 187 |
-
def total_ideas(self) -> int:
|
| 188 |
-
return len(self.ideas)
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 192 |
-
# 3. [독립항 (a)] 브루트포스 전수 탐색 + 스코어링
|
| 193 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 194 |
-
|
| 195 |
-
class BruteForceExplorer:
|
| 196 |
-
"""가능성 공간의 전수 탐색 및 스코어링 엔진
|
| 197 |
-
|
| 198 |
-
모든 2-way (또는 k-way) 조합을 열거하고 각 조합의 융합 점수를 산출.
|
| 199 |
-
대규모 공간의 경우 레이어별 대표 아이디어를 선별 후 탐색.
|
| 200 |
-
"""
|
| 201 |
-
|
| 202 |
-
def __init__(self, space: PossibilitySpace, fusion_matrix: 'FusionBonusMatrix'):
|
| 203 |
-
self.space = space
|
| 204 |
-
self.fusion_matrix = fusion_matrix
|
| 205 |
-
|
| 206 |
-
def enumerate_all_combinations(self, k: int = 2,
|
| 207 |
-
max_combos: int = MAX_BRUTE_FORCE_COMBOS,
|
| 208 |
-
cross_layer_only: bool = True) -> List[Combination]:
|
| 209 |
-
"""전수 탐색: k-way 조합 열거 및 스코어링
|
| 210 |
-
|
| 211 |
-
Args:
|
| 212 |
-
k: 조합 크기 (기본 2-way)
|
| 213 |
-
max_combos: 최대 조합 수 (메모리/시간 제한)
|
| 214 |
-
cross_layer_only: True면 이종 레이어 조합만 탐색 (동일 레이어 내 조합 제외)
|
| 215 |
-
|
| 216 |
-
Returns:
|
| 217 |
-
점수 내림차순 정렬된 조합 리스트
|
| 218 |
-
"""
|
| 219 |
-
ideas = self.space.ideas
|
| 220 |
-
if not ideas:
|
| 221 |
-
logger.warning("가능성 공간에 아이디어가 없습니다.")
|
| 222 |
-
return []
|
| 223 |
-
|
| 224 |
-
# 대규모 공간: 레이어별 상위 아이디어만 선별
|
| 225 |
-
if len(list(combinations(range(len(ideas)), k))) > max_combos:
|
| 226 |
-
ideas = self._select_representative_ideas(ideas, per_layer=max(5, max_combos // 100))
|
| 227 |
-
logger.info(f"대규모 공간 → 대표 아이디어 {len(ideas)}개로 축소")
|
| 228 |
-
|
| 229 |
-
scored = []
|
| 230 |
-
combo_count = 0
|
| 231 |
-
for combo_tuple in combinations(ideas, k):
|
| 232 |
-
if combo_count >= max_combos:
|
| 233 |
-
break
|
| 234 |
-
combo_items = list(combo_tuple)
|
| 235 |
-
|
| 236 |
-
# 이종 레이어 필터
|
| 237 |
-
if cross_layer_only:
|
| 238 |
-
layers = set(item.layer for item in combo_items)
|
| 239 |
-
if len(layers) < 2:
|
| 240 |
-
continue
|
| 241 |
-
|
| 242 |
-
score = self._score_combination(combo_items)
|
| 243 |
-
fusion_bonus = self.fusion_matrix.compute_bonus(combo_items)
|
| 244 |
-
|
| 245 |
-
combo = Combination(
|
| 246 |
-
items=combo_items,
|
| 247 |
-
score=score,
|
| 248 |
-
fusion_bonus=fusion_bonus,
|
| 249 |
-
)
|
| 250 |
-
scored.append(combo)
|
| 251 |
-
combo_count += 1
|
| 252 |
-
|
| 253 |
-
# 점수 내림차순 정렬
|
| 254 |
-
scored.sort(key=lambda c: c.score + c.fusion_bonus, reverse=True)
|
| 255 |
-
logger.info(f"✅ 전수 탐색 완료: {combo_count}개 조합 스코어링")
|
| 256 |
-
return scored
|
| 257 |
-
|
| 258 |
-
def _score_combination(self, items: List[IdeaVector]) -> float:
|
| 259 |
-
"""조합의 기본 점수 = 관련성 평균 + 공간적 거리 보너스"""
|
| 260 |
-
relevance_avg = np.mean([item.relevance_score for item in items])
|
| 261 |
-
|
| 262 |
-
# 공간적 거리: 멀수록 (이종 융합일수록) 보너스
|
| 263 |
-
if len(items) >= 2:
|
| 264 |
-
distances = [self.space.distance(a, b) for a, b in combinations(items, 2)]
|
| 265 |
-
distance_bonus = np.mean(distances) * 0.3 # 거리의 30%를 보너스로
|
| 266 |
-
else:
|
| 267 |
-
distance_bonus = 0.0
|
| 268 |
-
|
| 269 |
-
return float(relevance_avg + distance_bonus)
|
| 270 |
-
|
| 271 |
-
def _select_representative_ideas(self, ideas: List[IdeaVector], per_layer: int = 10) -> List[IdeaVector]:
|
| 272 |
-
"""각 레이어에서 관련성 상위 아이디어만 선별"""
|
| 273 |
-
by_layer = defaultdict(list)
|
| 274 |
-
for idea in ideas:
|
| 275 |
-
by_layer[idea.layer].append(idea)
|
| 276 |
-
selected = []
|
| 277 |
-
for layer in LAYER_ORDER:
|
| 278 |
-
layer_ideas = sorted(by_layer.get(layer, []), key=lambda x: x.relevance_score, reverse=True)
|
| 279 |
-
selected.extend(layer_ideas[:per_layer])
|
| 280 |
-
return selected
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 284 |
-
# 4. [독립항 (b)] 볼츠만 분포 기반 확률적 샘플링
|
| 285 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 286 |
-
|
| 287 |
-
class BoltzmannSampler:
|
| 288 |
-
"""볼츠만 분포 P(x) = exp(-E(x)/kT) / Z 기반 확률적 샘플링
|
| 289 |
-
|
| 290 |
-
온도 파라미터 T로 탐색 다양성을 동적 조절:
|
| 291 |
-
- 높은 T (>2.0): 탐색(exploration) 모드 — 저점수 아이디어도 높은 확률로 선택
|
| 292 |
-
- 중간 T (~1.0): 균형 모드
|
| 293 |
-
- 낮은 T (<0.5): 착취(exploitation) 모드 — 고점수 아이디어에 집중
|
| 294 |
-
"""
|
| 295 |
-
|
| 296 |
-
def __init__(self, temperature: float = DEFAULT_TEMPERATURE):
|
| 297 |
-
self.temperature = temperature
|
| 298 |
-
self._validate_temperature()
|
| 299 |
-
|
| 300 |
-
def _validate_temperature(self):
|
| 301 |
-
if self.temperature <= 0:
|
| 302 |
-
raise ValueError(f"온도 T는 양수여야 합니다 (현재: {self.temperature})")
|
| 303 |
-
|
| 304 |
-
def set_temperature(self, temperature: float):
|
| 305 |
-
"""온도 파라미터 동적 조절"""
|
| 306 |
-
self.temperature = temperature
|
| 307 |
-
self._validate_temperature()
|
| 308 |
-
logger.info(f"🌡️ 볼츠만 온도 변경: T={self.temperature:.2f}")
|
| 309 |
-
|
| 310 |
-
def compute_probabilities(self, combinations: List[Combination]) -> np.ndarray:
|
| 311 |
-
"""각 조합의 볼츠만 확률 P(x) 계산
|
| 312 |
-
|
| 313 |
-
P(x) = exp(-E(x) / T) / Z
|
| 314 |
-
여기서 E(x) = -score (높은 점수 = 낮은 에너지)
|
| 315 |
-
Z = Σ exp(-E(x) / T) (분배함수)
|
| 316 |
-
"""
|
| 317 |
-
if not combinations:
|
| 318 |
-
return np.array([])
|
| 319 |
-
|
| 320 |
-
scores = np.array([c.score + c.fusion_bonus for c in combinations])
|
| 321 |
-
energies = -scores # 높은 점수 = 낮은 에너지
|
| 322 |
-
|
| 323 |
-
# 로그-확률 계산 (수치 안정성)
|
| 324 |
-
log_probs = -energies / self.temperature
|
| 325 |
-
log_probs -= np.max(log_probs) # 오버플로 방지
|
| 326 |
-
probs = np.exp(log_probs)
|
| 327 |
-
|
| 328 |
-
# 분배함수 Z로 정규화
|
| 329 |
-
Z = probs.sum()
|
| 330 |
-
if Z > 0:
|
| 331 |
-
probs /= Z
|
| 332 |
-
else:
|
| 333 |
-
probs = np.ones(len(probs)) / len(probs)
|
| 334 |
-
|
| 335 |
-
return probs
|
| 336 |
-
|
| 337 |
-
def sample(self, combinations: List[Combination], n_samples: int = DEFAULT_SAMPLE_SIZE,
|
| 338 |
-
replace: bool = False) -> List[Combination]:
|
| 339 |
-
"""볼츠만 분포에 따른 확률적 샘플링
|
| 340 |
-
|
| 341 |
-
Args:
|
| 342 |
-
combinations: 전수 탐색 결과
|
| 343 |
-
n_samples: 샘플링할 조합 수
|
| 344 |
-
replace: True면 복원 추출 (동일 조합 중복 선택 가능)
|
| 345 |
-
|
| 346 |
-
Returns:
|
| 347 |
-
볼츠만 확률에 따라 선택된 조합 리스트
|
| 348 |
-
"""
|
| 349 |
-
if not combinations:
|
| 350 |
-
return []
|
| 351 |
-
|
| 352 |
-
n_samples = min(n_samples, len(combinations)) if not replace else n_samples
|
| 353 |
-
probs = self.compute_probabilities(combinations)
|
| 354 |
-
|
| 355 |
-
indices = np.random.choice(
|
| 356 |
-
len(combinations), size=n_samples, replace=replace, p=probs
|
| 357 |
-
)
|
| 358 |
-
|
| 359 |
-
sampled = [combinations[i] for i in indices]
|
| 360 |
-
logger.info(
|
| 361 |
-
f"✅ 볼츠만 샘플링 완료: T={self.temperature:.2f}, "
|
| 362 |
-
f"{len(combinations)}개 중 {n_samples}개 선택"
|
| 363 |
-
)
|
| 364 |
-
return sampled
|
| 365 |
-
|
| 366 |
-
def adaptive_sample(self, combinations: List[Combination],
|
| 367 |
-
n_samples: int = DEFAULT_SAMPLE_SIZE,
|
| 368 |
-
explore_ratio: float = 0.3) -> List[Combination]:
|
| 369 |
-
"""적응적 샘플링: 착취(저온) + 탐색(고온) 혼합
|
| 370 |
-
|
| 371 |
-
전체 샘플의 (1-explore_ratio)는 낮은 온도로, explore_ratio는 높은 온도로 샘플링.
|
| 372 |
-
이를 통해 고점수 조합을 확보하면서도 의외의 조합을 발견할 기회를 보장.
|
| 373 |
-
"""
|
| 374 |
-
n_exploit = int(n_samples * (1 - explore_ratio))
|
| 375 |
-
n_explore = n_samples - n_exploit
|
| 376 |
-
|
| 377 |
-
# 착취 (낮은 T)
|
| 378 |
-
self.set_temperature(self.temperature * 0.3)
|
| 379 |
-
exploited = self.sample(combinations, n_exploit)
|
| 380 |
-
|
| 381 |
-
# 탐색 (높은 T)
|
| 382 |
-
self.set_temperature(self.temperature * 10.0) # 원래의 ~3배
|
| 383 |
-
explored = self.sample(combinations, n_explore)
|
| 384 |
-
|
| 385 |
-
# 온도 복원
|
| 386 |
-
self.set_temperature(DEFAULT_TEMPERATURE)
|
| 387 |
-
|
| 388 |
-
result = exploited + explored
|
| 389 |
-
logger.info(f"✅ 적응적 샘플링: 착취 {n_exploit}개 + 탐색 {n_explore}개")
|
| 390 |
-
return result
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 394 |
-
# 5. [독립항 (c)] 지식그래프 연결 탐색
|
| 395 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 396 |
-
|
| 397 |
-
class EmergenceKnowledgeGraph:
|
| 398 |
-
"""기술 항목 간 지식그래프 구축 및 미발견 경로 탐색
|
| 399 |
-
|
| 400 |
-
노드: 카테고리, 기술 항목
|
| 401 |
-
엣지: contains(소속), related(관련성), cross_layer(교차 레이어)
|
| 402 |
-
미발견 경로: 직접 연결이 없는 노드 간 간접 경로 → 창발적 조합 후보
|
| 403 |
-
"""
|
| 404 |
-
|
| 405 |
-
def __init__(self):
|
| 406 |
-
# 인접 리스트 기반 그래프 (networkx 의존 제거)
|
| 407 |
-
self.nodes: Dict[str, Dict[str, Any]] = {}
|
| 408 |
-
self.edges: Dict[str, List[Tuple[str, str, float]]] = defaultdict(list)
|
| 409 |
-
self._adjacency: Dict[str, Set[str]] = defaultdict(set)
|
| 410 |
-
|
| 411 |
-
def add_node(self, node_id: str, **attrs):
|
| 412 |
-
self.nodes[node_id] = attrs
|
| 413 |
-
|
| 414 |
-
def add_edge(self, source: str, target: str, relation: str = "related", weight: float = 1.0):
|
| 415 |
-
self.edges[source].append((target, relation, weight))
|
| 416 |
-
self._adjacency[source].add(target)
|
| 417 |
-
self._adjacency[target].add(source) # 양방향
|
| 418 |
-
|
| 419 |
-
def build_from_space(self, space: PossibilitySpace, cross_layer_bonus: Dict = None):
|
| 420 |
-
"""가능성 공간의 아이디어들로 지식그래프 구축"""
|
| 421 |
-
# 1. 레이어 → 노드
|
| 422 |
-
for layer in space.dimensions:
|
| 423 |
-
self.add_node(f"LAYER:{layer}", type="layer", name=layer)
|
| 424 |
-
|
| 425 |
-
# 2. 카테고리 → 노드 + 레이어 엣지
|
| 426 |
-
categories_seen = set()
|
| 427 |
-
for idea in space.ideas:
|
| 428 |
-
cat_id = f"CAT:{idea.category}"
|
| 429 |
-
if cat_id not in categories_seen:
|
| 430 |
-
self.add_node(cat_id, type="category", name=idea.category, layer=idea.layer)
|
| 431 |
-
self.add_edge(f"LAYER:{idea.layer}", cat_id, "contains", 1.0)
|
| 432 |
-
categories_seen.add(cat_id)
|
| 433 |
-
|
| 434 |
-
# 3. 항목 → 노드 + 카테고리 엣지
|
| 435 |
-
item_id = f"ITEM:{idea.id}"
|
| 436 |
-
self.add_node(item_id, type="item", name=idea.item_name,
|
| 437 |
-
category=idea.category, layer=idea.layer)
|
| 438 |
-
self.add_edge(cat_id, item_id, "contains", idea.relevance_score)
|
| 439 |
-
|
| 440 |
-
# 4. 교차 레이어 엣지 (이종 카테고리 간 연결)
|
| 441 |
-
if cross_layer_bonus:
|
| 442 |
-
for (layer_a, layer_b), bonus in cross_layer_bonus.items():
|
| 443 |
-
self.add_edge(f"LAYER:{layer_a}", f"LAYER:{layer_b}", "cross_layer", bonus)
|
| 444 |
-
|
| 445 |
-
# 5. 가능성 공간 내 근접 아이디어 간 연결
|
| 446 |
-
self._connect_nearby_ideas(space, similarity_threshold=0.3)
|
| 447 |
-
|
| 448 |
-
logger.info(
|
| 449 |
-
f"✅ 지식그래프 구축: {len(self.nodes)}개 노드, "
|
| 450 |
-
f"{sum(len(v) for v in self.edges.values())}개 엣지"
|
| 451 |
-
)
|
| 452 |
-
|
| 453 |
-
def _connect_nearby_ideas(self, space: PossibilitySpace, similarity_threshold: float = 0.3):
|
| 454 |
-
"""가능성 공간에서 유사한 아이디어 간 엣지 추가"""
|
| 455 |
-
items = [idea for idea in space.ideas]
|
| 456 |
-
for i, a in enumerate(items):
|
| 457 |
-
for j, b in enumerate(items):
|
| 458 |
-
if j <= i:
|
| 459 |
-
continue
|
| 460 |
-
sim = space.cosine_similarity(a, b)
|
| 461 |
-
if sim > similarity_threshold:
|
| 462 |
-
self.add_edge(f"ITEM:{a.id}", f"ITEM:{b.id}", "similar", sim)
|
| 463 |
-
|
| 464 |
-
def discover_hidden_paths(self, max_hops: int = 3, max_paths: int = 500) -> List[Dict]:
|
| 465 |
-
"""기존 노드 간 미발견 경로 탐색 (BFS 기반)
|
| 466 |
-
|
| 467 |
-
직접 연결(엣지)이 없지만 간접 경로가 존재하는 아이템 쌍을 발견.
|
| 468 |
-
이러한 간접 경로는 창발적 아이디어 융합의 후보가 됨.
|
| 469 |
-
|
| 470 |
-
Returns:
|
| 471 |
-
[{"source": str, "target": str, "path": List[str], "novelty_score": float}, ...]
|
| 472 |
-
"""
|
| 473 |
-
item_nodes = [nid for nid, attrs in self.nodes.items() if attrs.get("type") == "item"]
|
| 474 |
-
hidden_paths = []
|
| 475 |
-
|
| 476 |
-
for source in item_nodes:
|
| 477 |
-
direct_neighbors = self._adjacency.get(source, set())
|
| 478 |
-
# BFS로 max_hops 이내 도달 가능한 노드 탐색
|
| 479 |
-
reachable = self._bfs(source, max_hops)
|
| 480 |
-
|
| 481 |
-
for target, path in reachable.items():
|
| 482 |
-
if target == source:
|
| 483 |
-
continue
|
| 484 |
-
if self.nodes.get(target, {}).get("type") != "item":
|
| 485 |
-
continue
|
| 486 |
-
# 직접 연결이 없는 노드만 (미발견 경로)
|
| 487 |
-
if target not in direct_neighbors:
|
| 488 |
-
# 신규도 = 1 / 경로 길이 (짧은 간접 경로가 더 의미 있음)
|
| 489 |
-
novelty = 1.0 / len(path)
|
| 490 |
-
# 이종 레이어 보너스
|
| 491 |
-
source_layer = self.nodes[source].get("layer", "")
|
| 492 |
-
target_layer = self.nodes[target].get("layer", "")
|
| 493 |
-
if source_layer != target_layer:
|
| 494 |
-
novelty *= 1.5 # 이종 레이어 간 미발견 경로 우대
|
| 495 |
-
|
| 496 |
-
hidden_paths.append({
|
| 497 |
-
"source": source,
|
| 498 |
-
"target": target,
|
| 499 |
-
"source_name": self.nodes[source].get("name", source),
|
| 500 |
-
"target_name": self.nodes[target].get("name", target),
|
| 501 |
-
"source_layer": source_layer,
|
| 502 |
-
"target_layer": target_layer,
|
| 503 |
-
"path": path,
|
| 504 |
-
"hops": len(path) - 1,
|
| 505 |
-
"novelty_score": novelty
|
| 506 |
-
})
|
| 507 |
-
|
| 508 |
-
if len(hidden_paths) >= max_paths:
|
| 509 |
-
break
|
| 510 |
-
if len(hidden_paths) >= max_paths:
|
| 511 |
-
break
|
| 512 |
-
|
| 513 |
-
hidden_paths.sort(key=lambda x: x["novelty_score"], reverse=True)
|
| 514 |
-
logger.info(f"✅ 미발견 경로 탐색: {len(hidden_paths)}개 발견")
|
| 515 |
-
return hidden_paths
|
| 516 |
-
|
| 517 |
-
def _bfs(self, start: str, max_depth: int) -> Dict[str, List[str]]:
|
| 518 |
-
"""BFS로 시작 노드에서 max_depth 이내 도달 가능한 모든 노드와 경로 반환"""
|
| 519 |
-
visited = {start: [start]}
|
| 520 |
-
queue = [(start, [start], 0)]
|
| 521 |
-
while queue:
|
| 522 |
-
current, path, depth = queue.pop(0)
|
| 523 |
-
if depth >= max_depth:
|
| 524 |
-
continue
|
| 525 |
-
for neighbor in self._adjacency.get(current, set()):
|
| 526 |
-
if neighbor not in visited:
|
| 527 |
-
new_path = path + [neighbor]
|
| 528 |
-
visited[neighbor] = new_path
|
| 529 |
-
queue.append((neighbor, new_path, depth + 1))
|
| 530 |
-
return visited
|
| 531 |
-
|
| 532 |
-
def enrich_combinations(self, combinations: List[Combination]) -> List[Combination]:
|
| 533 |
-
"""조합에 지식그래프 경로 정보를 추가"""
|
| 534 |
-
for combo in combinations:
|
| 535 |
-
item_ids = [f"ITEM:{item.id}" for item in combo.items]
|
| 536 |
-
paths_found = []
|
| 537 |
-
for a_id, b_id in zip(item_ids, item_ids[1:]):
|
| 538 |
-
reachable = self._bfs(a_id, 3)
|
| 539 |
-
if b_id in reachable:
|
| 540 |
-
paths_found.append(reachable[b_id])
|
| 541 |
-
combo.graph_paths = paths_found
|
| 542 |
-
if paths_found:
|
| 543 |
-
combo.novelty_score = np.mean([1.0 / len(p) for p in paths_found])
|
| 544 |
-
return combinations
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 548 |
-
# 6. [독립항 (d)] 교차 융합 보너스 매트릭스
|
| 549 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 550 |
-
|
| 551 |
-
class FusionBonusMatrix:
|
| 552 |
-
"""이종 계층 간 거리에 비례한 교차 융합 보너스 매트릭스
|
| 553 |
-
|
| 554 |
-
수학적 보장: bonus[i][j] = |index_i - index_j| / (N-1) * max_bonus
|
| 555 |
-
→ 먼 레이어 간 조합일수록 높은 보너스 (진정한 이종 융합 우대)
|
| 556 |
-
"""
|
| 557 |
-
|
| 558 |
-
def __init__(self, layers: List[str] = None, max_bonus: float = 0.15):
|
| 559 |
-
self.layers = layers or LAYER_ORDER
|
| 560 |
-
self.n_layers = len(self.layers)
|
| 561 |
-
self.max_bonus = max_bonus
|
| 562 |
-
self._layer_index = {l: i for i, l in enumerate(self.layers)}
|
| 563 |
-
self.matrix = self._build_matrix()
|
| 564 |
-
|
| 565 |
-
def _build_matrix(self) -> np.ndarray:
|
| 566 |
-
"""거리 비례 융합 보너스 매트릭스 구축
|
| 567 |
-
|
| 568 |
-
matrix[i][j] = |i - j| / (N-1) * max_bonus
|
| 569 |
-
대각선(i==j) = 0 (동일 레이어 보너스 없음)
|
| 570 |
-
"""
|
| 571 |
-
n = self.n_layers
|
| 572 |
-
matrix = np.zeros((n, n))
|
| 573 |
-
for i in range(n):
|
| 574 |
-
for j in range(n):
|
| 575 |
-
if i != j:
|
| 576 |
-
distance = abs(i - j) / (n - 1) # 정규화 거리 [0, 1]
|
| 577 |
-
matrix[i][j] = distance * self.max_bonus
|
| 578 |
-
return matrix
|
| 579 |
-
|
| 580 |
-
def get_bonus(self, layer_a: str, layer_b: str) -> float:
|
| 581 |
-
"""두 레이어 간 융합 보너스 조회"""
|
| 582 |
-
idx_a = self._layer_index.get(layer_a, 0)
|
| 583 |
-
idx_b = self._layer_index.get(layer_b, 0)
|
| 584 |
-
return float(self.matrix[idx_a][idx_b])
|
| 585 |
-
|
| 586 |
-
def compute_bonus(self, items: List[IdeaVector]) -> float:
|
| 587 |
-
"""조합 내 모든 아이템 쌍의 융합 보너스 합산"""
|
| 588 |
-
total_bonus = 0.0
|
| 589 |
-
for a, b in combinations(items, 2):
|
| 590 |
-
total_bonus += self.get_bonus(a.layer, b.layer)
|
| 591 |
-
return total_bonus
|
| 592 |
-
|
| 593 |
-
def to_dict(self) -> Dict:
|
| 594 |
-
"""매트릭스를 딕셔너리로 변환 (직렬화용)"""
|
| 595 |
-
result = {}
|
| 596 |
-
for i, layer_a in enumerate(self.layers):
|
| 597 |
-
for j, layer_b in enumerate(self.layers):
|
| 598 |
-
if i < j:
|
| 599 |
-
result[(layer_a, layer_b)] = float(self.matrix[i][j])
|
| 600 |
-
return result
|
| 601 |
-
|
| 602 |
-
def __repr__(self):
|
| 603 |
-
header = " " + " ".join(f"{l[:5]:>6}" for l in self.layers)
|
| 604 |
-
rows = []
|
| 605 |
-
for i, layer in enumerate(self.layers):
|
| 606 |
-
row_vals = " ".join(f"{self.matrix[i][j]:6.3f}" for j in range(self.n_layers))
|
| 607 |
-
rows.append(f"{layer[:5]:>5} {row_vals}")
|
| 608 |
-
return header + "\n" + "\n".join(rows)
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 612 |
-
# 7. [독립항 (e)] 창발성 임계점 (Emergence Threshold) 판정
|
| 613 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 614 |
-
|
| 615 |
-
class EmergenceThresholdJudge:
|
| 616 |
-
"""조합 복잡도가 창발성 임계점을 초과하는지 판정
|
| 617 |
-
|
| 618 |
-
복잡도 = f(참여 레이어 수, 교차 융합 보너스, 지식그래프 경로 신규도, 공간적 거리)
|
| 619 |
-
임계점 초과 시 해당 조합을 "창발 발현(Emergent)" 으로 판정.
|
| 620 |
-
"""
|
| 621 |
-
|
| 622 |
-
def __init__(self, threshold: float = MIN_EMERGENCE_THRESHOLD,
|
| 623 |
-
fusion_matrix: FusionBonusMatrix = None):
|
| 624 |
-
self.threshold = threshold
|
| 625 |
-
self.fusion_matrix = fusion_matrix or FusionBonusMatrix()
|
| 626 |
-
|
| 627 |
-
def calculate_complexity(self, combo: Combination, space: PossibilitySpace = None) -> float:
|
| 628 |
-
"""조합의 복잡도 계산
|
| 629 |
-
|
| 630 |
-
complexity = α * layer_diversity + β * fusion_bonus + γ * spatial_distance + δ * novelty
|
| 631 |
-
|
| 632 |
-
α=0.30: 참여 레이어 다양성 (N_layers / N_total_layers)
|
| 633 |
-
β=0.25: 교차 융합 보너스 정규화
|
| 634 |
-
γ=0.25: 공간적 거리 (멀수록 이종 융합)
|
| 635 |
-
δ=0.20: 지식그래프 경로 신규도
|
| 636 |
-
"""
|
| 637 |
-
# (1) 레이어 다양성
|
| 638 |
-
n_layers = combo.n_layers
|
| 639 |
-
layer_diversity = n_layers / len(LAYER_ORDER)
|
| 640 |
-
|
| 641 |
-
# (2) 교차 융합 보너스 (정규화)
|
| 642 |
-
max_possible_bonus = self.fusion_matrix.max_bonus * (n_layers * (n_layers - 1) / 2)
|
| 643 |
-
fusion_normalized = combo.fusion_bonus / max(max_possible_bonus, 0.01)
|
| 644 |
-
|
| 645 |
-
# (3) 공간적 거리 (평균)
|
| 646 |
-
if space and len(combo.items) >= 2:
|
| 647 |
-
distances = [space.distance(a, b) for a, b in combinations(combo.items, 2)]
|
| 648 |
-
spatial_distance = np.mean(distances)
|
| 649 |
-
else:
|
| 650 |
-
spatial_distance = 0.5
|
| 651 |
-
|
| 652 |
-
# (4) 지식그래프 경로 신규도
|
| 653 |
-
novelty = combo.novelty_score if combo.novelty_score > 0 else 0.3
|
| 654 |
-
|
| 655 |
-
# 가중 합산
|
| 656 |
-
complexity = (
|
| 657 |
-
0.30 * layer_diversity +
|
| 658 |
-
0.25 * min(fusion_normalized, 1.0) +
|
| 659 |
-
0.25 * min(spatial_distance, 1.0) +
|
| 660 |
-
0.20 * min(novelty, 1.0)
|
| 661 |
-
)
|
| 662 |
-
|
| 663 |
-
return float(complexity)
|
| 664 |
-
|
| 665 |
-
def judge(self, combo: Combination, space: PossibilitySpace = None) -> EmergenceResult:
|
| 666 |
-
"""창발성 임계점 초과 여부 판정"""
|
| 667 |
-
complexity = self.calculate_complexity(combo, space)
|
| 668 |
-
is_emergent = complexity > self.threshold
|
| 669 |
-
|
| 670 |
-
if complexity > self.threshold * 1.5:
|
| 671 |
-
level = "HIGH"
|
| 672 |
-
elif is_emergent:
|
| 673 |
-
level = "MODERATE"
|
| 674 |
-
else:
|
| 675 |
-
level = "LOW"
|
| 676 |
-
|
| 677 |
-
confidence = min(complexity / self.threshold, 2.0) / 2.0
|
| 678 |
-
|
| 679 |
-
result = EmergenceResult(
|
| 680 |
-
complexity=complexity,
|
| 681 |
-
threshold=self.threshold,
|
| 682 |
-
is_emergent=is_emergent,
|
| 683 |
-
emergence_level=level,
|
| 684 |
-
confidence=confidence,
|
| 685 |
-
contributing_factors={
|
| 686 |
-
"layer_diversity": combo.n_layers / len(LAYER_ORDER),
|
| 687 |
-
"fusion_bonus": combo.fusion_bonus,
|
| 688 |
-
"novelty_score": combo.novelty_score,
|
| 689 |
-
"n_layers": combo.n_layers,
|
| 690 |
-
}
|
| 691 |
-
)
|
| 692 |
-
|
| 693 |
-
# 조합에도 결과 반영
|
| 694 |
-
combo.complexity = complexity
|
| 695 |
-
combo.is_emergent = is_emergent
|
| 696 |
-
combo.emergence_level = level
|
| 697 |
-
|
| 698 |
-
return result
|
| 699 |
-
|
| 700 |
-
def judge_batch(self, combinations: List[Combination],
|
| 701 |
-
space: PossibilitySpace = None) -> List[Tuple[Combination, EmergenceResult]]:
|
| 702 |
-
"""대량 판정"""
|
| 703 |
-
results = []
|
| 704 |
-
emergent_count = 0
|
| 705 |
-
for combo in combinations:
|
| 706 |
-
result = self.judge(combo, space)
|
| 707 |
-
results.append((combo, result))
|
| 708 |
-
if result.is_emergent:
|
| 709 |
-
emergent_count += 1
|
| 710 |
-
|
| 711 |
-
logger.info(
|
| 712 |
-
f"✅ 창발성 판정 완료: {len(combinations)}개 중 {emergent_count}개 창발 발현 "
|
| 713 |
-
f"(임계점: {self.threshold:.2f})"
|
| 714 |
-
)
|
| 715 |
-
return results
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 719 |
-
# 8. [종속항 3] 엔트로피 기반 다양성 보장
|
| 720 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 721 |
-
|
| 722 |
-
class EntropyDiversityGuard:
|
| 723 |
-
"""탐색 경로의 다양성을 엔트로피로 측정하고 최소 수준을 보장
|
| 724 |
-
|
| 725 |
-
Shannon 엔트로피 H = -Σ p_i * log2(p_i)
|
| 726 |
-
최대 엔트로피 = log2(N_layers) ≈ 2.58 (6레이어)
|
| 727 |
-
최소 엔트로피 기본값 = 1.5 비트 (적어도 3개 레이어에 분산)
|
| 728 |
-
"""
|
| 729 |
-
|
| 730 |
-
def __init__(self, min_entropy: float = MIN_ENTROPY, layers: List[str] = None):
|
| 731 |
-
self.min_entropy = min_entropy
|
| 732 |
-
self.layers = layers or LAYER_ORDER
|
| 733 |
-
self.max_entropy = math.log2(len(self.layers))
|
| 734 |
-
|
| 735 |
-
def measure_entropy(self, combinations: List[Combination]) -> float:
|
| 736 |
-
"""현재 조합 집합의 레이어 분포 엔트로피 측정"""
|
| 737 |
-
if not combinations:
|
| 738 |
-
return 0.0
|
| 739 |
-
|
| 740 |
-
layer_counts = Counter()
|
| 741 |
-
for combo in combinations:
|
| 742 |
-
for item in combo.items:
|
| 743 |
-
layer_counts[item.layer] += 1
|
| 744 |
-
|
| 745 |
-
total = sum(layer_counts.values())
|
| 746 |
-
if total == 0:
|
| 747 |
-
return 0.0
|
| 748 |
-
|
| 749 |
-
probs = [layer_counts.get(l, 0) / total for l in self.layers]
|
| 750 |
-
# Shannon 엔트로피 (base-2, 비트 단위)
|
| 751 |
-
entropy_val = 0.0
|
| 752 |
-
for p in probs:
|
| 753 |
-
if p > 0:
|
| 754 |
-
entropy_val -= p * math.log2(p)
|
| 755 |
-
|
| 756 |
-
return entropy_val
|
| 757 |
-
|
| 758 |
-
def is_diverse_enough(self, combinations: List[Combination]) -> bool:
|
| 759 |
-
return self.measure_entropy(combinations) >= self.min_entropy
|
| 760 |
-
|
| 761 |
-
def ensure_diversity(self, combinations: List[Combination],
|
| 762 |
-
all_combinations: List[Combination]) -> Tuple[List[Combination], float]:
|
| 763 |
-
"""최소 엔트로피 미달 시 저빈도 레이어 아이디어를 추가 교체
|
| 764 |
-
|
| 765 |
-
Returns:
|
| 766 |
-
(다양성 보장된 조합 리스트, 최종 엔트로피)
|
| 767 |
-
"""
|
| 768 |
-
current = list(combinations)
|
| 769 |
-
current_entropy = self.measure_entropy(current)
|
| 770 |
-
|
| 771 |
-
if current_entropy >= self.min_entropy:
|
| 772 |
-
return current, current_entropy
|
| 773 |
-
|
| 774 |
-
logger.info(
|
| 775 |
-
f"⚠️ 엔트로피 부족: {current_entropy:.2f} < {self.min_entropy:.2f}, 다양성 보강 시작"
|
| 776 |
-
)
|
| 777 |
-
|
| 778 |
-
# 저빈도 레이어 식별
|
| 779 |
-
layer_counts = Counter()
|
| 780 |
-
for combo in current:
|
| 781 |
-
for item in combo.items:
|
| 782 |
-
layer_counts[item.layer] += 1
|
| 783 |
-
underrepresented = [l for l in self.layers if layer_counts.get(l, 0) < 2]
|
| 784 |
-
|
| 785 |
-
# 저빈도 레이어의 조합을 all_combinations에서 추가
|
| 786 |
-
additions = []
|
| 787 |
-
for combo in all_combinations:
|
| 788 |
-
if combo in current:
|
| 789 |
-
continue
|
| 790 |
-
if any(item.layer in underrepresented for item in combo.items):
|
| 791 |
-
additions.append(combo)
|
| 792 |
-
if len(additions) >= len(underrepresented) * 3:
|
| 793 |
-
break
|
| 794 |
-
|
| 795 |
-
# 현재 리스트의 가장 낮은 점수 조합을 교체
|
| 796 |
-
current.sort(key=lambda c: c.score + c.fusion_bonus)
|
| 797 |
-
n_replace = min(len(additions), len(current) // 4) # 최대 25% 교체
|
| 798 |
-
if n_replace > 0:
|
| 799 |
-
current = current[n_replace:] + additions[:n_replace]
|
| 800 |
-
|
| 801 |
-
final_entropy = self.measure_entropy(current)
|
| 802 |
-
logger.info(f"✅ 다양성 보강 완료: 엔트로피 {current_entropy:.2f} → {final_entropy:.2f}")
|
| 803 |
-
return current, final_entropy
|
| 804 |
-
|
| 805 |
-
def get_diversity_report(self, combinations: List[Combination]) -> Dict:
|
| 806 |
-
"""다양성 보고서 생성"""
|
| 807 |
-
entropy_val = self.measure_entropy(combinations)
|
| 808 |
-
layer_counts = Counter()
|
| 809 |
-
for combo in combinations:
|
| 810 |
-
for item in combo.items:
|
| 811 |
-
layer_counts[item.layer] += 1
|
| 812 |
-
|
| 813 |
-
return {
|
| 814 |
-
"entropy": entropy_val,
|
| 815 |
-
"max_entropy": self.max_entropy,
|
| 816 |
-
"min_entropy": self.min_entropy,
|
| 817 |
-
"diversity_ratio": entropy_val / self.max_entropy if self.max_entropy > 0 else 0,
|
| 818 |
-
"is_diverse": entropy_val >= self.min_entropy,
|
| 819 |
-
"layer_distribution": dict(layer_counts),
|
| 820 |
-
"underrepresented_layers": [l for l in self.layers if layer_counts.get(l, 0) < 2],
|
| 821 |
-
}
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 825 |
-
# 9. 통합 엔진: MAIAEmergenceEngine
|
| 826 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 827 |
-
|
| 828 |
-
class MAIAEmergenceEngine:
|
| 829 |
-
"""MAIA 창발성 발현 엔진 — 특허 제7호 독립항 (a)~(e) 통합 실행
|
| 830 |
-
|
| 831 |
-
파이프라인:
|
| 832 |
-
1. 가능성 공간 구축 (N≥5 차원)
|
| 833 |
-
2. (a) 브루트포스 전수 탐색 + 스코어링
|
| 834 |
-
3. (b) 볼츠만 분포 확률적 샘플링
|
| 835 |
-
4. (c) 지식그래프 미발견 경로 탐색 + 조합 보강
|
| 836 |
-
5. (d) 교차 융합 보너스 매트릭스 적용
|
| 837 |
-
6. (e) 창발성 임계점 판정
|
| 838 |
-
7. [종속항3] 엔트로피 기반 다양성 보장
|
| 839 |
-
"""
|
| 840 |
-
|
| 841 |
-
def __init__(self,
|
| 842 |
-
temperature: float = DEFAULT_TEMPERATURE,
|
| 843 |
-
emergence_threshold: float = MIN_EMERGENCE_THRESHOLD,
|
| 844 |
-
min_entropy: float = MIN_ENTROPY,
|
| 845 |
-
max_bonus: float = 0.15):
|
| 846 |
-
# 모듈 초기화
|
| 847 |
-
self.space = PossibilitySpace(LAYER_ORDER)
|
| 848 |
-
self.fusion_matrix = FusionBonusMatrix(LAYER_ORDER, max_bonus)
|
| 849 |
-
self.explorer = BruteForceExplorer(self.space, self.fusion_matrix)
|
| 850 |
-
self.sampler = BoltzmannSampler(temperature)
|
| 851 |
-
self.knowledge_graph = EmergenceKnowledgeGraph()
|
| 852 |
-
self.judge = EmergenceThresholdJudge(emergence_threshold, self.fusion_matrix)
|
| 853 |
-
self.diversity_guard = EntropyDiversityGuard(min_entropy, LAYER_ORDER)
|
| 854 |
-
|
| 855 |
-
# 실행 결과 저장
|
| 856 |
-
self.results: Dict[str, Any] = {}
|
| 857 |
-
self._initialized = False
|
| 858 |
-
|
| 859 |
-
logger.info("🚀 MAIA 창발성 발현 엔진 초기화 완료")
|
| 860 |
-
|
| 861 |
-
def initialize(self, categories, relevance_scores: Dict,
|
| 862 |
-
cross_layer_bonus: Dict = None):
|
| 863 |
-
"""엔진 초기화: 가능성 공간 구축 + 지식그래프 빌드"""
|
| 864 |
-
# 1. 가능성 공간에 아이디어 배치
|
| 865 |
-
n_placed = self.space.place_from_categories(categories, relevance_scores)
|
| 866 |
-
|
| 867 |
-
# 2. 지식그래프 구축
|
| 868 |
-
self.knowledge_graph.build_from_space(self.space, cross_layer_bonus)
|
| 869 |
-
|
| 870 |
-
self._initialized = True
|
| 871 |
-
self.results["initialization"] = {
|
| 872 |
-
"n_ideas": n_placed,
|
| 873 |
-
"n_dimensions": self.space.n_dims,
|
| 874 |
-
"n_graph_nodes": len(self.knowledge_graph.nodes),
|
| 875 |
-
}
|
| 876 |
-
return n_placed
|
| 877 |
-
|
| 878 |
-
def run(self, n_samples: int = DEFAULT_SAMPLE_SIZE,
|
| 879 |
-
k_way: int = 2,
|
| 880 |
-
max_brute_force: int = MAX_BRUTE_FORCE_COMBOS,
|
| 881 |
-
explore_ratio: float = 0.3) -> List[Combination]:
|
| 882 |
-
"""전체 파이프라인 실행
|
| 883 |
-
|
| 884 |
-
Args:
|
| 885 |
-
n_samples: 최종 출력 조합 수
|
| 886 |
-
k_way: 조합 크기 (2-way, 3-way 등)
|
| 887 |
-
max_brute_force: 전수 탐색 최대 조합 수
|
| 888 |
-
explore_ratio: 볼츠만 탐색 비율
|
| 889 |
-
|
| 890 |
-
Returns:
|
| 891 |
-
창발성 판정 완료된 최종 조합 리스트 (점수 내림차순)
|
| 892 |
-
"""
|
| 893 |
-
assert self._initialized, "먼저 initialize()를 호출하세요."
|
| 894 |
-
start_time = time.time()
|
| 895 |
-
|
| 896 |
-
# Step (a): 브루트포스 전수 탐색
|
| 897 |
-
logger.info("━━ Step (a): 브루트포스 전수 탐색 ━━")
|
| 898 |
-
all_combinations = self.explorer.enumerate_all_combinations(
|
| 899 |
-
k=k_way, max_combos=max_brute_force, cross_layer_only=True
|
| 900 |
-
)
|
| 901 |
-
self.results["brute_force"] = {"total_combinations": len(all_combinations)}
|
| 902 |
-
|
| 903 |
-
if not all_combinations:
|
| 904 |
-
logger.warning("전수 탐색 결과 없음")
|
| 905 |
-
return []
|
| 906 |
-
|
| 907 |
-
# Step (d): 교차 융합 보너스 적용 (스코어에 이미 반영됨)
|
| 908 |
-
logger.info("━━ Step (d): 교차 융합 보너스 매트릭스 적용 ━━")
|
| 909 |
-
# (이미 enumerate_all_combinations 내부에서 fusion_bonus 계산됨)
|
| 910 |
-
|
| 911 |
-
# Step (b): 볼츠만 분포 확률적 샘플링
|
| 912 |
-
logger.info("━━ Step (b): 볼츠만 분포 확률적 샘플링 ━━")
|
| 913 |
-
sampled = self.sampler.adaptive_sample(
|
| 914 |
-
all_combinations, n_samples=n_samples * 2, explore_ratio=explore_ratio
|
| 915 |
-
)
|
| 916 |
-
self.results["boltzmann_sampling"] = {
|
| 917 |
-
"temperature": self.sampler.temperature,
|
| 918 |
-
"input_count": len(all_combinations),
|
| 919 |
-
"sampled_count": len(sampled),
|
| 920 |
-
}
|
| 921 |
-
|
| 922 |
-
# Step (c): 지식그래프 미발견 경로로 조합 보강
|
| 923 |
-
logger.info("━━ Step (c): 지식그래프 미발견 경로 탐색 ━━")
|
| 924 |
-
hidden_paths = self.knowledge_graph.discover_hidden_paths(max_hops=3, max_paths=200)
|
| 925 |
-
sampled = self.knowledge_graph.enrich_combinations(sampled)
|
| 926 |
-
self.results["knowledge_graph"] = {"hidden_paths_found": len(hidden_paths)}
|
| 927 |
-
|
| 928 |
-
# [종속항3] 엔트로피 기반 다양성 보장
|
| 929 |
-
logger.info("━━ 엔트로피 기반 다양성 보장 ━━")
|
| 930 |
-
sampled, final_entropy = self.diversity_guard.ensure_diversity(sampled, all_combinations)
|
| 931 |
-
self.results["entropy"] = self.diversity_guard.get_diversity_report(sampled)
|
| 932 |
-
|
| 933 |
-
# Step (e): 창발성 임계점 판정
|
| 934 |
-
logger.info("━━ Step (e): 창발성 임계점 판정 ━━")
|
| 935 |
-
judged = self.judge.judge_batch(sampled, self.space)
|
| 936 |
-
|
| 937 |
-
# 창발 발현 조합만 필터 + 점수순 정렬
|
| 938 |
-
emergent_combos = [
|
| 939 |
-
combo for combo, result in judged if result.is_emergent
|
| 940 |
-
]
|
| 941 |
-
emergent_combos.sort(
|
| 942 |
-
key=lambda c: c.complexity * (c.score + c.fusion_bonus), reverse=True
|
| 943 |
-
)
|
| 944 |
-
|
| 945 |
-
# 최종 n_samples개 선택
|
| 946 |
-
final = emergent_combos[:n_samples]
|
| 947 |
-
|
| 948 |
-
elapsed = time.time() - start_time
|
| 949 |
-
self.results["summary"] = {
|
| 950 |
-
"total_time_sec": round(elapsed, 2),
|
| 951 |
-
"input_ideas": self.space.total_ideas,
|
| 952 |
-
"brute_force_combos": len(all_combinations),
|
| 953 |
-
"boltzmann_sampled": len(sampled),
|
| 954 |
-
"emergent_combos": len(emergent_combos),
|
| 955 |
-
"final_output": len(final),
|
| 956 |
-
"emergence_rate": f"{len(emergent_combos) / max(len(sampled), 1) * 100:.1f}%",
|
| 957 |
-
}
|
| 958 |
-
|
| 959 |
-
logger.info(
|
| 960 |
-
f"🎯 MAIA 창발성 엔진 완료: {self.space.total_ideas}개 아이디어 → "
|
| 961 |
-
f"{len(all_combinations)}개 조합 → {len(emergent_combos)}개 창발 → "
|
| 962 |
-
f"최종 {len(final)}개 (소요시간: {elapsed:.1f}초)"
|
| 963 |
-
)
|
| 964 |
-
|
| 965 |
-
return final
|
| 966 |
-
|
| 967 |
-
def get_results_summary(self) -> Dict:
|
| 968 |
-
"""실행 결과 요약"""
|
| 969 |
-
return self.results
|
| 970 |
-
|
| 971 |
-
def format_for_llm_prompt(self, combinations: List[Combination], top_n: int = 30) -> str:
|
| 972 |
-
"""LLM 프롬프트용 창발적 조합 텍스트 포맷팅
|
| 973 |
-
|
| 974 |
-
기존 app.py의 researcher_comprehensive_chunked()에 전달할 창발 후보 텍스트
|
| 975 |
-
"""
|
| 976 |
-
lines = [f"■■■ MAIA 창발성 엔진 출력 (상위 {min(top_n, len(combinations))}개) ■■■\n"]
|
| 977 |
-
for i, combo in enumerate(combinations[:top_n], 1):
|
| 978 |
-
layers = ", ".join(sorted(combo.layers_involved))
|
| 979 |
-
lines.append(f"[창발 #{i:02d}] 복잡도={combo.complexity:.3f} | 레이어: {layers}")
|
| 980 |
-
lines.append(f" 조합: {combo.description}")
|
| 981 |
-
lines.append(f" 융합 보너스: {combo.fusion_bonus:.3f} | 창발 수준: {combo.emergence_level}")
|
| 982 |
-
if combo.graph_paths:
|
| 983 |
-
lines.append(f" 지식그래프 경로: {len(combo.graph_paths)}개 미발견 경로")
|
| 984 |
-
lines.append("")
|
| 985 |
-
return "\n".join(lines)
|
| 986 |
-
|
| 987 |
-
|
| 988 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 989 |
-
# 10. 편의 함수 (기존 코드 연동용)
|
| 990 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 991 |
-
|
| 992 |
-
def run_emergence_engine(categories, relevance_scores: Dict,
|
| 993 |
-
cross_layer_bonus: Dict = None,
|
| 994 |
-
temperature: float = 1.0,
|
| 995 |
-
threshold: float = 0.65,
|
| 996 |
-
n_output: int = 50) -> Tuple[List[Combination], Dict]:
|
| 997 |
-
"""원스텝 실행 함수 (기존 app.py에서 호출용)
|
| 998 |
-
|
| 999 |
-
Usage:
|
| 1000 |
-
from emergence_engine import run_emergence_engine
|
| 1001 |
-
combos, report = run_emergence_engine(categories, relevance_scores,
|
| 1002 |
-
CROSS_LAYER_EMERGENCE_BONUS)
|
| 1003 |
-
prompt_text = engine.format_for_llm_prompt(combos)
|
| 1004 |
-
"""
|
| 1005 |
-
engine = MAIAEmergenceEngine(
|
| 1006 |
-
temperature=temperature,
|
| 1007 |
-
emergence_threshold=threshold,
|
| 1008 |
-
)
|
| 1009 |
-
engine.initialize(categories, relevance_scores, cross_layer_bonus)
|
| 1010 |
-
results = engine.run(n_samples=n_output)
|
| 1011 |
-
return results, engine.get_results_summary()
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 1015 |
-
# 11. 셀프테스트
|
| 1016 |
-
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 1017 |
-
|
| 1018 |
-
def _self_test():
|
| 1019 |
-
"""엔진 셀프테스트 (categories.py 없이 독립 실행)"""
|
| 1020 |
-
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
| 1021 |
-
|
| 1022 |
-
# 테스트용 더미 데이터
|
| 1023 |
-
from dataclasses import dataclass as dc
|
| 1024 |
-
|
| 1025 |
-
@dc
|
| 1026 |
-
class DummyCat:
|
| 1027 |
-
name_ko: str; name_en: str; items: list; layer: str; layer_description: str = ""
|
| 1028 |
-
|
| 1029 |
-
test_categories = [
|
| 1030 |
-
DummyCat("센서 기능", "Sensor", ["압력센서", "온도��서", "가속도센서", "라이다", "초음파센서"], "INPUT"),
|
| 1031 |
-
DummyCat("AI 및 ML", "AI/ML", ["트랜스포머", "RAG", "연합학습", "강화학습", "지식그래프"], "TRANSFORMATION"),
|
| 1032 |
-
DummyCat("시스템 제어", "Control", ["PID제어", "퍼지제어", "강건제어", "적응제어"], "CONTROL"),
|
| 1033 |
-
DummyCat("제조 방식", "Fabrication", ["3D프린팅", "레이저가공", "사출성형", "CNC가공"], "FABRICATION"),
|
| 1034 |
-
DummyCat("환경 상호작용", "Environment", ["대기정화", "수질정화", "탄소포집", "재활용"], "CONTEXT"),
|
| 1035 |
-
DummyCat("에너지 관리", "Energy", ["배터리", "태양전지", "연료전지", "에너지하베스팅", "무선충전"], "VALUE"),
|
| 1036 |
-
]
|
| 1037 |
-
|
| 1038 |
-
test_scores = {}
|
| 1039 |
-
for cat in test_categories:
|
| 1040 |
-
items_scores = {item: 0.3 + 0.5 * (i / len(cat.items)) for i, item in enumerate(cat.items)}
|
| 1041 |
-
test_scores[cat.name_ko] = {
|
| 1042 |
-
"category_score": 0.6,
|
| 1043 |
-
"items": items_scores,
|
| 1044 |
-
"layer": cat.layer,
|
| 1045 |
-
}
|
| 1046 |
-
|
| 1047 |
-
print("=" * 60)
|
| 1048 |
-
print("MAIA 창발성 발현 엔진 셀프테스트")
|
| 1049 |
-
print("=" * 60)
|
| 1050 |
-
|
| 1051 |
-
engine = MAIAEmergenceEngine(temperature=1.0, emergence_threshold=0.55)
|
| 1052 |
-
n = engine.initialize(test_categories, test_scores)
|
| 1053 |
-
print(f"\n배치 완료: {n}개 아이디어")
|
| 1054 |
-
|
| 1055 |
-
results = engine.run(n_samples=20, k_way=2)
|
| 1056 |
-
print(f"\n최종 창발 조합: {len(results)}개")
|
| 1057 |
-
|
| 1058 |
-
for i, combo in enumerate(results[:5], 1):
|
| 1059 |
-
print(f"\n[#{i}] {combo.description}")
|
| 1060 |
-
print(f" 복잡도={combo.complexity:.3f} | 레이어={combo.n_layers}개 | "
|
| 1061 |
-
f"수준={combo.emergence_level} | 점수={combo.score:.3f}")
|
| 1062 |
-
|
| 1063 |
-
print("\n" + "=" * 60)
|
| 1064 |
-
summary = engine.get_results_summary()
|
| 1065 |
-
for key, val in summary.items():
|
| 1066 |
-
print(f" {key}: {val}")
|
| 1067 |
-
|
| 1068 |
-
# 융합 보너스 매트릭스 출력
|
| 1069 |
-
print("\n교차 융합 보너스 매트릭스:")
|
| 1070 |
-
print(engine.fusion_matrix)
|
| 1071 |
-
|
| 1072 |
-
# 다양성 보고서
|
| 1073 |
-
report = engine.diversity_guard.get_diversity_report(results)
|
| 1074 |
-
print(f"\n엔트로피: {report['entrop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