online_sim.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. '''
  2. 模型模拟在线测试脚本
  3. 在线模式测试:event f1-score and decision trace
  4. '''
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7. import mne
  8. import yaml
  9. import os
  10. import argparse
  11. import logging
  12. from sklearn.metrics import accuracy_score
  13. from dataloaders import neo
  14. import bci_core.online as online
  15. import bci_core.utils as bci_utils
  16. from settings.config import settings
  17. logging.basicConfig(level=logging.DEBUG)
  18. logger = logging.getLogger(__name__)
  19. config_info = settings.CONFIG_INFO
  20. def parse_args():
  21. parser = argparse.ArgumentParser(
  22. description='Model validation'
  23. )
  24. parser.add_argument(
  25. '--subj',
  26. dest='subj',
  27. help='Subject name',
  28. default=None,
  29. type=str
  30. )
  31. parser.add_argument(
  32. '--state-change-threshold',
  33. '-scth',
  34. dest='state_change_threshold',
  35. help='Threshold for HMM state change',
  36. default=0.75,
  37. type=float
  38. )
  39. parser.add_argument(
  40. '--model-filename',
  41. dest='model_filename',
  42. help='Model filename',
  43. default=None,
  44. type=str
  45. )
  46. return parser.parse_args()
  47. class DataGenerator:
  48. def __init__(self, fs, X, epoch_step=1.):
  49. self.fs = int(fs)
  50. self.X = X
  51. self.epoch_step = epoch_step
  52. def get_data_batch(self, current_index):
  53. # return epoch_step length batch
  54. # create mne object
  55. ind = int(self.epoch_step * self.fs)
  56. data = self.X[:, current_index - ind:current_index].copy()
  57. return self.fs, [], data
  58. def loop(self, step_size=0.1):
  59. step = int(step_size * self.fs)
  60. for i in range(self.fs, self.X.shape[1] + 1, step):
  61. yield i / self.fs, self.get_data_batch(i)
  62. def _evaluation_loop(raw, events, model_hmm, step_length, event_trial_length):
  63. val_data = raw.get_data()
  64. fs = raw.info['sfreq']
  65. data_gen = DataGenerator(fs, val_data, epoch_step=step_length)
  66. decision_with_hmm = []
  67. decision_without_hmm = []
  68. probs = []
  69. for time, data in data_gen.loop():
  70. step_p, cls = model_hmm.viterbi(data, return_step_p=True)
  71. if cls >=0:
  72. cls = model_hmm.model.classes_[cls]
  73. decision_with_hmm.append((time, cls)) # map to unified label
  74. decision_without_hmm.append((time, model_hmm.model.classes_[np.argmax(step_p)]))
  75. probs.append((time, model_hmm.probability))
  76. probs = np.array(probs)
  77. events_pred = _construct_model_event(decision_with_hmm, fs)
  78. events_pred_naive = _construct_model_event(decision_without_hmm, fs)
  79. p_hmm, r_hmm, f1_hmm = bci_utils.event_metric(event_true=events, event_pred=events_pred, fs=fs)
  80. p_n, r_n, f1_n = bci_utils.event_metric(events, events_pred_naive, fs=fs)
  81. stim_true = _event_to_stim_channel(events, len(raw.times), trial_length=int(event_trial_length * fs))
  82. stim_pred = _event_to_stim_channel(events_pred, len(raw.times))
  83. stim_pred_naive = _event_to_stim_channel(events_pred_naive, len(raw.times))
  84. accu_hmm = accuracy_score(stim_true, stim_pred)
  85. accu_naive = accuracy_score(stim_true, stim_pred_naive)
  86. fig_pred, ax = plt.subplots(4, 1, sharex=True, sharey=False)
  87. ax[0].set_title('pred (naive)')
  88. ax[0].plot(raw.times, stim_pred_naive)
  89. ax[1].set_title('pred')
  90. ax[1].plot(raw.times, stim_pred)
  91. ax[2].set_title('true')
  92. ax[2].plot(raw.times, stim_true)
  93. ax[3].set_title('prob')
  94. ax[3].plot(probs[:, 0], probs[:, 1])
  95. ax[3].set_ylim([0, 1])
  96. return fig_pred, (p_hmm, r_hmm, f1_hmm, accu_hmm), (p_n, r_n, f1_n, accu_naive)
  97. def simulation(raw_val, event_id, model,
  98. state_change_threshold=0.8,
  99. step_length=1.,
  100. event_trial_length=5.):
  101. """模型验证接口,使用指定数据进行验证,绘制ersd map
  102. Args:
  103. raw (mne.io.Raw)
  104. event_id (dict)
  105. model: validate existing model,
  106. state_change_threshold (float): default 0.8
  107. step_length (float): batch data step length, default 1. (s)
  108. event_trial_length (float):
  109. Returns:
  110. None
  111. """
  112. fs = raw_val.info['sfreq']
  113. events_val, _ = mne.events_from_annotations(raw_val, event_id)
  114. events_val = neo.reconstruct_events(events_val,
  115. fs,
  116. finger_model=None,
  117. rest_trial_ind=[v for k, v in event_id.items() if k == 'rest'],
  118. mov_trial_ind=[v for k, v in event_id.items() if k != 'rest'],
  119. use_original_label=True)
  120. controller = online.Controller(0, model, state_change_threshold=state_change_threshold)
  121. model_hmm = controller.real_feedback_model
  122. # run with and without hmm
  123. fig_pred, metric_hmm, metric_naive = _evaluation_loop(raw_val,
  124. events_val,
  125. model_hmm,
  126. step_length,
  127. event_trial_length=event_trial_length)
  128. return metric_hmm, metric_naive, fig_pred
  129. def _construct_model_event(decision_seq, fs):
  130. events = []
  131. for i in decision_seq:
  132. time, cls = i
  133. if cls >= 0:
  134. events.append([int(time * fs), 0, cls])
  135. return np.array(events)
  136. def _event_to_stim_channel(events, time_length, trial_length=None):
  137. x = np.zeros(time_length)
  138. for i in range(0, len(events) - 1):
  139. if trial_length is not None:
  140. x[events[i, 0]: events[i, 0] + trial_length] = events[i, 2]
  141. else:
  142. x[events[i, 0]: events[i + 1, 0] - 1] = events[i, 2]
  143. return x
  144. if __name__ == '__main__':
  145. args = parse_args()
  146. subj_name = args.subj
  147. data_dir = f'./data/{subj_name}/'
  148. model_path = f'./static/models/{subj_name}/{args.model_filename}'
  149. with open(os.path.join(data_dir, 'val_info.yml'), 'r') as f:
  150. info = yaml.safe_load(f)
  151. sessions = info['sessions']
  152. event_id = {'rest': 0}
  153. for f in sessions.keys():
  154. event_id[f] = neo.FINGERMODEL_IDS[f]
  155. # preprocess raw
  156. trial_time = 5.
  157. raw = neo.raw_preprocessing(data_dir, sessions,
  158. unify_label=True,
  159. ori_epoch_length=trial_time,
  160. mov_trial_ind=[2],
  161. rest_trial_ind=[1],
  162. upsampled_epoch_length=None)
  163. # do validations
  164. metric_hmm, metric_naive, fig_pred = simulation(raw,
  165. event_id,
  166. model=model_path,
  167. state_change_threshold=args.state_change_threshold,
  168. step_length=config_info['buffer_length'],
  169. event_trial_length=trial_time)
  170. fig_pred.savefig(os.path.join(data_dir, 'pred.pdf'))
  171. logger.info(f'With HMM: precision: {metric_hmm[0]:.4f}, recall: {metric_hmm[1]:.4f}, f1_score: {metric_hmm[2]:.4f}, accuracy: {metric_hmm[3]:.4f}')
  172. logger.info(f'Without HMM: precision: {metric_naive[0]:.4f}, recall: {metric_naive[1]:.4f}, f1_score: {metric_naive[2]:.4f}, accuracy: {metric_naive[3]:.4f}')