import logging
import random
import numpy as np
import pymc as pm
from scipy.stats import binom, truncnorm
from ..agents.box_loop_helper import construct_dataframe
from .goal import Goal
from .parsing import parse_int_prediction
logger = logging.getLogger(__name__)
class DirectDeath(Goal):
ppl_direct_predictive_mode = "rounded_int"
ppl_observation_names = ("y_obs", "infected_num")
def __init__(self, env):
super().__init__(env)
self.eval_points = []
self.eval_pointer = 0
self.update_param_cache = {}
# Recomputed v2_2026-01-27: median of 5 seeds [42,123,456,789,101112]
# Previous: (222.2998, 189.7685) — confirmed correct, minor update
self.norm_mu, self.norm_sigma = (223.3291, 190.6460)
def get_system_message(self, include_prior):
if include_prior:
goal_description = "Your goal is to be able to reliably predict the number of infected individuals at specific times. Conduct experiments to learn about the environment and make predictions based on your observations."
else:
goal_description = "Your goal is to be able to reliably predict the positive integer output of the environment for different float inputs. Conduct experiments to learn about the environment and make predictions based on your observations."
description = self.env.get_system_message(include_prior, goal_description)
return description
def get_goal_eval_question(self, include_prior):
if self.eval_pointer + 1 > len(self.eval_points):
# Generate a time value greater than 0 and up to the upper limit
time = np.random.uniform(self.env.lower_bound + 0.001, self.env.upper_bound)
infected_num = self.env.step(time)
self.eval_points.append((time, infected_num))
else:
time, infected_num = self.eval_points[self.eval_pointer]
self.eval_pointer += 1
if include_prior:
question = f"What is the number of infected individuals at time {time}?"
else:
question = f"What is the output of the environment at input {time}?"
question += " Respond with a positive integer."
return question, infected_num
def evaluate_predictions(self, predictions, measurements):
parsed_predictions = []
for pred in predictions:
parsed_predictions.append(parse_int_prediction(pred))
mse = np.mean((np.array(parsed_predictions) - np.array(measurements)) ** 2)
std = np.std((np.array(parsed_predictions) - np.array(measurements)) ** 2)
return (mse, std)
def expected_information_gain(self, query_point, num_outer_samples=1000, num_inner_samples=10):
xi = query_point
existing_data = self.env.observation_data
if tuple(existing_data) not in self.update_param_cache:
# Update the parameter prior using PyMC
with pm.Model() as model:
theta = pm.TruncatedNormal(
"theta",
mu=self.env.mu,
sigma=self.env.sigma,
lower=self.env.lower_bound,
upper=self.env.upper_bound,
)
# Define the likelihood function
def likelihood(xi, infected_num):
eta = 1 - pm.math.exp(-theta * xi)
return pm.Binomial("infected_num", n=self.env.N, p=eta, observed=infected_num)
xi_obs = pm.Data("xi_obs", [d[0] for d in existing_data])
infected_num_obs = pm.Data("infected_num_obs", [d[1] for d in existing_data])
likelihood(xi_obs, infected_num_obs)
trace = pm.sample(
num_outer_samples * num_inner_samples + num_outer_samples,
tune=1000,
return_inferencedata=False,
)
thetas = trace["theta"]
random.shuffle(thetas)
updated_theta_samples = thetas[:num_outer_samples]
logger.debug("trace samples: %d", len(trace["theta"]))
logger.debug("updated theta samples: %d", len(updated_theta_samples))
logger.debug("inferred theta: %.4f", np.mean(updated_theta_samples))
self.update_param_cache[tuple(existing_data)] = (
updated_theta_samples,
thetas[num_outer_samples:],
)
else:
updated_theta_samples, thetas = self.update_param_cache[tuple(existing_data)]
log_likelihoods = []
for n, outer_theta in enumerate(updated_theta_samples):
# Calculate the log-likelihood for the new query point only
eta = 1 - np.exp(-outer_theta * xi)
inner_theta_samples = thetas[n * num_inner_samples : (n + 1) * num_inner_samples]
sampled_infected_num = np.random.binomial(self.env.N, eta)
preds = [1 for _ in range(sampled_infected_num)] + [
0 for _ in range(self.env.N - sampled_infected_num)
]
log_liks = [np.log(eta) if pred == 1 else np.log(1 - eta) for pred in preds]
log_likelihood = np.mean(log_liks)
# Calculate the marginal log-likelihood for the new query point only
marginal_log_likelihoods = []
for inner_theta in inner_theta_samples:
eta = 1 - np.exp(-inner_theta * xi)
marginal_log_likelihood = [
np.log(eta) if pred == 1 else np.log(1 - eta) for pred in preds
]
marginal_log_likelihood = np.mean(marginal_log_likelihood)
marginal_log_likelihoods.append(marginal_log_likelihood)
# Use the log-sum-exp trick for numerical stability
max_log = np.max(marginal_log_likelihoods)
log_marginal_likelihood = max_log + np.log(
np.mean(np.exp(np.array(marginal_log_likelihoods) - max_log))
)
log_likelihoods.append(log_likelihood - log_marginal_likelihood)
# Calculate the EIG for the new query point
eig_value = np.mean(log_likelihoods)
return eig_value
def get_norm_factors(self):
N = 10000
errs = []
outs = []
measurements = []
for _ in range(N):
self.env.reset()
sampled_input = self.env.sample_random_input()
out = self.env.step(sampled_input)
outs.append(out)
mu = np.mean(outs)
predicitons = [str(mu) for _ in range(N)]
mean_err, std_err = self.evaluate_predictions(predicitons, outs)
return mean_err, std_err
class DirectDeathNaive(DirectDeath):
def __init__(self, env):
super().__init__(env)
self.eval_points = []
self.eval_pointer = 0
def get_system_message(self, include_prior):
goal_description = "Your goal is to conduct experiments and explain the environment to the user so that they can achieve their goal."
if include_prior:
goal_description += "The goal of the user is to reliably predict the number of infected individuals at specific times. Conduct experiments to learn about the environment."
else:
goal_description += "The goal of the user is to reliably predict the positive integer output of the environment for different float inputs. Conduct experiments to learn about the environment."
description = self.env.get_system_message(include_prior, goal_description)
return description
def get_naive_system_message(self, include_prior):
if include_prior:
goal_description = (
"Your goal is to predict the number of infected individuals at specific times."
)
else:
goal_description = "Your goal is to predict the positive integer output of the environment for different float inputs."
format_instructions = """You must respond with a positive integer. You may also think before providing your predictions.
Here is an example:
your thought
1 your thought
0.1(time to observe)
When asked to answer a question about the environement, respond in the format specified in the question.
your thought
your answer
"""
else:
message = f"""You are observing a positive integer (with a maximum value of {self.N}) for a positive real input.
{goal}
The input must be greater than {self.lower_bound} and less than {self.upper_bound}.
Here is an example:
your thought
0.1
When asked to answer a question about the environement, respond in the format specified in the question.
your thought
your answer
"""
return message
def sample_random_input(self):
return np.random.uniform(self.lower_bound, self.upper_bound)
def step(self, xi):
# print(f"Theta: {self.theta}")
# print(f"Xi: {xi}")
eta = 1 - np.exp(-self.theta * xi)
infected_num = binom.rvs(self.N, eta)
return infected_num
def validate_input(self, input_string):
try:
act = float(input_string.strip())
except ValueError:
return "Error: The input must be a float."
if act <= self.lower_bound:
return f"Error: The input must be greater than {self.lower_bound}."
if act >= self.upper_bound:
return f"Error: The input must be less than the {self.upper_bound}."
# obs_times = [d[0] for d in self.observation_data]
# print(obs_times)
# max_time = max(obs_times) if obs_times else self.lower_bound
# if act <= max_time:
# return "Error: The input must be greater than the previous observation."
# print(f"Validated input: {act}")
return act
def run_experiment(self, input_string):
xi = self.validate_input(input_string)
if type(xi) == str:
return xi, False
# Run the simulation for each xi value
infected_num = self.step(xi)
self.observation_data.append((xi, infected_num))
return infected_num, True
def get_data(self):
return self.observation_data
def get_df(self):
"""
Construct dataframe used for Box's Loop
"""
self.df = construct_dataframe(self)
def get_description(self):
if self.include_prior:
return f"""
There is a disease spreading in a population of {self.N} individuals.
"""
else:
return f"""
You are observing a positive integer (with a maximum value of {self.N}) for a positive real input.
"""
def describe_data_columns(self):
return self.format_column_description()
def get_ordered_column_names(self):
if self.include_prior:
return ["Time", "Infected_Count"]
else:
return ["Input", "Output"]
def get_ordered_features(self):
return self.get_ordered_column_names()[:-1]
def format_column_description(self):
"""Keep descriptions consistent with ordered column names."""
if self.include_prior:
return (
"The observations are: \n -Infected_Count: number of infected people at time x \n"
"The input values are \n -Time: time \n"
"Use the values of the input values to help you model the observations. "
)
else:
return (
"The observations are: \n -Output \n"
"The input values are \n -Input \n"
"Use the values of the input values to help you model the observations. "
)
if __name__ == "__main__":
env = DeathProcess()
goal = DirectDeath(env)
print(goal.get_norm_factors())
# goal2 = InfectionRate(env)
# print(goal2.get_norm_factors())
# input_string = "0.1"
# print(env.run_experiment(input_string))
# # input_string = "1"
# # print(env.run_experiment(input_string))
# # input_string = "1.5"
# # print(env.run_experiment(input_string))
# # check eig
# inp_range = np.linspace(0.1, 2, 20)
# eig_values = []
# for inp in inp_range:
# eig = goal.expected_information_gain(inp)
# eig_values.append(eig)
# print(eig)
# print(eig_values)
# # plot
# import matplotlib.pyplot as plt
# plt.plot(inp_range, eig_values)
# plt.xlabel("Input")
# plt.ylabel("Expected Information Gain")
# plt.title("Expected Information Gain for Different Inputs")
# plt.show()