"""
Language models as proposal generators
======================================

Large language models know many scientific laws and can propose plausible
equation skeletons from a description of the variables; a numerical optimizer
then fits the constants (Merler et al., 2024; Shojaee et al., 2025). eqdisco
supports this through a *proposer*: any function that maps a prompt to text.
Here the proposer is offline -- :class:`~eqdisco.TemplateProposer` answers with
templates of enzyme kinetics -- so the example runs anywhere; a real model is
plugged in the same way (see the last section). Proposals are parsed by a
whitelist parser and are never executed.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

rng = np.random.default_rng(6)
S = np.sort(rng.uniform(0.05, 5, 30))
v = 2.0 * S / (0.6 + S) * (1 + 0.02 * rng.normal(size=30))
X = S.reshape(-1, 1)

# %%
# An offline proposer and the guided loop
# ---------------------------------------
templates = ["c0*x0", "c0*x0/(c1 + x0)", "c0*(1 - exp(-c1*x0))", "c0*x0^c1", "c0*log(1 + c1*x0)", "c0*x0^2/(c1 + x0^2)", "c0*x0/(c1 + x0 + c2*x0^2)"]
proposer = eq.TemplateProposer(templates, n=3, random_state=1)
llm = eq.LLMGuidedRegressor(proposer, n_iterations=5, n_proposals=3, feature_names=["S"],
                            description="initial rate of an enzyme reaction as a function of the substrate concentration",
                            variable_descriptions={"S": "substrate concentration, mmol/L"})
llm.fit(X, v)
print(llm.equation_)
print(llm.prompts_[0][:500])
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
axs[0].step(llm.history_["iteration"], llm.history_["best_mse"], where="post", color="#285780")
axs[0].set_yscale("log")
axs[0].set_xlabel("iteration")
axs[0].set_ylabel("best MSE in the pool")
s = np.linspace(0, 5, 200).reshape(-1, 1)
axs[1].scatter(S, v, color="#6B7785", s=15, label="data")
for k, e in enumerate(llm.pareto_front_[-3:]):
    axs[1].plot(s, e.predict(s), color=eq.viz.OKABE_ITO[k], lw=1.4, label=str(e)[:34])
axs[1].legend(frameon=False, fontsize=7)
axs[1].set_xlabel("S")
fig.tight_layout()

# %%
# Combining proposals with genetic programming
# --------------------------------------------
# The same proposer can feed a genetic-programming run: every ``llm_interval``
# generations its proposals are fitted and injected into the population.
sr = eq.SymbolicRegressor(population_size=150, generations=10, llm_proposer=proposer, llm_interval=3, feature_names=["S"], random_state=0).fit(X, v)
print("GP with proposals:", sr.equation_)

# %%
# Plugging in a real language model
# ---------------------------------
# Any client works; for example with the Anthropic SDK (not run here)::
#
#     import anthropic
#     client = anthropic.Anthropic()
#     def proposer(prompt):
#         msg = client.messages.create(model="claude-sonnet-5-5", max_tokens=400,
#                                      messages=[{"role": "user", "content": prompt}])
#         return msg.content[0].text
#     eq.LLMGuidedRegressor(proposer, n_iterations=10).fit(X, v)

# %%
# Parameter study: proposals per iteration
# ----------------------------------------
fig, ax = plt.subplots(figsize=(4.5, 3))
for k, n in enumerate((1, 3, 6)):
    m = eq.LLMGuidedRegressor(eq.TemplateProposer(templates, n=n, random_state=3), n_iterations=6, n_proposals=n).fit(X, v)
    print(f"{n} proposals per iteration: final best MSE {m.history_['best_mse'].iloc[-1]:.2e}")
    ax.step(m.history_["iteration"], m.history_["best_mse"], where="post", color=eq.viz.OKABE_ITO[k], label=f"{n} per iteration")
ax.set_yscale("log")
ax.set_xlabel("iteration")
ax.set_ylabel("best MSE")
ax.legend(frameon=False, fontsize=8)
plt.show()
