"""
Building blocks and variable interactions
=========================================

Which subtrees does the search keep reusing, and which variables does it combine
nonlinearly? The frequent subtrees of a final population form a co-occurrence
network (:func:`~eqdisco.analysis.building_block_network`), and the joint
occurrence of variables under nonlinear functions a variable interaction network
in the spirit of Kronberger et al. (2011). The target is Vladislavleva-7,
:math:`(x-3)(y-3)+2\\sin((x-4)(y-4))`.
"""

import matplotlib.pyplot as plt

import eqdisco as eq
from eqdisco.analysis import building_block_network, frequent_building_blocks, variable_interaction_network

prob = eq.datasets.get_problem("vladislavleva-7")
X = prob.X_train
import numpy as np  # noqa: E402

X3 = np.column_stack([X, np.random.default_rng(0).uniform(0, 6, len(X))])  # an irrelevant third input z
sr = eq.SymbolicRegressor(population_size=400, generations=30, functions=("add", "sub", "mul", "sin"), feature_names=["x", "y", "z"], random_state=0).fit(X3, prob.y_train)

# %%
# Frequent blocks of the final population
# ---------------------------------------
pop = sr.population_[:200]
print(frequent_building_blocks(pop, min_support=0.25).head(8))
G = building_block_network(pop, min_support=0.2, min_lift=1.05)
V = variable_interaction_network(pop)
print({e: round(d["weight"], 2) for e, d in ((tuple(sorted(e)), V.edges[e]) for e in V.edges)})
fig, axs = plt.subplots(1, 2, figsize=(11, 4.4), gridspec_kw={"width_ratios": [1.5, 1]})
eq.viz.plot_building_blocks(G, ax=axs[0])
axs[0].set_title("frequent building blocks (area: support; edges: lift)", fontsize=9)
eq.viz.plot_variable_interactions(V, ax=axs[1])
axs[1].set_title("variable interaction network", fontsize=9)
fig.tight_layout()

# %%
# Parameter study: minimum support
# --------------------------------
sups = [0.05, 0.1, 0.2, 0.4]
print("min support", sups, "blocks", [building_block_network(pop, min_support=s).number_of_nodes() for s in sups])
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(sups, [building_block_network(pop, min_support=s).number_of_nodes() for s in sups], "o-", color="#285780")
ax.set_xlabel("minimum support")
ax.set_ylabel("building blocks")
plt.show()
