Closed-loop optogenetic control of the dynamics of neural activity in non-human primates

Electrical neurostimulation is effective in the treatment of neurological disorders, but associated recording artefacts generally limit its applications to open-loop stimuli. Real-time and continuous closed-loop control of brain activity can however be achieved by pairing concurrent electrical recordings and optogenetics. Here we show that closed-loop optogenetic stimulation with excitatory opsins enables the precise manipulation of neural dynamics in brain slices from transgenic mice and in anesthetized non-human primates. The approach generates oscillations in quiescent tissue, enhances or suppresses endogenous patterns in active tissue, and modulates seizure-like bursts elicited by the convulsant 4-aminopyridine. A nonlinear model of the phase-dependent effects of optical stimulation reproduced the modulation of cycles of local-field potentials associated with seizure oscillations, as evidenced by the systematic changes in the variability and entropy of the phase-space trajectories of seizures, which correlated with changes in their duration and intensity. We also show that closed-loop optogenetic neurostimulation could be delivered using intracortical optrodes incorporating light-emitting diodes. Closed-loop optogenetic approaches may have translational therapeutic applications.

Article https://doi.org/10.1038/s41551-022-00945-8 and may therefore depend on the precise positioning of electrodes across different sessions. Therefore, we also examined the envelope of high-gamma (>100 Hz, right column of Fig. 1b) LFP activity as a surrogate for neural firing. High gamma activity was consistently correlated with optical stimulation (as expected for excitatory stimulation driving neural activity), but the relative phase between high-gamma and LFP oscillations varied between different sessions (Extended Data Fig. 1b). We used the cross-correlation between high gamma activity and LFP to calculate their relative phase and added this offline to the phase shift applied online by the filter (Extended Data Fig. 1c). We then replotted our data against the adjusted phase shift that represented the overall phase advance of optical stimulation relative to putative neural activity (Extended Data Fig. 1d). Following this adjustment, the phase shift associated with maximal positive-feedback LFP oscillations was consistently around 0-90° relative to the high-gamma envelope (right diagram of Fig. 1d, circular mean = 38°, Rayleigh test for circular non-uniformity P = 0.002; Extended Data Fig. 1e), whereas phase shifts around 180-270° were associated with minimal oscillation. We refer to these conditions as CLOSe + and CLOSe -, respectively. CLOSe + drove oscillations around the centre frequency of the filter as well as higher harmonics, and these frequencies increased systematically with increasing phase shift, as shown by the diagonal stripes in Fig. 1e (note that phase shift is unwrapped and plotted over two cycles). Conceptually, this behaviour can be understood by equating a phase advance in the feedback signal with a reduction in the feedback loop delay. As this delay is reduced, the frequencies associated with positive-feedback instabilities increase. By altering the central filter frequency, we were able to tune these resonant frequencies and drive oscillations up to 40 Hz, although the LFP power modulation was significantly reduced at higher frequencies (Fig. 1f, log-linear correlation P = 0.0002).

CLOSe modulates spontaneous activity in vivo
Next, we examined the effect of CLOSe on endogenous in vivo brain activity in two NHPs. Excitatory opsins were expressed under the neuron-specific human synapsin promoter (hSyn) using viral vectors (either AAV8-hSyn-Chronos-GFP or Lenti-hSyn-eYFP-2A-ChR2(H134R); Supplementary Table 1) injected into the primary motor cortex 7-19 weeks before recording sessions under terminal anaesthesia. Post-mortem histology confirmed widespread expression of associated fluorescent tags co-localized with neuronal markers in both animals ( Fig. 2a,b). LFPs and single units were recorded with multi-contact electrodes, whereas open-loop stimulation (200 or 500 ms pulses at 1 Hz) and CLOSe (driven by different phase shifts applied to one LFP from the array) were delivered through an optical fibre inserted into the cortex or an implanted optrode incorporating LED light sources ( Fig. 3a and Extended Data Fig. 2). The left column of Fig. 3b and top part of Fig. 3d show examples of open-loop stimulation using ChR2. Large LFP deflections were observed in response to light pulses, associated with bursts of neural firing (Fig. 2c). Note that unlike the promotor used in the EMX-ChR2 mice, the promoter used in the NHPs was not specific to excitatory neurons and, consistent with this, we very occasionally observed suppression of firing in some neurons, with histology confirming a small proportion of opsin expression in glutamic acid decarboxylase (GAD67)-positive interneurons in both animals (Fig. 2d,e). Surprisingly, there was relatively high expression in glial fibrillary acidic protein (GFAP)-positive astrocytes with Lenti-hSyn-eYFP-2A-ChR2(H134R), although this was far less prevalent with AAV8-hSyn-Chronos-GFP.
The polarity of LFP responses to open-loop stimulation varied with depth, as expected for a physiological response, rather than a photoelectric artefact (left column of Fig. 3b). Such responses were not observed when using a frequency of light that was outside the opsin absorption spectrum (right column of Fig. 3b) or when using blue light in an animal without opsin expression (Fig. 3c). As in the brain slices, CLOSe + drove strong oscillatory responses in LFPs and neural the real-time state of the system 2 . Thus, neuromodulation therapies may be more effective if controlled by ongoing electrophysiological measurements 3,4 , for example, to enhance beneficial oscillations or to destabilize pathological brain states such as epileptic seizures. Unfortunately, many potential applications of closed-loop neurostimulation are hampered by large artefacts associated with electrical stimulation, particularly when monitoring and modulating the same local population of neurons. This often limits control policies to simple decisions to turn on, or off, otherwise continual trains of stimuli 5,6 .
As the light stimuli used for optogenetics can be delivered without preventing concurrent electrical recording, these stimuli can be continuously modulated in real time by brain signals to allow true closed-loop interaction with local networks. Despite considerable theoretical motivation 7 , experimental demonstrations of closed-loop optogenetic stimulation have thus far been limited to in vitro preparations 8 and in vivo experiments on normal brain rhythms in rodents [9][10][11][12] . Here we aim to advance this technique towards therapeutic applications in humans by demonstrating the feasibility of closed-loop manipulation of network dynamics in non-human primates (NHPs) and examining its effect on pathological seizure-like activity. In addition, we compare optical stimulation delivered via an external light source with an implantable optrode incorporating encapsulated light-emitting diodes (LEDs). Although optogenetics allows specific cell types to be targeted with a range of different opsins, we focus here on closed-loop optogenetic stimulation with excitatory opsins (CLOSe) using efficient ion-channel opsins without the need to restrict expression to specific interneuron subtypes. We hypothesized that by altering the timing of stimulation relative to ongoing activity, we could exert differential effects on local networks, thus adding a temporal dimension to the control of neural dynamics that can be achieved with optogenetics.

CLOSe drives oscillations in quiescent brain slices
We first investigated CLOSe in quiescent brain slices taken from transgenic mice that expressed channelrhodopsin selectively in excitatory pyramidal cells (Emx1-ChR2). The local-field potential (LFP), recorded with an extracellular electrode, was passed through a finite impulse response (FIR) filter, which bandpass filtered and phase advanced the signal (Fig. 1a). The output of the filter was half-wave rectified (above a threshold set to reject most background noise) and sent in real time to control the intensity of optical stimulation delivered through an optical fibre. Within each experimental session, we delivered CLOSe epochs with the same filter frequency but different phase shifts (0, 45°, …, 315°) in pseudorandomized order, interspersed by control epochs with no stimulation.
We set the threshold of the closed-loop algorithm such that occasional small fluctuations in the LFP crossed the threshold and triggered optical stimulation. The resultant behaviour depended critically on the phase shift imposed between the LFP and stimulation. For some CLOSe phase shifts, no persistent activity was elicited, whereas other phase shifts drove strong and sustained oscillations (Fig. 1b,c). The frequency of the oscillations varied systematically with the closed-loop filter frequency (Extended Data Fig. 1a), suggesting that the oscillations reflected the dynamics of the closed-loop system (that is, the optical stimulation caused neural activity that then caused further stimulation creating a positive feedback loop), rather than intrinsic oscillatory properties of the tissue.
Qualitatively similar effects were obtained in 21 different sessions with brain slices from 11 mice using central filter frequencies between 2 and 40 Hz. However, we observed considerable variation in the phase shift associated with maximal LFP oscillations (Extended Data Fig. 1a and left diagram in Fig. 1d, circular mean = −27°, Raleigh test for circular non-uniformity P = 0.82). We speculated that this was due to variation in the relationship between LFPs and the underlying neural activity, which is known to change through the cortex 13 Article https://doi.org/10.1038/s41551-022-00945-8 firing (middle part of Fig. 3d), revealed by cycle-triggered LFP averages (Fig. 3e). Like the open-loop responses, the polarity of the driven oscillations also varied with depth. In each case, this depth profile resembled that of endogenous activity observed during control epochs with no stimulation, suggesting that CLOSe + drove naturalistic patterns of network activity (Fig. 3e,f).
We were interested in examining whether the activity of individual cells became more phase-locked to the LFP under CLOSe + conditions compared with no stimulation. Spike-triggered averaging (STA) suggested strong oscillatory coupling between spiking activity and the LFP under CLOSe + (Fig. 4a). However, STA analysis can be misleading, as the LFP amplitude increased markedly under CLOSe + , and this alone could explain the larger STA. Therefore, we assessed spike-LFP coupling using the phase-locking value (PLV) to quantify how consistently a neuron fired in the LFP cycle irrespective of amplitude. The PLV was calculated for each neuron with LFPs filtered into 1 Hz passbands (Fig. 4b). We observed a phase-dependent increase in the PLV that corresponded to frequencies of driven oscillations under CLOSe + (Fig. 4c), and these increases were statistically significant for approximately one-third of neurons recorded in this session (Fig. 4d).
Despite using an excitatory opsin, certain phase shifts (designated CLOSe -) reduced the amplitude of cycle-triggered LFP oscillations relative to no-stimulation epochs (Fig. 5a). To reveal this more clearly, we normalized the raw LFP power spectra during stimulation epochs for each phase shift (Fig. 5b) by the corresponding power spectrum for no-stimulation epochs. Figure 5c shows normalized oscillatory power at each frequency for each phase condition. Regions of red reflect CLOSe + driving positive-feedback oscillations, whereas interspersed regions of blue show CLOSephase shifts that suppressed LFP power below spontaneous levels. No such modulation was observed in control experiments using yellow light (Fig. 5d), demonstrating again that our results were mediated by optogenetic stimulation, rather than non-specific effects such as photoelectric artefacts or tissue heating.
We also tested the CLOSe delivered via the implanted LED optrode (Extended Data Fig. 2a). Significant modulation of LFP power could be obtained using a single LED (Fig. 5e), albeit with a weaker magnitude, consistent with the LED producing about half the light power of our commercial fibre-coupled system (Extended Data Fig. 2b). Figure 5f shows the modulation of power around the closed-loop filter band (0.8-1.2× the central frequency), with a statistically significant effect of the eight phase conditions for illumination with blue light via the optical fibre (circular-linear correlation, n = 57 stimulation epochs, R = 0.90, P = 1 × 10 −10 ) and LED (n = 60, R = 0.86, P = 2 × 10 −10 ) but not for control yellow light (n = 58, R = 0.13, P = 0.6). We observed statistically significant (circular-linear correlation, P < 0.05) phase-dependent power modulation in experiments made in three hemispheres from two animals (Fig. 5g) using both opsins (Supplementary Table 1). Once again, we could tune the frequencies of enhancement and suppression by altering the filter frequencies. We quantified modulation from both the maximum/minimum modulation of LFP power for any single phase shift (raw data, top part of Fig. 5h) and from a sinusoidal fit through all phase shifts (sine fit, bottom part of Fig. 5h). As with the brain slice experiments, the average modulation (0.8-1.2× the filter frequency) became progressively weaker for higher closed-loop filter frequencies, but statistically significant phase dependence at 40 Hz was nevertheless observed in two of the three datasets and, for dataset Z-L, the maximal modulation was comparable across all tested frequencies.

CLOSe modulates induced epileptiform activity in vitro
Having demonstrated phase-shift-dependent enhancement and suppression of endogenous oscillations, we next examined whether CLOSe could influence pharmacologically induced pathological states resembling seizures. In our in vitro brain slice model, the prolonged bath application of 4-aminopyridine (4-AP) generated sporadic but repeated seizure-like events over several hours consisting of multiple brief bursts of oscillatory discharge at around 15-20 Hz (Fig. 6a). Once this activity pattern had stabilized, we examined the effect of closed-loop The LFP, recorded from an Emx1-ChR2 mouse brain slice, was filtered, advanced by a variable phase ϕ and used to control optical stimulation in real time. Bottom: amplitude response of the filter. The inset shows the phase response across the passband. b, Example LFP, optical stimulation and high-gamma envelope under no stimulation (black) and CLOSe with different phase shifts (relative to the LFP, 2 Hz filter frequency). c, LFP power spectra for different phase shifts for the entire session. d, Left: phase shifts (relative to the LFP) associated with maximal oscillation in 21 sessions from 11 mice. Right: adjusted phase shifts (relative to high gamma activity; Extended Data Fig. 1). P values from the Rayleigh test for circular non-uniformity are shown. e, LFP power at different frequencies for different adjusted phase shifts (2 Hz filter, same session as b). The phase shift is unwrapped and plotted over two cycles. f, Phase-dependent modulation of LFP power for different filter frequencies. Colour indicates adjusted phase shift associated with maximal oscillation. The dashed line shows a log-linear fit to data (n = 21, coefficient of determination R 2 = 0.54, P = 0.0002).
Article https://doi.org/10.1038/s41551-022-00945-8 stimulation with a filter set to the frequency of the oscillatory bursts. CLOSe could lengthen or shorten the duration of individual bursts depending on the phase shift (left diagram of Fig. 6b). The right diagram of Fig. 6b shows a logarithmic plot of the modulation of burst durations under different CLOSe phase shifts relative to no-stimulation epochs. Across this whole session, the burst duration was doubled under CLOSe + (0° phase shift, mean ± s.e.m. over bursts, log 2 ratio burst duration = 1.00 ± 0.18) and decreased by about a quarter under CLOSe -(225° phase shift, log 2 ratio burst duration = −0.44 ± 0.15). Circular-linear correlations across the eight phase-shift conditions confirmed that modulation of burst duration depended significantly on closed-loop phase shifts (n = 221 seizure bursts, R = 0.62, P = 1 × 10 −16 ). Modulation was also evident as phase-dependent enhancement and suppression of LFP power spectra during seizure-like events (Fig. 6c). Averaged across our dataset of ten sessions with brain slices from ten different mice, the relative duration of seizure bursts was modulated at a maximum/ minimum log 2 ratio of 0.49 ± 0.13 to −0.48 ± 0.11 (mean ± s.e.m. over animals, equivalent to a 1.4× increase and a 0.7× decrease, respectively; Fig. 6d), and it depended significantly on closed-loop phase shifts in 8/10 individual sessions (circular-linear correlation, P < 0.05). When   all sessions were combined (after adjusting to high gamma activity as before), the relative burst duration also depended significantly on CLOSe phase shifts (circular-linear correlation, n = 10 sessions × 8 phase conditions, R = 0.29, P = 0.03; Fig. 6d), as did power modulations at seizure frequencies (n = 80, R = 0.39, P = 0.002; Fig. 6e). Note, however, that our (high-gamma) phase-shift adjustment did not perfectly align the different sessions, so the maximum/minimum modulation in the session-averaged plots was lower than that seen in individual sessions, and no single phase shift produced statistically significant suppression in the combined dataset.
Our in vitro experiments used transgenic mice to restrict opsin expression to excitatory neurons, whereas our NHP experiments used viral delivery of opsins, which were also expressed in a small proportion of inhibitory interneurons (Fig. 2). To aid in the comparison of these datasets, we also performed experiments in slices from three mice injected intracortically with one of the viruses used in the primates (AAV8-hSyn-Chronos-GFP) to replicate our key in vitro findings using this opsin-delivery method. CLOSe delivered to quiescent slices was able to drive strong oscillations (Extended Data Fig. 3a) with a phase dependence (Extended Data Fig. 3b) and closed-loop filter frequency dependence (Extended Data Fig. 3c) that resembled those seen in the Emx1-ChR2 slices (Fig. 1). CLOSe was also able to modulate 4-AP-elicited seizure-like events, albeit less strongly than in our experiments with germline transgenic expression of opsins (with more widespread expression). Averaged across the three animals, the relative duration of seizure bursts was modulated at a maximum/minimum log 2 ratio of 0.33 ± 0.06 to −0.33 ± 0.02 (equivalent to a 1.25× increase and a 0.8× decrease, respectively; Extended Data

CLOSe modulates epileptiform activity in vivo
In the NHPs in vivo, injection of 4-AP into the motor cortex reliably produced prolonged seizure events lasting around 20 s occurring at regular intervals (typically every minute for about an hour). Seizure events were characterized by an initial oscillation in the range of 15-25 Hz, followed by post-ictal discharges. Figure 7a shows two events from the right hemisphere of monkey Z (Chronos opsin): the first during a control period with no stimulation and the second during delivery of CLOSewith a phase shift of 225° with a marked suppression of oscillatory discharge. Unlike the in vitro data, background activity and seizure variability precluded the precise identification of the onset and offset of individual events. Therefore, to visualize the impact of CLOSe across the entire session, we computed the autocorrelation of the LFP However, this could result from the increased amplitude of the LFP under CLOSe + . Inset: spike waveform, scale bars 50 μV, 1 ms. b, The PLV was used to measure phase coupling independent of LFP amplitude, calculated from the distribution of instantaneous LFP phases at the time of spike firing (shown in blue for 0° CLOSe + and grey for no stimulation). The PLV is the resultant length of this distribution with a value between 0 and 1. The PLV was calculated for different frequencies within the LFP by filtering with different passbands of 1 Hz width from 4 to 20 Hz. For this example cell, there is an increase in the PLV within 9.5-10.5 Hz only for 0° CLOSe relative to other phase shifts (coloured) and no stimulation (black). c, Average change in the PLV relative to no stimulation across cells for different LFP frequencies and CLOSe phase shifts. d, Significant changes in phase locking were assessed by comparing the CLOSe PLV against the phasedistribution of an equal number of surrogate spikes drawn from no-stimulation epochs. Plots show the proportion of cells exhibiting a significant (P < 0.05, twotailed test, no correction for multiple comparisons) increase/decrease in the PLV relative to no stimulation for different LFP frequencies and CLOSe phase shifts. Dataset Z-L: Lenti-hSyn-eYFP-2A-ChR2(H134R), 10 Hz filter frequency, 17 neurons. Note that the phase shifts/frequencies of increased phase locking correspond to oscillations driven by CLOSe + (Fig. 5c).  amplitude envelope within the seizure band (10-30 Hz) over the whole duration of CLOSe and control epochs. The peaks in Fig. 7b with a width of approximately 20 s reveal the broad temporal structure of seizure bursts, and the variation in their height and width indicates modulation by closed-loop stimulation. We quantified seizure magnitude by calculating the area under this curve (±20 s), although this single measure is influenced by the intensity, duration and interval between individual events. In addition, we calculated power spectra, across all epochs for each stimulation condition (Fig. 7c), which, when normalized by the no-stimulation spectra, again revealed a characteristic pattern of phase-dependent modulation (Fig. 7d). Finally, we calculated the proportion of total time for which the seizure amplitude (defined by the smoothed, rectified LFP) exceeded a particular threshold. Rather than choosing the threshold arbitrarily, we calculated this for all possible threshold values up to the maximum amplitude observed in the no-stimulation condition. For all threshold values, the proportion of time spent in the seizure state increased under CLOSe + and reduced under CLOSe - (Fig. 7e). Similar results were obtained in two animals (Fig. 7f), as well as in one session in which stimulation was delivered using the implanted LED (Fig. 7g). Across our dataset of four sessions, seizure magnitude was modulated by CLOSe at a log 2 ratio of 1.11 ± 0.25 to −0.66 ± 0.13 (a 2.1× increase and a 0.6× decrease, respectively). When these data were combined, we observed a statistically significant effect of phase shifts on seizure magnitude (n = 4 sessions × 8 phase conditions, R = 0.70, P = 0.0004; Fig. 7h) as well as corresponding modulation of LFP power at seizure frequencies (n = 32, R = 0.67, P = 0.0007; Fig. 7i). Figure 7j summarizes the percentage change in time spent in seizure states under the most effective CLOSe + and CLOSephase shifts (45° and 270°, respectively) relative to no stimulation using different threshold values to define the seizure state. This was substantially increased under CLOSe + , especially for seizures defined by the highest threshold values. By contrast, under CLOSe -, the time spent in a seizure defined at 50% of maximum intensity was reduced by a third and was reduced to half for seizures greater than 68% of maximum. Seizure states with the highest amplitude (94% and greater) were completely eliminated. Extended Data Fig. 4 shows that the modulation of time spent in high-amplitude seizure states was related to a phase-dependent effect on both the duration (Extended Data Fig. 4d) and frequency (Extended Data Fig.  4f) of these states.

CLOSe stabilizes or destabilizes abnormal network dynamics
Epileptic activity is usually thought to reflect an excess of excitatory activity in brain networks. Our observation that excitatory stimulation can reduce the intensity of seizures is therefore counter-intuitive. To examine how CLOSewas capable of attenuating seizure-like events, we simulated a simple Wilson-Cowan neural mass model that has previously been applied to epileptic activity 14,15 . The model comprised two interconnected neural populations (excitatory and inhibitory), whose activity was represented in a two-dimensional phase space. The instantaneous state evolved through time according to nonlinear dynamics, which divided the phase space into two regimes (Fig. 8a). States initiated with low excitatory activity evolved towards a stable fixed point representing a quiescent network, whereas initial states with higher excitatory activity were attracted towards a limit cycle representing epileptiform oscillations. Connection weights were chosen to produce an oscillation frequency similar to the experimental data, and Gaussian noise input was added to both populations, allowing probabilistic transitions between quiescent and seizure regions. CLOSe was modelled as an additional excitatory input to the excitatory population, dependent on a phase-shifted LFP signal reflecting a high-pass filtered combination of the activity of both populations. Model simulations starting from the limit cycle under different closed-loop feedback conditions qualitatively captured many features of our experimental data (Fig. 8b, compare with Fig. 6b,c), including phase-shift-dependent lengthening or shortening of seizure durations, and associated modulation of spectral power. To understand this better, we examined the behaviour of the seizure limit cycle under different CLOSe conditions ( Fig. 8c and Supplementary Video 1). In the absence of input noise, excitatory stimulation alone never halted the seizure, but as the phase shift advanced from CLOSe + to CLOSe -, the limit cycle underwent period doubling and became increasingly complex, fluctuating between small and large cycles in the phase space. As the larger cycles came close to the boundary of the quiescent regime, there was a higher probability that the added noise input could push the network across into the attractor basin of the stable fixed point (Fig. 8d). In other words, the altered duration of seizure bursts relative to the no-stimulation condition in our model could be explained by the increased stability (in the presence of input noise) of the limit cycle under CLOSe + and its increased sensitivity to noise perturbations under CLOSe -.
To seek evidence for this phenomenon in our experimental data, we used delay-embedding to reconstruct the dynamics of the simulated and actual LFP data. Figure 8e,f and Extended Data Fig. 5 show 2D and 3D projections of delay-embedded trajectories for the in silico simulation and for an example in vitro session. There are notable qualitative similarities between the model and experimental data; some phases of closed-loop stimulation are associated with simple, planar cycles, whereas other phases generate complex and twisted trajectories. We quantified trajectories using two metrics: (1) the coefficient of variation (CoV) of the radius and (2) approximate entropy, which is an information-theoretic measure of complexity that has previously been applied to seizure data 16 . For both simulated and experimental data, these metrics showed a phase-shift-dependent modulation, with lower/ higher trajectory variability and entropy (relative to no stimulation) being associated with CLOSe + /CLOSe -, respectively (Fig. 8g). For both the in vitro (Fig. 8h) and in vivo datasets (Fig. 8i), CoV and approximate entropy trajectories were inversely correlated with seizure duration and seizure severity (P < 0.05 in all cases), providing evidence that the enhancement and suppression of epileptiform activity are associated with closed-loop feedback that, respectively, stabilizes and destabilizes the seizure cycle.

Open-loop versus closed-loop excitatory stimulation
Our results demonstrate that the effect of excitatory stimulation on neural circuits depends critically on when it is delivered, relative to the instantaneous phase of ongoing oscillations, and that this can be controlled in a closed-loop manner as optogenetics does not prevent concurrent LFP recording. Nevertheless, we were interested in whether suppression could also be obtained by open-loop delivery of an appropriate stimulus train. We therefore used our computational model to determine closed-loop stimulation patterns that attenuated seizure bursts and then replayed these patterns during subsequent simulation runs. However, the open-loop delivery of the same stimulation pattern failed to attenuate seizures, even when that pattern was initiated at the same phase of the seizure cycle (Extended Data Fig. 6a), because of subtle differences between each run introduced by noise in the model. Such sensitivity to noise is characteristic of the complex dynamics exhibited by our model, meaning that the appropriate stimulation pattern to suppress seizures cannot be determined in advance and can only be delivered via closed-loop stimulation.
We also explored the effect of open-loop stimulation with a constant frequency. For all frequencies tested, the duration of seizure bursts in our model increased monotonically with intensity under constant frequency stimulation (Extended Data Fig. 6b). Interestingly, stimulation at the frequency of seizure cycles was most effective at prolonging seizure duration, probably because this pattern entrained network oscillations and thus stabilized seizure dynamics. We tested this prediction in vitro using the bath application of 4-AP to brain slices taken from three Emx1-ChR2 mice. We delivered open-loop stimulation triggered by the onset of seizure-like events (Extended Data Fig. 6c), choosing stimulation parameters to match the frequency and intensity of our CLOSeintervention. As in our model, open-loop stimulation reliably entrained seizure cycles, evident from the consistent alignment of stimulation pulses to LFP cycles within and across seizure bursts. Moreover, this open-loop stimulation pattern only prolonged burst duration and increased LFP power relative to no stimulation, comparable to the effects of CLOSe + .

Discussion
In recent years, optogenetics has emerged as a powerful tool for manipulating neural populations with unprecedented spatial resolution and cell-type specificity. Our results highlight a further advantage of optical stimulation that is less widely appreciated, namely the ability to control feedback using concurrent electrical recordings without interference from artefacts, allowing continuous, dynamic interaction with the neural tissue. We found that the effects of closed-loop, excitatory optogenetic stimulation depended critically on the timing relative to ongoing activity, with CLOSe + able to drive strong oscillations at a range of frequencies in quiescent tissue, and CLOSesuppressing endogenous activity and pathological seizure-like oscillations. Although optical stimulation is not necessarily free from potential sources of artefacts (for example, photoelectric effects), several lines of evidence point conclusively to an opsin-mediated effect in our data. First, we verified opsin expression and functionality from spike recordings and  post-mortem histology. Second, we saw no modulation when using light outside the absorption spectrum of our opsins or in a monkey without opsin expression. Third, the evoked responses exhibited polarity reversals through the tissue that resembled those of spontaneous activity. Fourth, the modulatory effects of CLOSe depended consistently on the phase shift relative to high gamma activity, rather than the low-frequency LFP. Finally, optogenetic responses were attenuated with increasing frequency, as expected for physiological opsin activation 17 .
The ability to manipulate oscillatory activity systematically with CLOSe has many scientific applications for exploring the function of neural oscillations. Although other interventions (for example, pharmacological) can be used to enhance or block oscillations, an advantage of CLOSe is that enhancement and suppression at different frequencies can be interspersed within the same experimental design by tuning parameters of the feedback loop (for example, the filter passband and phase shift). Moreover, potential uses extend beyond driving the predefined activity up, or down, as the addition of closed-loop feedback to a recurrent network can qualitatively alter the dynamics expressed by that system. For example, we showed computational and experimental evidence that CLOSe altered the sensitivity of state-space limit cycles to noise perturbations, thus precipitating or delaying phase transitions to non-oscillatory states. We used a relatively simple feedback algorithm, but the combination of nonlinear control theory 18,19 with closed-loop optogenetic paradigms offers possibilities for testing hypotheses about the role of phase transitions and metastability in brain function and behaviour 20,21 . Closed-loop stimulation may also influence network dynamics on longer timescales, for example, by influencing associative plasticity mechanisms 22,23 .
In the future, these approaches may extend the scope of current neurostimulation treatments. For epilepsy, responsive electrical stimulators can intervene following the detection of seizure onset 6 . At present, these interventions comprise open-loop trains of high-frequency stimuli, but theoretical 24,25 and experimental 26,27 work suggests that the effect of stimulation may depend on the timing of stimulation relative to activity cycles, so closed-loop stimulation, which takes into account the phase of the seizure cycle, may be more effective than open-loop stimulation 28 . Similarly, adaptive DBS for Parkinson's disease is being trialled in humans, but at present this is limited to adjusting the amplitude of open-loop stimulation 29 . However, there is evidence that DBS arriving at a specific oscillatory phase can suppress the amplitude of pathophysiological rhythms in Parkinson's disease 30 , while delivering either DBS 31 or transcranial stimulation 32 phase-locked to accelerometer measurements can reduce the severity of tremor. Phase-dependent DBS controlled by LFPs in the overlying cortex has recently been used to disrupt parkinsonian oscillations in rodents 33 . Closed-loop optogenetics could allow such stimulation to be controlled in real time by abnormal activity recorded from the local network without interference from artefacts.  Article https://doi.org/10.1038/s41551-022-00945-8 Optogenetic therapies for epilepsy have been demonstrated in rodent models, but they thus far consist of continuous inhibitory stimulation delivered once a seizure is detected [34][35][36] . However, inhibition-based strategies may prove difficult to translate to humans because ion pumps such as halorhodopsin 34 are relatively inefficient and require high light levels to inhibit neuronal activity, while high expression of excitatory opsins in inhibitory neurons 35,36 is difficult to drive with viral methods (but see ref. 37 ). Moreover, some epilepsies are associated with the loss of interneuron populations 38,39 , and the suppression of epileptic activity by GABAergic inhibition, or hyperpolarizing ion channels like ACR, relies on appropriate ionic gradients being maintained, which may not be the case during seizures 40 . These considerations led us to test excitatory stimulation, relying on the precise timing of stimulation relative to network dynamics to suppress activity. The 4-AP model is relevant in this regard because over a relatively short time span the network stabilizes into a state of repeated discharges, which arises at least in part from raised intracellular chloride and associated effects on extracellular potassium 40,41 and is exacerbated by stimulating interneurons [42][43][44] . Given the ictogenic potential of GABA, our demonstration of reduced epileptic activity using excitatory stimulation delivered at the appropriate oscillatory phase (CLOSe -) thus represents a promising approach to seizure suppression. An added practical advantage of the 4-AP model used here was that seizure-like events occurred with sufficient regularity to allow a range of stimulation parameters to be explored in vivo within individual experimental sessions with NHPs. Nevertheless, many network states can give rise to seizures 45 , and future work will be needed to assess the effects of CLOSe in other situations, including chronic models of epilepsy.
Notwithstanding these practical issues with the delivery of inhibitory stimulation, it could be beneficial to test closed-loop inhibitory optogenetics, using cell-specific expression of either excitatory opsins in interneurons or inhibitory opsins in pyramidal neurons. For example, a recently reported fast-acting light-activated potassium channel 46 may provide a means to circumvent the issues of chloride loading described above. To further motivate this, we ran in silico simulations using our two-population neural mass model, delivering different strategies for closed-loop stimulation. Effective inhibition/excitation of either specific or mixed populations can be considered perturbations acting in different directions in the model phase space (middle part of Extended Data Fig. 7). The outer panels of Extended Data Fig. 7 show the effect on the seizure duration of delivering such stimulation in a phase-dependent manner. Not surprisingly, strategies that suppressed excitatory neurons (left part of Extended Data Fig. 7) and/or activated inhibitory neurons (top part of Extended Data Fig. 7) were generally more effective in shortening seizure bursts than the activation of excitatory neurons (right part of Extended Data Fig. 7) and/or suppression of inhibitory neurons (bottom part of Extended Data Fig.  7). Nevertheless, almost all stimulation strategies had the potential to either lengthen or shorten seizures depending on the phase at which closed-loop stimulation was delivered, and in all cases, there were particular phases that were most effective. In other words, due to the dynamics of the network, the timing of when stimulation is applied relative to ongoing activity is as important as what that stimulation does to the individual neuronal populations. Thus, closed-loop delivery (contingent on the instantaneous state of the local network) may also benefit seizure-suppression strategies with inhibitory opsins, enabling more effective suppression with less overall light delivered; however, this remains to be tested experimentally.
One difference between 4-AP-induced seizure-like events in vitro with mice versus in vivo with NHPs was that the former generally consisted of discrete oscillatory bursts of a single frequency whereas in vivo the pattern progressed from higher to lower frequency of oscillation. Thus, it may be advantageous in the future to use a closed-loop phase-shift algorithm that tracks changes in oscillation frequency 47 . Moreover, it is possible that different intervention approaches may be best suited to different time periods before or during seizures, for example, low-frequency open-loop stimulation in interictal periods 48,49 or optogenetic methods aiming to restore ionic concentration gradients 50 .
Recently, optogenetic therapy has been tested in humans for restoring sight 51 . There are, however, several challenges for the translation of optogenetics to the human brain, which is less surgically and optically accessible and less self-contained than the eye. The first is to demonstrate the safety and efficacy of opsin expression. The use of viral vectors in primates has lagged behind the progress being made in rodents, but our study is among several to show that widespread high expression levels can be obtained 52,53 . Optogenetic control of human neurons has been demonstrated in organotypic cultures 54 , but more work is needed to assess the potential risks of the long-term expression of opsins 55 . Second, a safe method of delivering sufficient light is required without the infection risk posed by percutaneous optical fibres. We demonstrated that the effective modulation of local brain activity in NHPs could be obtained using implanted LEDs. The long-term protection of active electronic components within brain tissue is a challenge, but the silicone-encapsulation technique we used in this study has proved to be highly reliable in the accelerated lifetime testing of insulators 56 . We are developing array implants that combine multiple forks with multiple LEDs on each prong to deliver uniform or patterned illumination to a large volume of cortex, together with a custom application-specific integrated circuit 57 to process LFP recordings, supply drive current and monitor LED temperature 58 . Such cell-specific control enabled by optogenetics has applications in many neurological disorders, and we hope that these technologies will help translate the promise of optogenetic therapies to the human brain.

Methods
All animal procedures were carried out under appropriate licenses issued by the UK Home Office under the Animals (Scientific Procedures) Act 1986 and were approved by the Animal Welfare and Ethical Review Board of Newcastle University.

In vitro mouse experiments
Brain slice experiments used 18 young adult male C57BL/6J transgenic mice expressing channelrhodopsin in pyramidal neurons. Cell-specific expression was achieved by crossing mice homozygous for Cre-recombinase under the Emx1 promoter (EMX1-IRES-Cre mice; stock no. 005628, Jackson Laboratory) with mice carrying the floxed channelrhodopsin gene (Ai19-flox-channelrhodopsin; stock no. 12569, Jackson Laboratory). We also performed a series of brain slice experiments in mice using the viral expression of opsins. Three young adult male wild-type C57BL/6J mice were administered with buprenorphine (0.05 mg kg −1 intraperitoneally) and meloxicam (5 mg kg −1 subcutaneously) before anaesthetic induction with 5% isoflurane in 1 l min −1 O 2 , maintained at 1.5-2%; 500 nl of AAV8-hSyn-Chronos-GFP (10 12 VP ml −1 , University of North Carolina Vector Core) was also injected at depths of 1.7 and 1.2 mm (AP +1, ML +1.5 relative to bregma) at a speed of 150 nl min −1 . Animals received post-operative meloxicam (5 mg kg −1 subcutaneously). All mice were group housed in individually ventilated cages kept at room temperature with a 12 h/12 h light/dark cycle and provided with food and water ad libitum. For brain slice preparation, mice were anaesthetized with isoflurane before the injection of ketamine (≥100 mg kg −1 intramuscularly) and xylazine (≥10 mg kg −1 intramuscularly) and intracardial perfusion with modified artificial cerebrospinal fluid composed of 252 mM sucrose, 3.0 mM KCl, 1.25 mM NaH 2 PO 4 , 24 mM NaHCO 3 , 2.0 mM MgSO 4 , 2.0 mM CaCl 2 and 10 mM glucose. Following brain removal, 450 μm horizontal slices were cut with a vibratome and transferred to a holding chamber at room temperature for approximately 1 h. They were then placed in a recording chamber at the interface of normal artificial cerebrospinal fluid (sucrose replaced with 126 mM NaCl) Article https://doi.org/10.1038/s41551-022-00945-8 maintained at 32-34 °C and humidified with 95% O 2 /5% CO 2 . Multielectrode arrays (A16x1-2mm-100-177, NeuroNexus) were used to record LFPs (connected to either a Multichannel Systems MP8I headstage, PGA amplifier and Micro1401 (CED) running Spike2 v7 (CED), or RHD2000 (Intan Technologies) running Recording Controller software v2 (Intan Technologies). Optical stimulation was delivered via a 200 μm fibre (M89L01-200, Thorlabs) positioned 40 mm above the slice. This was connected via a fibre optic cable to LED cubes delivering either a blue (470 nm, M470F1, Thorlabs to activate the opsin) or yellow (590 nm, M590F2, Thorlabs as a control) LED driven up to a maximum current of 1.2 A (T-cube, ThorLabs). We report data from 21 sessions in quiescent brain slices and 10 sessions in which seizure-like activity was induced by the bath application of 200 mM 4-AP. Datasets were only excluded from in vitro seizure experiment analyses in cases where 4-AP did not elicit epileptiform activity.

In vivo NHP experiments
Experiments were conducted on two female Macaca mulatta monkeys (age: 4.3-5.3 years, weight: 5.7-6.7 kg), coded Z and Y. The animals were injected with optogenetic viruses under anaesthesia (2% sevoflurane and alfentanil 0.2-0.3 μg kg −1 min −1 intravenously) and aseptic conditions. Methylprednisolone (30 mg kg −1 followed by 5.4 mg kg −1 h −1 intravenously) was given to reduce oedema, together with meloxicam (0.3 mg kg −1 subcutaneously). The injections were performed in the primary motor cortex (M1), following a craniotomy and dural resection to visualize the central sulcus. Z and Y both received AAV8-hSyn-Chronos-GFP (10 12 VP ml −1 , University of North Carolina Vector Core) in the right M1. Monkey Z was also injected with Lenti-hSyn-eYFP-2A-ChR2(H134R) (10 9 VP ml −1 , our construct, Vigene Biosciences) in the left M1 in a subsequent procedure. Injections used multiple stainless-steel needles (diameter = 0.3 mm, 1 mm separation, Y: 4 needles, Z: 8 needles) connected to Hamilton syringes via tubing filled with silicone oil. The syringes were mounted on ultra-micro-pumps (UMP3) synchronously controlled with the SYS-Micro4 controller (World Precision Instruments). At each site, 5 μl of virus was injected at multiple depths from 1 to 4 mm below the cortical surface at either 500 nl min −1 (Y) or 250 nl min −1 (Z). The total volume of virus injected is given in Supplementary Table 1.
Experiments were carried out under terminal anaesthesia in monkey Y (50 days after injection) and monkey Z (134 and 50 days after the injection of AAV-Chronos and Lenti-ChR2, respectively). Surgical preparation of the injection site was performed under inhalation anaesthesia (1-2% sevoflurane) after which we switched to intravenous infusion of ketamine (6 mg kg −1 h −1 ), alfentanil (0.2-0.3 μg kg −1 min −1 ) and midazolam (0.14 mg kg −1 h −1 ) to maintain cortical excitability. The animals were ventilated and hydrated, and heart rate, blood pressure, saturation, end-tidal CO 2 and temperature were monitored throughout. Neural activity in monkey Y was recorded using a NeuroNexus probe (A4X1-tet-3mm-150-121) and in monkey Z using U-probes (260 μm shaft diameter, 32 channels, 100 μm linear spacing, Plexon, Inc.). Data were amplified and acquired at 25 kHz using the RHD2000 system (Intan Technologies). Light was delivered through a 200 μm fibre (M89L01-200, Thorlabs) inserted superficially into the cortex and mounted to the same LED cubes as used in the in vitro experiments. In some experiments in monkey Z, we also used an implanted LED (see the following section) to deliver light to the tissue. After collecting data based on endogenous activity, 4-AP (100 mM) was injected into the cortex using a Hamilton syringe and an ultra-micro-pump (UMP3) with the SYS-Micro4 controller (World Precision Instruments). Multiple injections of 1 μl at 200 nl min −1 were made at the same site until sustained seizure activity was observed (typically 5-10 μl hemisphere −1 ). Supplementary Table 1 describes the datasets collected from each NHP; all experiments were included in the analyses, and no data points were excluded.

Implantable LED array
Extended Data Fig. 2a shows the implantable optrode fork. Optrode fabrication began with a 200 μm-thick silicon wafer, which underwent a standard solvent cleaning procedure in N-methylpyrrolidine, followed by isopropanol and then rinsing in deionized water. A 1 μm-thick insulation SiO 2 layer was deposited by chemical vapour deposition on the silicon surface. Ti/Au/Ti metallization was deposited by evaporation on top of the insulation and patterned by UV photolithography to outline the metal tracks and recording electrodes. Metal patterning was carried out by a selective wet etch based on NH 4 OH:H 2 O 2 (1:2) for titanium and K 3 Fe(CN) 6 , Na 2 S 2 O 3 and CS(NH 2 ) 2 in a deionized water mixture for gold. The Ti/Au/Ti patterns were then capped with a second SiO 2 insulation layer. Contact windows through the top insulation needed to access the bonding pads were opened by reactive-ion etching, using a Ti/Ni metal mask that was deposited by e-beam evaporation and patterned by UV photolithography and wet etching. Optrode singulation was achieved by deep reactive-ion etching.
Micro-LEDs (DA2432, Cree) were bonded to the gold LED pads on the optrode shaft using off-the-shelf Au/Sn preforms (Inseto, 100 μm × 100 μm × 10 μm, comparable with the LED footprint). Using a pick-and-place Fineplacer Lamda tool, a preform was placed on each of the two LED pads, the LED was placed directly on top of the AuSn preforms and the LED/preforms stack was heated to 320 °C to melt the preform and bond the LED.
The silicone rubber used for encapsulation was NuSil MED-6015, an optically clear, solvent-free, low-viscosity silicon elastomer safe for human implantation. The two-part rubber was mixed in a vortex mixer (10 parts A to 1 part B). The optrode surface was prepared by solvent cleaning in acetone and isopropanol in an ultrasonic bath and then rinsing in deionized water. The optrodes were dipped into the silicone mix and then mounted on the vacuum holder of a spin coater. A uniform thickness of the silicone around the optrode was achieved by spinning at 2,000 r.p.m. for 5 s and 4,000 r.p.m. for 10 s. The silicone was cured at 150 °C for 15 min.
The LED fork was inserted into the brain using a stereotaxic manipulator. We used a single LED at the tip of one shaft to deliver closed-loop stimulation. The LED was driven by a voltage-controlled constant current stimulator (DS4, Digitimer) up to a maximum current of 5 mA. Extended Data Fig. 2b compares the total light power emitted by the LED and the fibre-coupled Thorlab system over the full experimental range, measured using an integrating sphere (OPM150, Artifex Engineering). In both cases, the light source was placed near the centre of Article https://doi.org/10.1038/s41551-022-00945-8 the integrating sphere, which captured light emitted from all angles into an integrated calibrated photodiode.

Closed-loop stimulation
The closed-loop algorithm was implemented in custom-designed hardware based on a dsPIC30F6012A microcontroller running at 30 MHz. The microcontroller sampled the LFP from one electrode at 500 Hz, applied a causal phase-shifting finite impulse response (FIR) filter, thresholded ( just above the background noise level) and half-wave rectified the output to generate a voltage signal that controlled the LED current driver. The FIR filter convolved the input signal with a 512-sample kernel given by where t < 0 (for a causal filter working on past signals only), k determines the filter bandwidth and was set to 1.25 for all experiments, φ determines the extent to which the output is phase advanced from the input and f filt determines the central frequency of the passband. The amplitude and phase response of this filter are shown in Fig. 1a. In general, for our seizure experiments, we chose f filt to be the dominant frequency of the seizure bursts (in the range of 10-20 Hz), and for non-seizure recordings, we chose frequencies between 2 and 40 Hz. The remaining free parameter, α, is an overall scaling factor that determines the light intensity for a given filter output. We adjusted this in advance such that endogenous activity would drive the LED over its full current range. Note, however, that once engaged, CLOSe + feedback often enhanced the oscillations such that the light pulses saturated at the maximum level. CLOSe was delivered for epochs of fixed duration, each interspersed with an equal-duration epoch of no stimulation. We used phase shifts, φ, from 0, 45°, […], 315° delivered in pseudorandomized order. We chose epoch durations between 5 and 120 s depending on the experiment, ensuring that our datasets contained at least two repeats of each phase shift. For quiescent/endogenous experiments we tended to use short-duration epochs, whereas for seizure experiments we selected in advance a duration such that at least one seizure event would probably occur within each epoch. Our quiescent brain slice recordings lasted between 11 and 91 min (mean 51 min), whereas our seizure sessions lasted between 28 and 211 min (mean 93 min). Our endogenous recordings in NHPs lasted between 10 and 14 min (mean 11 min), whereas our seizure datasets lasted between 63 and 71 min (mean 67 min).

Data analysis
Data were analysed using custom scripts written in Matlab (Mathworks) and the circ_stats toolbox for circular statistics 59 . All offline filtering used four-pole Butterworth filters passed in forward and reverse directions. LFP was downsampled to 500 Hz after anti-alias filtering. Power spectra were compiled by Welch's method using overlapping windows with lengths of 512 sample points. CLOSe phase shifts were adjusted by the relative phase between the LFP and high-gamma (>100 Hz) envelope, which was determined by applying a Hilbert transform to the cross-correlation of these signals (Extended Data Fig. 1).
For data on quiescent mouse brain slices and endogenous activity in NHPs, we compiled power spectra of the LFP driving CLOSe for the entirety of stimulation/control epochs and averaged power modulation around the closed-loop filter frequency (0.8-1.2f filt ). For the NHP linear microelectrode datasets, we calculated the depth profile of cycle-triggered averages of the other LFPs, aligned to troughs in the bandpass-filtered (0.8-1.2f filt ) channel that was driving CLOSe.
Seizure events in mouse brain slices occurred sporadically and were readily distinguished from quiet interictal periods, so we restricted our analysis to time windows encompassing these events. The start times of these windows were identified using an appropriate threshold on the rectified LFP (typically 0.05-0.15 mV), and we calculated power spectra for a fixed duration that encompassed all the seizure bursts (typically around 20 s). Within these windows, we also defined individual bursts as periods during which the rectified LFP was not less than the threshold for more than 0.2 s and excluded events with a duration shorter than 0.2 s. Typically the first burst within each seizure event was longer than subsequent bursts. Therefore, when computing the ratio of burst lengths under CLOSe to the no-stimulation condition, we calculated this separately for first and subsequent bursts before averaging over all bursts.
The seizure events in NHPs occurred more frequently, and it was not straightforward to define a threshold to demarcate their onset from background spontaneous activity. Therefore, we computed power spectra over the entirety of stimulation/control epochs for these data. To obtain a measure of seizure magnitude, we computed the amplitude envelope of the LFP (bandpass filtered at 10-30 Hz, rectified and smoothed with a 1 s Hanning window) and corrected for baseline activity by subtracting the mode average of this envelope. We then computed the autocorrelation function of this signal, which provides a visualization of the temporal profile of seizure bursts. We quantified seizure magnitude from the area under this autocorrelation function (from −20 to +20 s). Note, however, that while the autocorrelation function reveals the temporal profile of seizure bursts (that is, the width of the peak reflects the duration of seizures), the area under this peak provides a composite measure that is also influenced by the number and duration of seizure bursts as well as their individual amplitudes. Therefore, we also calculated the proportion of total time for which this envelope exceeded different seizure thresholds ranging from 0 to 100% of the maximum amplitude seen in the no-stimulation condition. Finally, we calculated the frequency and duration of epochs for which the amplitude envelope exceeded each threshold level.
For rodent and NHP seizure datasets, we also calculated two metrics designed to quantify the stability of seizure cycles revealed by delay-embedded, bandpass-filtered (in vitro: 5-30 Hz, in vivo: 10-30 Hz) LFP trajectories. We chose an embedding dimension of three and obtained the optimal embedding delay from the average mutual information algorithm implemented by the Matlab function phaseSpaceReconstruction with default settings. Our first metric was geometric in nature and was designed to assess variations in the instantaneous scalar radius of the three-dimensional trajectory (from the origin). We calculated the mean, μ(t), and standard deviation, σ(t), of this radius using a sliding window of 100 ms width through time. We then defined a trajectory coefficient of variation (CoV) as the proportional relationship between these: CoV was calculated by the least-squares fit of equation (2) over time. We chose this regression approach (rather than calculating σ(t)/μ(t) and averaging over time) to avoid our result being skewed by quiescent epochs with low values of μ(t). Our second metric was approximate entropy, which is an information-theoretic measure of unpredictability in time series. This was calculated using the Matlab function approximateEntropy with the default similarity criterion of 0.2 times the standard deviation.
The modulation of all-positive metrics (LFP power, seizure burst duration/magnitude, trajectory stability) relative to no stimulation was analysed using log-transformed ratios (that is, a doubling/halving of seizure magnitude was treated as an equal and opposite modulation). We calculated the maximum/minimum modulation both for the raw datasets (that is, selecting the phase shift that yielded the largest average effect) and for a sinusoidal fit through all phase shifts in the dataset. The former may overestimate the modulation due to variability inherent in each measurement, and the latter may underestimate modulation if the data are not well fit by a sinusoid; therefore, we Article https://doi.org/10.1038/s41551-022-00945-8 show both values throughout. We also averaged our measures across datasets (aligned by adjusted phase shift) and assessed the statistical significance of phase-dependent modulation using circular-linear correlations.

Modelling
We used a simple two-population variant of the Wilson-Cowan neural population model, which has been described in detail in previous publications 14,15 . The model comprised a single excitatory population and a single inhibitory population evolving according to the following differential equations: where E(t) and I(t) are, respectively, the activity of the excitatory and inhibitory neural populations at time t. The parameters a, b, c and d determine the strength of interaction between these populations, decaying with time constants τ e and τ i . This system is also subject to tonic drive, P and Q, and Gaussian inputs, η e (t) and η i (t), with zero mean and standard deviation, η, reflecting synaptic noise and inputs from the surrounding tissue. The LFP was modelled as a combination of the activity of both neuronal populations, which was fed into the same closed-loop feedback algorithm as used in the experiments.
Optical stimulation acted as an additional input, S(t), to the excitatory neuronal population. Finally, the sigmoid function is We used the Euler-Maruyama method to simulate this system with a 1 ms time-step. The parameters used for the simulations are shown in Supplementary Table 2, putting the system in a bistable state regime where a limit cycle coexists with the lower fixed point.

Reporting summary
Further information on research design is available in the Nature Research Reporting Summary linked to this article.

Data availability
The source data supporting the results in this study are available from the Newcastle University research repository at https://doi. org/10.25405/data.ncl.19519630. All data generated during the study are available from the corresponding author on reasonable request. Article https://doi.org/10.1038/s41551-022-00945-8 Extended Data Fig. 1 | Realigning phase shifts relative to high gamma envelope. a LFP spectra from three different Emx1-ChR2 mouse brain slice sessions with different closed-loop filter frequencies. Bottom plot shows that the phase shifts and frequencies of driven oscillations varied across sessions. b Cross-correlation (over all phase conditions) reveals a varying phase relationship between the LFP and high gamma envelope for different sessions, while the stimulation to high gamma phase was relatively constant. c Schematic of the phase adjustment procedure. (1) During the experiment, the FIR filter generated optical stimulation that was phase shifted relative to the LFP (by an amount set by the experimenter). This stimulation drove neural activity, for which we used the high gamma envelope as a surrogate measure, which then produced LFP. (2) To assess the phase relationship between neural activity and resultant LFP, at the end of the experiment we measured the zero-lag phase of the overall LFP-gamma cross-correlation. (3) We added these two phase shifts to produce an adjusted phase shift of stimulation relative to high gamma envelope. We hypothesized that this overall phase-shift would determine whether the closed-loop dynamics was characterised by positive or negative feedback. d LFP spectra replotted after adjusting phase-shift relative to high gamma envelope. In addition, the frequency axis has been normalised by the filter frequency. As a result, the frequencies of oscillations driven by different phase-shifts are closely aligned. d Phase-shifts (relative to LFP) that drove maximal oscillation plotted against relative phase between LFP and high gamma envelope. Solid line indicates stimulation in phase with high gamma. Maximal modulation was typically obtained for phase-shifts advanced by 0-90° relative to this (circular mean 38°, dashed line).  Optogenetic activation/ suppression of excitatory/inhibitory neurons can be considered as weak perturbations of the seizure trajectory in different directions in the model state-space. Peripheral plots show predicted impact on seizure burst duration of closed-loop optogenetic strategies that deliver each types of stimulation in a phase-dependent manner. Strategies that suppress excitatory neurons and/ or activate inhibitory neurons are generally more effective than activation of excitatory neurons and/or suppression of inhibitory neurons. Nevertheless, most strategies can result in either lengthening or shortening of seizures depending on the phase at which stimulation is delivered, and in all cases, there are particular phases which are more effective at suppressing seizures. Thus optogenetic seizure suppression strategies using a range of different opsins/cell-targets may be improved by delivering stimulation in a closed-loop manner.
Corresponding author(s): Andrew Jackson Last updated by author(s): May 27, 2022 Reporting Summary Nature Research wishes to improve the reproducibility of the work that we publish. This form provides structure for consistency and transparency in reporting. For further information on Nature Research policies, see our Editorial Policies and the Editorial Policy Checklist.

Statistics
For all statistical analyses, confirm that the following items are present in the figure legend, table legend, main text, or Methods section.

n/a Confirmed
The exact sample size (n) for each experimental group/condition, given as a discrete number and unit of measurement A statement on whether measurements were taken from distinct samples or whether the same sample was measured repeatedly The statistical test(s) used AND whether they are one-or two-sided Only common tests should be described solely by name; describe more complex techniques in the Methods section.
A description of all covariates tested A description of any assumptions or corrections, such as tests of normality and adjustment for multiple comparisons A full description of the statistical parameters including central tendency (e.g. means) or other basic estimates (e.g. regression coefficient) AND variation (e.g. standard deviation) or associated estimates of uncertainty (e.g. confidence intervals) For null hypothesis testing, the test statistic (e.g. F, t, r) with confidence intervals, effect sizes, degrees of freedom and P value noted

Software and code
Policy information about availability of computer code Data collection Data were collected using Spike2 v7 and Intan RHD2000 controller v2.

Data analysis
Analysis and modelling code are available from the Newcastle University research repository at http://doi.org/10.25405/data.ncl.19519630.
For manuscripts utilizing custom algorithms or software that are central to the research but not yet described in published literature, software must be made available to editors and reviewers. We strongly encourage code deposition in a community repository (e.g. GitHub). See the Nature Research guidelines for submitting code & software for further information.

Data
Policy information about availability of data All manuscripts must include a data availability statement. This statement should provide the following information, where applicable: -Accession codes, unique identifiers, or web links for publicly available datasets -A list of figures that have associated raw data -A description of any restrictions on data availability The source data supporting the results in this study are available from the Newcastle University research repository at http://doi.org/10.25405/data.ncl.19519630. All data generated during the study are available for research purposes from the corresponding author on reasonable request.