import numpy as np
from ergodic import dag, estimate_contrast, identify_effect, tabular
from ergodic.inference import ContinuousDR

rng = np.random.default_rng(17)
n = 6000
z = rng.uniform(-1, 1, n)
dose = 0.3 * z + rng.normal(size=n)
response = 1.5 * dose + dose**2 + 0.5 * dose * z + z + rng.normal(0, 0.15, n)
context = tabular({"dose": dose, "z": z, "response": response})
graph = dag(["z -> dose", "z -> response", "dose -> response"])

linear = estimate_contrast(
    graph, context, "dose", "response",
    baseline=-0.5, value=1, method="partially_linear", random_state=0,
)
print(f"partially linear: {linear.value:.2f}")

identified = identify_effect(graph, "dose", "response")
fitted = ContinuousDR(random_state=0).fit(identified, context)
average = fitted.contrast(baseline=-0.5, value=1)
print(f"continuous DR: {average.value:.2f}")
print(f"bandwidth: {average.diagnostics['bandwidth']:.3f}")

# Query rows need only the adjustment covariates, not dose or response.
rows = tabular({"z": [-0.5, 0.0, 0.5]})
effects = fitted.effects(rows, baseline=-0.5, value=1)
print("conditional effects:", np.round(effects.values, 2))
print("true conditional effects:", np.array([2.625, 3.0, 3.375]))
print("query interval available:", effects.std_error is not None)
