1: import numpy as np
2: from numba import njit
3: from tqdm import tqdm
4: 
5: 
6: # Use numba to speed up the code
7: 
8: 
9: def bayes_learn(data: list,
10:                 alpha_update: float,
11:                 eps: float,
12:                 M: int,
13:                 intervals: np.array,
14:                 target: float = 0.5,
15:                 replacement: bool = False) -> tuple[np.array, list]:
16:     """
17:     A differential private implementation of BayesLearn for the median
18:     given a dataset D (np.array) of values in [B], an error alpha in (0, 0.25),
19:     and a number of steps (samples from D) M smaller than the length of the data,
20:     returns a list of visited intervals.
21: 
22:     Ref:  Gretta, Lucas, and Eric Price. "Sharp Noisy Binary Search with Monotonic Probabilities."
23:           arXiv preprint arXiv:2311.00840 (2023).
24: 
25:     :param data: dataset of values in [B]
26:     :param alpha_update: error used to update the weights
27:     :param eps: privacy parameter
28:     :param M: steps (samples)
29:     :param intervals: list of intervals [[x_1, x_2], [x_2, x_3], ...]
30:     :param target: target or quantile in (0,1) value
31:     :param replacement: with (True) / without (False) replacement
32: 
33:     :return: L, list (np.array) of visited intervals indices
34:     :return: D, the dataset after the sampling
35:     """
36:     assert 0 < alpha_update < 0.25, "alpha must be in (0, 0.25) for the median"
37:     assert 0 <= M < len(data), "M must be smaller than the length of the data"
38: 
39:     if not replacement:
40:         # generate a random permutation of the data indices
41:         data = np.random.permutation(data)
42:         data_to_use = data[:M]  # data to use for bayes learning
43:         data_not_used = data[M:]  # data not used
44:     else:
45:         indices = np.random.choice(len(data), M, replace=True)  # generate M random indices with replacement
46:         data_to_use = data[indices]  # data to use for bayes learning
47:         data_not_used = data  # data not used
48: 
49:     # generate bernoulli coins with probability np.exp(eps) / (1 + np.exp(eps))
50:     eps = np.clip(eps, 0.00001, 100)  # for stability
51:     random_coin = np.random.binomial(1, np.exp(eps) / (1 + np.exp(eps)), M)
52: 
53:     # compute
54: 
55:     # define uniform prior over the intervals
56:     w: np.array = np.ones(len(intervals)) / (len(intervals))
57:     # create array for the visited intervals
58:     L = np.zeros(M, dtype=int)
59: 
60:     if target == 0.5:
61:         update: callable = update_weights_median
62:     else:
63:         raise NotImplementedError("BayesLearn is only implemented for the median")
64: 
65:     for i, sample in enumerate(data_to_use):
66:         # get the median interval and closest coin of the weights
67:         interval_index, coin_index = get_interval_coin_from_quantile(w, target, i)
68:         j_i = intervals[interval_index]
69:         x_i = j_i[coin_index]
70: 
71:         # add the interval index to the list
72:         L[i] = interval_index
73: 
74:         # flip the coin
75:         y_i = flip_coin(coin=x_i, sample=sample)
76: 
77:         # apply randomized response to the coin flip
78:         y_i = RR(y_i, random_coin[i])
79: 
80:         # update the weights (this can be optimized by using a segment tree as proposed in the reference paper)
81:         w = update(w, alpha_update, y_i, interval_index)
82: 
83:     return L, data_not_used
84: 
85: 
86: @njit
87: def get_interval_coin_from_quantile(w: np.array, q: float, i: int) -> tuple[int, int]:
88:     """
89:     Get the interval from the quantile q of the weights w.
90:     :param w: weights
91:     :param q: quantile
92:     :param i: iteration
93: 
94:     :return: interval index, coin index
95:     """
96:     assert 0 <= q <= 1
97: 
98:     if i == 0:
99:         # get the middle interval
100:         return len(w) // 2, 0
101: 
102:     W = np.cumsum(w)  # get cumulative sum of the weights
103:     i = np.argmax(W >= q)  # Find the first index where W[i] >= q
104:     coin = round_interval_to_coin(w[i], W[i], q)
105:     return i, coin
106: 
107: 
108: @njit
109: def round_interval_to_coin(w: float, W: float, q: float) -> int:
110:     """
111:     Round interval i to a coin.
112:     :param w: weights of the intervals
113:     :param W: cumulative sum of the weights
114:     :param q: quantile
115:     :return: coin index {0,1}
116:     """
117: 
118:     flag = (q - W) / w - q
119:     if flag <= 0:
120:         # return left coin of the interval
121:         return 0
122:     else:
123:         # return right coin of the interval
124:         return 1
125: 
126: 
127: def flip_coin(coin: int, sample: int) -> int:
128:     return int(sample <= coin)
129: 
130: 
131: @njit
132: def RR(A: int, B: int) -> int:
133:     """
134:     Given the result of coin A and the result of DP coin due to randomized response B, we return the private coin
135:     Truth Table:
136:     A  B  result
137:     0  0  1
138:     0  1  0
139:     1  0  0
140:     1  1  1
141:     So if the DP coin is zero we flip coin A, otherwise we keep the result of coin A
142:     :param A:
143:     :param B:
144:     :return:
145:     """
146:     A = bool(A)
147:     B = bool(B)
148:     return int((A and B) or (not A and not B))
149: 
150: 
151: @njit
152: def update_weights_median(w: np.array, alpha: float, y: int, j: int) -> np.array:
153:     """
154:     Update the weights of the intervals. Specialized for the median.
155:     :param w: weights
156:     :param alpha: target error
157:     :param y: result of the comparison (0 or 1)
158:     :param j: interval chosen
159:     :return: updated weights
160: 
161:     Note that this function can be optimized in running time from O(B) to O(log B) by using a lazily initialized
162:     segment tree as proposed in the reference paper
163:     """
164:     # update left
165:     w[:j] *= (1 - 2 * alpha * (-1) ** y)
166:     # update right
167:     w[j + 1:] *= (1 + 2 * alpha * (-1) ** y)
168:     S = np.sum(w[:j]) + np.sum(w[j + 1:])
169:     # add the renormalization step
170:     w[j] = 1 - S
171:     return w
172: 
173: 
174: 