-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample.py
363 lines (313 loc) · 13.1 KB
/
sample.py
1
2
3
4
5
6
7
8
9
10
11
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
from dataclasses import dataclass
from typing import List, Union, Tuple
import numpy as np
from scipy.stats import bernoulli, norm
import pandas as pd
from functools import partial
from itertools import combinations, product
from math import comb, sqrt
@dataclass
class sample_generator:
p: int
sample_size: int
num_interactions: int = None
rng: np.random._generator.Generator = np.random.default_rng()
beta_range: Tuple[Union[int, float]] = (3, 8)
pi_range: Tuple[Union[float]] = (.2, .8)
error_scale: float = sqrt(5)
@property
def interactions(self):
if hasattr(self, '_interactions'):
pass
else:
beta = [f'beta_{i}' for i in range(1, self.p+1)]
beta_interaction_coef = []
if self.num_interactions:
assert self.num_interactions < 2**self.p -1 - self.p
else:
self.num_interactions = int(self.rng.uniform(0, 2**self.p - 1 - self.p))
r = self.num_interactions
size_total_int = 2**self.p -1 - self.p
chosen_index = np.sort(self.rng.choice(range(size_total_int), r, replace = False))
chosen_interactions = []
i = 0
for k in range(2, self.p + 1):
chosen_interactions += ['*'.join(beta_name) for idx, beta_name in \
zip(range(i, i+comb(self.p, k)), combinations(beta, k)) \
if idx in chosen_index.tolist() ]
i += comb(self.p, k)
chosen_index = [1 for _ in range(self.p + 1)] + \
[1 if x in chosen_index.tolist() else 0 for x in range(size_total_int)]
self.interactions_coef = [x if self.rng.random() < .5 else -x for x \
in self.rng.uniform(low=self.beta_range[0], high=self.beta_range[1], size=r)]
self.beta_effective = chosen_index
self._interactions = {x.replace('beta_', 'X'):val for x, val in zip(chosen_interactions, self.interactions_coef)}
return self._interactions
@property
def beta(self):
if hasattr(self, '_beta'):
pass
else:
self._beta = [x if self.rng.random() < .5 else -x for x in self.rng.uniform(low=self.beta_range[0], high=self.beta_range[1], size=self.p+1)]
return {f'beta_{i}': v for i,v in enumerate(self._beta)}
@property
def beta_names(self):
if hasattr(self, '_beta_names'):
pass
else:
beta_raw_names = [f'beta{i}' for i in range(1, self.p + 1)]
beta_names = [f'beta{i}' for i in range(self.p + 1)]
for r in range(2, self.p):
beta_names += ['*'.join(x) for x in combinations(beta_raw_names, r)]
beta_names += ['*'.join(beta_raw_names)]
self._beta_names = beta_names
del beta_names
del beta_raw_names
return self._beta_names
@property
def pi(self):
if hasattr(self, '_pi'):
pass
else:
self._pi = self.rng.uniform(low = self.pi_range[0], high = self.pi_range[1], size = self.p)
return {f'pi_{i+1}': v for i,v in enumerate(self._pi)}
@staticmethod
def x(p, n):
return bernoulli.rvs(p, size= n)
@property
def X(self):
if hasattr(self, '_X'):
pass
else:
self._X = pd.DataFrame({f'X{i+1}':self.x(pi, self.sample_size) for i, pi in enumerate(self.pi.values())}).astype(np.ubyte)
return self._X
@property
def y(self):
if hasattr(self, '_y'):
pass
else:
beta = self.beta
interactions = self.interactions
y = []
def find_interaction_effect(row, interactions = self.interactions):
output = 0
for key, val in interactions.items():
output += row[key.split('*')].prod() * val
return output
for idx, row in self.X.iterrows():
main = beta['beta_0'] + sum([x*y for x,y in zip(list(beta.values())[1:], row)])
interaction_eff = find_interaction_effect(row)
error = norm.rvs(scale = self.error_scale)
y.append(main + interaction_eff + error)
self._y = np.array(y).reshape(-1,1)
return self._y
# for idx, row in rng.X.iterrows():
# print(rng.beta['beta_0'] + sum([x*y for x,y in zip(list(rng.beta.values())[1:], row)]))
@property
def barcode(self):
if hasattr(self, '_barcode'):
pass
else:
self._barcode = self.gen_barcode(self.X)
return self._barcode
@staticmethod
def gen_barcode(X):
pack_bits = np.packbits(np.array(X), axis = -1)
if pack_bits.shape[1]>1:
def gen_barcode(a, k, return_float = False):
m = len(a)-1
total_sum = 0
for i, x in enumerate(a):
if i < m:
if return_float:
adjust = (x * 2**(m-i-1) * 2**k)
total_sum += float(adjust)
else:
total_sum += (x * 2**(m-i-1) << k)
else:
total_sum += (x >> (8-k))
return total_sum
if X.shape[1] > 500:
barcode = partial(gen_barcode, k = X.shape[1]%8, return_float = True)
else:
barcode = partial(gen_barcode, k = X.shape[1]%8)
else:
def adjust_barcode(a, k):
a = a >> k
return a
barcode = partial(adjust_barcode, k = 8-X.shape[1])
output = np.apply_along_axis(barcode, 1, pack_bits)
return output
@staticmethod
def barcode_to_beta(barcode):
if isinstance(barcode, list):
output = [1] + barcode
else:
output = [1] + list(barcode)
N = len(output)
for i in range(2, N):
output += [np.prod(x) for x in combinations(barcode, i)]
# output += [np.prod(output)]
return output
@property
def L(self):
if hasattr(self, '_L'):
pass
else:
all_sets = list(set(product([0,1], repeat = self.p))); all_sets.sort()
self._L = np.array([self.barcode_to_beta(x) for x in all_sets]).T
return self._L
# Just for a simulation ####################################################################################
################################################################################################################
########################################################v########################################################
@dataclass
class simple_sample_generator:
p: int
sample_size: int
num_interactions: int = None
rng: np.random._generator.Generator = np.random.default_rng()
beta_range: Tuple[Union[int, float]] = (1,1)
pi_range: Tuple[Union[float]] = (.5,.5)
error_scale: float = sqrt(1)
@property
def interactions(self):
if hasattr(self, '_interactions'):
pass
else:
beta = [f'beta_{i}' for i in range(1, self.p+1)]
beta_interaction_coef = []
if self.num_interactions:
assert self.num_interactions < 2**self.p -1 - self.p
else:
self.num_interactions = int(self.rng.uniform(0, 2**self.p - 1 - self.p))
r = self.num_interactions
size_total_int = 2**self.p -1 - self.p
chosen_index = np.sort(self.rng.choice(range(size_total_int), r, replace = False))
chosen_interactions = []
i = 0
for k in range(2, self.p + 1):
chosen_interactions += ['*'.join(beta_name) for idx, beta_name in \
zip(range(i, i+comb(self.p, k)), combinations(beta, k)) \
if idx in chosen_index.tolist() ]
i += comb(self.p, k)
chosen_index = [1 for _ in range(self.p + 1)] + \
[1 if x in chosen_index.tolist() else 0 for x in range(size_total_int)]
self.interactions_coef = [x for x \
in self.rng.uniform(low=self.beta_range[0], high=self.beta_range[1], size=r)]
self.beta_effective = chosen_index
self._interactions = {x.replace('beta_', 'X'):val for x, val in zip(chosen_interactions, self.interactions_coef)}
return self._interactions
@property
def beta(self):
if hasattr(self, '_beta'):
pass
else:
self._beta = [x for x in self.rng.uniform(low=self.beta_range[0], high=self.beta_range[1], size=self.p+1)]
return {f'beta_{i}': v for i,v in enumerate(self._beta)}
@property
def beta_names(self):
if hasattr(self, '_beta_names'):
pass
else:
beta_raw_names = [f'beta{i}' for i in range(1, self.p + 1)]
beta_names = [f'beta{i}' for i in range(self.p + 1)]
for r in range(2, self.p):
beta_names += ['*'.join(x) for x in combinations(beta_raw_names, r)]
beta_names += ['*'.join(beta_raw_names)]
self._beta_names = beta_names
del beta_names
del beta_raw_names
return self._beta_names
@property
def pi(self):
if hasattr(self, '_pi'):
pass
else:
self._pi = self.rng.uniform(low = self.pi_range[0], high = self.pi_range[1], size = self.p)
return {f'pi_{i+1}': v for i,v in enumerate(self._pi)}
@staticmethod
def x(p, n):
return bernoulli.rvs(p, size= n)
@property
def X(self):
if hasattr(self, '_X'):
pass
else:
self._X = pd.DataFrame({f'X{i+1}':self.x(pi, self.sample_size) for i, pi in enumerate(self.pi.values())}).astype(np.ubyte)
return self._X
@property
def y(self):
if hasattr(self, '_y'):
pass
else:
beta = self.beta
interactions = self.interactions
y = []
def find_interaction_effect(row, interactions = self.interactions):
output = 0
for key, val in interactions.items():
output += row[key.split('*')].prod() * val
return output
for idx, row in self.X.iterrows():
main = beta['beta_0'] + sum([x*y for x,y in zip(list(beta.values())[1:], row)])
interaction_eff = find_interaction_effect(row)
error = norm.rvs(scale = self.error_scale)
y.append(main + interaction_eff + error)
self._y = np.array(y).reshape(-1,1)
return self._y
# for idx, row in rng.X.iterrows():
# print(rng.beta['beta_0'] + sum([x*y for x,y in zip(list(rng.beta.values())[1:], row)]))
@property
def barcode(self):
if hasattr(self, '_barcode'):
pass
else:
self._barcode = self.gen_barcode(self.X)
return self._barcode
@staticmethod
def gen_barcode(X):
pack_bits = np.packbits(np.array(X), axis = -1)
if pack_bits.shape[1]>1:
def gen_barcode(a, k, return_float = False):
m = len(a)-1
total_sum = 0
for i, x in enumerate(a):
if i < m:
if return_float:
adjust = (x * 2**(m-i-1) * 2**k)
total_sum += float(adjust)
else:
total_sum += (x * 2**(m-i-1) << k)
else:
total_sum += (x >> (8-k))
return total_sum
if X.shape[1] > 500:
barcode = partial(gen_barcode, k = X.shape[1]%8, return_float = True)
else:
barcode = partial(gen_barcode, k = X.shape[1]%8)
else:
def adjust_barcode(a, k):
a = a >> k
return a
barcode = partial(adjust_barcode, k = 8-X.shape[1])
output = np.apply_along_axis(barcode, 1, pack_bits)
return output
@staticmethod
def barcode_to_beta(barcode):
if isinstance(barcode, list):
output = [1] + barcode
else:
output = [1] + list(barcode)
N = len(output)
for i in range(2, N):
output += [np.prod(x) for x in combinations(barcode, i)]
# output += [np.prod(output)]
return output
@property
def L(self):
if hasattr(self, '_L'):
pass
else:
all_sets = list(set(product([0,1], repeat = self.p))); all_sets.sort()
self._L = np.array([self.barcode_to_beta(x) for x in all_sets]).T
return self._L