更改

第432行: 第432行:  
== 代码实现 ==
 
== 代码实现 ==
 
这里分别针对状态空间和变量空间的因果涌现实例,提供了python代码实现的参考。
 
这里分别针对状态空间和变量空间的因果涌现实例,提供了python代码实现的参考。
 +
 +
python:<syntaxhighlight lang="python3">
 +
import torch
 +
 +
def Entropia(a):
 +
    b = torch.nonzero(a > 0).squeeze(1)
 +
    return -torch.sum(a[b]*torch.log2(a[b]))
 +
 +
 +
def effective_information(G1):
 +
    """
 +
    Calculate EI value of transition probability matrix
 +
    G1: TPM matrix
 +
    return the EI value
 +
    """
 +
    N = G1.shape[0]
 +
    G = torch.zeros_like(G1)
 +
    nozero_number = 0
 +
    for i in range(N):
 +
        if torch.sum(G1[i]) != 0:
 +
            G[i] = G1[i] / torch.sum(G1[i])
 +
            nozero_number += 1
 +
    Wout = torch.zeros(N)
 +
    Win = torch.zeros(N)
 +
 +
    for i in range(N):
 +
        if torch.sum(G[i]) != 0:
 +
            Wout[i] = torch.tensor(Entropia(G[i]))
 +
 +
    for i in range(N):
 +
        for j in range(N):
 +
            if G[i][j] != 0:
 +
                Win[j] += G[i][j] / nozero_number
 +
    Wout_average = torch.sum(Wout) / nozero_number
 +
    Win_entropy = Entropia(Win)
 +
    return Win_entropy - Wout_average
 +
 +
 +
def calc_tpm(micro_tpm, group):
 +
    """
 +
    Parameters
 +
    ----------
 +
    micro_tpm: the transition probability matrix of system in micro level.
 +
    group: the coarse-graining methods (e.g., group = [(0, 1, 2), (3,)]: the micro states 0,1,2 are grouped into macro state 0, and the micro state 3 is grouped into macro state 1.
 +
 +
    Returns
 +
    -------
 +
    micro_ei, macro_ei: the EI value of micro, macro TPM.
 +
    macro_tpm: the transition probability matrix of system in macro level
 +
 +
   
 +
    """
 +
    # the number of micro/macro states
 +
    Nmi = micro_tpm.shape[0]
 +
    Nma = len(group)
 +
   
 +
    # generate the mapping matrix from micro to macro
 +
    mapping = torch.zeros((Nmi, Nma), dtype=torch.float)
 +
    for j in range(Nma):
 +
        for i in group[j]:
 +
            mapping[i][j] = 1
 +
 +
    # apply the mapping matrix to micro_tpm, and get the macro_tpm
 +
    macro_tpm = mapping.t() @ micro_tpm @ mapping
 +
 +
    # calculate the EI of micro_tpm, macro_tpm
 +
    micro_ei = effective_information(micro_tpm)
 +
    macro_ei = effective_information(macro_tpm)
 +
 +
    return micro_ei, macro_ei, macro_tpm
 +
 +
 +
micro_tpm = torch.tensor([[1/3, 1/3, 1/3, 0], [1/3, 1/3, 1/3, 0], [1/3, 1/3, 1/3, 0], [0, 0, 0, 1]])
 +
group = [(0, 1, 2), (3,)]
 +
micro_ei, macro_ei, macro_tpm = calc_tpm(micro_tpm, group)
 +
</syntaxhighlight>
    
== 应用 ==
 
== 应用 ==
5,443

个编辑