更改

第283行: 第283行:     
== 由布尔网络生成TPM的代码 ==
 
== 由布尔网络生成TPM的代码 ==
−
这里提供了基于有效信息计算的因果涌现的python代码,以供参考:https://github.com/KellyPPeng/effective-information-calculation
+
python:<syntaxhighlight lang="python3">
 +
import numpy as np
 +
import networkx as nx
   −
代码包括两部分:第一部分上述实例的实现,即给定微观机制和粗粒化方案,分别在状态空间和变量空间计算因果涌现;第二部分是参考https://github.com/jkbren/einet,提供的使用贪婪算法和谱分解方法,在微观转移概率矩阵中学出最优粗粒化方案,算法实现步骤拆解可参考[[复杂网络中的因果涌现]]。
+
def bool2tpm(G, noise_prob=0.3):
 +
def update_state(node, state, G, noise_prob):
 +
"""
 +
result:该节点下一时刻状态返回为1的概率
 +
"""
 +
 
 +
predecessors = list(G.predecessors(node))
 +
pred_state = [state[nodes.index(pred)] for pred in predecessors]
 +
 
 +
result = 1
 +
for val in pred_state:
 +
result &= val  # AND
 +
 
 +
if result < 1:
 +
result += noise_prob  # 带噪音的AND门
 +
 
 +
return result
 +
 
 +
# 构建布尔网络的状态空间
 +
nodes = list(G.nodes())
 +
num_nodes = len(nodes)
 +
state_space = list(np.array(np.meshgrid(*[[0, 1]] * num_nodes)).T.reshape(-1, num_nodes))
 +
 
 +
# 计算TPM
 +
num_states = len(state_space)
 +
TPM = np.zeros((num_states, num_states))
 +
for idx, state in enumerate(state_space):
 +
p1 = np.zeros((1, num_nodes))
 +
 
 +
# 为每个节点更新下一时刻为1的概率p1
 +
for node in nodes:
 +
p1[0, nodes.index(node)] = update_state(node, state, G, noise_prob)
 +
 
 +
for next_idx, next_state in enumerate(state_space):
 +
TrueP = p1 * next_state + (1-p1) * (1-next_state)
 +
TPM[idx, next_idx] = np.prod(TrueP)
 +
 
 +
# 归一化TPM
 +
TPM /= TPM.sum(axis=1, keepdims=True)
 +
return TPM
 +
 
 +
 
 +
# 创建布尔网络
 +
G = nx.DiGraph()
 +
G.add_nodes_from(['A', 'B', 'C', 'D'])
 +
G.add_edges_from([('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'A'), ('C', 'B'), ('D', 'A'), ('D', 'B')])
 +
TPM = bool2tpm(G, noise_prob=0.3)
 +
</syntaxhighlight>
    
== 应用 ==
 
== 应用 ==
5,443

个编辑