"""
The size of the search space and the meaning of complexity
==========================================================

Why is equation discovery hard? The number of distinct expressions grows
exponentially with their size. :func:`~eqdisco.models.enumerate_expressions`
counts the canonical expressions -- with commutative arguments ordered and
constant-only subtrees merged -- for two variables and growing function sets.
The second part compares the complexity measures of
:func:`eqdisco.fitness.complexity` on a few textbook formulas: node count,
weighted node count, and the recursive measure of Kommenda et al. (2015), which
charges nested nonlinear functions much more than additions.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.fitness import complexity
from eqdisco.models import enumerate_expressions

# %%
# Counting expressions
# --------------------
sets = {"+ x": ("add", "mul"), "+ x -": ("add", "sub", "mul", "div"), "+ x - / exp log": ("add", "sub", "mul", "div", "exp", "log")}
counts = {}
for label, funcs in sets.items():
    pset = eq.PrimitiveSet(2, funcs)
    sizes = [e.size for e in enumerate_expressions(pset, max_size=7, max_params=3)]
    counts[label] = np.bincount(sizes)[1:]
    print(label, counts[label])
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
for k, (label, c) in enumerate(counts.items()):
    axs[0].semilogy(np.arange(1, len(c) + 1), np.maximum(c, 1), "o-", color=eq.viz.OKABE_ITO[k], label=label)
axs[0].set_xlabel("expression size (nodes)")
axs[0].set_ylabel("canonical expressions")
axs[0].legend(frameon=False, fontsize=8, title="function set", title_fontsize=8)

# %%
# Complexity measures
# -------------------
formulas = ["x0 + x1", "x0*x1", "x0^2 + x1^2", "sqrt(x0^2 + x1^2)", "exp(-x0)*x1", "sin(x0*x1)", "exp(sin(x0*x1))"]
kinds = ["size", "weighted", "recursive"]
table = np.array([[complexity(eq.Expression.from_string(f), k) for k in kinds] for f in formulas])
w = 0.27
for j, k in enumerate(kinds):
    axs[1].barh(np.arange(len(formulas)) + (j - 1) * w, table[:, j] / table[:, j].max(), height=w, color=eq.viz.OKABE_ITO[j], label=k)
axs[1].set_yticks(range(len(formulas)))
axs[1].set_yticklabels(formulas, fontsize=8)
axs[1].set_xlabel("complexity (relative to the largest)")
axs[1].legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# Parameter study: the maximum number of parameters
# -------------------------------------------------
# Every constant leaf is a free parameter. Limiting their number prunes the space
# considerably.
pset = eq.PrimitiveSet(2, ("add", "sub", "mul", "div"))
n_by_p = [len(enumerate_expressions(pset, 7, max_params=p)) for p in range(4)]
print("expressions up to size 7 with at most p parameters, p = 0..3:", n_by_p)
fig, ax = plt.subplots(figsize=(3.8, 2.8))
ax.bar(range(4), n_by_p, color="#285780")
ax.set_xlabel("maximum number of parameters")
ax.set_ylabel("expressions up to size 7")
plt.show()
