OSCR

Fuzzing the brain: automated stress testing for the safety of ML-driven neurostimulation.

Code ↔ Paper

5 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 5 matches
  1. [1] § Methods ↔ exp_code_and_data/corticalcovcomp_base1/main.py, lines 51–79 · score 0.52 · pulse duration, charge density, instantaneous, amplitude, electrodes, violation
  2. [2] § Methods ↔ exp_code_and_data/corticalcovcomp_nc/main.py, lines 51–79 · score 0.52 · pulse duration, charge density, instantaneous, amplitude, electrodes, violation
  3. [3] § Methods › Safety constraints for electrode-based neurostimulation ↔ exp_code_and_data/corticalcovcomp_base1/main.py, lines 51–79 · score 0.51 · pulse duration, Charge density, amplitude, threshold, electrochemical, violation
  4. [4] § Methods › Safety constraints for electrode-based neurostimulation ↔ exp_code_and_data/corticalcovcomp_nc/main.py, lines 51–79 · score 0.51 · pulse duration, Charge density, amplitude, threshold, electrochemical, violation
  5. [5] § Methods › Models under test › Retinal stimulus encoders ↔ exp_code_and_data/retinalcovcomp_phi1/main.py, lines 47–75 · score 0.50 · pulse duration, active electrodes, charge, instantaneous, thresholds, retinal

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

Python · 491 lines · 21 KB · BSD-3-Clause · 2 matches

  1. import sys
  2. import os
  3. import re
  4. import time
  5. import random
  6. import math
  7. import numpy as np
  8. import copy
  9. from boundslist import *
  10. from network import *
  11. from parseinputs import *
  12. from deephuntermutators import *
  13. def get_covprop_helper(grid):
  14. #recursive: for each elem in grid, if it is a number then check 1 or 0, otherwise recursively descend
  15. numcovered = 0
  16. numtotal = 0
  17. for i in range(len(grid)):
  18. if isinstance(grid[i], list):
  19. (a,b) = get_covprop_helper(grid[i])
  20. numcovered += a
  21. numtotal += b
  22. else:
  23. if(grid[i] == 1):
  24. numcovered += 1
  25. numtotal += 1
  26. else:
  27. numtotal += 1
  28. return (numcovered, numtotal)
  29. def get_covprop(grid):
  30. (numcovered, numtotal) = get_covprop_helper(grid)
  31. return float(numcovered)/float(numtotal)
  32. def invert_colors(sample, boundslist):
  33. for i in range(len(sample)):
  34. sample[i] = boundslist[i][1] - sample[i] + boundslist[i][0]
  35. return sample
  36. def generate_random(boundslist):
  37. sample = []
  38. for elem in boundslist:
  39. sample += [random.uniform(elem[0],elem[1])]
  40. return sample
  41. def check_violations(networkoutput, n, e1, e2, e3): #currently this expects thresholds already applied, I think that is best
  42. violations = [0,0,0,0,0,0] #will be one-hot encoding, first is frequency violation, third is charge density, fifth is instantaneous current, sixth is active electrodes
  43. #second and fourth are proportions out of n
  44. #elec[0] = freq
  45. #elec[1] = amplitude
  46. #elec[2] = pulse duration
  47. active_electrodes = 0
  48. instantaneous_current = 0
  49. assert(len(networkoutput) == n)
  50. for elec in networkoutput: #expect this to have 225 electrodes
  51. if(elec[0] == 0):
  52. if(elec[2] > 0):
  53. violations[0] = 1
  54. violations[1] += 1
  55. elif(2 * elec[2] > 1000/elec[0]):
  56. violations[0] = 1
  57. violations[1] += 1
  58. if(elec[2] * elec[1] > e1):
  59. violations[2] = 1
  60. violations[3] += 1
  61. instantaneous_current += elec[1]
  62. if(elec[1] > 20):
  63. active_electrodes += 1
  64. if(instantaneous_current > e2):
  65. violations[4] = 1
  66. # print(active_electrodes)
  67. if(active_electrodes > e3):
  68. violations[5] = 1
  69. return violations
  70. # def check_v_prop(networkoutput, n, e1, e2, e3):
  71. # vprops = []
  72. # active_electrodes = 0
  73. # instantaneous_current = 0
  74. # assert(len(networkoutput) == n)
  75. # for elec in networkoutput: #expect this to have 225 electrodes
  76. # if(elec[0] == 0):
  77. # if(elec[2] > 0):
  78. # vprops += [2]#200%
  79. # else:
  80. # vprops += [0]#0%
  81. # else:
  82. # vprops += [2 * elec[2] / (1000/elec[0])]
  83. # # print(len(vprops))
  84. # for elec in networkoutput:
  85. # vprops += [elec[2] * elec[1] / e1]
  86. # instantaneous_current += elec[1]
  87. # if(elec[1] > 0):
  88. # active_electrodes += 1
  89. # # print(len(vprops))
  90. # vprops += [instantaneous_current/e2]
  91. # vprops += [active_electrodes]
  92. # # print(str(2*n+2))
  93. # # print(len(vprops))
  94. # assert(len(vprops) == 2*n+2)
  95. # return vprops
  96. #initialize variables from cmd line input
  97. countlimit = int(sys.argv[1])
  98. n = int(sys.argv[2])
  99. e1 = float(sys.argv[3])
  100. e2 = float(sys.argv[4])
  101. e3 = int(sys.argv[5])
  102. seedsfile = sys.argv[6]
  103. mutation_specs_file = sys.argv[7]
  104. fuzzing_coverage_strat = "KVPV"
  105. fuzzing_coverage_strat_param = 0 #update this with best found default
  106. fuzzing_coverage_strat_param2 = 0 #update this with best found default
  107. training_profile_tests_file = ""
  108. for i in range(8,len(sys.argv)):
  109. if(sys.argv[i] == "-fuzz_coverage"):
  110. fuzzing_coverage_strat = sys.argv[i+1] #current options are NC, KMNC, NBC, SNAC, TKNC, KVPA, KVPV, KMOC, R0, RA, KVPO, Local, KMIC, Div-Approx
  111. j = 1
  112. if "K" in fuzzing_coverage_strat or fuzzing_coverage_strat == "Div-Approx":
  113. j += 1
  114. fuzzing_coverage_strat_param = int(sys.argv[i+j]) #KVPA and KVPV: K; KMNC: K; TKNC: K
  115. if(fuzzing_coverage_strat == "KVPA" or fuzzing_coverage_strat == "KVPV" or fuzzing_coverage_strat == "KVPO"):
  116. j += 1
  117. fuzzing_coverage_strat_param2 = float(sys.argv[i+j])
  118. else:
  119. fuzzing_coverage_strat_param = 0
  120. if fuzzing_coverage_strat == "KMNC" or fuzzing_coverage_strat == "NBC" or fuzzing_coverage_strat == "SNAC" or fuzzing_coverage_strat == "KMOC" or fuzzing_coverage_strat == "Div-Approx":
  121. j += 1
  122. training_profile_tests_file = sys.argv[i+j]
  123. i += j
  124. outputdirname = "output_" + sys.argv[1] + "_" + sys.argv[2] + "_" + sys.argv[3] + "_" + sys.argv[4] + "_" + sys.argv[5] + "_" + (sys.argv[6].split("/")[-1]).split(".")[0] + "_" + (sys.argv[7].split("/")[-1]).split(".")[0] + "_" + fuzzing_coverage_strat
  125. if(fuzzing_coverage_strat_param != 0):
  126. outputdirname += str(fuzzing_coverage_strat_param)
  127. if(fuzzing_coverage_strat_param2 != 0):
  128. outputdirname += "_" + str(fuzzing_coverage_strat_param2)
  129. if(training_profile_tests_file != ""):
  130. outputdirname += (training_profile_tests_file.split("/")[-1]).split(".")[0]
  131. #check if folder exists, otherwise create
  132. if not os.path.isdir(outputdirname):
  133. os.mkdir(outputdirname)
  134. outfileinstances = open(outputdirname + "/instances.txt", "w")
  135. progresstimes = open(outputdirname + "/progress.txt", "w")
  136. if "K" in fuzzing_coverage_strat:
  137. assert(fuzzing_coverage_strat_param != 0)
  138. if fuzzing_coverage_strat == "KMNC" or fuzzing_coverage_strat == "NBC" or fuzzing_coverage_strat == "SNAC":
  139. assert(training_profile_tests_file != "")
  140. starttime = time.time()
  141. #if seeds file present, read it in
  142. seedlist = parse_inputs(seedsfile)
  143. random.shuffle(seedlist) #makes sure elements are in random order to start
  144. violations = [0,0,0,0,0,0]
  145. progresslogstep = 50
  146. #read in allowed mutations and put into list
  147. infile = open(mutation_specs_file, "r")
  148. data = infile.readlines()
  149. infile.close()
  150. allowed_mutations = []
  151. for line in data:
  152. if line[-1] == "\n":
  153. line = line[:-1]
  154. if line == "" or line[0] == "#":
  155. continue
  156. allowed_mutations += [line]
  157. print(allowed_mutations)
  158. #if we have a training_profile... file, read it in and run all those tests.
  159. high_n = []
  160. low_n = []
  161. #create low_n and high_n but do not add coverage or log violations based on these tests.
  162. if(fuzzing_coverage_strat == "KMNC" or fuzzing_coverage_strat == "NBC" or fuzzing_coverage_strat == "SNAC"):
  163. for i in range(len(model.layers)-1):
  164. if "dense" in model.layers[i].name:
  165. high_n += [[-9999999] * model.layers[i].units]
  166. low_n += [[9999999] * model.layers[i].units]
  167. preplist = parse_inputs(training_profile_tests_file)
  168. for item in preplist:
  169. test = (np.array([np.reshape(item, (49,49,1)),]),np.array([phi,]))
  170. layer_outs = [func([test]) for func in functors]
  171. row = 0
  172. for i in range(len(layer_outs)):
  173. if "dense" in model.layers[i].name:
  174. assert(len(high_n[row]) == len(layer_outs[i][0][0]))
  175. for j in range(len(layer_outs[i][0][0])):
  176. if(high_n[row][j] < layer_outs[i][0][0][j]):
  177. high_n[row][j] = layer_outs[i][0][0][j]
  178. if(low_n[row][j] > layer_outs[i][0][0][j]):
  179. low_n[row][j] = layer_outs[i][0][0][j]
  180. row += 1
  181. print("done with preprocess")
  182. elif(fuzzing_coverage_strat == "KMOC"):
  183. high_n = [-9999999] * 3
  184. low_n = [9999999] * 3
  185. preplist = parse_inputs(training_profile_tests_file)
  186. for item in preplist:
  187. input2d = []
  188. singlerow = []
  189. for i in range(len(item)):
  190. singlerow += [item[i]]
  191. if(len(singlerow) == 128):
  192. input2d += [singlerow]
  193. singlerow = []
  194. singleinput = torch.tensor(input2d).float()
  195. singleinput = singleinput.to('cuda:0')
  196. singleinput = torch.unsqueeze(singleinput, 0)
  197. singleinput = torch.unsqueeze(singleinput, 0)
  198. stimulation = encoder(singleinput)
  199. stimulation1d = stimulation[0].tolist()
  200. result = []
  201. for elem in stimulation1d:
  202. result += [[300,elem*1000000,0.17]]
  203. for i in range(len(result)):
  204. for j in range(len(result[i])):#3 things
  205. if(high_n[j] < result[i][j]):
  206. high_n[j] = result[i][j]
  207. if(low_n[j] > result[i][j]):
  208. low_n[j] = result[i][j]
  209. print("done with preprocess")
  210. elif(fuzzing_coverage_strat == "Div-Approx"):
  211. high_n = [-9999999] * 4608
  212. low_n = [9999999] * 4608
  213. preplist = parse_inputs(training_profile_tests_file)
  214. singletest = preplist[0][:]
  215. singletest = [x * 255 for x in singletest]
  216. singletest = np.array(singletest)
  217. x_test = np.reshape(singletest, (1,128,128))
  218. preplist = preplist[1:]
  219. for item in preplist:
  220. singletest = item[:]
  221. singletest = [x * 255 for x in singletest]
  222. singletest = np.array(singletest)
  223. singletest = np.reshape(singletest, (1,128,128))
  224. x_test = np.append(x_test, singletest, axis=0)
  225. x_test1=np.dstack([x_test]*3)
  226. x_test1= x_test1.reshape(-1,128,128,3)
  227. x_test1 = np.asarray([img_to_array(array_to_img(im, scale=False).resize((48,48))) for im in x_test1])
  228. x_test1 = x_test1.astype("float32")
  229. x_test1 = (x_test1 / 255.0) - (1.0 - CLIP_MAX)
  230. input_layer=layers.Input(shape=(48,48,3))
  231. model_vgg16=VGG16(weights='imagenet',input_tensor=input_layer,include_top=False)
  232. # model_vgg16.summary()
  233. base_model = model_vgg16
  234. # You can select another layer of VGG16 that you want to test.
  235. name_layer = 'block5_conv3'
  236. intermediate_layer_model = Model(inputs=base_model.input, outputs=base_model.get_layer(name_layer).output)
  237. FF = intermediate_layer_model.predict(x_test1)
  238. features= FF.reshape((len(x_test1),9*512))
  239. print(features.shape)
  240. # print("rank of feature matrix", np.linalg.matrix_rank(features))
  241. # nom = (features-features.min(axis=0))*(1-0)
  242. # print(nom.shape)
  243. # denom = features.max(axis=0) - features.min(axis=0)
  244. # denom[denom==0] = 1
  245. # print(denom.shape)
  246. # X_scf = nom/denom
  247. # print(X_scf.shape)
  248. for outerindex in range(len(features)):
  249. for index in range(len(features[outerindex])):
  250. # print(index)
  251. # print(type(X_scf[0][index].item()))
  252. if(features[outerindex][index].item() > high_n[index]):
  253. high_n[index] = features[outerindex][index].item()
  254. elif(features[outerindex][index].item() < low_n[index]):
  255. low_n[index] = features[outerindex][index].item()
  256. print("done with preprocess")
  257. #initialize seed list tracking
  258. seedprobslist = [0.8]*len(seedlist)
  259. seedntimesused = [0]*len(seedlist)
  260. #initialize grid for coverage here based on coverage data, fill with zeroes
  261. coveragegrid = []
  262. # coveragedims = [] #auxilliary variable used to track how coveragegrid is used by some fuzzing strategies
  263. if(fuzzing_coverage_strat == "NC"):
  264. for i in range(len(model.layers)-1):
  265. if "dense" in model.layers[i].name:
  266. coveragegrid += [[0] * model.layers[i].units]
  267. # print(coveragegrid)
  268. # for elem in coveragegrid:
  269. # print(len(elem))
  270. elif(fuzzing_coverage_strat == "KMNC"):
  271. for i in range(len(model.layers)-1):
  272. if "dense" in model.layers[i].name:
  273. layergrid = []
  274. for j in range(model.layers[i].units):
  275. layergrid += [[0]*fuzzing_coverage_strat_param]
  276. coveragegrid += [layergrid]
  277. elif(fuzzing_coverage_strat == "NBC"):
  278. for i in range(len(model.layers)-1):
  279. if "dense" in model.layers[i].name:
  280. layergrid = []
  281. for j in range(model.layers[i].units):
  282. layergrid += [[0,0]]
  283. coveragegrid += [layergrid]
  284. elif(fuzzing_coverage_strat == "SNAC"):
  285. #same code as NC
  286. for i in range(len(model.layers)-1):
  287. if "dense" in model.layers[i].name:
  288. coveragegrid += [[0] * model.layers[i].units]
  289. elif(fuzzing_coverage_strat == "TKNC"):
  290. for i in range(len(model.layers)-1):
  291. if "dense" in model.layers[i].name:
  292. coveragegrid += [[0] * model.layers[i].units]
  293. elif(fuzzing_coverage_strat == "KVPA" or fuzzing_coverage_strat == "KVPV" or fuzzing_coverage_strat == "KVPO"):
  294. #first 225 (n) entries for frequency violations, each one with K splits (per neuron)
  295. for i in range(n):
  296. coveragegrid += [[0]*fuzzing_coverage_strat_param]
  297. #next n entries for charge density violations, each one with K splits
  298. for i in range(n):
  299. coveragegrid += [[0]*fuzzing_coverage_strat_param]
  300. #next 1 entry for total amplitude with K splits
  301. coveragegrid += [[0]*fuzzing_coverage_strat_param]
  302. #finally 1 entry for active electrodes with K splits
  303. coveragegrid += [[0]*fuzzing_coverage_strat_param]
  304. elif(fuzzing_coverage_strat == "KMOC"):
  305. for i in range(n):
  306. singleelecgrid = []
  307. for j in range(3):
  308. singleelecgrid += [[0]*fuzzing_coverage_strat_param]
  309. coveragegrid += [singleelecgrid]
  310. elif(fuzzing_coverage_strat == "KMIC"):
  311. for i in range(128*128):
  312. coveragegrid += [[0]*fuzzing_coverage_strat_param]
  313. elif(fuzzing_coverage_strat == "Div-Approx"):
  314. for i in range(4608):
  315. coveragegrid += [[0]*fuzzing_coverage_strat_param]
  316. elif(fuzzing_coverage_strat == "R0" or fuzzing_coverage_strat == "RA" or fuzzing_coverage_strat == "Local"):
  317. coveragegrid = [0]
  318. else:
  319. print("Not a valid fuzzing coverage metric")
  320. exit()
  321. is_local = False
  322. if(fuzzing_coverage_strat == "Local"):
  323. fuzzing_coverage_strat = "R0"
  324. is_local = True
  325. most_v = [0,0,0,0,0,0]
  326. seed_index = 0
  327. #go through seedlist and check off any boxes filled by existing seeds, remove seeds that don't fill a new box. Check time during.
  328. count = 0
  329. for seed in seedlist:
  330. count += 1
  331. (res,new_coverage) = run_network(seed, fuzzing_coverage_strat, fuzzing_coverage_strat_param, fuzzing_coverage_strat_param2, coveragegrid, high_n, low_n, n, e1, e2, e3)
  332. v_array = check_violations(res, n, e1, e2, e3)
  333. if sum(v_array) > 0:
  334. # print("Violation found: " + str(v_array))
  335. violations = [x + y for x, y in zip(violations, v_array)]
  336. for elem in seed:
  337. outfileinstances.write(str(elem) + ",")
  338. outfileinstances.write(str(v_array) + "\n")
  339. if(is_local and v_array[1] + v_array[3] + v_array[5] + v_array[5] > most_v[1] + most_v[3] + most_v[4] + most_v[5]):
  340. most_v = v_array[:]
  341. seed_index = count - 1
  342. if(count % progresslogstep == 0):
  343. progresstimes.write(str(time.time() - starttime) + "," + str(violations[0]) + "," + str(violations[1]) + "," + str(violations[2]) + "," + str(violations[3]) + "," + str(violations[4]) + "," + str(violations[5]) + ",")
  344. covprop = get_covprop(coveragegrid)
  345. progresstimes.write(str(covprop) + "\n")
  346. #if(time.time() - starttime >= timelimit):
  347. # progresstimes.write(str(time.time() - starttime) + "," + str(violations[0]) + "," + str(violations[1]) + "," + str(violations[2]) + "," + str(violations[3]) + "," + str(violations[4]) + "," + str(violations[5]) + ",")
  348. # covprop = get_covprop(coveragegrid)
  349. ## progresstimes.write(str(covprop) + ",TIMEOUTINSEEDS\n")
  350. # print("Timeout")
  351. # outfileinstances.close()
  352. # progresstimes.close()
  353. # exit()
  354. #log the time, coverage, and violations at the end of the provided seedset
  355. progresstimes.write(str(time.time() - starttime) + "," + str(violations[0]) + "," + str(violations[1]) + "," + str(violations[2]) + "," + str(violations[3]) + "," + str(violations[4]) + "," + str(violations[5]) + ",")
  356. covprop = get_covprop(coveragegrid)
  357. progresstimes.write(str(covprop) + ",ENDOFSEEDS\n")
  358. if(is_local):
  359. seedlist = [seedlist[seed_index]]
  360. seedprobslist = [0.8]*len(seedlist)
  361. seedntimesused = [0]*len(seedlist)
  362. seedchoicecount = 0
  363. leninitialseedlist = len(seedlist)
  364. ntwkrunavgtime = 0
  365. ntwkruncount = 0
  366. #main loop: choose a seed, create 50 mutations, check each mutation and update seedlist if necessary, check time, repeat.
  367. while(count < countlimit):
  368. # print(len(seedlist))
  369. # print(len(seedprobslist))
  370. baseseedindex = 0
  371. if(seedchoicecount < leninitialseedlist):
  372. baseseedindex = seedchoicecount
  373. else:
  374. baseseedindex = random.choices(range(len(seedlist)), weights=seedprobslist, k=1)[0]#select randomly weighted by seedprobslist
  375. seedchoicecount += 1
  376. for iter in range(10):
  377. mutation = random.choice(allowed_mutations)
  378. count += 1
  379. seedntimesused[baseseedindex] += 1
  380. sample = []#use mutation on seed elem to get sample
  381. if mutation == "random_u":
  382. sample = generate_random(boundslist)
  383. elif mutation == "invert":
  384. sample = invert_colors(copy.deepcopy(seedlist[baseseedindex]), boundslist)
  385. else:
  386. # print("Here")
  387. # print(mutation)
  388. to_mutate = copy.deepcopy(seedlist[baseseedindex])
  389. to_mutate = [x * 255 for x in to_mutate]
  390. numpysample = np.reshape(to_mutate, (128,128,1))
  391. if mutation == "translate":
  392. sample = image_translation(copy.deepcopy(numpysample))
  393. elif mutation == "scale":
  394. sample = image_scale(copy.deepcopy(numpysample))
  395. elif mutation == "shear":
  396. sample = image_shear(copy.deepcopy(numpysample))
  397. elif mutation == "rotate":
  398. sample = image_rotation(copy.deepcopy(numpysample))
  399. elif mutation == "contrast":
  400. sample = image_contrast(copy.deepcopy(numpysample))
  401. elif mutation == "brightness":
  402. sample = image_brightness(copy.deepcopy(numpysample))
  403. elif mutation == "blur":
  404. sample = image_blur(copy.deepcopy(numpysample))
  405. elif mutation == "pixel_change":
  406. sample = image_pixel_change(copy.deepcopy(numpysample))
  407. elif mutation == "noise":
  408. sample = image_noise(copy.deepcopy(numpysample))
  409. else:
  410. print("mutation type not yet implemented: " + mutation)
  411. exit()
  412. if(numpysample.shape != sample.shape):
  413. sample = sample.reshape(numpysample.shape)
  414. singleinput = []
  415. for row in sample:
  416. for col in row:
  417. singleinput += [col[0]]
  418. sample = singleinput
  419. assert(len(sample) == 128*128)
  420. sample = [x / 255.0 for x in sample]
  421. for i in range(len(sample)):
  422. if sample[i] > boundslist[i][1]:
  423. sample[i] = boundslist[i][1]
  424. elif sample[i] < boundslist[i][0]:
  425. sample[i] = boundslist[i][0]
  426. ntwkrunstarttime = time.time()
  427. (res, new_coverage) = run_network(sample, fuzzing_coverage_strat, fuzzing_coverage_strat_param, fuzzing_coverage_strat_param2, coveragegrid, high_n, low_n, n, e1, e2, e3)
  428. ntwkrunavgtime += time.time() - ntwkrunstarttime
  429. ntwkruncount += 1
  430. v_array = check_violations(res, n, e1, e2, e3)
  431. if sum(v_array) > 0:
  432. # print("Violation found: " + str(v_array))
  433. violations = [x + y for x, y in zip(violations, v_array)]
  434. for elem in sample:
  435. outfileinstances.write(str(elem) + ",")
  436. outfileinstances.write(str(v_array) + "\n")
  437. if(fuzzing_coverage_strat == "KVPV"):
  438. if(new_coverage and sum(v_array) > 0):
  439. seedlist += [sample]
  440. seedprobslist += [0.8]
  441. seedntimesused += [0]
  442. else:
  443. if(new_coverage):
  444. seedlist += [sample]
  445. seedprobslist += [0.8]
  446. seedntimesused += [0]
  447. if(count % progresslogstep == 0):
  448. progresstimes.write(str(time.time() - starttime) + "," + str(violations[0]) + "," + str(violations[1]) + "," + str(violations[2]) + "," + str(violations[3]) + "," + str(violations[4]) + "," + str(violations[5]) + "," + str(count) + ",")
  449. covprop = get_covprop(coveragegrid)
  450. progresstimes.write(str(covprop) + "\n")
  451. #update seed at baseseedindex probabliity
  452. if(seedntimesused[baseseedindex] < (0.8-0.3)*5):
  453. seedprobslist[baseseedindex] = 0.8 - seedntimesused[baseseedindex]/5
  454. else:
  455. seedprobslist[baseseedindex] = 0.3
  456. progresstimes.write(str(time.time() - starttime) + "," + str(violations[0]) + "," + str(violations[1]) + "," + str(violations[2]) + "," + str(violations[3]) + "," + str(violations[4]) + "," + str(violations[5]) + "," + str(count) + ",")
  457. covprop = get_covprop(coveragegrid)
  458. progresstimes.write(str(covprop) + ",NTESTSFINISHED\n")
  459. print("N Tests Finished")
  460. print(ntwkrunavgtime/ntwkruncount)
  461. outfileinstances.close()
  462. progresstimes.close()

main.py at commit 5783f98, under BSD-3-Clause · at the source

Overview

  1. Department of Computer Science, University of California, Santa Barbara, CA, United States of America
  2. Department of Psychological & Brain Sciences, University of California, Santa Barbara, CA, United States of America
Institutions: University of California, Santa Barbara (United States)
Journal: Journal of neural engineering, volume 23, issue 2, article 026004
Dates: received 24 November 2025; accepted 23 February 2026; published online 5 March 2026; in print 1 April 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1088/1741-2552/ae4927 · PMID 41730246 · PMCID PMC12961644 · OpenAlex W7131077256
Open access: hybrid, a free copy (OpenAlex)
Status: code verified
Categories: human (organism)
Methods: Machine learning
Keywords: coverage-guided fuzzing, neural networks, safety constraints, biomedical implants, neuroprostheses
MeSH: Brain*, Electric Stimulation*, Machine Learning*, Animals, Humans, Retina, Soft Computing (* major topic)
Topic: Neuroscience and Neural Engineering (Cellular and Molecular Neuroscience, Neuroscience), according to OpenAlex
Funding: National Science Foundation (2008660); NLM NIH HHS (DP2 LM014268); U.S. National Library of Medicine (DP2-LM014268)
Citations: not cited yet (Europe PMC); 65 references in the paper

Abstract

Objective. Machine learning (ML) models are increasingly used to generate electrical stimulation patterns in neuroprosthetic devices such as visual prostheses. While these models promise precise and personalized control, they also introduce new safety risks when model outputs are delivered directly to neural tissue. We propose a systematic, quantitative approach to detect and characterize unsafe stimulation patterns in ML-driven neurostimulation systems. Approach. We adapt an automated software testing technique known as coverage-guided fuzzing to the domain of neural stimulation. Here, fuzzing performs stress testing by perturbing model inputs and tracking whether resulting stimulation violates biophysical limits on charge density, instantaneous current, or electrode co-activation. The framework treats encoders as black boxes and steers exploration with coverage metrics that quantify how broadly test cases span the space of possible outputs and violation types. Main results. Applied to deep stimulus encoders for the retina and cortex, the method systematically reveals diverse stimulation regimes that exceed established safety limits. Two violation-output coverage metrics identify the highest number and diversity of unsafe outputs, enabling interpretable comparisons across architectures and training strategies. Significance. Violation-focused fuzzing reframes safety assessment as an empirical, reproducible process. By transforming safety from a training heuristic into a measurable property of the deployed model, it establishes a foundation for evidence-based benchmarking, regulatory readiness, and ethical assurance in next-generation neural interfaces.

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

Repository

Its files are read in the Code ↔ Paper reader above, with 5 matches between paragraphs and lines of code.

mara-downing/safety_violation_fuzzing_visual_prostheses

License: BSD-3-Clause
State: the link answers, verified on 30 September 2026
Evidence: files inventoried
Commit: 5783f985635f4bc0ae5e41685f9654f2264816f2, 13 November 2025
Languages: Python (63)
Size: 977 files, 63 scripts
Software Heritage: not archived
Found in: the text, “Experimental setup”
Holds: README, license file
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (41 files), TensorFlow (28 files), PyTorch (17 files), Pillow (16 files), Keras (11 files), Matplotlib (11 files), OpenCV (10 files), pandas (4 files)
Availability: 1 check, the latest on 30 September 2026: the link answers
  • 30 September 2026: the link answers
65 files

The paper's code and data availability statement is in the Data section.

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;
  • 63 scripts, each with its path and the digest of its content;
  • 5 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • 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

The data that support the findings of this study are openly available at the following URL/DOI: https://github.com/mara-downing/safety_violation_fuzzing_visual_prostheses (Downing et al 2026).

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 1, 30 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 5 authors, 5 keywords, 7 MeSH terms, 3 funders, 56 references.

Cite

This paper

Downing, M., Peng, M., Granley, J., Beyeler, M., & Bultan, T. (2026). Fuzzing the brain: automated stress testing for the safety of ML-driven neurostimulation. Journal of neural engineering, 23(2), 026004. https://doi.org/10.1088/1741-2552/ae4927

BibTeX

@article{downing2026fuzzing,
author = {Downing, Mara and Peng, Matthew and Granley, Jacob and Beyeler, Michael and Bultan, Tevfik},
title = {{Fuzzing the brain: automated stress testing for the safety of ML-driven neurostimulation}},
journal = {Journal of neural engineering},
year = {2026},
month = mar,
volume = {23},
number = {2},
pages = {026004},
publisher = {IOP Publishing},
issn = {1741-2560},
doi = {10.1088/1741-2552/ae4927},
url = {https://doi.org/10.1088/1741-2552/ae4927},
pmid = {41730246},
pmcid = {PMC12961644}
}

RIS

TY - JOUR
AU - Downing, Mara
AU - Peng, Matthew
AU - Granley, Jacob
AU - Beyeler, Michael
AU - Bultan, Tevfik
TI - Fuzzing the brain: automated stress testing for the safety of ML-driven neurostimulation
T2 - Journal of neural engineering
J2 - J Neural Eng
PY - 2026
DA - 2026/03/05
VL - 23
IS - 2
SP - 026004
SN - 1741-2560
PB - IOP Publishing
DO - 10.1088/1741-2552/ae4927
UR - https://doi.org/10.1088/1741-2552/ae4927
LA - en
ER -

CSL-JSON

{
"id": "10.1088/1741-2552/ae4927",
"type": "article-journal",
"title": "Fuzzing the brain: automated stress testing for the safety of ML-driven neurostimulation",
"container-title": "Journal of neural engineering",
"author": [
{
"family": "Downing",
"given": "Mara"
},
{
"family": "Peng",
"given": "Matthew"
},
{
"family": "Granley",
"given": "Jacob"
},
{
"family": "Beyeler",
"given": "Michael"
},
{
"family": "Bultan",
"given": "Tevfik"
}
],
"container-title-short": "J Neural Eng",
"volume": "23",
"issue": "2",
"page": "026004",
"DOI": "10.1088/1741-2552/ae4927",
"PMID": "41730246",
"PMCID": "PMC12961644",
"ISSN": "1741-2560",
"publisher": "IOP Publishing",
"URL": "https://doi.org/10.1088/1741-2552/ae4927",
"language": "en",
"issued": {
"date-parts": [
[
2026,
3,
5
]
]
}
}

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.1016/j.celrep.2026.117420 [code]
Neural population dynamics of direct electrical stimulation of neocortex.
Journal: Cell reports
In common: OpenCV, Pillow, pandas, 2 other tools, 3 references
[2] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: Keras, TensorFlow, OpenCV, 5 other tools
[3] doi:10.1371/journal.pcbi.1014571 [code]
SynAPSeg: A novel dataset and image analysis framework for deep learning-based synapse detection and quantification.
Journal: PLoS computational biology
In common: Keras, TensorFlow, OpenCV, 5 other tools
[4] doi:10.1093/jnen/nlaf152 [code]
Clinical and pathologic correlations of machine learning quantification of Aβ deposits across 3 brain regions of decedents with Alzheimer disease.
Journal: Journal of neuropathology and experimental neurology
In common: Keras, TensorFlow, OpenCV, 5 other tools
[5] doi:10.1371/journal.pone.0347867 [code]
LiteFeatNet: A parameter-efficient and performance-centric deep learning model for multi-ocular disease identification using intermediate feature reduction from fundus images.
Journal: PloS one
In common: Keras, TensorFlow, OpenCV, 5 other tools
[6] doi:10.1038/s41597-025-05174-7 [code]
A large-scale MEG and EEG dataset for object recognition in naturalistic scenes
Journal: n/a
In common: Keras, TensorFlow, OpenCV, 5 other tools
[7] doi:10.1126/sciadv.aed3650 [code]
Truthful visualizations for mass spectrometry imaging enable high-spatial-resolution interactive &lt;i&gt;m/z&lt;/i&gt; mapping and exploration.
Journal: Science advances
In common: Keras, TensorFlow, OpenCV, 5 other tools
[8] doi:10.1364/boe.605322 [code]
Generalized plaque digitization framework for multi-dimensional mesoscopic images.
Journal: Biomedical optics express
In common: Keras, TensorFlow, OpenCV, 5 other tools
[9] doi:10.1038/s41467-026-72057-9 [code]
Sex-specific behavioral feedback modulates sensorimotor processing and drives flexible social behavior.
Journal: Nature communications
In common: Keras, TensorFlow, OpenCV, 5 other tools
[10] doi:10.1126/sciadv.aee6952 [code]
Wafer-scale SOT-MRAM for analog crossbar array applications.
Journal: Science advances
In common: Keras, TensorFlow, OpenCV, 4 other tools

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.