import numpy as np
import pandas as pd
import graphviz
import lingam
from lingam.utils import make_dot, print_causal_directions, print_dagc

print([np.__version__, pd.__version__, graphviz.__version__, lingam.__version__])

np.set_printoptions(precision=3, suppress=True)
np.random.seed(0)

"""
Explanation: VARLiNGAM
Import and settings
In this example, we need to import numpy, pandas, and graphviz in addition to lingam.
End of explanation
"""


B0 = [
    [0,-0.12,0,0,0],
    [0,0,0,0,0],
    [-0.41,0.01,0,-0.02,0],
    [0.04,-0.22,0,0,0],
    [0.15,0,-0.03,0,0],
]
B1 = [
    [-0.32,0,0.12,0.32,0],
    [0,-0.35,-0.1,-0.46,0.4],
    [0,0,0.37,0,0.46],
    [-0.38,-0.1,-0.24,0,-0.13],
    [0,0,0,0,0],
]
causal_order = [1, 0, 3, 2, 4]

# data generated from B0 and B1
X = pd.read_csv('data/sample_data_var_lingam.csv')

"""
Explanation: Test data
We create test data consisting of 5 variables.
End of explanation
"""


model = lingam.VARLiNGAM()
model.fit(X)

"""
Explanation: Causal Discovery
To run causal discovery, we create a VARLiNGAM object and call the fit method.
End of explanation
"""


model.causal_order_

"""
Explanation: Using the causal_order_ properties, we can see the causal ordering as a result of the causal discovery.
End of explanation
"""


# B0
model.adjacency_matrices_[0]

# B1
model.adjacency_matrices_[1]

model.residuals_

"""
Explanation: Also, using the adjacency_matrices_ properties, we can see the adjacency matrix as a result of the causal discovery.
End of explanation
"""


dlingam = lingam.DirectLiNGAM()
dlingam.fit(model.residuals_)
dlingam.adjacency_matrix_

"""
Explanation: Using DirectLiNGAM for the residuals_ properties, we can calculate B0 matrix.
End of explanation
"""


labels = ['x0(t)', 'x1(t)', 'x2(t)', 'x3(t)', 'x4(t)', 'x0(t-1)', 'x1(t-1)', 'x2(t-1)', 'x3(t-1)', 'x4(t-1)']
make_dot(np.hstack(model.adjacency_matrices_), ignore_shape=True, lower_limit=0.05, labels=labels)

"""
Explanation: We can draw a causal graph by utility funciton.
End of explanation
"""


p_values = model.get_error_independence_p_values()
print(p_values)

"""
Explanation: Independence between error variables
To check if the LiNGAM assumption is broken, we can get p-values of independence between error variables. The value in the i-th row and j-th column of the obtained matrix shows the p-value of the independence of the error variables $e_i$ and $e_j$.
End of explanation
"""


model = lingam.VARLiNGAM()
result = model.bootstrap(X, n_sampling=100)

"""
Explanation: Bootstrap
Bootstrapping
We call bootstrap() method instead of fit(). Here, the second argument specifies the number of bootstrap sampling.
End of explanation
"""


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

"""
Explanation: Causal Directions
Since BootstrapResult object is returned, we can get the ranking of the causal directions extracted by get_causal_direction_counts() method. In the following sample code, n_directions option is limited to the causal directions of the top 8 rankings, and min_causal_effect option is limited to causal directions with a coefficient of 0.3 or more.
End of explanation
"""


print_causal_directions(cdc, 100, labels=labels)

"""
Explanation: We can check the result by utility function.
End of explanation
"""


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

"""
Explanation: Directed Acyclic Graphs
Also, using the get_directed_acyclic_graph_counts() method, we can get the ranking of the DAGs extracted. In the following sample code, n_dags option is limited to the dags of the top 3 rankings, and min_causal_effect option is limited to causal directions with a coefficient of 0.2 or more.
End of explanation
"""


print_dagc(dagc, 100, labels=labels)

"""
Explanation: We can check the result by utility function.
End of explanation
"""


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

"""
Explanation: Probability
Using the get_probabilities() method, we can get the probability of bootstrapping.
End of explanation
"""


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

"""
Explanation: Total Causal Effects
Using the get_causal_effects() method, we can get the list of total causal effect. The total causal effects we can get are dictionary type variable.
We can display the list nicely by assigning it to pandas.DataFrame. Also, we have replaced the variable index with a label below.
End of explanation
"""


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

"""
Explanation: We can easily perform sorting operations with pandas.DataFrame.
End of explanation
"""


df[df['to']=='x1(t)'].head()

"""
Explanation: And with pandas.DataFrame, we can easily filter by keywords. The following code extracts the causal direction towards x1(t).
End of explanation
"""


import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
%matplotlib inline

from_index = 7 # index of x2(t-1). (index:2)+(n_features:5)*(lag:1) = 7
to_index = 2 # index of x2(t). (index:2)+(n_features:5)*(lag:0) = 2
plt.hist(result.total_effects_[:, to_index, from_index])

"""
Explanation: Because it holds the raw data of the total causal effect (the original data for calculating the median), it is possible to draw a histogram of the values of the causal effect, as shown below.
End of explanation
"""


