<jupyter_start><jupyter_text>RCD  Import and settingsIn this example, we need to import `numpy`, `pandas`, and `graphviz` in addition to `lingam`.<jupyter_code>import numpy as np
import pandas as pd
import graphviz
import lingam
from lingam.utils import print_causal_directions, print_dagc, make_dot

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

np.set_printoptions(precision=3, suppress=True)<jupyter_output>['1.16.2', '0.24.2', '0.11.1', '1.5.2']<jupyter_text>Test dataFirst, we generate a causal structure with 7 variables. Then we create a dataset with 5 variables from x0 to x4, with x5 and x6 being the latent variables.<jupyter_code>np.random.seed(0)

get_external_effect = lambda n: np.random.normal(0.0, 0.5, n) ** 3
n_samples = 300

x5 = get_external_effect(n_samples)
x6 = get_external_effect(n_samples)
x1 = 0.6*x5 + get_external_effect(n_samples)
x3 = 0.5*x5 + get_external_effect(n_samples)
x0 = 1.0*x1 + 1.0*x3 + get_external_effect(n_samples)
x2 = 0.8*x0 - 0.6*x6 + get_external_effect(n_samples)
x4 = 1.0*x0 - 0.5*x6 + get_external_effect(n_samples)

# The latent variable x6 is not included.
X = pd.DataFrame(np.array([x0, x1, x2, x3, x4, x5]).T, columns=['x0', 'x1', 'x2', 'x3', 'x4', 'x5'])

X.head()
m = np.array([[ 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0],
              [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.6, 0.0],
              [ 0.8, 0.0, 0.0, 0.0, 0.0, 0.0,-0.6],
              [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0],
              [ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0,-0.5],
              [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
              [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]])
dot = make_dot(m, labels=['x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'f1(x6)'])

# Save pdf
dot.render('dag')

# Save png
dot.format = 'png'
dot.render('dag')

dot<jupyter_output><empty_output><jupyter_text>Causal DiscoveryTo run causal discovery, we create a `RCD` object and call the `fit` method.<jupyter_code>model = lingam.RCD()
model.fit(X)<jupyter_output><empty_output><jupyter_text>Using the `ancestors_list_` properties, we can see the list of ancestors sets as a result of the causal discovery.<jupyter_code>ancestors_list = model.ancestors_list_

for i, ancestors in enumerate(ancestors_list):
    print(f'M{i}={ancestors}')<jupyter_output>M0={1, 3, 5}
M1={5}
M2={0, 1, 3, 5}
M3={5}
M4={0, 1, 3, 5}
M5=set()<jupyter_text>Also, using the `adjacency_matrix_` properties, we can see the adjacency matrix as a result of the causal discovery. The coefficients between variables with latent confounders are np.nan.<jupyter_code>model.adjacency_matrix_
make_dot(model.adjacency_matrix_)<jupyter_output><empty_output><jupyter_text>Independence between error variablesTo 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$.<jupyter_code>p_values = model.get_error_independence_p_values(X)
print(p_values)<jupyter_output>[[0.    0.      nan 0.413   nan 0.68 ]
 [0.    0.      nan 0.732   nan 0.382]
 [  nan   nan 0.      nan   nan   nan]
 [0.413 0.732   nan 0.      nan 0.054]
 [  nan   nan   nan   nan 0.      nan]
 [0.68  0.382   nan 0.054   nan 0.   ]]<jupyter_text>BootstrappingWe call `bootstrap()` method instead of `fit()`. Here, the second argument specifies the number of bootstrap sampling.<jupyter_code>import warnings
warnings.filterwarnings('ignore', category=UserWarning)

model = lingam.RCD()
result = model.bootstrap(X, n_sampling=100)<jupyter_output><empty_output><jupyter_text>Causal DirectionsSince `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.01 or more.<jupyter_code>cdc = result.get_causal_direction_counts(n_directions=8, min_causal_effect=0.01, split_by_causal_effect_sign=True)<jupyter_output><empty_output><jupyter_text>We can check the result by utility function.<jupyter_code>print_causal_directions(cdc, 100)<jupyter_output>x0 <--- x1 (b>0) (100.0%)
x4 <--- x0 (b>0) (99.0%)
x1 <--- x5 (b>0) (97.0%)
x2 <--- x0 (b>0) (96.0%)
x0 <--- x3 (b>0) (92.0%)
x3 <--- x5 (b>0) (67.0%)
x2 <--- x4 (b>0) (13.0%)
x4 <--- x3 (b<0) (11.0%)<jupyter_text>Directed Acyclic GraphsAlso, 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.01 or more.<jupyter_code>dagc = result.get_directed_acyclic_graph_counts(n_dags=3, min_causal_effect=0.01, split_by_causal_effect_sign=True)<jupyter_output><empty_output><jupyter_text>We can check the result by utility function.<jupyter_code>print_dagc(dagc, 100)<jupyter_output>DAG[0]: 47.0%
	x0 <--- x1 (b>0)
	x0 <--- x3 (b>0)
	x1 <--- x5 (b>0)
	x2 <--- x0 (b>0)
	x3 <--- x5 (b>0)
	x4 <--- x0 (b>0)
DAG[1]: 20.0%
	x0 <--- x1 (b>0)
	x0 <--- x3 (b>0)
	x1 <--- x5 (b>0)
	x2 <--- x0 (b>0)
	x4 <--- x0 (b>0)
DAG[2]: 10.0%
	x0 <--- x1 (b>0)
	x0 <--- x3 (b>0)
	x1 <--- x5 (b>0)
	x2 <--- x0 (b>0)
	x3 <--- x5 (b>0)
	x4 <--- x0 (b>0)
	x4 <--- x3 (b<0)<jupyter_text>ProbabilityUsing the `get_probabilities()` method, we can get the probability of bootstrapping.<jupyter_code>prob = result.get_probabilities(min_causal_effect=0.01)
print(prob)<jupyter_output>[[0.   1.   0.   0.92 0.   0.08]
 [0.   0.   0.   0.   0.   0.97]
 [0.96 0.   0.   0.   0.13 0.  ]
 [0.   0.   0.   0.   0.   0.67]
 [0.99 0.01 0.02 0.12 0.   0.  ]
 [0.   0.   0.   0.   0.   0.  ]]<jupyter_text>Total Causal EffectsUsing the `get_total_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.<jupyter_code>causal_effects = result.get_total_causal_effects(min_causal_effect=0.01)

# Assign to pandas.DataFrame for pretty display
df = pd.DataFrame(causal_effects)
labels = [f'x{i}' for i in range(X.shape[1])]
df['from'] = df['from'].apply(lambda x : labels[x])
df['to'] = df['to'].apply(lambda x : labels[x])
df<jupyter_output>C:\Users\AA005431\OneDrive - SCREEN Holdings Co., Ltd\code\as\lingam\v1.5.2\get_causal_effects\lingam\bootstrap.py:305: RuntimeWarning: invalid value encountered in greater
  min_causal_effect, 1, 0), axis=0, keepdims=True)[0]
C:\Users\AA005431\OneDrive - SCREEN Holdings Co., Ltd\code\as\lingam\v1.5.2\get_causal_effects\lingam\bootstrap.py:315: RuntimeWarning: invalid value encountered in greater
  idx = np.where(np.abs(self._total_effects[:, to, from_]) > 0)<jupyter_text>We can easily perform sorting operations with pandas.DataFrame.<jupyter_code>df.sort_values('effect', ascending=False).head()
df.sort_values('probability', ascending=True).head()<jupyter_output><empty_output><jupyter_text>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.<jupyter_code>import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
%matplotlib inline

from_index = 5 # index of x5
to_index = 0 # index of x0
plt.hist(result.total_effects_[:, to_index, from_index])<jupyter_output>C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\histograms.py:824: RuntimeWarning: invalid value encountered in greater_equal
  keep = (tmp_a >= first_edge)
C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\histograms.py:825: RuntimeWarning: invalid value encountered in less_equal
  keep &= (tmp_a <= last_edge)
{'fraction_non_alphanumeric': 0.1438676266262473, 'fraction_numerical': 0.0618921308576481, 'mean_word_length': 4.254147312541473, 'pattern_counts': {'":': 0, '<': 82, '<?xml version=': 0, '>': 79, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '171867', 'license': 'MIT', 'n_tokens_mistral': 3372, 'n_tokens_neox': 3104, 'n_words': 825, 'path': 'examples/RCD.ipynb', 'repo_name': 'Koji-Kurihara/lingam', 'size': '7917'}