bayesreconpy 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bayesreconpy/PMF.py ADDED
@@ -0,0 +1,213 @@
1
+ import numpy as np
2
+ from scipy.stats import poisson, nbinom
3
+ from bayesreconpy.utils import DEFAULT_PARS
4
+
5
+
6
+ # Compute the empirical PMF from a vector of samples
7
+ def pmf_from_samples(v):
8
+ # Check that samples are discrete
9
+ if not np.array_equal(v, v.astype(int)):
10
+ raise ValueError("Input error: samples are not all discrete")
11
+ else:
12
+ v = v.astype(int)
13
+ # Compute the PMF by tabulating the occurrences
14
+ pmf = np.bincount(v) / len(v) # Support starts from 0
15
+
16
+ # Check for any negative samples
17
+ if not np.isclose(np.sum(pmf), 1.0):
18
+ raise ValueError("Input error: some samples are negative")
19
+
20
+ return pmf
21
+
22
+
23
+ # Compute the PMF from a parametric distribution
24
+ def pmf_from_params(params, distr, rtol=DEFAULT_PARS['RTOL']):
25
+ # Validate the distribution type
26
+ if distr not in ['poisson', 'nbinom']:
27
+ raise ValueError(f"Input error: distr must be one of ['poisson', 'nbinom']")
28
+
29
+ # Initialize PMF
30
+ pmf = None
31
+
32
+ # Compute the PMF based on the distribution type
33
+ if distr == 'poisson':
34
+ lambda_ = params['lambda']
35
+ M = poisson.ppf(1 - rtol, lambda_).astype(int)
36
+ pmf = poisson.pmf(np.arange(M + 1), lambda_)
37
+
38
+ elif distr == 'nbinom':
39
+ size = params['size']
40
+ prob = params.get('prob')
41
+ mu = params.get('mu')
42
+
43
+ if prob is not None:
44
+ M = nbinom.ppf(1 - rtol, n=size, p=prob).astype(int)
45
+ pmf = nbinom.pmf(np.arange(M + 1), n=size, p=prob)
46
+
47
+ elif mu is not None:
48
+ M = nbinom.ppf(1 - rtol, n=size, p=size / (size + mu)).astype(int)
49
+ pmf = nbinom.pmf(np.arange(M + 1), n=size, p=size / (size + mu))
50
+
51
+ # Normalize the PMF to ensure it sums to 1
52
+ pmf = pmf / np.sum(pmf)
53
+
54
+ return pmf
55
+
56
+
57
+ def pmf_sample(pmf, N_samples):
58
+ pmf = np.atleast_1d(pmf)
59
+ # Ensure that pmf is a normalized probability distribution
60
+ if not np.isclose(np.sum(pmf), 1.0):
61
+ raise ValueError("PMF must be normalized; the sum of probabilities should be 1.")
62
+
63
+ # Create an array of possible outcomes
64
+ outcomes = np.arange(len(pmf))
65
+
66
+ # Sample from the PMF
67
+ samples = np.random.choice(outcomes, size=N_samples, p=pmf)
68
+
69
+ return samples
70
+
71
+
72
+ def pmf_get_mean(pmf):
73
+ pmf = np.atleast_1d(pmf)
74
+ # Ensure that pmf is a normalized probability distribution
75
+ if not np.isclose(np.sum(pmf), 1.0):
76
+ raise ValueError("PMF must be normalized; the sum of probabilities should be 1.")
77
+
78
+ # Create an array of possible outcomes
79
+ supp = np.arange(len(pmf))
80
+
81
+ # Calculate the mean
82
+ mean = np.dot(pmf, supp)
83
+
84
+ return mean
85
+
86
+
87
+ def pmf_get_var(pmf):
88
+ pmf = np.atleast_1d(pmf)
89
+ # Ensure that pmf is a normalized probability distribution
90
+ if not np.isclose(np.sum(pmf), 1.0):
91
+ raise ValueError("PMF must be normalized; the sum of probabilities should be 1.")
92
+
93
+ # Create an array of possible outcomes
94
+ supp = np.arange(len(pmf))
95
+
96
+ # Calculate the mean
97
+ mean = np.dot(pmf, supp)
98
+
99
+ # Calculate the second moment
100
+ second_moment = np.dot(pmf, supp ** 2)
101
+
102
+ # Calculate the variance
103
+ variance = second_moment - mean ** 2
104
+
105
+ return variance
106
+
107
+
108
+ def pmf_get_quantile(pmf, p):
109
+ # Check that the probability p is within the valid range
110
+ if p <= 0 or p >= 1:
111
+ raise ValueError("Input error: probability p must be between 0 and 1")
112
+
113
+ # Compute the cumulative distribution function (CDF)
114
+ cdf = np.cumsum(pmf)
115
+
116
+ # Find the smallest index where CDF is greater than or equal to p
117
+ x = np.min(np.where(cdf >= p)[0])
118
+
119
+ return x
120
+
121
+
122
+ def pmf_summary(pmf, Ltoll=DEFAULT_PARS['TOL'], rtol=DEFAULT_PARS['RTOL']):
123
+ min_pmf = np.min(np.where(pmf > Ltoll)) - 1
124
+ max_pmf = np.max(np.where(pmf > rtol)) - 1
125
+ summary = {
126
+ "Min.": min_pmf,
127
+ "1st Qu.": pmf_get_quantile(pmf, 0.25),
128
+ "Median": pmf_get_quantile(pmf, 0.5),
129
+ "Mean": pmf_get_mean(pmf),
130
+ "3rd Qu.": pmf_get_quantile(pmf, 0.75),
131
+ "Max": max_pmf
132
+ }
133
+ return summary
134
+
135
+
136
+ def pmf_smoothing(pmf, alpha=DEFAULT_PARS['ALPHA'], laplace=False):
137
+ if alpha is None:
138
+ alpha = np.min(pmf[pmf != 0])
139
+
140
+ if np.any(pmf == 0):
141
+ if laplace:
142
+ pmf = pmf + alpha
143
+ else:
144
+ pmf[pmf == 0] = alpha
145
+
146
+ return pmf / np.sum(pmf)
147
+
148
+
149
+ def pmf_conv(pmf1, pmf2, toll=DEFAULT_PARS['TOL'], rtol=DEFAULT_PARS['RTOL']):
150
+ # Convolution
151
+ pmf = np.convolve(pmf1, pmf2, mode='full')
152
+
153
+ # Trim values below rtol
154
+ last_pos = np.max(np.where(pmf > rtol)) + 1
155
+ pmf = pmf[:last_pos]
156
+
157
+ # Set values below toll to zero
158
+ pmf[pmf < toll] = 0
159
+
160
+ # Set to zero values to the left of the minimal support
161
+ m1 = np.min(np.where(pmf1 > 0))
162
+
163
+ m2 = np.min(np.where(np.atleast_1d(pmf2) > 0))
164
+
165
+ m = m1 + m2 - 1
166
+ if m > 1:
167
+ pmf[:m - 1] = 0
168
+
169
+ return pmf / np.sum(pmf)
170
+
171
+
172
+ def pmf_bottom_up(l_pmf, toll=DEFAULT_PARS['TOL'], rtol=DEFAULT_PARS['RTOL'], return_all=False, smoothing=True, alpha_smooth=DEFAULT_PARS['ALPHA_SMOOTHING'],
173
+ laplace_smooth=False):
174
+ if smoothing:
175
+ l_pmf = [pmf_smoothing(pmf, alpha=alpha_smooth, laplace=laplace_smooth) for pmf in l_pmf]
176
+
177
+ if len(l_pmf) == 1:
178
+ return l_pmf if return_all else l_pmf[0]
179
+
180
+ l_l_v = [l_pmf]
181
+ while len(l_pmf) > 1:
182
+ new_v = []
183
+ for j in range(len(l_pmf) // 2):
184
+ new_v.append(pmf_conv(l_pmf[2 * j], l_pmf[2 * j + 1], toll=toll, rtol=rtol))
185
+ if len(l_pmf) % 2 == 1:
186
+ new_v.append(l_pmf[-1])
187
+
188
+ l_pmf = new_v
189
+ l_l_v.append(l_pmf)
190
+
191
+ return l_l_v if return_all else l_pmf[0]
192
+
193
+
194
+ def pmf_check_support(v_u, l_pmf, toll=DEFAULT_PARS['TOL'], rtol=DEFAULT_PARS['RTOL'], smoothing=True, alpha_smooth=DEFAULT_PARS['ALPHA_SMOOTHING'], laplace_smooth=False):
195
+ # Compute the bottom-up PMF
196
+ pmf_u = pmf_bottom_up(l_pmf, toll=toll, rtol=rtol, return_all=False, smoothing=smoothing,
197
+ alpha_smooth=alpha_smooth, laplace_smooth=laplace_smooth)
198
+
199
+ # Support of the PMF
200
+ supp_u = np.where(pmf_u > 0)[0]
201
+ # Check if elements of v_u are in the support of pmf_u
202
+ mask = np.isin(v_u, supp_u)
203
+ return mask
204
+
205
+
206
+ def pmf_tempering(pmf, temp):
207
+ if temp <= 0:
208
+ raise ValueError("temp must be positive")
209
+ if temp == 1:
210
+ return pmf
211
+
212
+ temp_pmf = np.power(pmf, 1 / temp)
213
+ return temp_pmf / np.sum(temp_pmf)
File without changes
@@ -0,0 +1,321 @@
1
+ import numpy as np
2
+ from pulp import LpProblem, LpVariable, LpMinimize, lpSum, PULP_CBC_CMD
3
+
4
+
5
+
6
+ def get_hier_rows(A, scale=196):
7
+ # This function is equivalent to .get_hier_rows in python
8
+
9
+ A = np.array(A)
10
+ k, m = A.shape
11
+
12
+ # Matrix C of the coefficients of the non-linear problem
13
+ C = np.dot(A, A.T)
14
+
15
+ for i in range(k):
16
+ for j in range(k):
17
+ diff_ij = A[i, :] - A[j, :]
18
+ C[i, j] = C[i, j] * np.sum(diff_ij * (diff_ij - 1)) * np.sum((A[j, :] - A[i, :]) * (A[j, :] - A[i, :] - 1))
19
+
20
+ # Linearized Problem
21
+ f_obj = [-1] * k + [0] * (k ** 2) + [1 - 1 / (2 * k)]
22
+
23
+ coeff = [0] * k + list(C.flatten()) + [0]
24
+
25
+ M1 = np.zeros((k ** 2, k + k ** 2 + 1)) # z_{ij} <= x_i
26
+ for i in range(k):
27
+ temp = np.zeros((k, k))
28
+ temp[i, :] = -1
29
+ M1[:, i] = temp.flatten()
30
+ M1[:, k:(k + k ** 2)] = np.eye(k ** 2)
31
+
32
+ M2 = np.zeros((k ** 2, k + k ** 2 + 1)) # z_{ij} <= x_j
33
+ for i in range(k):
34
+ temp = np.zeros((k, k))
35
+ temp[:, i] = -1
36
+ M2[:, i] = temp.flatten()
37
+ M2[:, k:(k + k ** 2)] = np.eye(k ** 2)
38
+
39
+ M3 = np.zeros((k ** 2, k + k ** 2 + 1)) # z_{ij} >= x_i + x_j - 1
40
+ M3[:, :k] = M1[:, :k] + M2[:, :k]
41
+ M3[:, k:(k + k ** 2)] = np.eye(k ** 2)
42
+
43
+ M4 = np.zeros((m, k + k ** 2 + 1)) # sum_i x_i A_{ij} <= y
44
+ M4[:, :k] = A.T
45
+ M4[:, k + k ** 2] = -1
46
+
47
+ f_con = np.vstack([coeff, M1, M2, M3, M4])
48
+
49
+ f_dir = ['='] + ['<='] * (k ** 2) + ['<='] * (k ** 2) + ['>='] * (k ** 2) + ['<='] * m
50
+ f_rhs = [0] + [0] * (k ** 2) + [0] * (k ** 2) + [-1] * (k ** 2) + [0] * m
51
+
52
+ prob = LpProblem("Minimize_Steps", LpMinimize)
53
+
54
+ vars = LpVariable.dicts("x", range(k + k ** 2 + 1), 0, 1, cat='Binary')
55
+
56
+ prob += lpSum([f_obj[i] * vars[i] for i in range(k + k ** 2 + 1)])
57
+
58
+ #for i in range(len(f_con)):
59
+ # prob += lpSum([f_con[i][j] * vars[j] for j in range(k + k ** 2 + 1)]) <= f_rhs[i]
60
+
61
+ # first constraint
62
+ prob += lpSum([f_con[0][j] * vars[j] for j in range(k + k ** 2 + 1)]) == f_rhs[0]
63
+ # second set of constraints
64
+ for i in np.arange(1, k ** 2 + 1):
65
+ prob += lpSum([f_con[i][j] * vars[j] for j in range(k + k ** 2 + 1)]) <= f_rhs[i]
66
+ # third set of constraints
67
+ for i in np.arange(k ** 2 + 1, 2 * k ** 2 + 1):
68
+ prob += lpSum([f_con[i][j] * vars[j] for j in range(k + k ** 2 + 1)]) <= f_rhs[i]
69
+ # fourth set of constraints
70
+ for i in np.arange(2 * k ** 2 + 1, 3 * k ** 2 + 1):
71
+ prob += lpSum([f_con[i][j] * vars[j] for j in range(k + k ** 2 + 1)]) >= f_rhs[i]
72
+ # fifth set of constraints
73
+ for i in np.arange(3 * k ** 2 + 1, 3 * k ** 2 + 1 + m):
74
+ prob += lpSum([f_con[i][j] * vars[j] for j in range(k + k ** 2 + 1)]) <= f_rhs[i]
75
+
76
+ prob.solve(PULP_CBC_CMD(msg=False, timeLimit=scale))
77
+
78
+ indices_sol = np.array([vars[i].varValue for i in range(k)])
79
+
80
+ return indices_sol
81
+
82
+
83
+ def get_HG(A, v, d, it):
84
+ indices_sol = get_hier_rows(A)
85
+
86
+ ind_h = indices_sol.astype(bool)
87
+ H = A[ind_h]
88
+ v_h = np.array(v)[ind_h]
89
+ d_h = np.array(d)[ind_h]
90
+ it_h = np.array(it)[ind_h]
91
+
92
+ ord = np.argsort(np.sum(H, axis=1))
93
+ H = H[ord]
94
+ v_h = v_h[ord]
95
+ d_h = d_h[ord]
96
+ it_h = it_h[ord]
97
+
98
+ ind_g = ~ind_h
99
+ if np.sum(ind_g) == 0:
100
+ G = None
101
+ v_g = None
102
+ d_g = None
103
+ it_g = None
104
+ else:
105
+ G = A[ind_g]
106
+ v_g = np.array(v)[ind_g]
107
+ d_g = np.array(d)[ind_g]
108
+ it_g = np.array(it)[ind_g]
109
+
110
+ return {
111
+ 'H': H,
112
+ 'G': G,
113
+ 'Hv': v_h,
114
+ 'Gv': v_g,
115
+ 'Hdistr': d_h,
116
+ 'Gdistr': d_g,
117
+ 'Hin_type': it_h,
118
+ 'Gin_type': it_g
119
+ }
120
+
121
+
122
+ def gen_monthly():
123
+ H = np.zeros((10, 12), dtype=int)
124
+ for j in range(6):
125
+ H[j, (2 * j):(2 * (j + 1))] = 1
126
+ for j in range(3):
127
+ H[6 + j, (4 * j):(4 * (j + 1))] = 1
128
+ H[9, :] = 1
129
+
130
+ G = np.zeros((6, 12), dtype=int)
131
+ for j in range(4):
132
+ G[j, (3 * j):(3 * (j + 1))] = 1
133
+ for j in range(2):
134
+ G[4 + j, (6 * j):(6 * (j + 1))] = 1
135
+
136
+ return np.vstack([H, G])
137
+
138
+
139
+ def gen_weekly():
140
+ H = np.zeros((40, 52), dtype=int)
141
+ for j in range(26):
142
+ H[j, (2 * j):(2 * (j + 1))] = 1
143
+ for j in range(13):
144
+ H[26 + j, (4 * j):(4 * (j + 1))] = 1
145
+ H[39, :] = 1
146
+
147
+ G = np.zeros((6, 52), dtype=int)
148
+ for j in range(4):
149
+ G[j, (13 * j):(13 * (j + 1))] = 1
150
+ for j in range(2):
151
+ G[4 + j, (26 * j):(26 * (j + 1))] = 1
152
+
153
+ return np.vstack([H, G])
154
+
155
+
156
+ def temporal_aggregation(y, agg_levels=None):
157
+ f = len(y) // (np.arange(1, len(y) + 1) % len(y)).max()
158
+ L = len(y)
159
+ s = np.arange(len(y)) / f + 1
160
+ if agg_levels is None:
161
+ agg_levels = [i for i in range(1, f + 1) if f % i == 0 and L >= i]
162
+ else:
163
+ agg_levels = sorted([level for level in agg_levels if level <= L])
164
+ if 1 not in agg_levels:
165
+ agg_levels = [1] + agg_levels
166
+
167
+ out = []
168
+ for k in agg_levels:
169
+ num_aggs = L // k
170
+ y_trunc = y[-num_aggs * k:]
171
+ y_matrix = y_trunc.reshape((k, num_aggs))
172
+ y_start = s[-num_aggs * k] + (L - num_aggs * k) / f
173
+ y_f = f // k
174
+ y_agg = np.sum(y_matrix, axis=0)
175
+ out.append((y_agg, y_f, y_start))
176
+
177
+ return out[::-1]
178
+
179
+
180
+ def get_reconc_matrices(agg_levels, h):
181
+ A = []
182
+ for k in agg_levels:
183
+ if k == 1:
184
+ continue
185
+ k_r = h // k
186
+ k_A = np.zeros((k_r, h), dtype=int)
187
+ for r in range(k_r):
188
+ k_A[r, r * k:(r + 1) * k] = 1
189
+ A.append(k_A)
190
+
191
+ A = np.vstack(A[::-1])
192
+ S = np.vstack([A, np.eye(h, dtype=int)])
193
+ return {'A': A, 'S': S}
194
+
195
+
196
+ def get_A_from_S(S):
197
+ S = np.array(S)
198
+ bottom_idxs = np.where(np.sum(S, axis=1) == 1)[0]
199
+ if len(bottom_idxs) < S.shape[1]:
200
+ raise ValueError("Check S: some bottom rows are missing")
201
+ upper_idxs = np.setdiff1d(np.arange(S.shape[0]), bottom_idxs)
202
+ A = S[upper_idxs, :]
203
+ return {'A': A, 'upper_idxs': upper_idxs, 'bottom_idxs': bottom_idxs}
204
+
205
+
206
+ def split_hierarchy(S, Y):
207
+ if len(S) != len(Y):
208
+ raise ValueError(f"Error: summing matrix rows ({len(S)}) != length base forecasts ({len(Y)})")
209
+
210
+ result = get_A_from_S(S)
211
+ upper = np.array(Y)[result['upper_idxs']]
212
+ bottom = np.array(Y)[result['bottom_idxs']]
213
+ return {
214
+ 'A': result['A'],
215
+ 'upper': upper,
216
+ 'bottom': bottom,
217
+ 'upper_idxs': result['upper_idxs'],
218
+ 'bottom_idxs': result['bottom_idxs']
219
+ }
220
+
221
+
222
+ def check_hierarchical(A):
223
+ A = np.array(A)
224
+ k, m = A.shape
225
+
226
+ for i in range(k):
227
+ for j in range(k):
228
+ if i < j:
229
+ cond1 = np.dot(A[i, :], A[j, :]) != 0
230
+ cond2 = np.any(A[j, :] > A[i, :])
231
+ cond3 = np.any(A[i, :] > A[j, :])
232
+ if cond1 and cond2 and cond3:
233
+ return False
234
+ return True
235
+
236
+
237
+ def check_BU_matr(A):
238
+ A = np.array(A)
239
+ k, m = A.shape
240
+
241
+ for i in range(k):
242
+ for j in range(k):
243
+ if i < j:
244
+ cond1 = np.dot(A[i, :], A[j, :]) != 0
245
+ cond2 = np.any(A[i, :] > A[j, :])
246
+ if cond1 and cond2:
247
+ return False
248
+ return True
249
+
250
+
251
+ def lowest_lev(A):
252
+ A = np.array(A)
253
+ if not check_hierarchical(A):
254
+ raise ValueError("Matrix A is not hierarchical")
255
+
256
+ indexes = np.unique(A, return_index=True, axis=0)[1];
257
+ A_uni = np.vstack([A[index] for index in sorted(indexes)])
258
+ k, m = A_uni.shape
259
+
260
+ low_rows_A_uni = []
261
+ for i in range(k):
262
+ low_rows_A_uni.append(i)
263
+ for j in range(k):
264
+ if i != j:
265
+ if np.all(A_uni[j, :] <= A_uni[i, :]):
266
+ low_rows_A_uni.pop()
267
+ break
268
+
269
+
270
+ # Keep all rows except those that have no descendants among the uppers
271
+ low_rows_A_uni = list(dict.fromkeys(low_rows_A_uni)) # Remove duplicates and keep order
272
+
273
+ # Now, change the indices of the lowest rows to match with A (instead of A_uni)
274
+ #low_rows_A = np.arange(A.shape[0])[np.unique(A, axis=0, return_index=True)[1]][low_rows_A_uni]
275
+
276
+ _, unique_idxs = np.unique(A, axis=0, return_index=True)
277
+ low_rows_A = np.sort(unique_idxs)[low_rows_A_uni]
278
+
279
+ # The sum of the rows corresponding to the lowest level should be a vector of 1
280
+ if not np.all(np.sum(A[low_rows_A, :], axis=0) == 1):
281
+ unbal_bott = np.where(np.sum(A[low_rows_A, :], axis=0) != 1)[0]
282
+ err_mess = "It is impossible to find the lowest upper level. Probably the hierarchy is unbalanced, the following bottom should be duplicated (see example): "
283
+ err_mess += " ".join(map(str, unbal_bott))
284
+ raise ValueError(err_mess)
285
+ return low_rows_A
286
+
287
+
288
+ def get_Au(A, lowest_rows=None):
289
+ if lowest_rows is None:
290
+ lowest_rows = lowest_lev(A)
291
+
292
+ if len(lowest_rows) == len(A):
293
+ print("Warning: All the upper are lowest-upper. Return None")
294
+ return None
295
+
296
+ A = np.array(A)
297
+ lowest_rows = np.array(lowest_rows)
298
+
299
+ A_ = np.delete(A, lowest_rows, axis=0)
300
+ n_upp_u = A_.shape[0]
301
+ n_bott_u = len(lowest_rows)
302
+ A_u = np.zeros((n_upp_u, n_bott_u), dtype=int)
303
+
304
+ for j, l in enumerate(lowest_rows):
305
+ for i in range(n_upp_u):
306
+ A_u[i, j] = np.all(A[l, :] <= A_[i, :]) # check if "lower upper" j is a descendant of "upper upper" i
307
+
308
+ return A_u
309
+
310
+
311
+ def check_ordered_A(A):
312
+ A = np.array(A)
313
+ aggregates_sum = np.sum(A, axis=1)
314
+ ordered_aggreg = np.argsort(aggregates_sum)[::-1] # Sort indices in decreasing order
315
+
316
+ if np.all(aggregates_sum == aggregates_sum[ordered_aggreg]):
317
+ return {'value': True}
318
+ else:
319
+ return {'value': False, 'order': ordered_aggreg}
320
+
321
+