-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathnasagamma_test.py
610 lines (499 loc) · 17.8 KB
/
nasagamma_test.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
"""
Test nasagamma modules
"""
from nasagamma import spectrum as sp
from nasagamma import peaksearch as ps
from nasagamma import peakfit as pf
from nasagamma import file_reader
import traceback
import pandas as pd
import pytest
# import sys, os
# # Disable print
# def blockPrint():
# sys.stdout = open(os.devnull, 'w')
# # Restore print
# def enablePrint():
# sys.stdout = sys.__stdout__
file_csv = "examples/data/gui_test_data_cebr.csv"
file_cnf = "examples/data/gui_test_data_lab_sources.cnf"
file_cal = "examples/data/gui_test_data_cebr_cal.csv"
file_hpge = "examples/data/gui_test_data_hpge.csv"
def green(s):
return "\033[1;32m%s\033[m" % s
def yellow(s):
return "\033[1;33m%s\033[m" % s
def red(s):
return "\033[1;31m%s\033[m" % s
def log(*m):
print(" ".join(map(str, m)))
def log_exit(*m):
log(red("ERROR:"), *m)
exit(1)
def test_nasagamma():
try:
import nasagamma
log(green("PASS"), "nasagamma installed")
except ModuleNotFoundError:
log(red("FAIL"), "nasagamma not installed")
def test_csv_reader():
try:
e_units1, _ = file_reader.read_csv_file(file_csv)
e_units2, _ = file_reader.read_csv_file(file_cal)
if e_units1 == "channels" and e_units2 == "MeV":
log(green("PASS"), "csv file reader OK")
else:
log(red("FAIL"), "csv file reader unable to read units")
except:
log(red("FAIL"), "csv file reader unable to run")
def test_cnf_reader():
try:
e_units, spect = file_reader.read_cnf_to_spect(file_cnf)
if e_units == "keV" and spect.counts.shape[0] > 0:
log(green("PASS"), "cnf file reader OK")
except:
log(red("FAIL"), "cnf file reader unable to run")
def test_spectrum():
try:
df = pd.read_csv(file_csv)
cts_np = df["counts"].to_numpy()
spect = sp.Spectrum(counts=cts_np)
if len(spect.counts) == 0:
log(red("FAIL"), "Empty counts in spectrum")
else:
log(green("PASS"), "Spectrum class OK")
except:
log(red("FAIL"), "Cannot instantiate a spectrum object")
def test_peaksearch():
try:
df = pd.read_csv(file_csv)
cts_np = df["counts"].to_numpy()
spect_csv = sp.Spectrum(counts=cts_np)
_, spect_cnf = file_reader.read_cnf_to_spect(file_cnf)
# without range
try:
search1 = ps.PeakSearch(spect_csv, ref_x=420, ref_fwhm=20)
search2 = ps.PeakSearch(spect_cnf, ref_x=420, ref_fwhm=20)
log(green("PASS"), "Peaksearch class ok before xrange")
except:
log(red("FAIL"), "Peaksearch class failed before testing xrange")
# with defined range
try:
search3 = ps.PeakSearch(
spect_csv, ref_x=420, ref_fwhm=20, xrange=[500, 800]
)
search4 = ps.PeakSearch(
spect_cnf, ref_x=420, ref_fwhm=20, xrange=[523, 1400]
)
log(green("PASS"), "Peaksearch class ok after xrange")
except:
log(red("FAIL"), "Peaksearch class failed after testing xrange")
except:
log(red("FAIL"), "Cannot instantiate a peaksearch object")
return search1, search2, search3, search4
def test_peakfit():
search1, search2, search3, search4 = test_peaksearch()
try:
# blockPrint()
fit1 = pf.PeakFit(search1, xrange=[600, 800], bkg="poly1")
fit2 = pf.PeakFit(search2, xrange=[1080, 1400], bkg="poly1")
fit3 = pf.PeakFit(search3, xrange=[700, 745], bkg="poly1")
fit4 = pf.PeakFit(search4, xrange=[550, 700], bkg="poly1")
# enablePrint()
log(green("PASS"), "Peakfit class ok")
except:
log(red("FAIL"), "Cannot instantiate a peakfit object")
def main():
try:
test_nasagamma()
test_csv_reader()
test_cnf_reader()
test_spectrum()
test_peakfit()
except Exception:
log_exit(traceback.format_exc())
if __name__ == "__main__":
main()
# import os
# import sys
# import time
# import traceback
# import project1 as p1
# import numpy as np
# verbose = False
# def green(s):
# return '\033[1;32m%s\033[m' % s
# def yellow(s):
# return '\033[1;33m%s\033[m' % s
# def red(s):
# return '\033[1;31m%s\033[m' % s
# def log(*m):
# print(" ".join(map(str, m)))
# def log_exit(*m):
# log(red("ERROR:"), *m)
# exit(1)
# def test_real(ex_name, f, exp_res, *args):
# try:
# res = f(*args)
# except NotImplementedError:
# log(red("FAIL"), ex_name, ": not implemented")
# return True
# if not np.isreal(res):
# log(red("FAIL"), ex_name, ": does not return a real number, type: ", type(res))
# return True
# if res != exp_res:
# log(red("FAIL"), ex_name, ": incorrect answer. Expected", exp_res, ", got: ", res)
# return True
# def equals(x, y):
# if type(y) == np.ndarray:
# return (x == y).all()
# return x == y
# def test_tuple(ex_name, f, exp_res, *args, **kwargs):
# try:
# res = f(*args, **kwargs)
# except NotImplementedError:
# log(red("FAIL"), ex_name, ": not implemented")
# return True
# if not type(res) == tuple:
# log(red("FAIL"), ex_name, ": does not return a tuple, type: ", type(res))
# return True
# if not len(res) == len(exp_res):
# log(red("FAIL"), ex_name, ": expected a tuple of size ", len(exp_res), " but got tuple of size", len(res))
# return True
# if not all(equals(x, y) for x, y in zip(res, exp_res)):
# log(red("FAIL"), ex_name, ": incorrect answer. Expected", exp_res, ", got: ", res)
# return True
# def test_array(ex_name, f, exp_res, *args):
# try:
# res = f(*args)
# except NotImplementedError:
# log(red("FAIL"), ex_name, ": not implemented")
# return True
# if not type(res) == np.ndarray:
# log(red("FAIL"), ex_name, ": does not return a numpy array, type: ", type(res))
# return True
# if not len(res) == len(exp_res):
# log(red("FAIL"), ex_name, ": expected an array of shape ", exp_res.shape, " but got array of shape", res.shape)
# return True
# if not all(equals(x, y) for x, y in zip(res, exp_res)):
# log(red("FAIL"), ex_name, ": incorrect answer. Expected", exp_res, ", got: ", res)
# return True
# def test_list(ex_name, f, exp_res, *args):
# try:
# res = f(*args)
# except NotImplementedError:
# log(red("FAIL"), ex_name, ": not implemented")
# return True
# if not type(res) == list:
# log(red("FAIL"), ex_name, ": does not return a list, type: ", type(res))
# return True
# if not len(res) == len(exp_res):
# log(red("FAIL"), ex_name, ": expected a list of size ", len(exp_res), " but got list of size", len(res))
# return True
# if not all(equals(x, y) for x, y in zip(res, exp_res)):
# log(red("FAIL"), ex_name, ": incorrect answer. Expected", exp_res, ", got: ", res)
# return True
# def test_get_order():
# ex_name = "Get order"
# if test_list(
# ex_name, p1.get_order,
# [0], 1):
# log("You should revert `get_order` to its original implementation for this test to pass")
# return
# if test_list(
# ex_name, p1.get_order,
# [1, 0], 2):
# log("You should revert `get_order` to its original implementation for this test to pass")
# return
# log(green("PASS"), ex_name, "")
# def test_hinge_loss_single():
# ex_name = "Hinge loss single"
# feature_vector = np.array([1, 2])
# label, theta, theta_0 = 1, np.array([-1, 1]), -0.2
# exp_res = 1 - 0.8
# if test_real(
# ex_name, p1.hinge_loss_single,
# exp_res, feature_vector, label, theta, theta_0):
# return
# log(green("PASS"), ex_name, "")
# def test_hinge_loss_full():
# ex_name = "Hinge loss full"
# feature_vector = np.array([[1, 2], [1, 2]])
# label, theta, theta_0 = np.array([1, 1]), np.array([-1, 1]), -0.2
# exp_res = 1 - 0.8
# if test_real(
# ex_name, p1.hinge_loss_full,
# exp_res, feature_vector, label, theta, theta_0):
# return
# log(green("PASS"), ex_name, "")
# def test_perceptron_single_update():
# ex_name = "Perceptron single update"
# feature_vector = np.array([1, 2])
# label, theta, theta_0 = 1, np.array([-1, 1]), -1.5
# exp_res = (np.array([0, 3]), -0.5)
# if test_tuple(
# ex_name, p1.perceptron_single_step_update,
# exp_res, feature_vector, label, theta, theta_0):
# return
# feature_vector = np.array([1, 2])
# label, theta, theta_0 = 1, np.array([-1, 1]), -1
# exp_res = (np.array([0, 3]), 0)
# if test_tuple(
# ex_name + " (boundary case)", p1.perceptron_single_step_update,
# exp_res, feature_vector, label, theta, theta_0):
# return
# log(green("PASS"), ex_name, "")
# def test_perceptron():
# ex_name = "Perceptron"
# feature_matrix = np.array([[1, 2]])
# labels = np.array([1])
# T = 1
# exp_res = (np.array([1, 2]), 1)
# if test_tuple(
# ex_name, p1.perceptron,
# exp_res, feature_matrix, labels, T):
# return
# feature_matrix = np.array([[1, 2], [-1, 0]])
# labels = np.array([1, 1])
# T = 1
# exp_res = (np.array([0, 2]), 2)
# if test_tuple(
# ex_name, p1.perceptron,
# exp_res, feature_matrix, labels, T):
# return
# feature_matrix = np.array([[1, 2]])
# labels = np.array([1])
# T = 2
# exp_res = (np.array([1, 2]), 1)
# if test_tuple(
# ex_name, p1.perceptron,
# exp_res, feature_matrix, labels, T):
# return
# feature_matrix = np.array([[1, 2], [-1, 0]])
# labels = np.array([1, 1])
# T = 2
# exp_res = (np.array([0, 2]), 2)
# if test_tuple(
# ex_name, p1.perceptron,
# exp_res, feature_matrix, labels, T):
# return
# log(green("PASS"), ex_name, "")
# def test_average_perceptron():
# ex_name = "Average perceptron"
# feature_matrix = np.array([[1, 2]])
# labels = np.array([1])
# T = 1
# exp_res = (np.array([1, 2]), 1)
# if test_tuple(
# ex_name, p1.average_perceptron,
# exp_res, feature_matrix, labels, T):
# return
# feature_matrix = np.array([[1, 2], [-1, 0]])
# labels = np.array([1, 1])
# T = 1
# exp_res = (np.array([-0.5, 1]), 1.5)
# if test_tuple(
# ex_name, p1.average_perceptron,
# exp_res, feature_matrix, labels, T):
# return
# feature_matrix = np.array([[1, 2]])
# labels = np.array([1])
# T = 2
# exp_res = (np.array([1, 2]), 1)
# if test_tuple(
# ex_name, p1.average_perceptron,
# exp_res, feature_matrix, labels, T):
# return
# feature_matrix = np.array([[1, 2], [-1, 0]])
# labels = np.array([1, 1])
# T = 2
# exp_res = (np.array([-0.25, 1.5]), 1.75)
# if test_tuple(
# ex_name, p1.average_perceptron,
# exp_res, feature_matrix, labels, T):
# return
# log(green("PASS"), ex_name, "")
# def test_pegasos_single_update():
# ex_name = "Pegasos single update"
# feature_vector = np.array([1, 2])
# label, theta, theta_0 = 1, np.array([-1, 1]), -1.5
# L = 0.2
# eta = 0.1
# exp_res = (np.array([-0.88, 1.18]), -1.4)
# if test_tuple(
# ex_name, p1.pegasos_single_step_update,
# exp_res,
# feature_vector, label, L, eta, theta, theta_0):
# return
# feature_vector = np.array([1, 1])
# label, theta, theta_0 = 1, np.array([-1, 1]), 1
# L = 0.2
# eta = 0.1
# exp_res = (np.array([-0.88, 1.08]), 1.1)
# if test_tuple(
# ex_name + " (boundary case)", p1.pegasos_single_step_update,
# exp_res,
# feature_vector, label, L, eta, theta, theta_0):
# return
# feature_vector = np.array([1, 2])
# label, theta, theta_0 = 1, np.array([-1, 1]), -2
# L = 0.2
# eta = 0.1
# exp_res = (np.array([-0.88, 1.18]), -1.9)
# if test_tuple(
# ex_name, p1.pegasos_single_step_update,
# exp_res,
# feature_vector, label, L, eta, theta, theta_0):
# return
# log(green("PASS"), ex_name, "")
# def test_pegasos():
# ex_name = "Pegasos"
# feature_matrix = np.array([[1, 2]])
# labels = np.array([1])
# T = 1
# L = 0.2
# exp_res = (np.array([1, 2]), 1)
# if test_tuple(
# ex_name, p1.pegasos,
# exp_res, feature_matrix, labels, T, L):
# return
# feature_matrix = np.array([[1, 1], [1, 1]])
# labels = np.array([1, 1])
# T = 1
# L = 1
# exp_res = (np.array([1-1/np.sqrt(2), 1-1/np.sqrt(2)]), 1)
# if test_tuple(
# ex_name, p1.pegasos,
# exp_res, feature_matrix, labels, T, L):
# return
# log(green("PASS"), ex_name, "")
# def test_classify():
# ex_name = "Classify"
# feature_matrix = np.array([[1, 1], [1, 1], [1, 1]])
# theta = np.array([1, 1])
# theta_0 = 0
# exp_res = np.array([1, 1, 1])
# if test_array(
# ex_name, p1.classify,
# exp_res, feature_matrix, theta, theta_0):
# return
# feature_matrix = np.array([[-1, 1]])
# theta = np.array([1, 1])
# theta_0 = 0
# exp_res = np.array([-1])
# if test_array(
# ex_name + " (boundary case)", p1.classify,
# exp_res, feature_matrix, theta, theta_0):
# return
# log(green("PASS"), ex_name, "")
# def test_classifier_accuracy():
# ex_name = "Classifier accuracy"
# train_feature_matrix = np.array([[1, 0], [1, -1], [2, 3]])
# val_feature_matrix = np.array([[1, 1], [2, -1]])
# train_labels = np.array([1, -1, 1])
# val_labels = np.array([-1, 1])
# exp_res = 1, 0
# T=1
# if test_tuple(
# ex_name, p1.classifier_accuracy,
# exp_res,
# p1.perceptron,
# train_feature_matrix, val_feature_matrix,
# train_labels, val_labels,
# T=T):
# return
# train_feature_matrix = np.array([[1, 0], [1, -1], [2, 3]])
# val_feature_matrix = np.array([[1, 1], [2, -1]])
# train_labels = np.array([1, -1, 1])
# val_labels = np.array([-1, 1])
# exp_res = 1, 0
# T=1
# L=0.2
# if test_tuple(
# ex_name, p1.classifier_accuracy,
# exp_res,
# p1.pegasos,
# train_feature_matrix, val_feature_matrix,
# train_labels, val_labels,
# T=T, L=L):
# return
# log(green("PASS"), ex_name, "")
# def test_bag_of_words():
# ex_name = "Bag of words"
# texts = [
# "He loves to walk on the beach",
# "There is nothing better"]
# try:
# res = p1.bag_of_words(texts)
# except NotImplementedError:
# log(red("FAIL"), ex_name, ": not implemented")
# return
# if not type(res) == dict:
# log(red("FAIL"), ex_name, ": does not return a tuple, type: ", type(res))
# return
# vals = sorted(res.values())
# exp_vals = list(range(len(res.keys())))
# if not vals == exp_vals:
# log(red("FAIL"), ex_name, ": wrong set of indices. Expected: ", exp_vals, " got ", vals)
# return
# log(green("PASS"), ex_name, "")
# keys = sorted(res.keys())
# exp_keys = ['beach', 'better', 'he', 'is', 'loves', 'nothing', 'on', 'the', 'there', 'to', 'walk']
# stop_keys = ['beach', 'better', 'loves', 'nothing', 'walk']
# if keys == exp_keys:
# log(yellow("WARN"), ex_name, ": does not remove stopwords:", [k for k in keys if k not in stop_keys])
# elif keys == stop_keys:
# log(green("PASS"), ex_name, " stopwords removed")
# else:
# log(red("FAIL"), ex_name, ": keys are missing:", [k for k in stop_keys if k not in keys], " or are not unexpected:", [k for k in keys if k not in stop_keys])
# def test_extract_bow_feature_vectors():
# ex_name = "Extract bow feature vectors"
# texts = [
# "He loves her ",
# "He really really loves her"]
# keys = ["he", "loves", "her", "really"]
# dictionary = {k:i for i, k in enumerate(keys)}
# exp_res = np.array(
# [[1, 1, 1, 0],
# [1, 1, 1, 1]])
# non_bin_res = np.array(
# [[1, 1, 1, 0],
# [1, 1, 1, 2]])
# try:
# res = p1.extract_bow_feature_vectors(texts, dictionary)
# except NotImplementedError:
# log(red("FAIL"), ex_name, ": not implemented")
# return
# if not type(res) == np.ndarray:
# log(red("FAIL"), ex_name, ": does not return a numpy array, type: ", type(res))
# return
# if not len(res) == len(exp_res):
# log(red("FAIL"), ex_name, ": expected an array of shape ", exp_res.shape, " but got array of shape", res.shape)
# return
# log(green("PASS"), ex_name)
# if (res == exp_res).all():
# log(yellow("WARN"), ex_name, ": uses binary indicators as features")
# elif (res == non_bin_res).all():
# log(green("PASS"), ex_name, ": correct non binary features")
# else:
# log(red("FAIL"), ex_name, ": unexpected feature matrix")
# return
# def main():
# log(green("PASS"), "Import project1")
# try:
# test_get_order()
# test_hinge_loss_single()
# test_hinge_loss_full()
# test_perceptron_single_update()
# test_perceptron()
# test_average_perceptron()
# test_pegasos_single_update()
# test_pegasos()
# test_classify()
# test_classifier_accuracy()
# test_bag_of_words()
# test_extract_bow_feature_vectors()
# except Exception:
# log_exit(traceback.format_exc())
# if __name__ == "__main__":
# main()