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
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
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:
<thought>your thought</thought>
<answer>1</answer
"""
        description = goal_description + "\n" + format_instructions
        description += "Here is what you know about the enivronment:\n"
        return description

    def get_comm_prompt(
        self,
        include_prior,
        com_limit=300,
        use_ppl=False,
        str_prob_prog=None,
        params_summary_str=None,
    ):
        description = f"""Assume that the user has no prior knowledge, and will not be able to run any experiments before making predictions. 
They will make predictions based solely on your explanation, so provide as much detail as possible. You cannot provide your own experiments or observations.
Limit your explanation to {com_limit} words."""

        if use_ppl:
            description += "To make your explanation clearer and more informative, look at the statistical model (written in pymc) designed by a colleague for the experimental data and the inferred parameters.\n"
            description += f"Here is the statistical model.\n{str_prob_prog}\n"
            description += f"Here are the inferred params.\n{params_summary_str}\n"
            description += "Don't literally describe the model verbatim but use it to conceptually motivate your explanation."
            description += "The agent will not be able to use the model explicitly but having a conceptual understanding will be beneficial."
        return description


class InfectionRate(Goal):
    ppl_parameter_mode = "positive_scalar"
    ppl_parameter_primary_names = ("theta", "log_theta")
    ppl_parameter_exponentiated_names = ("log_theta",)
    ppl_parameter_name_hints = ("theta",)

    def __init__(self, env):
        super().__init__(env)
        self.eval_points = []
        self.eval_pointer = 0
        self.update_param_cache = {}
        self.norm_mu, self.norm_sigma = (0.2902838787350395, 1.756991075450312)

    def get_system_message(self, include_prior):
        if include_prior:
            goal_description = "Your goal is to be able to reliably predict the infection rate of the disease. Conduct experiments to learn about the environment and make predictions based on your observations. The infection rate is a positive real number. It is the rate at which healthy individuals become infected. Specifically, probability of a person being infected is proportional to 1-exp(-theta*x), where theta is the infection rate and x is the time."
        else:
            goal_description = "Your goal is to be able to reliably predict the latent parameter theta that governs the system's outputs. Conduct experiments to learn about the environment and make predictions based on your observations. Theta is a positive real number."
        description = self.env.get_system_message(include_prior, goal_description)
        return description

    def get_goal_eval_question(self, include_prior):
        if include_prior:
            question = "What is the infection rate?"
        else:
            question = "What is the latent parameter theta?"
        question += " Respond with a positive real number."
        return question, self.env.theta

    def evaluate_predictions(self, predictions, measurements):
        parsed_predictions = []
        for pred in predictions:
            parsed_predictions.append(float(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)

                if len(existing_data) == 0:
                    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,
                    chains=2,
                    cores=2,
                    target_accept=0.95,
                )

            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 = 100000
        errs = []
        preds = []
        measurements = []
        for _ in range(N):
            self.env.reset()
            sampled_infection_rate = np.random.normal(self.env.mu, scale=self.env.sigma)
            true_infection_rate = self.env.theta
            preds.append(sampled_infection_rate)
            errs.append(np.mean((sampled_infection_rate - true_infection_rate) ** 2))
            measurements.append(true_infection_rate)
        pred_mu = np.mean(preds)
        predicitons = [str(pred_mu) for _ in range(N)]
        mean_err, _ = self.evaluate_predictions(predicitons, measurements)
        stds = np.std(errs)
        return mean_err, stds


class DeathProcess:
    def __init__(self, N=50, mu=1, sigma=1, lower_bound=0):
        self.mu = mu
        self.sigma = sigma
        self.lower_bound = lower_bound
        # TODO: Set upper bound based on the mu and sigma values
        self.upper_bound = 2
        self.N = N
        self.reset()
        self.env_name = "death_process"

    def reset(self):
        a, b = (self.lower_bound - self.mu) / self.sigma, (self.upper_bound - self.mu) / self.sigma
        self.theta = truncnorm(a, b, loc=self.mu, scale=self.sigma).rvs()
        self.observation_data = []

    def get_system_message(self, include_prior=True, goal=None):
        assert goal is not None, "Please provide a goal for the task."
        if include_prior:
            message = f"""There is a disease spreading in a population of {self.N} individuals. 
{goal}
Make observations by querying how many healthy individuals are infected at a specific time (positive real numbers). You cannot query at time 0. Please specify the observation time as real number. The input time must be greater than {self.lower_bound} and less than {self.upper_bound}.

Here is an example:
<thought> your thought </thought>
<observe>0.1(time to observe)</observe>
When asked to answer a question about the environement, respond in the format specified in the question.
<thought> your thought </thought>
<answer> your answer </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:
<thought> your thought </thought>
<observe>0.1</observe>
When asked to answer a question about the environement, respond in the format specified in the question.
<thought> your thought </thought>
<answer> your answer </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()