2
0

online.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import joblib
  2. import numpy as np
  3. import random
  4. import logging
  5. from scipy import signal
  6. import mne
  7. from .feature_extractors import filterbank_extractor
  8. from .utils import parse_model_type
  9. logger = logging.getLogger(__name__)
  10. class Controller:
  11. """在线控制接口
  12. 运行时主要调用decision方法,
  13. 每次气动手反馈后调用reset_buffer方法,用以跳过气动手不应期
  14. Args:
  15. virtual_feedback_rate (float): 0-1之间浮点数,控制假反馈占比
  16. model_path (string): 模型文件路径
  17. buffer_steps (int):
  18. """
  19. def __init__(self,
  20. virtual_feedback_rate=1.,
  21. model_path=None,
  22. state_change_threshold=0.6):
  23. if (model_path is None) or (model_path == 'None'):
  24. self.real_feedback_model = None
  25. else:
  26. self.model_type, _ = parse_model_type(model_path)
  27. if self.model_type == 'baseline':
  28. self.real_feedback_model = BaselineHMM(model_path, state_change_threshold=state_change_threshold)
  29. elif self.model_type == 'riemann':
  30. self.real_feedback_model = RiemannHMM(model_path, state_change_threshold=state_change_threshold)
  31. else:
  32. raise NotImplementedError
  33. self.virtual_feedback_rate = virtual_feedback_rate
  34. def step_decision(self, data, true_label=None):
  35. """抓握训练调用接口,只进行单次判决,不涉及马尔可夫过程,
  36. 假反馈的错误反馈默认输出为10000
  37. Args:
  38. data (mne.io.RawArray): 数据
  39. true_label (None or int): 训练时假反馈的真实标签
  40. Return:
  41. int: 统一化标签 (-1: keep, 0: rest, 1: cylinder, 2: ball, 3: flex, 4: double, 5: treble)
  42. """
  43. virtual_feedback = self.virtual_feedback(true_label)
  44. logger.debug('step_decision: virtual feedback: {}'.format(virtual_feedback))
  45. if virtual_feedback is not None:
  46. return virtual_feedback
  47. if self.real_feedback_model is not None:
  48. fs, data = self.real_feedback_model.parse_data(data)
  49. p = self.real_feedback_model.step_probability(fs, data)
  50. logger.debug('step_decison: model probability: {}'.format(str(p)))
  51. pred = np.argmax(p)
  52. real_decision = self.real_feedback_model.model.classes_[pred]
  53. return real_decision
  54. else:
  55. raise ValueError('Neither decision model nor true label are given')
  56. def decision(self, data, true_label=None):
  57. """决策主要方法,输出逻辑如下:
  58. 如果有决策模型,无论是否有true_label,都会使用模型进行一步决策计算并填入buffer(不一定返回)
  59. 如果有true_label(训练模式),产生一个随机数确定本trial是否为假反馈,
  60. 是假反馈,产生一个随机数确定本trial产生正确or错误的假反馈,假反馈的标签为10000
  61. 不是假反馈,使用模型决策
  62. 如果没有true_label(测试模式),直接使用模型决策
  63. 模型决策逻辑:
  64. 根据模型记录的last_state,
  65. 如果当前state和last_state相同,输出-1
  66. 如果当前state和last_state不同,输出当前state
  67. Args:
  68. data (mne.io.RawArray): 数据
  69. true_label (None or int): 训练时假反馈的真实标签
  70. Return:
  71. int: 统一化标签 (-1: keep, 0: rest, 1: cylinder, 2: ball, 3: flex, 4: double, 5: treble)
  72. """
  73. if self.real_feedback_model is not None:
  74. real_decision = self.real_feedback_model.viterbi(data)
  75. # map to unified label
  76. if real_decision != -1:
  77. real_decision = self.real_feedback_model.model.classes_[real_decision]
  78. virtual_feedback = self.virtual_feedback(true_label)
  79. if virtual_feedback is not None:
  80. return virtual_feedback
  81. # true_label is None or not running virtual feedback in this trial
  82. # if no real model, raise ValueError
  83. if self.real_feedback_model is None:
  84. raise ValueError('Neither decision model nor true label are given')
  85. return real_decision
  86. def virtual_feedback(self, true_label=None):
  87. if true_label is not None:
  88. p = random.random()
  89. if p < self.virtual_feedback_rate: # virtual feedback (error rate 0.2)
  90. p_correct = random.random()
  91. if p_correct < 0.8:
  92. return true_label
  93. else:
  94. return 10000
  95. return None
  96. class HMMModel:
  97. def __init__(self, n_classes=2, state_trans_prob=0.6, state_change_threshold=0.7):
  98. self.n_classes = n_classes
  99. self._probability = np.ones(n_classes) / n_classes
  100. self._last_state = 0
  101. self.state_change_threshold = state_change_threshold
  102. # TODO: train with daily use data
  103. # build state transition matrix
  104. self.state_trans_matrix = np.zeros((n_classes, n_classes))
  105. # fill diagonal
  106. np.fill_diagonal(self.state_trans_matrix, state_trans_prob)
  107. # fill 0 -> each state,
  108. self.state_trans_matrix[0, 1:] = (1 - state_trans_prob) / (n_classes - 1)
  109. self.state_trans_matrix[1:, 0] = 1 - state_trans_prob
  110. def reset_state(self):
  111. self._last_state = 0
  112. self._probability = np.ones(self.n_classes) / self.n_classes
  113. def set_current_state(self, current_state):
  114. self._last_state = current_state
  115. self._probability = np.zeros(self.n_classes)
  116. self._probability[current_state] = 1
  117. def step_probability(self, fs, data):
  118. # do preprocessing here
  119. # common average
  120. data -= data.mean(axis=0)
  121. return data
  122. def parse_data(self, data):
  123. fs, event, data_array = data
  124. return fs, data_array
  125. def viterbi(self, data, return_step_p=False):
  126. """
  127. Interface for class decision
  128. """
  129. fs, data = self.parse_data(data)
  130. p = self.step_probability(fs, data)
  131. if return_step_p:
  132. return p, self.update_state(p)
  133. else:
  134. return self.update_state(p)
  135. def update_state(self, current_p):
  136. # veterbi algorithm
  137. self._probability = (self.state_trans_matrix * self._probability.T).sum(axis=1) * current_p
  138. # normalize
  139. self._probability /= np.sum(self._probability)
  140. logger.debug("viterbi probability, {}".format(str(self._probability)))
  141. current_state = np.argmax(self._probability)
  142. if current_state == self._last_state:
  143. return -1
  144. else:
  145. if self._probability[current_state] > self.state_change_threshold:
  146. self.set_current_state(current_state)
  147. return current_state
  148. else:
  149. return -1
  150. @property
  151. def probability(self):
  152. return np.max(self._probability[1:]) # largest prob except the rest state
  153. class BaselineHMM(HMMModel):
  154. def __init__(self, model, **kwargs):
  155. if isinstance(model, str):
  156. model = joblib.load(model)
  157. self.feat_extractor, self.model = model
  158. super(BaselineHMM, self).__init__(n_classes=len(self.model.classes_), **kwargs)
  159. def step_probability(self, fs, data):
  160. """Step
  161. """
  162. data = super(BaselineHMM, self).step_probability(fs, data)
  163. # filter data
  164. filter_bank_data = self.feat_extractor.transform(data)
  165. # downsampling
  166. decimate_rate = np.sqrt(fs / 10).astype(np.int16)
  167. filter_bank_data = signal.decimate(filter_bank_data, decimate_rate, axis=-1, zero_phase=True)
  168. filter_bank_data = signal.decimate(filter_bank_data, decimate_rate, axis=-1, zero_phase=True)
  169. # predict proba
  170. p = self.model.predict_proba(filter_bank_data[None]).squeeze()
  171. return p
  172. class RiemannHMM(HMMModel):
  173. def __init__(self, model, **kwargs):
  174. if isinstance(model, str):
  175. model = joblib.load(model)
  176. self.feat_extractor, self.scaler, self.cov, self.model = model
  177. super(RiemannHMM, self).__init__(n_classes=len(self.model.classes_), **kwargs)
  178. def step_probability(self, fs, data):
  179. """Step
  180. """
  181. data = super(RiemannHMM, self).step_probability(fs, data)
  182. data = self.feat_extractor.transform(data)
  183. data = data[None] # pad trial dimension
  184. # scale data
  185. data = self.scaler.transform(data)
  186. # compute cov
  187. data = self.cov.transform(data)
  188. # predict proba
  189. p = self.model.predict_proba(data).squeeze()
  190. return p