#!/usr/bin/env python3
import math
train_result = __import__('HMM_train_result')
print(train_result.B['B']['终'] / train_result.SUM_B['B'])
print(train_result.B['M']['终'] / train_result.SUM_B['M'])
print(train_result.B['E']['终']/ train_result.SUM_B['E'])
print(train_result.B['S']['终']/ train_result.SUM_B['S'])

inputstr = '习近平指出，中国欧盟构建和平、增长、改革、文明四大伙伴关系的共识正在落地生根。双方在重大国际事务上保持着战略对话，共同为改善全球经济治理、促进世界可持续发展作出了积极努力，在加强中欧各自发展战略对接方面达成重要共识并付诸行动。中欧双方要不断深化互利共赢的全面战略伙伴关系。'
d = {}#当前状态
d_1 = {}#上一状态
status = train_result.Pi.keys()
print(status)

w = inputstr[0]
for s in status:
    try:

        d_1[s] = train_result.Pi[s] / train_result.SUM_Pi * train_result.B[s][w] / train_result.SUM_B[s]*100
    except:
        d_1[s] = 1e-10


def FindMax(d):
    keys = tuple(d.keys())
    max_key = 'S'
    max_v = d[max_key]
    for i in keys:
        if d[i] > max_v:
            max_v = d[i]
            max_key = i
            
    return (max_key,max_v)

result = FindMax(d_1)
r2 = result[0]
print(result[0],end = '')

d = {}
d_t = {}#临时存储前一状态到当前状态的概率，确定前一状态对应下一状态

Psi = []#路径矩阵
P_0 =  1e-10#概率为0时取得概率

for w in inputstr[1:]:
    Psi_t = {}

    for s in status:#现在新的状态
        for s1 in status:#之前是哪一个状态转移过来的

            try:
                #print('前一状态：%s 概率 d_1[s1] = %e \n转移概率%s->%s : %lf\n 输出\'%s\'概率：%lf'\
                #%(s1,d_1[s1],s1,s,train_result.A[s1 + s]/ train_result.SUM_A,w,train_result.B[s][w] / train_result.SUM_B[s]))
                d_t[s1] = d_1[s1] * train_result.A[s1 + s] / train_result.SUM_A* train_result.B[s][w] / train_result.SUM_B[s]*10000
            except:
                d_t[s1] = P_0
        #print('状态转移 到 %s' %(s))
        #print(d_t)
        result = FindMax(d_t)
        d[s] = result[1]
        Psi_t[s] = result[0] 
    #print('到达状态的概率')
    #print(d)

    result = FindMax(d)
    r2 += result[0]
    #print(result[0],end = '')
    d_1 = d
    Psi.append(Psi_t)

#找出最后一个结果的最大值
result = FindMax(d)
r = [result[0]]
lasts = result[0]
for i in range(len(Psi)-1,-1,-1):
    lasts = Psi[i][lasts]
    r.append(lasts)
r.reverse()
ret = ''.join(r)
print('')
for i in range(len(r2)):
    if r2[i]== 'E' or r2[i]=='S':
        print(inputstr[i],end=' ')
    else:
        print(inputstr[i],end='')
print('')
print(ret)

for i in range(len(ret)):
    if ret[i]== 'E' or ret[i]=='S':
        print(inputstr[i],end=' ')
    else:
        print(inputstr[i],end='')
#for w in inputstr:
