Closed-loop optogenetic control of normal and pathological network dynamics

Electrical neurostimulation is effective in treating neurological disorders, but associated recording 14 artefacts generally limit applications to ‘open-loop’ stimuli. Since light does not prevent concurrent 15 electrical recordings, optogenetics enables real-time, continuous ‘closed-loop’ control of brain 16 activity. Here we show that closed-loop optogenetic stimulation with excitatory opsins (CLOSe) 17 affords precise manipulation of neural dynamics, both in vitro , in brain slices from transgenic mice, 18 and in vivo, with anesthetised monkeys. We demonstrate the generation of oscillations in quiescent 19 tissue, enhancement or suppression of endogenous patterns in active tissue, and modulation of 20 seizure-like bursts elicited by 4-aminopyridine. New network properties, emergent under CLOSe, 21 depended on the phase-shift imposed between neural activity and optical stimulation, and could

Many neurological conditions lead to altered network dynamics, characterised by abnormally low or 29 high levels of oscillatory synchrony within, and between, brain areas (Uhlhaas and Singer, 2006). 30 Neuromodulation therapies such as Deep Brain Stimulation (DBS) typically deliver 'open-loop' trains 31 of electrical stimulation in an attempt to disrupt pathological patterns and maintain brain activity 32 within a range of functional states. However, from a control theory perspective, open-loop methods 33 are generally inferior to closed-loop control that incorporates feedback based on the real-time state 34 of the system (Shanechi, 2019 36 example to enhance beneficial oscillations or to destabilise pathological brain states such as epileptic 37 seizures. Unfortunately, many potential applications of closed-loop neurostimulation are hampered 38 by large artefacts associated with electrical stimulation, particularly when monitoring and modulating 39 the same local population of neurons. This often limits control policies to simple decisions to turn on 40 or off otherwise continuous trains of stimuli (Little et al., 2013, Skarpaas et al., 2019. 41 Since the light stimuli used for optogenetics can be delivered without preventing concurrent electrical 42 recording, it can be continuously modulated in real-time by brain signals to allow true closed-loop 43 interaction with local networks. Despite considerable theoretical motivation (Grosenick et al., 2015), 44 experimental demonstrations of closed-loop optogenetic stimulation have thus far been limited to in 45 vitro preparations (Nicholson et al., 2018) and in vivo experiments on normal brain rhythms in rodents 1 (Sohal et al., 2009, Siegle and Wilson, 2014, Stark et al., 2014. Here we aim to advance this technique 2 towards therapeutic applications in humans, by demonstrating the feasibility of closed-loop 3 manipulation of network dynamics in non-human primates and examining its effect on pathological 4 seizure-like activity. In addition, we compare optical stimulation delivered via an external light source 5 with an implantable optrode incorporating encapsulated light-emitting diodes (LEDs). While 6 optogenetics allows specific cell types to be targeted with a range of different opsins, we focus here 7 on closed-loop optogenetic stimulation with excitatory opsins (CLOSe), using efficient ion channel 8 opsins without the need to restrict expression to specific neuronal subtypes. We hypothesized that by 9 altering the timing of stimulation relative to ongoing activity, we could exert differential effects on the 10 local networks, thus adding a new temporal dimension to the control of neural dynamics that can be 11 achieved with optogenetics. setup. LFP, recorded from an Emx1-ChR2 mouse, brain slice was filtered and used to control 16 optical stimulation in real-time. Bottom: Amplitude response of filter. Inset shows phase 17 response across the passband. b Example LFP and stimulation traces under no stimulation 18 (black) and CLOSe with different phase-shifts (relative to LFP, 2 Hz filter frequency). c LFP 19 power spectra for different phase-shifts. d Left: Phase-shifts (relative to LFP) associated with 20 maximal oscillation in 21 sessions. Right: Adjusted phase-shifts (relative to high gamma 21 activity; see Supp. Fig. 1). P values from Rayleigh test for circular non-uniformity. e LFP power 22 at different frequencies for different adjusted phase-shifts (2 Hz filter). Phase-shift is 23 unwrapped and plotted over two cycles. f Phase-dependent modulation of LFP power for 24 different filter frequencies. Colour indicates adjusted phase-shift associated with maximal 25 oscillation. Dashed line shows log-linear fit to data. 26

28
Closed-loop optogenetic stimulation drives oscillations in quiescent brain slices 1 We first investigated CLOSe in quiescent brain slices taken from transgenic mice, expressing 2 channelrhodopsin selectively in excitatory pyramidal cells (Emx1-ChR2). The local field potential (LFP), 3 recorded with an extracellular electrode, was passed through a finite impulse response (FIR) filter 4 using a kernel which band-passed and phase-shifted the signal (Fig. 1a). The output of the filter was 5 half-wave rectified (above a threshold set to reject background noise) and controlled in real-time the 6 intensity of optical stimulation delivered through a light fibre. Within each experimental session we 7 delivered CLOSe epochs with different phase-shifts (0, 45°, …, 315°) in pseudorandomised order, 8 interspersed by control epochs with no stimulation. Across different sessions, we tested filters with 9 central frequencies between 2-40 Hz. 10 Application of CLOSe with some phase-shifts produced no stable oscillation, while others created a 11 positive feedback loop which drove strong oscillations at frequencies within the filter pass-band ( Fig.  12 1b,c). Qualitatively similar effects were obtained in 21 sessions with different slices, but we observed 13 considerable variation in the phase-shift associated with maximal LFP oscillations (Supp. Fig. 1a, Fig.  14 1d left; circular mean=-27°, Raleigh test for circular non-uniformity P=0.82). We speculated that this 15 was due to variation in the relationship between LFPs and underlying neural activity, which is known 16 to vary through the cortex (Hall et al., 2014). Therefore, we used the envelope of high-gamma (>100 17 Hz) LFP activity as a surrogate of neural firing, and calculated the zero-lag phase of its cross-correlation 18 with the LFP in each session (Supp. Fig. 1b). Off-line, we added this correction to the phase-shift 19 applied by the filter in order to replot our data against an adjusted phase-shift that represented the 20 overall phase-advance of optical stimulation relative to putative neural activity (Supp. Fig. 1c). 21 Following this adjustment, the phase-shift associated with maximal positive-feedback LFP oscillations 22 was consistently around 0-90° relative to the high gamma envelope (Fig. 1d, right, circular mean=38°, 23 Rayleigh test for circular non-uniformity P=0.002), while phase-shifts around 180-270° were 24 associated with minimal oscillation. We refer to these conditions as CLOSe + and CLOSerespectively. 25 CLOSe + drove oscillations around the centre-frequency of the filter as well as higher harmonics, and 26 these frequencies increased systematically with increasing phase-shift, as shown by the diagonal 27 stripes in Fig. 1e (note that phase-shift is unwrapped and plotted over two cycles). Conceptually, this 28 behaviour can be understood by equating a phase-advance in the feedback signal with a reduction of 29 the feedback loop delay. As this delay is reduced, the frequencies associated with positive feedback 30 instabilities increase. By altering the central filter frequency, we were able to tune these resonant 31 frequencies (Supp. Fig. 1a) and drive oscillations up to 40 Hz, although the LFP power modulation was 32 significantly reduced at higher frequencies (Fig. 1f). 33 34 1 2 Supplemental Figure 1 -Realigning phase-shifts to high gamma envelope. a LFP spectra from three 3 different Emx1-ChR2 mouse brain slice sessions. Bottom plot shows that the phase-shifts and 4 frequencies of driven oscillations varied across sessions. b Cross-correlation between the LFP 5 and high gamma envelope was used to infer the phase relationship between LFP and 6 underlying neural activity. c LFP spectra replotted after adjusting phase-shift relative to high 7 gamma envelope. In addition, the frequency axis has been normalised by the filter frequency. 8 As a result, the frequencies of oscillations driven by different phase-shifts are more closely 9 aligned. d Phase-shifts (relative to LFP) that drove maximal oscillation plotted against relative 10 phase between LFP and high gamma envelope. Solid line indicates stimulation in phase with 11 high gamma. Maximal modulation was typically obtained for phase-shifts advanced by 0-90° 12 relative to this (circular mean 38°, dashed line). 13

15
CLOSe can boost or suppress endogenous in vivo activity in non-human primates 1 Next, we examined the effect of CLOSe on endogenous in vivo brain activity in two non-human 2 primates (NHPs). Excitatory opsins were expressed under the neuron-specific human synapsin 3 promoter (hSyn) using viral vectors [either AAV8-hSyn-Chronos-GFP or Lenti-hSyn-eYFP-2A-4 ChR2(H134R); Supp. Table 1] injected into the primary motor cortex, 7-19 weeks prior to recording  5 sessions under terminal anaesthesia. Post-mortem histology confirmed widespread expression of 6 associated fluorescent tags in both animals (Supp. Fig. 2a). LFPs and single-units were recorded with 7 multi-contact electrodes. Open-loop stimulation (200 or 500 ms pulses at 1 Hz) and CLOSe (driven by 8 different phase-shifts applied to one LFP from the array) was delivered through an optic ferrule 9 inserted into the cortex. Figure 2a (top) shows example open-loop stimulation using ChR2. Large LFP 10 deflections were observed in response to light pulses, associated with bursts of neural firing (Fig. 2b). 11 Note that, unlike our EMX-ChR2 mice, the promoter used in the NHPs was not specific to excitatory 12 neurons and, consistent with this, we occasionally observed suppression of firing in some neurons 13 (Supp. Fig. 2b). Importantly, the polarity of field responses varied with depth, as expected for a 14 physiological response rather than photoelectric artefact ( Fig. 2b; left). 15 CLOSe + again drove strong oscillatory responses in field potentials and neural firing ( Fig. 2a; middle), 16 revealed by cycle-triggered LFP averages (Fig. 2b). Note that the depth profile of the driven oscillations 17 resembled that of endogenous activity observed during control epochs with no stimulation, suggesting 18 that CLOSe + drove naturalistic patterns of network activity (Supp. Fig. 3). Despite using an excitatory 19 opsin, CLOSe was also capable of suppressing oscillations below levels seen with no stimulation. This 20 can be seen in the cycle-triggered LFP averages for different phase-shifts (Fig. 2c) as well as in the LFP 21 power spectra (Fig. 2d). Figure 2e shows oscillatory power at each frequency for each phase condition, 22 normalised by the corresponding power spectrum for no-stimulation epochs. Regions of red reflect 23 CLOSe + driving positive feedback oscillations, while interspersed regions of blue show CLOSephase-24 shifts that suppressed background activity. No such modulation was observed in control experiments 25 using a frequency of light that was outside the opsin absorption spectrum delivered through the same 26 optic ferrule (Fig. 2f), demonstrating our results were mediated by optogenetic stimulation rather than 27 non-specific effects such as photoelectric artefacts or tissue heating. 28 We additionally tested CLOSe delivered via an implanted optrode incorporating LED light sources 29 placed inside the brain. Significant modulation of field potential power could also be obtained using a 30 single LED ( Fig. 2g and Supp. Fig. 4a), albeit with a weaker magnitude, consistent with the LED 31 producing about half the light power of our commercial fibre-coupled system (Supp. Fig. 4b). Figure  32 2h shows modulation of power around the closed-loop filter frequency, with a statistically significant 33 effect of the eight phase conditions for illumination with blue light via the ferrule (circular-linear 34 correlation, n=57 stimulation epochs, R=0.90, P=1x10 -10 ) and LED (n=60, R=0.86, P=2x10 -10 ) but not for 35 control yellow light (n=58, R=0.13, P=0.6). We observed statistically significant (circular-linear 36 correlation, P<0.05) phase-dependent power modulation in experiments made in three hemispheres 37 from two animals (Figure 2i), using both opsins (Supp. Table 1). Once again, we could tune the 38 frequencies of enhancement and suppression by altering the filter frequencies. We quantified 39 modulation from both the maximum/minimum modulation of LFP power for any single phase-shift 40 (raw data, Fig. 2j top) and from a sinusoidal fit through all phase-shifts (sine fit, Fig. 2j bottom). As with 41 the brain slice experiments, modulation became progressively weaker for higher closed-loop filter 42 frequencies, with statistically significant phase-dependence at 40 Hz observed in only two of the three 43 datasets. Confocal imaging in the three hemispheres from two animals demonstrating expression of 6 fluorescent marker (green) in neurons including pyramidal neurons, co-localised with NeuN 7 neuronal marker (red). Also overlain is Hoechst nuclear stain (blue) and GFAP astrocytic 8 marker (white). c Example spike raster plots and peri-stimulus histograms showing 9 optogenetic responses in neurons recorded from the three hemispheres. Two cells show 10 strong excitatory responses to blue light stimulation (shaded region), while one cell is 11 inhibited, possibly mediated by inhibitory interneurons due to the non-selective promotor.  frequencies with increased (red) and reduced (blue) activity relative to no stimulation. f No 3 modulation was observed when stimulating with a frequency of light outside the opsin 4 absorption range. g LFP modulation driven by an implanted LED. h LFP modulation (between 5 0.8-1.2x the filter frequency) for the three datasets. R and P values from circular-linear 6 correlation over stimulation epochs. i LFP modulation for different filter frequencies 7 replicated in three datasets (Z-L: Lenti-hSyn-eYFP-2A-ChR2(H134R); Z-R and Y: AAV8-hSyn-8 Chronos-GFP). j Maximum/minimum power modulation (between 0.8-1.2x the filter 9 frequency) for different filter frequencies. Top: maximum/minimum value for any phase-shift. 10 Shading indicates s.e.m. over stimulation epochs. Bottom: maximum/minimum values of 11 sinusoidal fit to data. Filled circles indicate significant phase-dependent modulation (circular-12 linear correlation over stimulus epochs, P<0.05). LED for different supply currents (blue). Also shown is the light power output for the 5 commercial light source used for the other datasets. The horizontal axis encompasses the full 6 range of stimulation intensities in both cases. Note that the datasets analysed here used a 7 single LED to activate the tissue. 8 9

CLOSe can modulate pharmacologically-induced epileptiform activity in vitro 10
Having demonstrated phase-shift-dependent enhancement and suppression of endogenous 11 oscillations, we next examined whether CLOSe could influence pharmacologically-induced 12 pathological states resembling seizures. In our in vitro brain slice model, bath application of 4-13 aminopyridine (4-AP) generated sporadic seizure-like events consisting of multiple brief bursts of 14 oscillatory discharge around 15-20 Hz. An example of this activity is shown in Figure 3a. Applying 15 CLOSe with a 20 Hz filter frequency in this session could shorten the duration of individual bursts 16 depending on phase-shift (Fig. 3b, left). Figure 3b (right) shows a logarithmic plot of the modulation 17 of burst durations under different CLOSe phase-shifts relative to no-stimulation epochs. Across this 18 whole session, the burst duration was doubled under CLOSe + (0° phase-shift, mean ± s.e.m. log2-ratio 19 burst duration = 1.00 ± 0.18) and decreased by about a quarter under CLOSe -(225° phase-shift, log2-20 ratio burst duration = -0.44 ± 0.15). Circular-linear correlation across the eight phase-shift conditions 21 confirmed that modulation of burst duration depended significantly on closed-loop phase-shift (n=221 22 seizure bursts, R=0.62, P=1x10 -16 ). Modulation was also evident as phase-dependent enhancement 1 and suppression of LFP power spectra during seizure-like events (Fig. 3c). Averaged across our dataset 2 of 10 sessions, the relative duration of seizure bursts was modulated between a max/min log2-ratio of 3 0.49 ± 0.13 to -0.48 ± 0.11 (equivalent to 1.4x increase and 0.7x decrease respectively; Fig. 3d), and 4 depended significantly on closed-loop phase-shift in 8/10 individual sessions (circular-linear 5 correlation, P<0.05). When all sessions were combined (after adjusting to high-gamma activity as 6 before), the relative burst duration also depended significantly on CLOSe phase-shift (circular-linear 7 correlation, n=10 sessions x 8 phase conditions, R=0.29, P=0.03), as did power modulations at seizure 8 frequencies (Fig. 3e, n=80, R=0.39, P=0.002). Note however that our (high-gamma) phase-shift 9 adjustment did not perfectly align the different sessions so the max/min modulation in the session-10 averaged plots was lower than that seen in individual sessions, and no single phase-shift produced 11 statistically significant suppression in the combined dataset.

CLOSe can modulate pharmacologically-induced epileptiform activity in vivo 1
In the non-human primates in vivo, injection of 4-AP into the motor cortex reliably produced 2 prolonged seizure events lasting around 20 s occurring at regular intervals (typically every minute for  3 about an hour). Seizure events were characterised by an initial oscillation in the range 15-25 Hz 4 followed by post-ictal discharges. Figure 4a shows two events from the right hemisphere of monkey Z 5 (Chronos opsin); the first during a control period with no stimulation, and the second during delivery 6 of CLOSewith a phase-shift of 225° with a marked suppression of oscillatory discharge. Unlike the in 7 vitro data, background activity and seizure variability precluded precise identification of the onset and 8 offset of individual events. Therefore, to visualise the impact of CLOSe across the entire session, we 9 instead computed the autocorrelation of the LFP amplitude envelope within the seizure band (10- 30 10 Hz) over the whole duration of CLOSe and control epochs. The peaks in Fig. 4b with a width of 11 approximately 20s reveal the broad temporal structure of seizures bursts, and the variation in their 12 height and width indicates modulation by closed-loop stimulation. We quantified seizure magnitude 13 by calculating the area under this curve (between ±20 s), although note that this single measure is 14 influenced by the intensity, duration and interval between individual events. In addition, we calculated 15 power spectra, across all epochs for each stimulation condition (Fig. 4c), which, when normalised by 16 the no-stimulation spectra, again revealed a characteristic pattern of phase-dependent modulation 17 (Fig. 4d). Similar results were obtained in two animals ( Fig. 4e), as well as one session in which 18 stimulation was delivered using the implanted LED (Fig. 4f). Across our dataset of 4 sessions, seizure 19 magnitude was modulated by CLOSe between a log2 ratio of 1.11 ± 0.25 to -0.66 ± 0.13 (a 2.1x increase 20 and 0.6x suppression respectively). When these data were combined, we observed a statistically 21 Example seizure-like event elicited by intracortical injection of 4-AP in monkey motor cortex. Epileptic activity is usually thought to reflect an excess of excitatory activity in brain networks. 2 Therefore, our observation that excitatory stimulation can reduce the duration and intensity of 3 seizures is counterintuitive. To examine how CLOSewas capable of attenuating seizure-like events, 4 we simulated a simple Wilson-Cowan neural mass model that has previously been applied to epileptic 5 activity ( populations (excitatory and inhibitory) whose activity was represented in a two-dimensional phase 7 space. The instantaneous state evolved through time according to nonlinear dynamics, which divided 8 the phase space into two regimes (Fig. 5a). States initiated with low excitatory activity evolved towards 9 a stable fixed point representing a quiescent network, while initial states with higher excitatory activity 10 were attracted towards a limit cycle representing epileptiform oscillations. Connection weights were 11 chosen to produce an oscillation frequency similar to the experimental data and Gaussian noise input 12 was added to both populations, allowing probabilistic transitions between quiescent and seizure 13 regions. CLOSe was modelled as an additional excitatory input to the excitatory population, dependent 14 on a phase-shifted LFP signal reflecting a high-pass filtered combination of the activity of both 15 populations. 16 Model simulations starting from the limit cycle under different closed-loop feedback conditions 17 qualitatively captured many features of our experimental data (Fig. 5b, c.f. Fig. 3b,c), including phase-18 shift-dependent lengthening or shortening of seizure durations, and associated modulation of spectral 19 power. To understand this better, we examined the behaviour of the seizure limit cycle under different 20 CLOSe conditions (Fig. 5c and Supp. Movie 1). In the absence of input noise, excitatory stimulation 21 alone never halted the seizure, but as the phase-shift advanced from CLOSe + to CLOSe -, the limit cycle 22 underwent period doubling and became increasingly complex, fluctuating between small and large 23 cycles in the phase space. Since the larger cycles came close to the boundary of the quiescent regime, 24 there was a higher probability that the added noise input could push the network across into the 25 attractor basin of the stable fixed point (Fig. 5d). In other words, the altered duration of seizure bursts 26 relative to the no-stimulation condition in our model could be explained by the increased stability (in 27 the presence of input noise) of the limit cycle under CLOSe + , and its increased sensitivity to noise 28 perturbations under CLOSe -. 29 To seek evidence for this phenomenon in our experimental data, we used delay embedding to 30 reconstruct the dynamics of simulated and actual LFP data. information theoretic measure of complexity that has previously been applied to seizure data (Zhou 37 et al., 2012). For both simulated and experimental data, these metrics showed a phase-shift-38 dependent modulation, with lower/higher trajectory variability and entropy associated with 39 CLOSe + /CLOSerespectively, relative to no stimulation (Fig. 4g). For both the in vitro (Fig. 4h) and in 40 vivo datasets (Fig. 4i), trajectory CV and AppEn were inversely correlated with seizure duration and 41 seizure severity (P<0.05 in all cases), providing evidence that the enhancement and suppression of 42 epileptiform activity are associated with closed-loop feedback that respectively stabilises and 43 destabilises the seizure cycle. Over recent years, optogenetics has emerged as a powerful tool for manipulating neural populations 2 with unprecedented spatial resolution and cell-type specificity. Our results highlight a further 3 advantage of optical stimulation that is less widely appreciated, namely the ability for feedback control 4 using concurrent electrical recordings without interference from artefacts, allowing for continuous, 5 dynamic interaction with the neural tissue. We found that the effects of closed-loop, excitatory 6 optogenetic stimulation depended critically on the timing relative to ongoing activity, with CLOSe + 7 able to drive strong oscillations at a range of frequencies in quiescent tissue, and CLOSesuppressing 8 endogenous activity and pathological seizure-like oscillations. While optical stimulation is not free 9 from potential sources of artefact (e.g. photoelectric effects), several lines of evidence point 10 conclusively to an opsin-mediated effect in our data. First, we verified opsin expression and 11 functionality from spike recordings and post-mortem histology (Supp. Fig. 2). Second, we saw no 12 modulation when using light outside the absorption spectrum of our opsins (Fig. 2f). Third, the evoked 13 responses exhibited polarity-reversals through the tissue, which resembled those of spontaneous 14 activity (Supp. Fig. 3). Fourth, the modulatory effects of CLOSe depended consistently on the phase-15 shift relative to high-gamma activity rather the low-frequency LFP (Fig. 1d). Finally, optogenetic 16 responses were attenuated with increasing frequency, as expected for physiological opsin activation 17 (Boyden et al., 2005). 18 The ability to manipulate oscillatory activity systematically with CLOSe has many scientific applications 19 for exploring the function of neural oscillations. While other interventions (e.g. pharmacological) can 20 be used to enhance or block oscillations, an advantage of CLOSe is that enhancement and suppression 21 at different frequencies can be interspersed within the same experimental design, simply by tuning 22 parameters of the feedback loop (e.g. the filter pass-band and phase-shift). Moreover, potential uses 23 extend beyond driving the predefined activity up, or down, since the addition of closed-loop feedback 24 to a recurrent network can qualitatively alter the dynamics expressed by that system. For example, 25 we showed computational and experimental evidence that CLOSe altered the sensitivity of state-space 26 limit cycles to noise perturbations, thus precipitating or delaying phase transitions to non-oscillatory 27 states. We used a relatively simple feedback algorithm, but the combination of nonlinear control 28 theory (Taylor et al suggests the effect of stimulation may depend on its timing of stimulation relative to activity cycles 37 ( A major consideration here, is that control of epileptic activity by GABAergic inhibition, or 9 hyperpolarising ion channels like ACR, relies on appropriate chloride gradients being maintained 10 during seizures, which may not be the case in practice (Alfonsa et al., 2015). As might be expected 11 from an excitatory opsin, CLOSe was generally more effective at enhancing rather than suppressing 12 oscillations, although both were possible with the appropriate phase-shift. Nevertheless, given the 13 above considerations, it is likely that the effect of inhibitory stimulation may also depend on the 14 instantaneous network state. Thus, closed-loop optogenetics may also benefit seizure-suppression 15 strategies using inhibitory opsins by allowing more effective suppression with less overall light 16 delivered, but this remains to be tested experimentally. 17 Several major challenges face the translation of optogenetics to the human brain. First, is to 18 demonstrate the safety and efficacy of opsin expression. The use of viral vectors in primates has lagged 19 somewhat behind the progress being made in rodents, but our study is among several to show that 20 widespread, high expression levels can be obtained (Diester et  protection of active electronic components within brain tissue is a challenge but the silicone 27 encapsulation technique we used here has proven to be highly reliable in accelerated lifetime testing 28 of insulators (Lamont, 2020). We are currently developing array implants that combine multiple forks 29 with multiple LEDs on each prong to deliver uniform or patterned illumination to a large volume of 30 cortex, together with custom CMOS circuitry (Ramezani et al., 2018) to process LFP recordings, supply 31 drive current and monitor LED temperature . The cell-specific control enabled 32 by optogenetics has applications in many neurological disorders, and we hope these technologies will 33 help translate the promise of optogenetic therapies to the human brain.  Table. 1 details the datasets collected in each animal. Surgical preparation of the injection site was 6 performed under inhalation anaesthesia (1-2% sevoflurane) after which we switched to intravenous 7 infusion of ketamine (6 mg/kg/h), alfentanil (0.2-0.3 μg/kg/min) and midazolam (0.14 mg/kg/hr) in 8 order to maintain cortical excitability. The animals were ventilated and hydrated, and heart rate, blood 9 pressure, saturation, end-tidal CO2 and temperature were monitored throughout. 10 Neural activity in monkey Y was recorded using a NeuroNexus probe (A4X1-tet-3mm-150-121) and in 11 monkey Z using U-probes (260 μm shaft diameter, 32 channels, 100 µm linear spacing, Plexon Inc). 12 Data were amplified and acquired at 25 kHz using the RHD2000 system (Intan Technologies). Light was 13 delivered through a 200 μm ferule (M89L01-200, Thorlabs) inserted superficially into the cortex, 14 mounted to the same LED cubes as used in the in vitro experiments. In some experiments in monkey 15 Z, we additionally used an implanted LED (see section below) to deliver light to the tissue. 16 After collecting data based on endogenous activity, 4-AP (100 mM) was injected into the cortex using 17 a Hamilton syringe and ultra-micro-pump (UMP3) with the SYS-Micro4 controller (World Precision  18 Instruments). Multiple injections of 1 µl at 200 nl/min were made at the same site until sustained 19 seizure activity was observed (typically 5-10 µl per hemisphere). 20 At the end of the experiment, monkeys were deeply anesthetized with propofol and transcardially 21 perfused with phosphate-buffered saline followed by 4% paraformaldehyde. The brain tissue 22 containing the injection/recording site was stereotaxically dissected and equilibrated in 30% sucrose 23 before 20 μm horizontal sectioning. Antibodies for the fluorescent marker (anti-GFP ab290, anti-24 mCherry ab167453), neuronal nuclei markers (anti-NeuN, ab104224) and astroglia (anti-GFAP, 25 ab4674, all Abcam) were used prior to upright fluorescence microscopy (Eclipse NiE, Nikon) and 26 confocal imaging (LSM 800 Airyscan, Zeiss). 27 28 Implantable LED array 29 Supplemental Figure 4a shows the implantable optrode fork. Optrode fabrication began with a 200 1 µm-thick silicon wafer which underwent a standard solvent clean procedure in n-methyl pyrrolidine 2 (NMP) followed by isopropanol (IPA) and then rinsed in deionised water. A 1 µm-thick insulation SiO2 3 layer was deposited by chemical vapour deposition on the silicon surface. Ti/Au/Ti metallisation was 4 deposited by evaporation on top of the insulation, and patterned by UV photolithography to outline 5 the metal tracks and recording electrodes. Metal patterning was carried out by a selective wet etch 6 based on NH4OH:H2O2 (1:2) for titanium, and a K3Fe(CN)6, Na2S2O3 and CS(NH2)2 in deionised water 7 mixture for gold. The Ti/Au/Ti patterns were then capped with a second SiO2 insulation layer. Contact 8 windows through the top insulation needed to access the bonding pads were opened by reactive ion 9 etch (RIE), using a Ti/Ni metal mask which was deposited by e-beam evaporation and patterned by UV 10 photolithography and wet etching. Optrode singulation was achieved by deep reactive ion etching 11 (DRIE). 12 Micro-LEDs (DA2432, Cree) were bonded on the gold LED pads on the optrode shaft using off-the-shelf 13 Au/Sn preforms (Inseto, 100 µm x 100 µm x 10 µm, comparable with the LED footprint). Using a pick-14 and-place Fineplacer Lamda tool, a preform was placed on each of the two LED pads, the LED was 15 placed directly on top of the AuSn preforms, and the LED/preforms stack was heated to 320°C to melt 16 the preform and bond the LED. 17 The silicone rubber used for encapsulation was NuSIL MED6015, an optically clear, solvent free, low 18 viscosity silicon elastomer safe for human implantation. The two-part rubber was mixed in a vortex 19 mixer (10 part A:1 part B). The optrode surface was prepared by a solvent clean in acetone and IPA in 20 an ultrasonic bath, then rinsed in deionised water. The optrodes were dipped into the silicone mix and 21 then mounted on the vacuum holder of a spin coater. A uniform thickness of the silicone around the 22 optrode was achieved by spinning at 2000 rpm for 5 seconds and 4000 rpm 10 seconds. The silicone 23 was cured at 150°C for 15min. 24 The LED fork was inserted into the brain using a stereotaxic manipulator. We used a single LED at the 25 tip of one shaft to deliver closed-loop stimulation. The LED was driven by a voltage-controlled constant 26 current stimulator (DS4, Digitimer) up to a maximum current of 5mA. Supplemental Figure 4b  27 compares the total light power emitted by the LED and the fibre-coupled Thorlab system over the full 28 experimental range, measured using an integrating sphere (OPM150, Artifex Engineering). In both 29 cases, the light source was placed near the centre of the integrating sphere, which captures light 30 emitted from all angles into an integrated calibrated photodiode. 31 32

Closed-loop stimulation 33
The closed-loop algorithm was implemented in custom-designed hardware based around a 34 dsPIC30F6012A microcontroller running at 30MHz. The microcontroller sampled the LFP from one 35 electrode at 500 Hz, applied a causal phase-shifting finite impulse response (FIR) filter, thresholded 36 (just above the background noise level) and half-wave rectified the output to generate a voltage signal 37 which controlled the LED current driver. The FIR filter convolved the input signal with a 512 sample 38 kernel given by: 39 ( ) = 2" 3456 % . cos ;2 "#$% + @ (Equ. 1) 40 where <0 (for a causal filter working on past signals only), determines the filter band-width and 41 was set to 1.25 for all experiments, determines the extent to which the output is phase-advanced 42 from the input, and "#$% determines the central frequency of the pass-band. The amplitude and phase 43 response of this filter are shown in Figure 1a. In general, for our seizure experiments we chose "#$% to 1 be the dominant frequency of the seizure bursts (in the range 10-20 Hz), and for non-seizure 2 recordings, we chose frequencies between 2-40 Hz. The remaining free parameter, , is an overall 3 scaling factor that determines the light intensity for a given filter output. We adjusted this in advance 4 such that endogenous activity would drive the LED over its full current range. Note however that once 5 engaged, CLOSe + feedback often enhanced the oscillations such that the light pulses saturated at the 6 maximum level. 7 CLOSe was delivered for epochs of fixed duration, each interspersed with an equal-duration epoch of 8 no stimulation. We used phase-shifts, , from 0, 45°,…, 315° delivered in pseudorandomised order. 9 We chose epoch durations between 5-120s depending on the experiment, ensuring our datasets 10 contained at least two repeats of each phase-shift. For quiescent/endogenous experiments we tended 11 to use short-duration epochs, while for seizure experiments we selected in advance a duration such 12 that at least one seizure event would likely occur within each epoch. Our quiescent brain slice 13 recordings lasted between 11-91 min (mean 51 min), while our seizure sessions lasted between 28-14 211 min (mean 93 min). Our endogenous recordings in NHPs lasted between 10-14 min (mean 11 min) 15 while our seizure datasets lasted between 63-71 min (mean 67 min). 16

Data analysis 18
Data were analysed using custom scripts written in Matlab (Mathworks, USA) and used the circ_stats 19 toolbox for circular statistics (Berens, 2009). All off-line filtering used 4-pole Butterworth filters passed 20 in forward and reverse directions. LFP was down-sampled to 500 Hz after anti-alias filtering. Power 21 spectra were compiled using Welch's method using overlapping windows of length 512 sample points. 22 CLOSe phase-shifts were adjusted by the relative phase between the LFP and high-gamma (>100 Hz) 23 envelope which was determined by applying a Hilbert transform to the cross-correlation of these 24 signals (Supp. Fig. 1). 25 For data on quiescent mouse brain slices and endogenous activity in NHPs, we compiled power spectra 26 of the LFP driving CLOSe for the entirety of stimulation/control epochs, and averaged power 27 modulation around the closed-loop filter frequency (0.8-1.2 "#$% ). Additionally, for the NHP linear 28 microelectrode datasets, we calculated the depth-profile of cycle-triggered averages of the other LFPs, 29 aligned to troughs in the band-pass filtered (0.8-1.2 "#$% ) channel that was driving CLOSe. 30 Seizure events in mouse brain slices occurred sporadically and were readily distinguished from quiet 31 inter-ictal periods so we restricted our analysis to time-windows encompassing these events. The start 32 times of these windows were identified using an appropriate threshold on the rectified LFP (typically 33 0.05-0.15 mV) and we calculated power spectra for a fixed duration that encompassed all the seizure 34 bursts (typically around 20s). Within these windows, we additionally defined individual bursts as 35 periods during which the rectified LFP was not less than threshold for more than 0.2 s, and excluded 36 events with a duration less than 0.2 s. Typically the first burst within each seizure event was longer 37 than subsequent bursts. Therefore, when computing the ratio of burst lengths under CLOSe to the no 38 stimulation condition, we calculated this separately for first and subsequent bursts, before averaging 39 over all bursts. 40 The seizure events in NHPs occurred more frequently and regularly, and it was not always possible to 41 demarcate their onset from background activity. Therefore, we computed power spectra over the 42 entirety of stimulation/control epochs for these data. To obtain a measure of seizure magnitude, we 43 computed the amplitude envelope of the LFP (band-pass filtered 10-30 Hz, rectified, and smoothed 44 with a 1 s Hanning window) and corrected for baseline activity by subtracting the mode average of 1 this envelope. We then computed the autocorrelation function of this signal, which provides a 2 visualisation of the temporal profile of seizure bursts. We quantified seizure magnitude from the area 3 under this autocorrelation function (from -20 to +20 s). Note, however, that while the autocorrelation 4 function reveals the temporal profile of seizure bursts (i.e. the width of the peak reflects the duration 5 of seizures), the area under this peak provides a composite measure that is also influenced by the 6 number and duration of seizure bursts as well as their individual amplitudes. 7 For the seizure datasets, we additionally calculated two metrics designed to quantify the stability of 8 seizure cycles revealed by delay-embedded, band-pass filtered (in vitro: 5-30 Hz, in vivo: 10-30 Hz) LFP 9 trajectories. We chose an embedding dimension of three, and obtained the optimal embedding delay 10 from the average mutual information algorithm implemented by the Matlab function  11 phaseSpaceReconstruction with default settings. Our first metric was geometric in nature and 12 designed to assess variations in the instantaneous scalar radius of the three-dimensional trajectory 13 (from the origin). We calculated the mean, ( ), and standard deviation, ( ), of this radius using a 14 sliding window of 100 ms width through time. We then defined a trajectory Coefficient of Variation 15 (CoV) as the proportional relationship between these: 16 CoV was calculated by least-squares fit of Equ. 2 over time. We chose this regression approach (rather 18 than calculating ( )/ ( ) and averaging over time) to avoid our result being skewed by quiescent 19 epochs with low values of ( ). Our second metric was approximate entropy (AppEn) which is an 20 information-theoretic measure of unpredictability in time series. This was calculated using the Matlab 21 function approximateEntropy with the default similarity criterion of 0.2 times the standard deviation. 22 The modulation of all-positive metrics (LFP power, seizure burst duration/magnitude, trajectory 23 stability) relative to no-stimulation was analysed using log-transformed ratios (i.e. a doubling/halving 24 of seizure magnitude was treated as an equal and opposite modulation). We calculated the max/min 25 modulation both for the raw datasets (i.e. selecting the phase-shift that yielded the largest average 26 effect), and for a sinusoidal fit through all phase-shifts in the dataset. The former may overestimate 27 the modulation due to variability inherent in each measurement and the latter may underestimate 28 modulation if the data is not well fit by a sinusoid; therefore we show both values throughout. 29 Additionally, we averaged our measures across datasets (aligned by adjusted phase-shift) and 30 assessed the statistical significance of phase-dependent modulation using circular-linear correlation 31 (CircStats Matlab toolbox).  The  2 parameters , , and determine the strength of interaction between these populations, decaying 3 with time constants T and # . This system additionally is subject to tonic drive, and , and Gaussian 4 noise inputs, T ( ) and # ( ) reflecting synaptic noise and inputs from the surrounding tissue. The LFP 5 was modelled as a combination of the activity of both neuronal populations, which was fed in to the 6 same closed-loop feedback algorithm as used in the experiments. Optical stimulation acted as an 7 additional input, ( ), to the excitatory neuronal population. Finally, the sigmoid function is: 8 We used the Euler-Maruyama method to simulate this system with a 1 ms time-step. Parameters used 10 for the simulations are shown in Supp.