import pandas as pd
import numpy as np
import statsmodels.api as sm
import lingam
import pyvis
from lingam.utils import make_dot, print_causal_directions, print_dagc
from graphviz import Digraph
from math import log10, floor
from decimal import Decimal, ROUND_HALF_UP
import matplotlib.pyplot as plt
plt.style.use('ggplot') #グラフのスタイル
plt.rcParams['figure.figsize'] = [12, 9] # グラフサイズ設定

# # データセット読み込み
# path = 'datasets/short_tukizimatome.csv'
# df = pd.read_csv(path,
#                  parse_dates=True,
#                  index_col='day',
#                  encoding="utf-8"
#                 )
# df #確認
path = 'C:/Users/Owner/OneDrive - 富山県立大学/研究室/flask/csv/fusion_data_forVARLiNGAM.csv'
df = pd.read_csv(path,
                 parse_dates=True,
                 index_col='データ日付',
                 encoding="cp932"
                )
df #確認

#
# VAR-LiNGAMの構築
#
# インスタンス生成
model = lingam.VARLiNGAM(lags=3, prune=True)
# 学習
model.fit(df)

#
# 係数行列の推定結果
#

model.adjacency_matrices_

import pandas as pd
# data = np.array([
#     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# ])
data_list = []
for i in range(len(df.columns)):
    data_list.append(model.adjacency_matrices_[0][i])
dfd=pd.DataFrame(data_list)
dfd=dfd.set_axis([df.columns],axis=0)
dfd=dfd.set_axis([df.columns],axis='columns')
dfd
# df_causal = pd.DataFrame({f'{col}(t)':data_list for i, col in zip(data_list,df.columns)})
# df_causal = df.T         #{'金利(t)':data_list[0],
# dfd

p_values = model.get_error_independence_p_values()
print(p_values)
labels = [f'{col}(t)' for i, col in enumerate(df.columns)]+[f'{col}(t-1)' for i,col in enumerate(df.columns)]
model = lingam.VARLiNGAM()
result = model.bootstrap(df, n_sampling=100)

cdc = result.get_causal_direction_counts(n_directions=8, min_causal_effect=0.3, split_by_causal_effect_sign=True)

print_causal_directions(cdc, 100, labels=labels)

dagc = result.get_directed_acyclic_graph_counts(n_dags=3, min_causal_effect=0.2, split_by_causal_effect_sign=True)

print_dagc(dagc, 100, labels=labels)

prob = result.get_probabilities(min_causal_effect=0.1)
print('Probability of B0:\n', prob[0])
print('Probability of B1:\n', prob[1])

causal_effects = result.get_total_causal_effects(min_causal_effect=0.01)
df = pd.DataFrame(causal_effects)

df['from'] = df['from'].apply(lambda x : labels[x])
df['to'] = df['to'].apply(lambda x : labels[x])
df

df = df.sort_values('effect', ascending=False)

def kyoki_word_network():
    from pyvis.network import Network
    import pandas as pd

    #got_net = Network(height="500px", width="100%", bgcolor="#222222", font_color="white", notebook=True)
    got_net = Network(height="1000px", width="95%", bgcolor="#FFFFFF", font_color="black", notebook=True,directed=True)
    # set the physics layout of the network
    #got_net.barnes_hut()
    got_net.force_atlas_2based()
    got_data = pd.read_csv("csv/kekka.csv")[:1000]

    sources = got_data['from']#count
    targets = got_data['to']#first
    weights = got_data['effect']#second

    edge_data = zip(sources, targets, weights)

    for e in edge_data:
        src = e[0]
        dst = e[1]
        w = e[2]
        w=round(w,4)
        if w < 0 :
            color='red'
        elif w > 0:
            color='blue'
        got_net.add_node(src, src, title=src)
        got_net.add_node(dst, dst, title=dst)
        w=str(w)
        got_net.add_edge(src, dst, color=color,label=w)
    neighbor_map = got_net.get_adj_list()

    # add neighbor data to node hover data
    for node in got_net.nodes:
        node["title"] += " Neighbors:<br>" + "<br>".join(neighbor_map[node["id"]])
        node["value"] = len(neighbor_map[node["id"]])

    got_net.show_buttons(filter_=['physics'])
    return got_net
network = kyoki_word_network()
network.show('your_network.html')