Repository navigation
Expand file tree
/
Copy pathAD_simul.py
More file actions
299 lines (243 loc) · 9.21 KB
/
Copy pathAD_simul.py
File metadata and controls
299 lines (243 loc) · 9.21 KB
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
import numpy as np
import time
import json
from src.data.generate_AD_data import ActivityDetetionDataset
from joblib import Parallel, delayed
import subprocess
import copy
def clone_method(met):
# returns a deep copy: same attributes, independent state
return copy.deepcopy(met)
#%%
def run_AD_monte_carlo_experiment(
CL,
SSR,
CLmethods,
titlestr,
MC_iters=500,
N=1000, # number of devices
L=64, # pilot length
Mlist=np.arange(10, 61, 10), # list of number of snapshots
Klist=np.arange(10, 51, 10), # list of active devices K
SNRlow=-15,
SNRhigh=0,
):
methods = CLmethods + list(SSR.keys())
num_methods = len(methods)
# ----------------------------
# BUILD CONFIG DICTIONARY
# ----------------------------
config = {
"MC_iters": int(MC_iters),
"N": int(N),
"L": int(L),
"Mlist": [int(m) for m in Mlist],
"Klist": [int(k) for k in Klist],
"SNRlow": float(SNRlow),
"SNRhigh": float(SNRhigh),
"methods": methods,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"python_version": subprocess.check_output(
["python", "--version"]
).decode().strip(),
}
# Try to log algorithm parameters if available in CL objects
algo_params = {}
for m in CLmethods:
obj = CL[m]
algo_params[m] = extract_simple_params(obj)
for m in list(SSR.keys()):
obj = SSR[m]
algo_params[m] = extract_simple_params(obj)
config["algorithm_parameters"] = algo_params
# ------------------------------------
# PREALLOCATE RESULT ARRAYS
# ------------------------------------
Pmd = np.zeros((len(Mlist), num_methods, len(Klist)))
Per = np.zeros((len(Mlist), num_methods, len(Klist)))
tme = np.zeros((len(Mlist), num_methods, len(Klist)))
nmse = np.zeros((len(Mlist), num_methods, len(Klist)))
print(f"MC iterations = {MC_iters}, L = {L}, N = {N}")
print(f"Detected methods: {methods}")
for k_idx, K in enumerate(Klist):
print(f"\n---- K = {K:3d}")
base_rng = np.random.default_rng(0)
if "CLMP" in list(methods):
CL["CLMP"].K = int(K)
if "CLMP2" in list(methods):
CL["CLMP2"].K = int(K)
if "SNIHT" in list(methods):
SSR["SNIHT"].K = int(K)
for m_idx, M in enumerate(Mlist):
print(f"- M = {M:3d} ", end="", flush=True)
# ---- Dataset
dataset = ActivityDetetionDataset(
NRSIM=MC_iters,
N=N, # devices
L=L, # pilot length
K=K, # sparsity
M=M, # snapshots
SNRlow=SNRlow,
SNRhigh=SNRhigh,
rng=base_rng,
)
# ---- Run evaluation (fast loop) ----
Pmd_k, Per_k, tme_k, nmse_k = run_ActivityDetection_parallel(
#Pmd_k, Per_k, tme_k, nmse_k = run_ActivityDetection(
dataset=dataset,
K=K,
CL=CL,
SSR = SSR,
CLmethods=CLmethods,
)
# convert dict -> array in method order
Pmd[m_idx, :, k_idx] = np.array([Pmd_k[m] for m in methods])
Per[m_idx, :, k_idx] = np.array([Per_k[m] for m in methods])
tme[m_idx, :, k_idx] = np.array([tme_k[m] for m in methods])
nmse[m_idx, :, k_idx] = np.array([nmse_k[m] for m in methods])
print("done.")
with open(f"saved_results/json/{titlestr}_config.json", "w") as f:
json.dump(config, f, indent=4)
print("\nSaved:")
print(f" - results/json/{titlestr}_config.json")
print("\nMonte Carlo simulation complete.")
return Pmd, Per, tme, nmse, config
#%%
def run_ActivityDetection_parallel(dataset, K, CL, SSR, CLmethods, n_jobs=-1):
"""
This function runs the activity detection for a given dataset, K, and methods
in CL and SSR. It returns the missdetection rate, probability of exact recovery,
computation time, and NMSE for each method.
It runs the evaluation in parallel using joblib. The dataset is expected to be an
instance of ActivityDetetionDataset, which generates fresh data for each sample.
The function uses joblib's Parallel and delayed to distribute the workload across
available CPU cores.
"""
methods = CLmethods + list(SSR.keys())
cputme = {m: 0.0 for m in methods}
md = {m: 0.0 for m in methods}
per = {m: 0.0 for m in methods}
nmse = {m: 0.0 for m in methods}
total_samples = len(dataset)
res_list = Parallel(n_jobs=n_jobs)(
delayed(process_one_sample)(i, dataset, K, CL,SSR,CLmethods)
for i in range(total_samples)
)
for res in res_list:
for m in methods:
cputme[m] += res[m]["time"]
md[m] += res[m]["md"]
per[m] += res[m]["per"]
nmse[m] += res[m]["nmse"]
for m in methods:
cputme[m] /= total_samples
md[m] /= total_samples
per[m] /= total_samples
nmse[m] /= total_samples
return md, per, cputme, nmse
#%%
def process_one_sample(idx, dataset, K, CL,SSR,CLmethods):
Y, A, sup, S_K = dataset[idx]
S = np.zeros((A.shape[1], Y.shape[1]), dtype=Y.dtype)
S[sup,:] = S_K.copy()
cov_m = (Y @ Y.conj().T) / Y.shape[1]
results = {}
for metname in CLmethods:
met = CL[metname]
met_clone = clone_method(met) # ensure no cross-contamination of state
if hasattr(met_clone, "_rng"):
met_clone._rng = np.random.default_rng(idx) # fresh, per-trial, reproducible
if hasattr(met_clone, "seed"):
met_clone.seed = idx
t0 = time.perf_counter()
met_clone.fit(A, cov_m)
t1 = time.perf_counter()
met_clone.support(K)
md_met = len(np.setdiff1d(met_clone.supp, sup))
met_clone.estimate_sources(A, Y)
diff = S - met_clone.signal_estimates_
nmse = np.sum(np.abs(diff)**2) / np.sum(np.abs(S)**2)
results[metname] = {
"time": t1 - t0,
"md": md_met / K,
"per": 1 if md_met == 0 else 0,
"nmse": nmse
}
for metname, met in SSR.items():
met_clone = clone_method(met) # ensure no cross-contamination of state
t0 = time.perf_counter()
met_clone.fit(Y, A)
t1 = time.perf_counter()
md_met = len(np.setdiff1d(met_clone.supp, sup))
diff = S - met_clone.signal_estimates_
nmse = np.sum(np.abs(diff)**2) / np.sum(np.abs(S)**2)
results[metname] = {
"time": t1 - t0,
"md": md_met / K,
"per": 1 if md_met == 0 else 0,
"nmse": nmse
}
return results
#%%
def extract_simple_params(obj):
params = {}
# Case 1: normal object with __dict__
if hasattr(obj, "__dict__"):
items = vars(obj).items()
else:
# Case 2: fallback — look at all attributes via dir()
items = ((k, getattr(obj, k)) for k in dir(obj))
for k, v in items:
# skip private/internal stuff
if k.startswith("_"):
continue
# only keep JSON-friendly scalar types
if isinstance(v, (int, float, bool, str)):
params[k] = v
return params
#%%
def run_ActivityDetection(dataset, K, CL,SSR,CLmethods):
methods = CLmethods + list(SSR.keys())
cputme = {m: 0.0 for m in methods}
md = {m: 0.0 for m in methods}
per = {m: 0.0 for m in methods}
nmse = {m: 0.0 for m in methods}
total_samples = len(dataset)
for it, (Y, A, sup,S_K) in enumerate(dataset):
S = np.zeros((A.shape[1], Y.shape[1]), dtype=Y.dtype)
S[sup,:] = S_K
cov_m = (Y @ Y.conj().T) / Y.shape[1]
for metname in CLmethods:
met = CL[metname]
t0 = time.perf_counter()
met.fit(A, cov_m)
t1 = time.perf_counter()
cputme[metname] += (t1 - t0)
met.support(K)
md_met = len(np.setdiff1d(met.supp, sup))
md[metname] += md_met / K
if md_met == 0:
per[metname] += 1
met.estimate_sources(A, Y)
diff = S - met.signal_estimates_
nmse[metname] += np.sum(np.abs(diff)**2) / np.sum(np.abs(S)**2)
for metname, met in SSR.items():
t0 = time.perf_counter()
met.fit(Y, A)
t1 = time.perf_counter()
cputme[metname] += (t1 - t0)
md_met = len(np.setdiff1d(met.supp, sup))
md[metname] += md_met / K
if md_met == 0:
per[metname] += 1
#met.estimate_sources(A, Y)
diff = S - met.signal_estimates_
nmse[metname] += np.sum(np.abs(diff)**2) / np.sum(np.abs(S)**2)
if (it + 1) % 100 == 0:
print(".", end="", flush=True)
for m in methods:
md[m] /= total_samples
per[m] /= total_samples
cputme[m] /= total_samples
nmse[m] /= total_samples
return md, per, cputme, nmse