# main.py
import logging
import time
import random
import json
from collections import deque
from conscious_system import MemorySystem, UnconsciousLayer, PreconsciousLayer, ConsciousLayer, Stimulus, ConsciousState
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('MainSimulation')
class BiologicalStateSimulator:
"""模拟生物状态随时间变化"""
def __init__(self):
self.state = {
"sensor_acuity": 0.9, # 感官敏锐度 (0.0-1.0)
"arousal_level": 0.7, # 觉醒水平 (0.0-1.0)
"fatigue": 0.3, # 疲劳度 (0.0-1.0)
"stress": 0.2, # 压力水平 (0.0-1.0)
"nutrition": 0.8, # 营养水平 (0.0-1.0)
"hydration": 0.9 # 水分水平 (0.0-1.0)
}
self.history = deque(maxlen=100)
self.last_update = time.time()
def update(self):
"""更新生物状态"""
current_time = time.time()
time_diff = current_time - self.last_update
# 随时间自然变化
self.state["fatigue"] = min(1.0, self.state["fatigue"] + 0.01 * (time_diff / 10))
self.state["sensor_acuity"] = max(0.5, self.state["sensor_acuity"] - 0.005 * (time_diff / 10))
self.state["arousal_level"] = max(0.3, self.state["arousal_level"] - 0.003 * (time_diff / 10))
# 营养和水分随时间减少
self.state["nutrition"] = max(0.3, self.state["nutrition"] - 0.002 * (time_diff / 10))
self.state["hydration"] = max(0.4, self.state["hydration"] - 0.003 * (time_diff / 10))
# 如果疲劳度高,压力也会增加
if self.state["fatigue"] > 0.6:
self.state["stress"] = min(1.0, self.state["stress"] + 0.01 * (time_diff / 10))
# 记录历史
self.history.append({
"timestamp": current_time,
"state": self.state.copy()
})
self.last_update = current_time
return self.state
def apply_event(self, event_type: str, intensity: float):
"""应用外部事件影响生物状态"""
if event_type == "rest":
self.state["fatigue"] = max(0.0, self.state["fatigue"] - 0.2 * intensity)
self.state["arousal_level"] = min(1.0, self.state["arousal_level"] + 0.1 * intensity)
elif event_type == "meal":
self.state["nutrition"] = min(1.0, self.state["nutrition"] + 0.3 * intensity)
self.state["hydration"] = min(1.0, self.state["hydration"] + 0.2 * intensity)
elif event_type == "exercise":
self.state["fatigue"] = min(1.0, self.state["fatigue"] + 0.3 * intensity)
self.state["stress"] = max(0.0, self.state["stress"] - 0.2 * intensity)
elif event_type == "stressful_event":
self.state["stress"] = min(1.0, self.state["stress"] + 0.4 * intensity)
self.state["arousal_level"] = min(1.0, self.state["arousal_level"] + 0.2 * intensity)
logger.info(f"生物状态事件: {event_type}(强度:{intensity})")
return self.state
def generate_stimulus_sequence(sequence_length: int = 20) -> list:
"""生成多样化的刺激序列"""
stimuli = []
stimulus_types = [
("视觉", "外部", "场景"),
("听觉", "外部", "声音"),
("触觉", "外部", "感觉"),
("内部", "内部", "想法"),
("情感", "内部", "情绪"),
("记忆", "内部", "回忆"),
("威胁", "外部", "危险"),
("机会", "外部", "奖励")
]
emotional_valences = [-0.9, -0.7, -0.5, -0.3, 0.0, 0.3, 0.5, 0.7, 0.9]
intensities = [0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
for i in range(sequence_length):
# 随机选择刺激类型
stype = random.choice(stimulus_types)
content = f"{stype[2]}刺激 #{i + 1}"
# 创建刺激
stimulus = Stimulus(
content=content,
intensity=random.choice(intensities),
emotional_valence=random.choice(emotional_valences),
source=stype[1],
category=stype[0]
)
# 添加额外属性
stimulus.associations = [f"关联{i}", f"标签{random.randint(1, 5)}"]
stimulus.priority = random.uniform(0.3, 0.95)
stimuli.append(stimulus)
return stimuli
# 更新后的刺激处理循环
for i in range(len(stimuli)):
bio_state = bio_simulator.update()
stimulus = stimuli[i]
# 通过协调器处理刺激
processing_result = coordinator.process_stimulus(
stimulus=stimulus,
biological_state=bio_state
)
if processing_result["reached_consciousness"]:
conscious_output = processing_result["conscious_output"]
# 记录到报告...
# 主动回忆通过协调器
if i % 4 == 0:
recalled = coordinator.deliberate_recall(keyword, max_results=4)
# 获取完整报告
if i % 5 == 0:
full_report = coordinator.get_system_report()
# 添加意识流数据
stream_report = coordinator.get_consciousness_stream(
last_n=5,
summary=True
)
full_report["consciousness_stream"] = stream_report
def simulate_consciousness():
"""模拟意识系统运行"""
# 更新后的初始化部分
logger.info("初始化意识系统...")
# 初始化记忆系统
from .memory.memory_system import MemorySystem
memory_system = MemorySystem()
# 初始化各层次
from .layers.unconscious import UnconsciousLayer
from .layers.preconscious import PreconsciousLayer
from .layers.conscious import ConsciousLayer
unconscious_layer = UnconsciousLayer(memory_system)
preconscious_layer = PreconsciousLayer(memory_system)
conscious_layer = ConsciousLayer(memory_system)
# 初始化协调器
from .conscious_layer import ConsciousSystemCoordinator
coordinator = ConsciousSystemCoordinator(
unconscious_layer=unconscious_layer,
preconscious_layer=preconscious_layer,
conscious_layer=conscious_layer,
memory_system=memory_system
)
# 初始化生物状态模拟器
bio_simulator = BiologicalStateSimulator()
logger.info("意识系统初始化完成")
# 生成刺激序列
stimuli = generate_stimulus_sequence(30)
# 添加一些预定义的刺激
predefined_stimuli = [
Stimulus("A beautiful sunset over the mountains", 0.7, 0.8, "external", "visual"),
Stimulus("Loud crash from the kitchen", 0.9, -0.6, "external", "auditory"),
Stimulus("Remember mom's birthday tomorrow", 0.6, 0.5, "internal", "reminder"),
Stimulus("Danger! Snake in the garden!", 1.0, -0.9, "external", "threat"),
Stimulus("I should learn a new programming language", 0.5, 0.4, "internal", "thought"),
Stimulus("Dream about flying over the city", 0.3, 0.2, "internal", "dream")
]
stimuli.extend(predefined_stimuli)
# 模拟生命事件序列
life_events = deque([
(5, "rest", 0.8), # 休息
(10, "meal", 0.9), # 进餐
(15, "stressful_event", 0.7), # 压力事件
(20, "exercise", 0.6), # 锻炼
(25, "rest", 0.7) # 休息
])
# 报告收集
simulation_reports = []
# 处理刺激序列
for i in range(len(stimuli)):
logger.info(f"\n===== 处理周期 {i + 1} =====")
# 更新生物状态
bio_state = bio_simulator.update()
logger.info(f"当前生物状态: {json.dumps(bio_state, indent=2)}")
# 检查是否应用生命事件
if life_events and life_events[0][0] == i:
_, event_type, intensity = life_events.popleft()
bio_simulator.apply_event(event_type, intensity)
# 选择刺激
stimulus = stimuli[i]
logger.info(f"接收刺激: {stimulus}")
# 前意识层处理
elevated = preconscious.receive_stimulus(stimulus)
if elevated:
logger.info(f"刺激提升到意识层 (优先级: {elevated.get('priority', 0.5):.2f})")
# 意识层处理,传入生物状态
result = conscious.process_input(elevated, bio_state)
# 提取关键信息
state = result.get("state", "UNKNOWN")
attention = result.get("attention", [])[:3]
workload = result.get("workload", {}).get("cognitive_load", 0.0)
logger.info(f"意识层处理结果: 状态={state}, 注意力={attention}, 认知负荷={workload:.2f}")
# 详细记录
report = {
"cycle": i + 1,
"stimulus": str(stimulus),
"state": state,
"attention": attention,
"cognitive_load": workload,
"biological_state": bio_state.copy(),
"timestamp": time.time()
}
simulation_reports.append(report)
else:
logger.info("刺激未达到意识阈值")
# 模拟主动回忆
if i % 4 == 0:
keywords = ["danger", "learn", "beautiful", "memory", "dream", "threat"]
keyword = random.choice(keywords)
recalled = conscious.deliberate_recall(keyword, max_results=4)
logger.info(f"主动回忆 '{keyword}': {recalled}")
# 添加回忆任务报告
recall_report = {
"cycle": i + 1,
"type": "recall",
"keyword": keyword,
"results": recalled,
"timestamp": time.time()
}
simulation_reports.append(recall_report)
# 每5个周期获取一次详细报告
if i % 5 == 0:
conscious_report = conscious.get_consciousness_report()
logger.info(f"意识层状态报告:\n{json.dumps(conscious_report, indent=2)}")
# 添加报告到模拟记录
report_entry = {
"cycle": i + 1,
"type": "full_report",
"report": conscious_report,
"timestamp": time.time()
}
simulation_reports.append(report_entry)
# 记忆衰减
memory_system.decay_memories()
# 随机睡眠模拟时间流逝
sleep_time = random.uniform(0.5, 1.5)
time.sleep(sleep_time)
# 关闭系统
unconscious.shutdown()
shutdown_data = conscious.shutdown()
logger.info(f"意识系统已安全关闭: {json.dumps(shutdown_data, indent=2)}")
# 保存模拟报告
with open("simulation_report.json", "w") as f:
json.dump(simulation_reports, f, indent=2)
logger.info("模拟报告已保存到 simulation_report.json")
return simulation_reports
def analyze_simulation_report(report: list):
"""分析模拟报告"""
if not report:
logger.warning("没有可分析的报告数据")
return
# 收集关键指标
states = []
cognitive_loads = []
attention_changes = 0
high_load_cycles = []
for entry in report:
if entry.get("type") == "full_report":
# 分析完整报告
r = entry["report"]
states.append(r["state"])
# 分析工作负载
workload = r["workload"]["cognitive_load"]
cognitive_loads.append(workload)
if workload > 0.8:
high_load_cycles.append(entry["cycle"])
# 分析注意力变化
attention_history = r["attention"]["history"]
if len(attention_history) > 1:
attention_changes += len(attention_history)
# 输出分析结果
logger.info("\n===== 模拟分析结果 =====")
logger.info(f"总周期数: {len(report)}")
logger.info(f"最常见的意识状态: {max(set(states), key=states.count)}")
logger.info(f"平均认知负荷: {sum(cognitive_loads) / len(cognitive_loads):.2f}")
logger.info(f"高认知负荷周期: {high_load_cycles}")
logger.info(f"注意力变化次数: {attention_changes}")
# 状态分布
state_dist = {}
for state in states:
state_dist[state] = state_dist.get(state, 0) + 1
logger.info(f"状态分布: {state_dist}")
if __name__ == "__main__":
simulation_report = simulate_consciousness()
analyze_simulation_report(simulation_report)
这样改对吗