test_validation.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import unittest
  2. import os
  3. import numpy as np
  4. from glob import glob
  5. import shutil
  6. from bci_core import utils as ana_utils
  7. from training import train_model, model_saver
  8. from dataloaders import library_ieeg
  9. from validation import validation
  10. class TestValidation(unittest.TestCase):
  11. @classmethod
  12. def setUpClass(cls):
  13. root_path = './tests/data'
  14. cls.event_id = {'ball': 2, 'rest': 0}
  15. raw = library_ieeg.raw_preprocessing(os.path.join(root_path, 'ecog-data/1', 'bp_mot_t_h.mat'), finger_model='ball')
  16. raw = raw.pick_channels([raw.info['ch_names'][i] for i in [5,6,7,12,13,14,20,21]])
  17. cls.raw = raw
  18. # split into 2 pieces
  19. t_min, t_max = raw.times[0], raw.times[-1]
  20. t_mid = raw.times[len(raw.times) // 2]
  21. raw_train = raw.copy().crop(tmin=t_min, tmax=t_mid, include_tmax=True)
  22. cls.raw_val = raw.copy().crop(tmin=t_mid, tmax=t_max)
  23. # reconstruct single event for validation
  24. if cls.raw_val.annotations.onset[0] > t_mid:
  25. # correct time by first timestamp
  26. cls.raw_val.annotations.onset -= t_mid
  27. # train with the first half
  28. model = train_model(raw_train, event_id=cls.event_id, model_type='baseline')
  29. model_saver(model, './tests/data/', 'baseline', 'test', cls.event_id)
  30. cls.model_path = glob(os.path.join('./tests/data/', 'test', '*.pkl'))[0]
  31. @classmethod
  32. def tearDownClass(cls) -> None:
  33. shutil.rmtree(os.path.join('./tests/data/', 'test'))
  34. return super().tearDownClass()
  35. def test_event_metric(self):
  36. event_gt = np.array([[0, 0, 0], [5, 0, 1], [7, 0, 0], [9, 0, 2]])
  37. event_pred = np.array([[1, 0, 0], [4, 0, 1], [6, 0, 1], [7, 0, 0], [10, 0, 1], [11, 0, 2]])
  38. fs = 1
  39. precision, recall, f1_score = ana_utils.event_metric(event_gt, event_pred, fs, ignore_event=(0,))
  40. self.assertEqual(f1_score, 2 / 3)
  41. self.assertEqual(precision, 1 / 2)
  42. self.assertEqual(recall, 1)
  43. def test_validation(self):
  44. (precision, recall, f1_score, r), fig_erds, fig_pred = validation(self.raw, self.event_id, model=self.model_path, state_change_threshold=0.7)
  45. fig_erds.savefig('./tests/data/erds.pdf')
  46. fig_pred.savefig('./tests/data/pred.pdf')
  47. self.assertTrue(f1_score > 0.9)
  48. self.assertTrue(r > 0.5)
  49. if __name__ == '__main__':
  50. unittest.main()