OSCR

Long-term independent use of an intracortical brain-computer interface for speech and cursor control.

Code ↔ Paper

The paper beside its authors' code: matches between them have not been computed for this paper yet.

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Jupyter notebook · 516 lines · 20 KB · no license

  1. # %%
  2. import pickle
  3. import numpy as np
  4. import os
  5. import pandas as pd
  6. import datetime
  7. import re
  8. from scipy.ndimage import gaussian_filter1d
  9. import matplotlib.pyplot as plt
  10. from matplotlib import rcParams
  11. from tqdm.notebook import tqdm
  12. sigma=4
  13. # 1. Configure Matplotlib for optimal vector graphic output
  14. rcParams.update({
  15. 'pdf.fonttype': 42, # Use TrueType fonts in PDF
  16. 'ps.fonttype': 42, # Use TrueType fonts in PS
  17. 'svg.fonttype': 'none', # Keep text as text in SVG
  18. 'font.size': 12, # Set a default font size
  19. 'axes.labelsize': 12, # Font size for axis labels
  20. 'xtick.labelsize': 10, # Font size for x-axis tick labels
  21. 'ytick.labelsize': 10, # Font size for y-axis tick labels
  22. 'legend.fontsize': 10, # Font size for legends
  23. 'figure.autolayout': True, # Automatically adjust subplot params
  24. })
  25. dat_info_path = 'data/dat_info.csv'
  26. personal_use_data_path = 'data/personal_use_data.csv'
  27. usage_by_session_data_path = 'data/usage_by_session_data.csv'
  28. dat_info = pd.read_csv(dat_info_path)
  29. personal_use_data = pd.read_csv(personal_use_data_path)
  30. usage_by_session_data = pd.read_csv(usage_by_session_data_path)
  31. # %% [markdown]
  32. # ## cumulative hours of use over time
  33. # %%
  34. plt.figure(figsize=(8, 4))
  35. plt.plot(usage_by_session_data['post_implant_day'], np.cumsum(usage_by_session_data['usage_hours']), linestyle='-')
  36. plt.xlabel('Post-Implant Day')
  37. plt.ylabel('Cumulative Usage Duration (hours)')
  38. plt.title(f'Cumulative Usage Duration Over Time: {usage_by_session_data["usage_hours"].sum():.1f} hours total')
  39. plt.grid(alpha=0.3)
  40. plt.gca().spines['top'].set_visible(False)
  41. plt.gca().spines['right'].set_visible(False)
  42. plt.ylim(0, 4000)
  43. plt.show()
  44. # %% [markdown]
  45. # # words per minute by post-implant day
  46. # %%
  47. dat_info
  48. # %%
  49. unique_post_implant_days = list(set(dat_info['post_implant_day']))
  50. unique_post_implant_days.sort()
  51. num_words_by_day = []
  52. speaking_time_s_by_day = []
  53. # calculate aggregate words per minute for each day, only including logs where speaking duration > 0.3s and num words > 3
  54. for day in unique_post_implant_days:
  55. day_idx_logs = np.where(dat_info['post_implant_day'] == day)[0]
  56. all_valid_num_words = []
  57. all_valid_speaking_time_s = []
  58. all_valid_wpm = []
  59. for i in day_idx_logs:
  60. if (
  61. dat_info['speaking_duration_s'][i] > 0.3
  62. and dat_info['num_words'][i] > 3
  63. ):
  64. all_valid_num_words.append(dat_info['num_words'][i])
  65. all_valid_speaking_time_s.append(dat_info['speaking_duration_s'][i])
  66. all_valid_num_words = np.array(all_valid_num_words)
  67. all_valid_speaking_time_s = np.array(all_valid_speaking_time_s)
  68. num_words_by_day.append(np.array(all_valid_num_words))
  69. speaking_time_s_by_day.append(np.array(all_valid_speaking_time_s))
  70. # calculate 95% confidence intervals for each day via boostrap resampling
  71. n_resamples = 10000
  72. wpm_mean_by_day = []
  73. wpm_ci_by_day = []
  74. from tqdm.notebook import tqdm
  75. pbar = tqdm(total=len(num_words_by_day), desc='Calculating WPM confidence intervals')
  76. for i in range(len(num_words_by_day)):
  77. resampled_wpm = np.zeros([n_resamples,])
  78. for n in range(n_resamples):
  79. resample_idx = np.random.randint(0, num_words_by_day[i].shape[0], [speaking_time_s_by_day[i].shape[0]])
  80. resampled_wpm[n] = np.sum(num_words_by_day[i][resample_idx]) / (np.sum(speaking_time_s_by_day[i][resample_idx]) / 60)
  81. wpmCI = np.percentile(resampled_wpm, [2.5, 97.5])
  82. wpm_mean_by_day.append(np.sum(num_words_by_day[i]) / (np.sum(speaking_time_s_by_day[i]) / 60))
  83. wpm_ci_by_day.append(wpmCI)
  84. pbar.update(1)
  85. pbar.close()
  86. # %%
  87. # moving average of mean WPM by day
  88. plt.figure(figsize=(10, 5))
  89. plt.plot(unique_post_implant_days, wpm_mean_by_day, '.', color='lightblue', alpha=0.5)
  90. plt.plot(unique_post_implant_days, wpm_mean_by_day, '-', color='lightblue', alpha=0.35)
  91. for i in range(len(unique_post_implant_days)):
  92. plt.plot([unique_post_implant_days[i], unique_post_implant_days[i]], [wpm_ci_by_day[i][0], wpm_ci_by_day[i][1]], color='lightblue', linewidth=0.4)
  93. plt.plot(unique_post_implant_days, gaussian_filter1d(wpm_mean_by_day, sigma=sigma), color='blue', linewidth=2)
  94. plt.xlabel('Post-implant Day')
  95. plt.ylabel('Words Per Minute (WPM)')
  96. plt.title('Words Per Minute (WPM) Over Time')
  97. plt.grid(axis='y', alpha=0.3)
  98. plt.ylim([0,100])
  99. plt.gca().spines['top'].set_visible(False)
  100. plt.gca().spines['right'].set_visible(False)
  101. plt.tight_layout()
  102. plt.show()
  103. # %% [markdown]
  104. # # speech decoding performance over time plots
  105. # %%
  106. unique_post_implant_days = list(set(dat_info['post_implant_day']))
  107. unique_post_implant_days.sort()
  108. correct_counts = []
  109. correct_with_correction_counts = []
  110. incorrect_counts = []
  111. one_word_wrong_counts = []
  112. mostly_correct_counts = []
  113. false_positive_counts = []
  114. no_response_counts = []
  115. blank_counts = []
  116. skipped_counts = []
  117. total_counts = []
  118. sentence_lengths = []
  119. syllables_per_word = []
  120. sentence_lengths_spelling_mode = []
  121. trials_per_day = []
  122. for day in unique_post_implant_days:
  123. day_idx_logs = np.where(personal_use_data['post_implant_day'] == day)[0]
  124. correct_counts.append(0)
  125. correct_with_correction_counts.append(0)
  126. incorrect_counts.append(0)
  127. one_word_wrong_counts.append(0)
  128. mostly_correct_counts.append(0)
  129. false_positive_counts.append(0)
  130. no_response_counts.append(0)
  131. blank_counts.append(0)
  132. skipped_counts.append(0)
  133. for idx in day_idx_logs:
  134. if personal_use_data['sentence_correctness_rating'][idx] == 'correct':
  135. correct_counts[-1] += 1
  136. elif personal_use_data['sentence_correctness_rating'][idx] == 'correct with correction':
  137. correct_with_correction_counts[-1] += 1
  138. elif personal_use_data['sentence_correctness_rating'][idx] == 'incorrect':
  139. incorrect_counts[-1] += 1
  140. elif personal_use_data['sentence_correctness_rating'][idx] == 'one word wrong':
  141. one_word_wrong_counts[-1] += 1
  142. elif personal_use_data['sentence_correctness_rating'][idx] == 'mostly correct':
  143. mostly_correct_counts[-1] += 1
  144. elif personal_use_data['sentence_correctness_rating'][idx] == 'no response':
  145. no_response_counts[-1] += 1
  146. elif personal_use_data['sentence_correctness_rating'][idx] == 'blank':
  147. blank_counts[-1] += 1
  148. elif personal_use_data['sentence_correctness_rating'][idx] == 'skipped':
  149. skipped_counts[-1] += 1
  150. elif personal_use_data['sentence_correctness_rating'][idx] == 'false positive':
  151. false_positive_counts[-1] += 1
  152. total_counts.append(correct_counts[-1] + correct_with_correction_counts[-1] + incorrect_counts[-1] + one_word_wrong_counts[-1] + mostly_correct_counts[-1])
  153. sentence_length = 0
  154. num_sentences = 0
  155. num_syllables = 0
  156. perplexity = 0
  157. correct_sentences = 0
  158. sentence_length_spelling_mode = 0
  159. num_sentences_spelling_mode = 0
  160. for idx in day_idx_logs:
  161. # skip if sentence correctness rating is blank, no response, or skipped
  162. if personal_use_data['sentence_correctness_rating'][idx] in ['skipped', 'no response', 'blank']:
  163. continue
  164. # check if this is a spelling mode trial
  165. if not personal_use_data['spelling_mode'][idx]:
  166. # not a spelling mode trial
  167. sentence_length += personal_use_data['num_words'][idx]
  168. num_sentences += 1
  169. else:
  170. # this is a spelling mode trial
  171. sentence_length_spelling_mode += personal_use_data['num_words'][idx]
  172. num_sentences_spelling_mode += 1
  173. sentence_lengths.append(sentence_length / num_sentences if num_sentences > 0 else 0)
  174. sentence_lengths_spelling_mode.append(sentence_length_spelling_mode / num_sentences_spelling_mode if num_sentences_spelling_mode > 0 else 0)
  175. trials_per_day.append(len(day_idx_logs))
  176. correct_counts = np.array(correct_counts)
  177. correct_with_correction_counts = np.array(correct_with_correction_counts)
  178. incorrect_counts = np.array(incorrect_counts)
  179. one_word_wrong_counts = np.array(one_word_wrong_counts)
  180. mostly_correct_counts = np.array(mostly_correct_counts)
  181. no_response_counts = np.array(no_response_counts)
  182. blank_counts = np.array(blank_counts)
  183. skipped_counts = np.array(skipped_counts)
  184. total_counts = np.array(total_counts)
  185. sentence_lengths = np.array(sentence_lengths)
  186. sentence_lengths_spelling_mode = np.array(sentence_lengths_spelling_mode)
  187. syllables_per_word = np.array(syllables_per_word)
  188. trials_per_day = np.array(trials_per_day)
  189. hours_per_day = np.array(usage_by_session_data['usage_hours'])
  190. correct_perc = 100 * correct_counts / total_counts
  191. correct_perc_with_correction_perc = 100 * correct_with_correction_counts / total_counts
  192. one_word_wrong_perc = 100 * one_word_wrong_counts / total_counts
  193. mostly_correct_perc = 100 * mostly_correct_counts / total_counts
  194. incorrect_perc = 100 * incorrect_counts / total_counts
  195. # %%
  196. np.array(unique_post_implant_days)[~np.isnan(correct_perc)]
  197. # %%
  198. fig = plt.figure(figsize=(7, 7))
  199. plt.subplot2grid((6, 1), (0, 0), rowspan=2)
  200. plt.plot(
  201. np.array(unique_post_implant_days)[~np.isnan(correct_perc)],
  202. correct_perc[~np.isnan(correct_perc)],
  203. '.', color='green', alpha=0.1, markeredgecolor='none',
  204. )
  205. plt.plot(
  206. np.array(unique_post_implant_days)[~np.isnan(correct_perc_with_correction_perc)],
  207. correct_perc_with_correction_perc[~np.isnan(correct_perc_with_correction_perc)],
  208. '.', color='mediumseagreen', alpha=0.1, markeredgecolor='none',
  209. )
  210. plt.plot(
  211. np.array(unique_post_implant_days)[~np.isnan(one_word_wrong_perc + mostly_correct_perc)],
  212. (one_word_wrong_perc + mostly_correct_perc)[~np.isnan(one_word_wrong_perc + mostly_correct_perc)],
  213. '.', color='xkcd:tangerine', alpha=0.1, markeredgecolor='none',
  214. )
  215. plt.plot(
  216. np.array(unique_post_implant_days)[~np.isnan(incorrect_perc)],
  217. incorrect_perc[~np.isnan(incorrect_perc)],
  218. '.', color='xkcd:scarlet', alpha=0.1, markeredgecolor='none',
  219. )
  220. plt.plot(
  221. np.array(unique_post_implant_days)[~np.isnan(correct_perc)],
  222. gaussian_filter1d(correct_perc[~np.isnan(correct_perc)], sigma=sigma),
  223. '-', label='correct w/o correction', color='green',
  224. )
  225. plt.plot(
  226. np.array(unique_post_implant_days)[~np.isnan(correct_perc_with_correction_perc)],
  227. gaussian_filter1d(correct_perc_with_correction_perc[~np.isnan(correct_perc_with_correction_perc)], sigma=sigma),
  228. '-', label='correct after correction', color='mediumseagreen',
  229. )
  230. plt.plot(
  231. np.array(unique_post_implant_days)[~np.isnan(one_word_wrong_perc + mostly_correct_perc)],
  232. gaussian_filter1d((one_word_wrong_perc + mostly_correct_perc)[~np.isnan(one_word_wrong_perc + mostly_correct_perc)], sigma=sigma),
  233. '-', label='mostly correct', color='xkcd:tangerine',
  234. )
  235. plt.plot(
  236. np.array(unique_post_implant_days)[~np.isnan(incorrect_perc)],
  237. gaussian_filter1d(incorrect_perc[~np.isnan(incorrect_perc)], sigma=sigma),
  238. '-', label='incorrect', color='xkcd:scarlet',
  239. )
  240. plt.legend(ncols=2, fontsize=7)
  241. plt.ylim([0, 100])
  242. plt.grid(axis='y', alpha=0.3)
  243. plt.gca().spines['top'].set_visible(False)
  244. plt.gca().spines['right'].set_visible(False)
  245. plt.ylabel('Percentage of trials', fontsize=8)
  246. xlimits = plt.xlim()
  247. plt.xlim([xlimits[0], xlimits[1]])
  248. plt.xticks([100,200,300,400,500,600,700], labels=['', '', '', '', '', '', ''])
  249. # wpm
  250. plt.subplot2grid((6, 1), (2, 0), rowspan=1)
  251. plt.plot(unique_post_implant_days, wpm_mean_by_day, '.', color='lightblue', alpha=0.4, markeredgecolor='none')
  252. plt.plot(unique_post_implant_days, gaussian_filter1d(wpm_mean_by_day, sigma=sigma), '-', color='blue')
  253. plt.ylabel('Words / minute', fontsize=8)
  254. plt.grid(axis='y', alpha=0.3)
  255. plt.gca().spines['top'].set_visible(False)
  256. plt.gca().spines['right'].set_visible(False)
  257. plt.ylim([25,75])
  258. plt.yticks([25,50,75])
  259. plt.xlim([xlimits[0], xlimits[1]])
  260. plt.xticks([100,200,300,400,500,600,700], labels=['', '', '', '', '', '', ''])
  261. # sentence length
  262. plt.subplot2grid((6, 1), (3, 0), rowspan=1)
  263. plt.plot(np.array(unique_post_implant_days)[sentence_lengths>0], sentence_lengths[sentence_lengths>0], '.', color='lightblue', alpha=0.4, markeredgecolor='none')
  264. plt.plot(np.array(unique_post_implant_days)[sentence_lengths>0], gaussian_filter1d(sentence_lengths[sentence_lengths>0], sigma=sigma), '-', label='regular', color=(0/255, 0/255, 200/255))
  265. plt.grid(axis='y', alpha=0.3)
  266. plt.gca().spines['top'].set_visible(False)
  267. plt.gca().spines['right'].set_visible(False)
  268. plt.ylabel('Words / sentence', fontsize=8)
  269. plt.ylim([0, 25])
  270. plt.yticks([0, 10, 20])
  271. plt.xlim([xlimits[0], xlimits[1]])
  272. plt.xticks([100,200,300,400,500,600,700], labels=['', '', '', '', '', '', ''])
  273. plt.subplot2grid((6, 1), (4, 0), rowspan=1)
  274. plt.plot(unique_post_implant_days, trials_per_day, '.', color='lightgray', alpha=0.4, markeredgecolor='none')
  275. plt.plot(unique_post_implant_days, gaussian_filter1d(trials_per_day, sigma=sigma), '-', color=(100/255, 100/255, 100/255))
  276. plt.grid(axis='y', alpha=0.3)
  277. plt.gca().spines['top'].set_visible(False)
  278. plt.gca().spines['right'].set_visible(False)
  279. plt.yticks([0,500,1000])
  280. plt.ylabel('Sentences / day', fontsize=8)
  281. plt.xlim([xlimits[0], xlimits[1]])
  282. plt.xticks([100,200,300,400,500,600,700], labels=['', '', '', '', '', '', ''])
  283. plt.subplot2grid((6, 1), (5, 0), rowspan=1)
  284. plt.plot(unique_post_implant_days, hours_per_day, '.', color='lightgray', alpha=0.4, markeredgecolor='none')
  285. plt.plot(unique_post_implant_days, gaussian_filter1d(hours_per_day, sigma=sigma), '-', color=(100/255, 100/255, 100/255))
  286. plt.grid(axis='y', alpha=0.3)
  287. plt.gca().spines['top'].set_visible(False)
  288. plt.gca().spines['right'].set_visible(False)
  289. plt.yticks([0,10,20])
  290. plt.ylabel('Hours / day', fontsize=8)
  291. plt.xlabel('Days since implant', fontsize=12)
  292. plt.xlim([xlimits[0], xlimits[1]])
  293. plt.tight_layout()
  294. fig.align_labels()
  295. plt.show()
  296. # %%
  297. # pie chart
  298. labels = [
  299. f'Correct: {correct_counts.sum():,}',
  300. f'Correct with correction: {correct_with_correction_counts.sum():,}',
  301. f'Mostly correct: {one_word_wrong_counts.sum() + mostly_correct_counts.sum():,}',
  302. f'Incorrect: {incorrect_counts.sum():,}',
  303. ]
  304. sizes = [
  305. correct_counts.sum(),
  306. correct_with_correction_counts.sum(),
  307. one_word_wrong_counts.sum() + mostly_correct_counts.sum(),
  308. incorrect_counts.sum(),
  309. ]
  310. colors = [
  311. 'green',
  312. 'lightgreen',
  313. 'xkcd:tangerine',
  314. 'lightcoral',
  315. ]
  316. fig, ax = plt.subplots()
  317. ax.pie(sizes, labels=labels, colors=colors,
  318. autopct='%1.1f%%', shadow=False, startangle=90)
  319. ax.axis('equal')
  320. plt.title(f'Personal use sentence correctness ratings\nTotal sentences: {np.sum(sizes):,}')
  321. plt.tight_layout()
  322. plt.show()
  323. # %% [markdown]
  324. # # accuracy statistics
  325. # %%
  326. start_idx = unique_post_implant_days.index(412)
  327. from scipy.stats import ranksums
  328. # compare correct_perc before and after start_idx
  329. before = correct_perc[~np.isnan(correct_perc)][:start_idx]
  330. after = correct_perc[~np.isnan(correct_perc)][start_idx:]
  331. stat, p_value = ranksums(before, after)
  332. print(f'Rank sum test of % correct before and after post-implant day {unique_post_implant_days[start_idx]}: statistic={stat:.4f}, p-value={p_value:.8f}')
  333. # plot histogram of correct_perc before and after start_idx
  334. plt.figure(figsize=(10, 5))
  335. plt.subplot(1, 2, 1)
  336. plt.hist(before, range=(0,100), bins=25, alpha=0.5, label='Before', color='blue')
  337. plt.hist(after, range=(0,100), bins=25, alpha=0.5, label='After', color='orange')
  338. plt.xlabel('Correct Percentage')
  339. plt.ylabel('Frequency')
  340. plt.title(f'Correct Percentage Histogram\nBefore and After {unique_post_implant_days[start_idx]} Days')
  341. plt.legend()
  342. plt.subplot(1, 2, 2)
  343. plt.boxplot([before, after], tick_labels=['Before', 'After'])
  344. plt.ylabel('Correct Percentage')
  345. plt.title(f'Correct Percentage Boxplot\nBefore and After {unique_post_implant_days[start_idx]} Days')
  346. plt.ylim(0,100)
  347. plt.grid(axis='y', alpha=0.3)
  348. plt.tight_layout()
  349. plt.show()
  350. # compare sentence lengths before and after start_idx
  351. before = sentence_lengths[sentence_lengths>0][:start_idx]
  352. after = sentence_lengths[sentence_lengths>0][start_idx:]
  353. stat, p_value = ranksums(before, after)
  354. print(f'Rank sum test of sentence lengths before and after post-implant day {unique_post_implant_days[start_idx]}: statistic={stat:.4f}, p-value={p_value:.8f}')
  355. # %% [markdown]
  356. # # sentence correctness vs sentence length
  357. # %%
  358. # sentence correctness rating vs length
  359. num_word_ranges = [
  360. (1, 2),
  361. (2, 3),
  362. (3, 4),
  363. (4, 5),
  364. (5, 6),
  365. (6, 7),
  366. (7, 8),
  367. (8, 9),
  368. (9, 10),
  369. (10, 15),
  370. (15, 20),
  371. (20, 25),
  372. (25, 30),
  373. (30, 35),
  374. (35, 40),
  375. (40, 45),
  376. (45, 50),
  377. (50, 75),
  378. (75, 100),
  379. (100, 1000),
  380. ]
  381. correctness_by_num_words = {}
  382. for i in range(len(personal_use_data['num_words'])):
  383. num_words = personal_use_data['num_words'][i]
  384. correctness = personal_use_data['sentence_correctness_rating'][i]
  385. if correctness in ['skipped', 'no response', 'blank', 'false positive']:
  386. continue
  387. if num_words == 0:
  388. continue
  389. for r in num_word_ranges:
  390. if num_words >= r[0] and num_words < r[1]:
  391. if r not in correctness_by_num_words:
  392. correctness_by_num_words[r] = {
  393. 'correct': 0,
  394. 'correct with correction': 0,
  395. 'one word wrong': 0,
  396. 'mostly correct': 0,
  397. 'incorrect': 0,
  398. }
  399. correctness_by_num_words[r][correctness] += 1
  400. break
  401. # convert to percentages
  402. totals = []
  403. for r in correctness_by_num_words:
  404. total = sum(correctness_by_num_words[r].values())
  405. totals.append(total)
  406. for correctness in correctness_by_num_words[r]:
  407. correctness_by_num_words[r][correctness] = 100 * correctness_by_num_words[r][correctness] / total
  408. # plot
  409. fig = plt.figure(figsize=(8, 5))
  410. plt.subplot2grid((3, 1), (0, 0), rowspan=2)
  411. colors = ['green', 'mediumseagreen', 'xkcd:dirty yellow', 'xkcd:tangerine', 'xkcd:scarlet']
  412. for c, correctness in enumerate(['correct', 'correct with correction', 'one word wrong', 'mostly correct', 'incorrect']):
  413. x = []
  414. y = []
  415. for i, r in enumerate(num_word_ranges):
  416. if r in correctness_by_num_words:
  417. x.append(i)
  418. y.append(correctness_by_num_words[r][correctness])
  419. plt.plot(x, y, '.-', label=correctness, color=colors[c], alpha=0.6)
  420. plt.ylabel('Percentage of\nsentences')
  421. plt.title('Sentence correctness rating vs length')
  422. plt.legend()
  423. plt.grid(axis='y', alpha=0.2)
  424. plt.gca().spines['top'].set_visible(False)
  425. plt.gca().spines['right'].set_visible(False)
  426. plt.ylim([0, 100])
  427. xlimits = plt.xlim()
  428. plt.xticks([])
  429. plt.yticks(horizontalalignment='right', rotation=0)
  430. plt.subplot2grid((3, 1), (2, 0), rowspan=1)
  431. plt.semilogy(range(len(num_word_ranges)), totals, '.-', color='gray')
  432. plt.xlabel('Number of words in sentence')
  433. plt.xlim(xlimits)
  434. plt.ylim([10, 1e5])
  435. plt.yticks([10, 1000, 100000], horizontalalignment='right', rotation=0)
  436. plt.xticks(range(len(num_word_ranges)), [f'{r[0]}-{r[1]-1}' if (r[1]-r[0]) > 1 else f'{r[0]}' for r in num_word_ranges], rotation=90, verticalalignment='top')
  437. plt.ylabel('Number of\nsentences')
  438. plt.grid(axis='y', alpha=0.2)
  439. plt.gca().spines['top'].set_visible(False)
  440. plt.gca().spines['right'].set_visible(False)
  441. plt.tight_layout()
  442. fig.align_labels()
  443. plt.show()
  444. # %% [markdown]
  445. # # other general stats
  446. # %%
  447. print(f'Total decoded words: {personal_use_data["num_words"].sum():,}')
  448. print(f'Total decoded sentences: {len(personal_use_data["num_words"]):,}')
  449. print(f'Words per sentence: {personal_use_data["num_words"].sum() / len(personal_use_data["num_words"]):0.2f}')
  450. print(f'Total hours of BCI usage: {usage_by_session_data["usage_hours"].sum():0.2f}')
  451. print(f'Total speech hours: {dat_info["speaking_duration_s"].sum() / 60 / 60:0.2f}')
  452. print(f'Total number of sessions: {len(usage_by_session_data["post_implant_day"])} spanning {usage_by_session_data["post_implant_day"].min()} to {usage_by_session_data["post_implant_day"].max()} days post-implant')
  453. print(f'Avg hours per day: {np.mean(hours_per_day):0.2f} (median: {np.median(hours_per_day):0.2f})')
  454. print(f'Max hours per day: {np.max(hours_per_day):0.2f}')

speech_decoding_plots.ipynb at commit 22d5931, no license · at the source

Overview

Authors: Nicholas S Card1, Tyler Singer-Clark1, Hamza Peracha1, Carrina Iacobacci1, Xianda Hou1, Maitreyee Wairagkar1, Zachery Fogg1, Elena C Offenberg1,2, Leigh R Hochberg3,4,5, Sergey D Stavisky1, David M Brandman1
  1. Department of Neurological Surgery, University of California, Davis, Davis, CA USA
  2. Department of Neurology and Neurosurgery, University Medical Center Utrecht Brain Center, Utrecht University, Utrecht, the Netherlands
  3. School of Engineering and Carney Institute for Brain Science, Brown University, Providence, RI USA
  4. VA Center for Neurorestoration and Neurotechnology, Rehabilitation Research Development and Translation Service, Department of Veterans Affairs, Providence, RI USA
  5. Department of Neurology, Massachusetts General Hospital, Boston, MA USA
Institutions: University of California, Davis (United States); Utrecht University (Netherlands); University Medical Center Utrecht (Netherlands); United States Department of Veterans Affairs (United States); Brown University (United States); Providence VA Medical Center (United States); Massachusetts General Hospital (United States)
Journal: Nature medicine, volume 32, issue 7, pages 2504-2510
Dates: received 22 July 2025; accepted 16 April 2026; published online 15 June 2026; in print 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1038/s41591-026-04414-6 · PMID 42297978 · PMCID PMC13375540 · OpenAlex W4412093874
Open access: hybrid, a free copy (OpenAlex)
Status: code verified
Categories: human (organism), other condition (population), cognitive (subfield)
Methods: Spectral & time-frequency, Connectivity, Machine learning, Statistics, Preprocessing, Physiology & signal measures
Keywords: Brain-machine interface, Motor cortex, Premotor cortex
MeSH: Brain-Computer Interfaces*, Speech*, Amyotrophic Lateral Sclerosis, Communication Devices for People with Disabilities, Dysarthria, Humans, Male, Paralysis (* major topic)
Topic: EEG and Brain-Computer Interfaces (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: U.S. Department of Health & Human Services | NIH | NIH Office of the Director (OD) (1DP2DC021055); U.S. Department of Health &amp; Human Services | NIH | NIH Office of the Director (1DP2DC021055); United States Department of Defense | Office of the Secretary of Defense (OSD) (AL220043); Amyotrophic Lateral Sclerosis Association (23-SGP-652); NIDCD NIH HHS (DP2 DC021055); A. P. Giannini Foundation Postdoctoral Fellowship and Leadership Award; VHA Office of Research and Development | Rehabilitation Research and Development Service (Rehabilitation Research & Development Service) (A2295-R); Searle Scholars Program; Burroughs Wellcome Fund (N/A); Achievement Rewards for College Scientists Foundation (N/A)
Citations: cited by 6 papers (Europe PMC); 41 references in the paper

Abstract

Brain–computer interfaces (BCIs) can provide naturalistic communication and digital access to people with severe paralysis by decoding neural activity associated with attempted speech and movement. Recent work has demonstrated highly accurate intracortical BCIs for speech and cursor control, but two critical capabilities needed for practical viability were unmet: independent at-home operation without researcher assistance and reliable long-term performance supporting accurate speech and cursor decoding. Here we demonstrate the independent and near-daily use of a multimodal BCI with novel brain-to-text speech and computer cursor decoders by a man with paralysis and severe dysarthria due to amyotrophic lateral sclerosis. Over nearly 2 years, the participant used the BCI for more than 3,800 h at home with no researchers present to maintain rich interpersonal communication with his family and friends, independently control his personal computer and sustain full-time employment—despite being paralyzed. He communicated 183,060 sentences—totaling 1,960,163 words—at an average rate of 56 words per minute. He labeled 92% of sentences as being decoded at least mostly correctly. In formal quantifications of performance where he was asked to say words presented on a screen, attempted speech was consistently decoded with more than 99% word accuracy (125,000 word vocabulary). The participant also used the speech BCI as keyboard input and the cursor BCI as mouse input to control his personal computer, enabling him to send text messages and emails and to browse the internet. These results demonstrate that intracortical BCIs have the potential to support independent use in the home, marking a critical step toward practical assistive technology for people with severe motor impairment.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above.

Neuroprosthetics-Lab/NatMed_independent_personal_use

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 22d593152ff45f569a168c90bbdea3f2d8d0e181, 1 April 2026
Languages: Jupyter (1)
Size: 6 files, 1 script
Software Heritage: not archived
Found in: “Code availability”
Holds: README, 1 notebook
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Matplotlib (1 file), NumPy (1 file), pandas (1 file), SciPy (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
2 files

Code availability

Code to reproduce the figures and statistical results in this manuscript are available via GitHub at https://github.com/Neuroprosthetics-Lab/NatMed_independent_personal_use.

Reproduced under the paper's license (CC BY), from the paper cited above.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 1 script, each with its path and the digest of its content;
  • no match between paragraphs and code yet;
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data Availability Statement

Neural data and speech decoding transcripts recorded during the participant’s independent use of the BCI system cannot be shared to preserve the participant’s privacy. Data to reproduce the figures and statistical results in this manuscript are available via GitHub at https://github.com/Neuroprosthetics-Lab/NatMed_independent_personal_use.

Code to reproduce the figures and statistical results in this manuscript are available via GitHub at https://github.com/Neuroprosthetics-Lab/NatMed_independent_personal_use.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 2, 28 September 2026

  • Publisher: n/a → Nature Portfolio

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 11 authors, 3 keywords, 8 MeSH terms, 10 funders, 33 references.

Cite

This paper

Card, N. S., Singer-Clark, T., Peracha, H., Iacobacci, C., Hou, X., Wairagkar, M., Fogg, Z., Offenberg, E. C., Hochberg, L. R., Stavisky, S. D., & Brandman, D. M. (2026). Long-term independent use of an intracortical brain-computer interface for speech and cursor control. Nature medicine, 32(7), 2504-2510. https://doi.org/10.1038/s41591-026-04414-6

BibTeX

@article{card2026long,
author = {Card, Nicholas S and Singer-Clark, Tyler and Peracha, Hamza and Iacobacci, Carrina and Hou, Xianda and Wairagkar, Maitreyee and Fogg, Zachery and Offenberg, Elena C and Hochberg, Leigh R and Stavisky, Sergey D and Brandman, David M},
title = {{Long-term independent use of an intracortical brain-computer interface for speech and cursor control}},
journal = {Nature medicine},
year = {2026},
month = jun,
volume = {32},
number = {7},
pages = {2504--2510},
publisher = {Nature Portfolio},
issn = {1078-8956},
doi = {10.1038/s41591-026-04414-6},
url = {https://doi.org/10.1038/s41591-026-04414-6},
pmid = {42297978},
pmcid = {PMC13375540}
}

RIS

TY - JOUR
AU - Card, Nicholas S
AU - Singer-Clark, Tyler
AU - Peracha, Hamza
AU - Iacobacci, Carrina
AU - Hou, Xianda
AU - Wairagkar, Maitreyee
AU - Fogg, Zachery
AU - Offenberg, Elena C
AU - Hochberg, Leigh R
AU - Stavisky, Sergey D
AU - Brandman, David M
TI - Long-term independent use of an intracortical brain-computer interface for speech and cursor control
T2 - Nature medicine
J2 - Nat Med
PY - 2026
DA - 2026/06/15
VL - 32
IS - 7
SP - 2504
EP - 2510
SN - 1078-8956
PB - Nature Portfolio
DO - 10.1038/s41591-026-04414-6
UR - https://doi.org/10.1038/s41591-026-04414-6
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41591-026-04414-6",
"type": "article-journal",
"title": "Long-term independent use of an intracortical brain-computer interface for speech and cursor control",
"container-title": "Nature medicine",
"author": [
{
"family": "Card",
"given": "Nicholas S"
},
{
"family": "Singer-Clark",
"given": "Tyler"
},
{
"family": "Peracha",
"given": "Hamza"
},
{
"family": "Iacobacci",
"given": "Carrina"
},
{
"family": "Hou",
"given": "Xianda"
},
{
"family": "Wairagkar",
"given": "Maitreyee"
},
{
"family": "Fogg",
"given": "Zachery"
},
{
"family": "Offenberg",
"given": "Elena C"
},
{
"family": "Hochberg",
"given": "Leigh R"
},
{
"family": "Stavisky",
"given": "Sergey D"
},
{
"family": "Brandman",
"given": "David M"
}
],
"container-title-short": "Nat Med",
"volume": "32",
"issue": "7",
"page": "2504-2510",
"DOI": "10.1038/s41591-026-04414-6",
"PMID": "42297978",
"PMCID": "PMC13375540",
"ISSN": "1078-8956",
"publisher": "Nature Portfolio",
"URL": "https://doi.org/10.1038/s41591-026-04414-6",
"language": "en",
"issued": {
"date-parts": [
[
2026,
6,
15
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s41467-026-71284-4 [code]
Encoding of speech modes and loudness in ventral precentral gyrus.
Journal: Nature communications
In common: pandas, SciPy, Matplotlib, 1 other tool, cognitive, 8 references, 6 authors
[2] doi:10.1038/s41586-026-10653-x [code]
A mosaic of whole-body representations on the human precentral gyrus.
Journal: Nature
In common: SciPy, Matplotlib, NumPy, other condition, 5 references, 5 authors
[3] doi:10.1007/s12021-026-09807-z [code]
Optimal Size of Electrocorticography Grids for Classification of Hand Movements.
Journal: Neuroinformatics
In common: pandas, SciPy, Matplotlib, 1 other tool, 5 references, author Elena C Offenberg
[4] doi:10.1126/sciadv.adw3876 [code]
Intracortical brain-computer interface for navigation in virtual reality in macaque monkeys.
Journal: Science advances
In common: pandas, SciPy, Matplotlib, 1 other tool, 7 references
[5] doi:10.1038/s42003-026-10144-9 [code]
Low-power differencing feature extracts spiking-band activities for high-performance intracortical brain-computer interfaces.
Journal: Communications biology
In common: SciPy, Matplotlib, NumPy, 7 references
[6] doi:10.1038/s41467-026-75455-1 [code]
Shared latent representations of speech production for cross-patient speech decoding.
Journal: Nature communications
In common: pandas, SciPy, Matplotlib, 1 other tool, cognitive, 6 references
[7] doi:10.1038/s41467-026-76109-y [code]
Assistive algorithms influence neural representations in motor brain-computer interfaces.
Journal: Nature communications
In common: pandas, SciPy, Matplotlib, 1 other tool, 4 references
[8] doi:10.1038/s41586-026-10691-5 [code]
Mapping the neuronal building blocks of human language with language models.
Journal: Nature
In common: pandas, SciPy, Matplotlib, 1 other tool, cognitive, 3 references
[9] doi:10.1038/s41467-026-75588-3 [code]
Frequency-dependent effects of motor thalamus deep brain stimulation on speech and swallowing.
Journal: Nature communications
In common: cognitive, 5 references
[10] doi:10.7554/elife.109400 [code]
High-fidelity neural speech reconstruction through an efficient acoustic-linguistic dual-pathway framework.
Journal: eLife
In common: SciPy, Matplotlib, NumPy, cognitive, 3 references

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.