1: import jax
2: import jax.numpy as np
3: import numpy as np1
4: from jax.scipy.special import logsumexp
5: import cvxpy as cp
6: import matplotlib.pyplot as plt
7: from scipy.stats import beta, norm
8: from collections import Counter
9: import os
10: 
11: ############OUR MODEL:
12: 
13: def _simulate_singlekey(x, key, params):
14: 
15:     # ENVIRONMENT:
16: 
17:     key, subkey = jax.random.split(key)
18:     events = jax.random.uniform(subkey, shape=(x.size,))
19:     events = events < x
20:     #print("Events:", events)
21:     """     
22:     jax.debug.print("Events: {}", events)
23:     jax.debug.print("Size (Events): {}", events.shape)
24:     jax.debug.print("\n") 
25:     
26:     """
27: 
28:     key, subkey = jax.random.split(key)
29:     events_time = params['mean_event_times']  # Tn
30:     #events_time = jax.random.exponential(subkey, shape=(x.size,)) * events_time
31:     
32:     #mean_event_times = params['mean_event_times']  # Shape (1, 2), e.g., [mean_disease1, mean_disease2]
33: 
34:     # Compute the scale as 1 / mean_event_times
35:     #scale = 1 / mean_event_times
36: 
37:     events_time = events_time + 3 * jax.random.normal(subkey, shape=(x.size,))
38:     events_time = np.where(events, events_time, np.inf)
39:     #print("Event times:", events_time)
40:     """ jax.debug.print("Event times: {}", events_time)
41:     jax.debug.print("Size (Event times): {}", events_time.shape)
42:     jax.debug.print("\n") """
43: 
44:     key, subkey = jax.random.split(key)
45:     death_time = params['mean_death_time']
46:     #death_time = death_time + .1 * jax.random.normal(subkey)
47:     #print("Death times:", death_time)
48:     """ jax.debug.print("Death times: {}", death_time)
49:     jax.debug.print("Size (Death times): {}", death_time.shape)
50:     jax.debug.print("\n")
51:      """
52:     #tau_k = jax.random.randint(key, shape=(2,), minval=1, maxval=6)
53:     tau_k = params['sampling_freq']
54:     SAMPLE_STD = .5
55:     key, subkey = jax.random.split(key)
56:     samples = events[:,None] + SAMPLE_STD * jax.random.normal(subkey, shape=params['sample_sizes'].shape)
57:     #samples = samples * delta_k 
58:     #print("Samples (y):", samples)
59:     """ jax.debug.print("Samples (y): {}", samples)
60:     jax.debug.print("Size (Samples): {}", samples.shape)
61:     jax.debug.print("\n") """
62: 
63: 
64:     # AGENT:
65: 
66:     _log_prior = np.stack((np.log(x), np.log(1-x)), axis=0)
67:     _log_likelihoods = np.stack((
68:         np.cumsum(-.5 * ((samples - 1) / SAMPLE_STD)**2, axis=-1),
69:         np.cumsum(-.5 * (samples / SAMPLE_STD)**2, axis=-1)), axis=0)
70:     _log_posteriors = np.concatenate((_log_prior[:,:,None], _log_prior[:,:,None] + _log_likelihoods), axis=-1)
71:     posteriors = np.exp(_log_posteriors[0] - logsumexp(_log_posteriors, axis=0))
72: 
73:     gamma = params['diagnosis_threshold']
74:     
75:     diagnoses = np.any(posteriors > gamma, axis=-1)
76:     diagnoses_time = np.where(diagnoses, np.argmax(posteriors > gamma, axis=-1), np.inf)
77: 
78:     # GAIN-COST:
79:     # assuming x.size == 2
80: 
81:     events_time_diag = np.where(diagnoses_time < events_time, np.inf, events_time) #T*
82:     
83:     survival_00 = np.minimum(death_time, np.minimum(events_time[0], events_time[1]))
84:     survival_10 = np.minimum(death_time, np.minimum(events_time_diag[0], events_time[1]))
85:     survival_01 = np.minimum(death_time, np.minimum(events_time[0], events_time_diag[1]))
86:     survival_11 = np.minimum(death_time, np.minimum(events_time_diag[0], events_time_diag[1]))
87:     
88:     gain_00 = survival_00 - survival_00  # = 0
89:     gain_10 = survival_10 - survival_00
90:     gain_01 = survival_01 - survival_00
91:     gain_11 = survival_11 - survival_00
92: 
93:     samples_time = np.minimum(diagnoses_time, params['sample_sizes'].sum(axis=-1))
94: 
95:     tau_k = params["sampling_freq"]
96:     ck = params['screening_costs']
97:      
98:     
99:     cost_00 = 0
100:     cost_10 = ck[0] * np.floor(np.minimum(survival_10, samples_time[0]))
101:     cost_01 = ck[1] * np.floor(np.minimum(survival_01, samples_time[1]))
102:     cost_11 = 0
103:     cost_11 = cost_11 + ck[0] * np.floor(np.minimum(survival_11, samples_time[0]))
104:     cost_11 = cost_11 + ck[1] * np.floor(np.minimum(survival_11, samples_time[1]))
105:    
106:     
107:     """ return (
108:         np.array([survival_00, survival_10, survival_01, survival_11]), 
109:         np.array([cost_00, cost_10, cost_01, cost_11])) """
110:     
111:     return (
112:         np.array([survival_00, survival_10, survival_01, survival_11]), 
113:         np.array([cost_00, cost_10, cost_01, cost_11]),
114:         events_time[0],
115:         diagnoses_time[0],
116:         events[0])
117: 
118: ###
119: 
120: N_INNER = 200
121: N = 10000
122: 
123: _simulate_multikey = jax.vmap(_simulate_singlekey, in_axes=(None,0,None))
124: _simulate_multikey = jax.jit(_simulate_multikey)
125: 
126: @jax.jit
127: def simulate(x, key, params):
128:     keys = jax.random.split(key, N_INNER)
129:     gains, costs, tn, t_star, thetas = _simulate_multikey(x, keys, params)
130:     mean_gain = gains.mean(axis=0)
131:     mean_cost = costs.mean(axis=0)
132:     return mean_gain, mean_cost
133: 
134: _simulate_batch = jax.vmap(simulate, in_axes=(0,0,None))
135: _simulate_batch = jax.jit(_simulate_batch)
136: 
137: @jax.jit
138: def simulate_batch(xs, key, params):
139:     keys = jax.random.split(key, xs.shape[0])
140:     return _simulate_batch(xs, keys, params)
141: 
142: ###
143: 
144: params = dict()
145: params['mean_death_time'] = 40 #T0
146: params['mean_event_times'] = np.array([30.1, 30.1]) #Tn means
147: params['sample_sizes'] = np.ones((1, 40)) #1,40, assuming annual screening
148: # params['sample_perrors'] = np.array([.2, .2])
149: params['diagnosis_threshold'] = .95
150: params['screening_costs'] = np.array([1, 1]) #screening costs cn, will be modified accordingly. 1-1
151: params['sampling_freq'] = np.array([5., 5.]) #assume a sampling with fixed frequency (for old implementation) 
152: 
153: ###
154: 
155: 
156: 
157: def monte_carlo_simulation(num_iterations, xs, key, params, save_dir="results"):
158:     """
159:     Monte Carlo simulation saving each iteration's gains and costs as separate .npy files.
160:     Computes and prints mean, variance, and std at the end.
161:     """
162:     os.makedirs(save_dir, exist_ok=True)
163: 
164:     N = xs.shape[0]
165:     all_gains_list = []
166:     all_costs_list = []
167: 
168:     for i in range(num_iterations):
169:         key, subkey = jax.random.split(key)
170: 
171:         key, subkey = jax.random.split(key)
172:         gains, costs = simulate_batch(xs, subkey, params)
173: 
174:         # Convert to NumPy and save separately
175:         gains_np = np1.array(gains)
176:         costs_np = np1.array(costs)
177: 
178:         np1.save(f"{save_dir}/gains_iter_{i}.npy", gains_np)
179:         np1.save(f"{save_dir}/costs_iter_{i}.npy", costs_np)
180: 
181:         all_gains_list.append(gains_np)
182:         all_costs_list.append(costs_np)
183: 
184:     # Stack results for statistics
185:     all_gains = np1.stack(all_gains_list)
186:     all_costs = np1.stack(all_costs_list)
187: 
188:     mean_gains = np1.mean(all_gains, axis=0)
189:     var_gains = np1.var(all_gains, axis=0)
190:     std_gains = np1.std(all_gains, axis=0)
191: 
192:     mean_costs = np1.mean(all_costs, axis=0)
193:     var_costs = np1.var(all_costs, axis=0)
194:     std_costs = np1.std(all_costs, axis=0)
195: 
196:     """ print("Expected gains (mean):", mean_gains)
197:     print("Variance of gains:", var_gains)
198:     print("Standard deviation of gains:", std_gains)
199: 
200:     print("Expected costs (mean):", mean_costs)
201:     print("Variance of costs:", var_costs)
202:     print("Standard deviation of costs:", std_costs) """
203: 
204:     return mean_gains, mean_costs
205: 
206: 
207: num_iterations = 100  #number of Monte Carlo iterations
208: 
209: # Parameters for the Beta distributions
210: a, b = 5, 5  # Parameters
211: 
212: x1 = np.linspace(0, 1, 100)
213: x2 = np.linspace(0, 1, 100)
214: X1, X2 = np.meshgrid(x1, x2)
215: xs = np.stack([X1.ravel(), X2.ravel()], axis=-1)
216: dx = x1[1] - x1[0]
217: 
218: #compute the PDF values
219: pdf_x1 = beta.pdf(x1, a, b)
220: pdf_x2 = beta.pdf(x2, a, b)
221: 
222: joint_pmf = np.outer(pdf_x1, pdf_x2) * dx * dx
223: joint_pmf /= np.sum(joint_pmf)
224: pmf_x = joint_pmf.flatten()
225: 
226: 
227: key = jax.random.PRNGKey(0)
228: key, subkey = jax.random.split(key)
229: 
230: expected_gains, expected_costs = monte_carlo_simulation(num_iterations, xs, key, params)
231: 
232: folder_path = "comparison/unified_data"
233: os.makedirs(folder_path, exist_ok=True)
234: 
235: np.save(os.path.join(folder_path, "expected_gains.npy"), expected_gains)
236: np.save(os.path.join(folder_path, "expected_costs.npy"), expected_costs)
237: 
238: print(f"Data saved successfully in '{folder_path}'!")
239: 
240: folder_path_2 = "comparison/xs"
241: os.makedirs(folder_path_2, exist_ok=True)
242: 
243: np.save(os.path.join(folder_path_2, "xs.npy"), xs)
244: np.save(os.path.join(folder_path_2, "pmf_x.npy"), pmf_x)
245: 
246: print(f"Data saved successfully in '{folder_path_2}'!")