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
8: from collections import Counter
9: import os
10: 
11: independent_folder_path = "comparison/independent_data"
12: unified_folder_path = "comparison/unified_data"
13: xs_folder_path = "comparison/xs"
14: 
15: survival_disease_1 = np.load(os.path.join(independent_folder_path, "survival_disease_1.npy"))
16: cost_disease_1 = np.load(os.path.join(independent_folder_path, "cost_disease_1.npy"))
17: survival_disease_2 = np.load(os.path.join(independent_folder_path, "survival_disease_2.npy"))
18: cost_disease_2 = np.load(os.path.join(independent_folder_path, "cost_disease_2.npy"))
19: 
20: expected_gains = np.load(os.path.join(unified_folder_path, "expected_gains.npy"))
21: expected_costs = np.load(os.path.join(unified_folder_path, "expected_costs.npy"))
22: 
23: xs = np.load(os.path.join(xs_folder_path, "xs.npy"))
24: pmf_x = np.load(os.path.join(xs_folder_path, "pmf_x.npy"))
25: 
26: #For unified screening:
27: def optimize_linear(x, pmf_x, expected_gains, expected_costs, k, B):
28:     N = x.shape[0]
29:     a = 2**k #nb of possible combinations for policies
30:     
31:     #optimization variables (q's)
32:     q = cp.Variable(a*N) #corresponds to the "x" variable in the linear CVXPY program
33:     
34:     gain_product = (expected_gains.T * pmf_x).T
35:     c = gain_product.flatten()
36:     print("Size of c=", c.shape)
37:     
38:     constraints = []
39:     constraints.append(q >= 0) #we can add the constraint that every q should be non-negative like this
40:     
41:     cost_product = (expected_costs.T * pmf_x).T
42:     A = cost_product.flatten()
43:     print("Size of A=", A.shape)
44:     
45:     constraints.append( A @ q <= B) #the cost constraint
46:     #I didn't apply the cost constraint and the sum of q(a|x) = 1 constraints together 
47:     # since one of them is an inequality and the other is an equality
48:     
49:     O = np1.zeros((N, a * N)) #to create the sum of q(a|x) = 1 constr
50:     for i in range(N):
51:         O[i, 4 * i : 4 * (i + 1)] = 1
52:         
53:     p = np1.ones(N)
54:     constraints.append( O @ q == p)
55:     
56:     prob = cp.Problem(cp.Maximize(c.T @ q), constraints)
57:     prob.solve()
58:     
59:     q_s = q.value
60:     optimal_qs = np1.zeros(N)
61:     
62:     #choosing the maximum probability for each feature x
63:     for i in range(N):
64:         optimal_qs[i] = np.argmax(q_s[4 * i : 4 * (i + 1)])
65:     
66:     return optimal_qs
67: 
68: 
69: 
70: ######For independent model:
71: def optimize_separately(x1, x2, pmf_x, expected_gains_x1, expected_costs_x1, expected_gains_x2, expected_costs_x2, k, B):
72:     N = x1.shape[0]
73:     a = 2 #number of possible combinations for policies
74:     
75:     #pmf = np1.ones(shape = pmf_x.shape)
76:     #pmf_x = pmf / 10000
77:     
78:     # Optimization variables (q's) for both x1 and x2
79:     q1 = cp.Variable(a * N)  #for disease 1 (x1)
80:     q2 = cp.Variable(a * N)  #for disease 2 (x2)
81: 
82:     gain_product_x1 = (expected_gains_x1 * pmf_x).T
83:     c1 = gain_product_x1.flatten()
84: 
85:     gain_product_x2 = (expected_gains_x2 * pmf_x).T
86:     c2 = gain_product_x2.flatten()
87: 
88:     constraints_1 = []
89:     constraints_2 = []
90:     constraints_1.append(q1 >= 0)  #non-negative q1
91:     constraints_2.append(q2 >= 0)  #non-negative q2
92: 
93:     cost_product_x1 = (expected_costs_x1 * pmf_x).T
94:     A1 = cost_product_x1.flatten()
95: 
96:     cost_product_x2 = (expected_costs_x2 * pmf_x).T
97:     A2 = cost_product_x2.flatten()
98: 
99:     constraints_1.append(A1 @ q1 <= B)  #cost constraint for disease 1
100:     constraints_2.append(A2 @ q2 <= B)  #cost constraint for disease 2
101: 
102:     O = np1.zeros((N, a * N))  #sum of q(a|x) = 1 constraint for both diseases
103:     for i in range(N):
104:         O[i, a * i : a * (i + 1)] = 1
105:     
106:     p = np1.ones(N)
107:     constraints_1.append(O @ q1 == p)  #constraint for disease 1
108:     constraints_2.append(O @ q2 == p)  #constraint for disease 2
109:     
110:     #solve the optimization problem
111:     prob1 = cp.Problem(cp.Maximize(c1.T @ q1), constraints_1)
112:     prob2 = cp.Problem(cp.Maximize(c2.T @ q2), constraints_2)
113: 
114:     prob1.solve()
115:     prob2.solve()
116: 
117:     q1_s = q1.value
118:     q2_s = q2.value
119:     
120:     #get the optimal policies for each disease
121:     optimal_qs_x1 = np1.zeros(N)
122:     optimal_qs_x2 = np1.zeros(N)
123: 
124:     for i in range(N):
125:         optimal_qs_x1[i] = np.argmax(q1_s[a * i : a * (i + 1)])
126:         optimal_qs_x2[i] = np.argmax(q2_s[a * i : a * (i + 1)])
127: 
128:     return optimal_qs_x1, optimal_qs_x2
129:    
130: 
131: #get the final policy based on the q's
132: optimal_qs_x1, optimal_qs_x2 = optimize_separately(
133:     xs[:, 0], xs[:, 1], pmf_x, survival_disease_1, cost_disease_1, survival_disease_2, cost_disease_2, 2, 5)
134: 
135: #get the final policy based on the q's FOR UNIFIED MODEL
136: policy = optimize_linear(xs, pmf_x, expected_gains, expected_costs, 2, 5)
137: 
138: """ print("Optimal qs for x1: ", optimal_qs_x1)
139: print("Optimal qs for x2: ", optimal_qs_x2) """
140: 
141: def get_independent_policy(optimal_qs_x1, optimal_qs_x2):
142:     optimal_qs_x1 = optimal_qs_x1.astype(int)
143:     optimal_qs_x2 = optimal_qs_x2.astype(int)
144:     
145:     #combine the independent decisions for x1 and x2 into a single policy
146:     independent_policy = (optimal_qs_x2 << 1) | optimal_qs_x1  #bitwise operation to encode policy
147:     return independent_policy
148: 
149: # Derive the independent policy
150: independent_policy = get_independent_policy(optimal_qs_x1, optimal_qs_x2)
151:               
152: 
153: def calculate_policy_differences(policy, independent_policy):
154:     policy_counts = Counter(policy)
155:     independent_policy_counts = Counter(independent_policy)
156: 
157:     for i in range(4):
158:         policy_counts[i] = policy_counts.get(i, 0)
159:         independent_policy_counts[i] = independent_policy_counts.get(i, 0)
160: 
161:     #calculate the differences for specified policies
162:     diff_1_3 = (policy_counts[1] + policy_counts[3]) - (independent_policy_counts[1] + independent_policy_counts[3])
163:     diff_2_3 = (policy_counts[2] + policy_counts[3]) - (independent_policy_counts[2] + independent_policy_counts[3])
164:     diff_1_2_3 = (policy_counts[1] + policy_counts[2] + policy_counts[3]) - (
165:         independent_policy_counts[1] + independent_policy_counts[2] + independent_policy_counts[3])
166: 
167:     return {
168:         "policy_counts": dict(policy_counts),
169:         "independent_policy_counts": dict(independent_policy_counts),
170:         "diff_1_3": diff_1_3,
171:         "diff_2_3": diff_2_3,
172:         "diff_1_2_3": diff_1_2_3
173:     }
174:     
175: results = calculate_policy_differences(policy, independent_policy)
176: 
177: folder_path = "comparison/policies_2"
178: os.makedirs(folder_path, exist_ok=True)
179: 
180: np.save(os.path.join(folder_path, "policy.npy"), policy)
181: np.save(os.path.join(folder_path, "independent_policy.npy"), independent_policy)
182: np.save(os.path.join(folder_path, "action_number_results.npy"), results)
183: np.save(os.path.join(folder_path, "optimal_qs_x1.npy"), optimal_qs_x1)
184: np.save(os.path.join(folder_path, "optimal_qs_x2.npy"), optimal_qs_x2)
185: 
186: print(f"Data saved successfully in '{folder_path}'!")
187: 
188: #plot the resulting policy assignments for our model
189: def plot_policy(policy):
190:     plt.figure()
191:     #plt.title("Unified Screening for Two Diseases")
192:     plt.scatter(xs[policy == 0, 0], xs[policy == 0, 1], color='silver', s=50, label='a = 1 (00)')
193:     plt.scatter(xs[policy == 1, 0], xs[policy == 1, 1], color='tab:pink', s=50, label='a = 2 (10)')
194:     plt.scatter(xs[policy == 2, 0], xs[policy == 2, 1], color='tab:purple', s=50, label='a = 3 (01)')
195:     plt.scatter(xs[policy == 3, 0], xs[policy == 3, 1], color='tab:red', s=50, label='a = 4 (11)')
196: 
197:     plt.axis('scaled')
198:     plt.xlim(0, 1)
199:     plt.ylim(0, 1)
200:     plt.xlabel(r"$x_1$", fontsize=18)
201:     plt.ylabel(r"$x_2$", fontsize=18)
202:     plt.grid()
203:     plt.legend(fontsize=18)
204:     plt.tight_layout()
205:     plt.show()
206: 
207: plot_policy(policy)
208: 
209: def plot_policy_separately(optimal_qs_x1, optimal_qs_x2, xs): 
210:     plt.figure(figsize=(6, 6))
211:     
212:     # Mask to exclude points on the edges
213:     mask = (xs[:, 0] > 0) & (xs[:, 0] < 1) & (xs[:, 1] > 0) & (xs[:, 1] < 1)
214:     
215:     # Plot for the four combinations of disease 1 (x1) and disease 2 (x2), excluding edges
216:     plt.scatter(xs[(optimal_qs_x1 == 0) & (optimal_qs_x2 == 0) & mask, 0], 
217:                 xs[(optimal_qs_x1 == 0) & (optimal_qs_x2 == 0) & mask, 1], 
218:                 color='silver', s=50, label='a = 1 (00)')
219:     plt.scatter(xs[(optimal_qs_x1 == 1) & (optimal_qs_x2 == 0) & mask, 0], 
220:                 xs[(optimal_qs_x1 == 1) & (optimal_qs_x2 == 0) & mask, 1], 
221:                 color='tab:pink', s=50, label='a = 2 (10)')
222:     plt.scatter(xs[(optimal_qs_x1 == 0) & (optimal_qs_x2 == 1) & mask, 0], 
223:                 xs[(optimal_qs_x1 == 0) & (optimal_qs_x2 == 1) & mask, 1], 
224:                 color='tab:purple', s=50, label='a = 3 (01)')
225:     plt.scatter(xs[(optimal_qs_x1 == 1) & (optimal_qs_x2 == 1) & mask, 0], 
226:                 xs[(optimal_qs_x1 == 1) & (optimal_qs_x2 == 1) & mask, 1], 
227:                 color='tab:red', s=50, label='a = 4 (11)')
228:     
229:     plt.axis('scaled')
230:     plt.xlim(0, 1)
231:     plt.ylim(0, 1)
232:     plt.xlabel(r"$x_1$")
233:     plt.ylabel(r"$x_2$")
234:     plt.grid()
235:     plt.legend()
236:     plt.tight_layout()
237:     plt.show()
238: 
239: 
240: plot_policy_separately(optimal_qs_x1, optimal_qs_x2, xs)