Closed-loop modulation of local slow oscillations in human NREM sleep

Slow-wave sleep is the deep non-rapid eye-movement (NREM) sleep stage that is most relevant for the recu- perative function of sleep. Its deﬁning property is the presence of slow oscillations ( < 2 Hz) in the scalp electroencephalogram (EEG). Slow oscillations are generated by a synchronous back and forth between highly active UP-states and silent DOWN-states in neocortical neurons. Growing evidence suggests that closed-loop sensory stimulation targeted at UP-states of EEG-deﬁned slow oscillations can enhance the slow oscillatory activity, in- crease sleep depth, and boost sleep’s recuperative functions. However, several studies failed to replicate such ﬁndings. Failed replications might be due to the use of conventional closed-loop stimulation algorithms that an- alyze the signal from one single electrode and thereby neglect the fact that slow oscillations vary with respect to their origins, distributions, and trajectories on the scalp. In particular, conventional algorithms nonspeciﬁcally target functionally heterogeneous UP-states of distinct origins. After all, slow oscillations at distinct sites of the scalp have been associated with distinct functions. Here we present a novel EEG-based closed-loop stimulation algorithm that allows targeting UP- and DOWN-states of distinct cerebral origins based on topographic analyses of the EEG: the topographic targeting of slow oscillations (TOPOSO) algorithm. We present evidence that the TOPOSO algorithm can detect and target local slow oscillations with speciﬁc, predeﬁned voltage maps on the scalp in real-time. When compared to a more conventional, single-channel-based approach, TOPOSO leads to fewer but locally more speciﬁc stimulations in a simulation study. In a validation study with napping participants, TOPOSO targets auditory stimulation reliably at local UP-states over frontal, sensorimotor, and centro-parietal regions. Importantly, auditory stimulation temporarily enhanced the targeted local state. However, stimulation then elicited a standard frontal slow oscillation rather than local slow oscillations. The TOPOSO algorithm is suitable for the modulation and the study of the functions of local slow oscillations.


Introduction
Slow-wave sleep (SWS) is the deep, restorative sleep stage that helps us to recover from our daily activity. It is vital for our mental and physical health. Recent research has provided groundbreaking insights into the processes and mechanisms by which SWS contributes to health ( Abel et al., 2013 ;Bodizs, 2021 ;Frank & Heller, 2018 ;Lanza et al., 2022 ;Zielinski et al., 2016 ). First of all, SWS was found to help maintain synaptic homeostasis ( Tononi & Cirelli, 2020 ). During SWS, unused and obsolete synaptic connections are down-scaled to compensate for the net synaptic growth and potentiation that occurred during prior wakefulness. This process prevents excessive synaptic potentiation, increases the signal-to-noise ratio of neuronal activity, and thereby renews our Abbreviations: SWS, slow-wave sleep; TOPOSO, topographic targeting of slow oscillations; EEG, electroencephalogramm; NREM, non-rapid eye-movement. Geiser et al., 2020 ;Grimaldi et al., 2020 ;Scholes et al., 2020 ;Talamini & Juan, 2020 ;Wunderlin et al., 2021 ). Interestingly, sensory and especially auditory stimulation during sleep can be used to entrain and enhance the slow oscillatory electric activity in the EEG that defines SWS. During SWS, cortical neurons oscillate between hyperpolarized and therefore inactive "DOWN "-states, and depolarized and highly active "UP "-states. Both states last between 0.25 and 1 s each. The back and forth between these two states occurs in a highly synchronized manner which induces strong electrical fields that manifest in the scalp EEG as slow oscillations with frequencies between 0.5 and 2 Hz ( Iber et al., 2007 ). Hence the term slow-wave sleep. There is compelling evidence that sensory -especially auditory -stimulation temporarily enhances the slow oscillatory activity during sleep if stimulation is applied during the EEG-defined "UP "-state ( Danilenko et al., 2020 ;Ngo et al., 2015 ;Santostasi et al., 2016 ). UP-targeted stimulation probably increases the synchronicity between neurons' back and forth between UP-and DOWNstates.
UP-state targeted closed-loop auditory stimulation during sleep was not only found to temporarily enhance slow oscillations in the EEG, but to boost the cognitive and biological functions of SWS. Several studies suggested that closed-loop auditory stimulation can improve overnight memory retention in young ( Ngo, Martinetz, et al., 2013 ;Ong et al., 2016 ) and old ( Papalambros et al., 2017 ) adults. Other studies reported improved hippocampus-dependent learning on the next day ( Ong et al., 2018 ) -probably due to enhanced synaptic down-scaling during sleep. A full night of UP-state targeted auditory stimulation was also found to improve immune function ( Besedovsky et al., 2017 ) and autonomic regulation .
Unfortunately, determining the presence of slow oscillations from the scalp EEG for targeting stimulation at neuronal UP-states is not trivial because slow oscillations are a heterogeneous phenomenon. Highdensity EEG recordings of sleep suggest that there exist different subtypes of slow oscillations -some representing a global phenomenon on the scalp, and some being more local in that they only involve a few electrodes . Slow oscillations further are not stationary but appear to travel across the scalp . Source modeling of sleep EEG recordings confirmed that single slow oscillations have distinct origins and unique propagation patterns in the cortex ( Murphy et al., 2009 ), and that different local slow oscillations can coexist ( Riedner et al., 2007 ). Intracranial recordings in humans further suggested that most slow oscillations are a local rather than a brain-wide phenomenon ( Mak-McCully et al., 2015 ;Nir et al., 2011 ).
Different subtypes of slow oscillations might exert different functions in the brain. This is indirectly suggested by the finding that the scalp distribution of spontaneous slow oscillatory activity during SWS mirrors prior experience as well as individual differences in cognitive abilities (see e.g. Avvenuti & Bernardi, 2022 for an up-to-date review on local sleep). For example, scalp maps of sleep slow oscillations change as a function of prior learning -potentially due to local changes in the need for synaptic renormalization ( Huber et al., , 2006 as well as due to locally restricted neuronal activity related to the consolidation of newly acquired skills and memories ( Fattinger et al., 2017 ;Mascetti et al., 2013 ). Slow oscillations are thus locally regulated in a use-dependent manner ( Avvenuti & Bernardi, 2022 ). The topographic pattern of slow oscillatory activity is further known to change throughout adolescence ( Kurth et al., 2010( Kurth et al., , 2012Ringli & Huber, 2011 ) and with aging ( Landolt & Borbély, 2001 ;Sprecher et al., 2016 ), and these changes are associated with skill maturation in adolescents ( Kurth et al., 2012 ), and presumably with cognitive decline ( Mander et al., 2013( Mander et al., , 2017 in the elderly. Finally, different individuals show unique but stable, trait-like topographic distributions of slow oscillatory activity that might reflect individual differences in brain organization and function ( Markovic et al., 2018 ). Successful enhancement or modulation of specific sleep functions by means of closed-loop stimulation might thus require stimulation techniques that are capable of precise targeting of the relevant local slow-oscillations.
To the best of our knowledge, all existing EEG-based algorithms for slow oscillation phase-targeted stimulation ignore the fact that slow oscillations are a spatially heterogeneous phenomenon. All currently used algorithms analyze the signal from one single location (one single electrode, e. g. Fz, or the average signal from a patch of neighboring electrodes) referenced to pooled mastoids (standard reference in sleep research) to determine the current phase of ongoing slow oscillations and to predict and target upcoming "UP-" and "DOWN-" states ( Cox et al., 2014 ;Ngo et al., 2015 ;Santostasi et al., 2016 ;Sousouri et al., 2021 ). Single-channel EEG provides little information about the location and the polarity of the neuronal generator of a wave-form, i.e. about where in the brain a slow oscillation is most prominent, and whether the involved neurons are in an UP-or in a DOWN-state. Existing algorithms thus most likely target a very heterogeneous set of slow oscillations with different scalp maps and distinct cortical origins and trajectories. The fate of a phase-targeted stimulus, i.e. whether and where it elicits (or interrupts) a slow oscillation in the brain, might not only depend on the phase of ongoing slow oscillations ( Schabus et al., 2012 ), but also on their origin in the brain ( Sousouri et al., 2021 ).
Although some studies observed that UP-state targeted auditory stimulation can improve the cognitive and health benefits of SWS, other studies failed to replicate these findings ( Henin et al., 2019 ;Wunderlin et al., 2021 ). For example, older adults showed reduced entrainment and enhancement of slow oscillations during stimulation  and their overnight memory consolidation did not improve with stimulation Schneider et al., 2020 ;Wunderlin et al., 2021 ). The contradictory findings on the effect of UP-state targeted stimulation could result from the fact that studies did not take into account the heterogeneous nature of slow oscillations. If, for example, slow oscillatory patterns during SWS change throughout adolescence ( Kurth et al., 2010( Kurth et al., , 2012Ringli & Huber, 2011 ) and with age ( Landolt & Borbély, 2001 ;Sprecher et al., 2016 ), the same stimulation algorithm might target different UP-states and thus yield different effects on sleep's functions in children, young adults, and the elderly.
Phase-targeted stimulation might provide more consistent insights into the function of sleep and might yield more reliable and replicable effects on behavior if only those subtypes of local slow oscillations were targeted that are thought to be relevant for a specific research question or a specific aim. For example, phase-dependent stimulation might improve the consolidation of a newly learned motor skill during sleep following learning only if stimulation targets slow oscillations in the motor cortex ( Fattinger et al., 2017 ;Huber et al., 2004 ). We suggest that specific local slow oscillations can be identified and targeted by analyzing the temporal evolution of the voltage distribution in the scalp EEG, i.e. the scalp maps, instead of or in addition to the wave-form of the voltage of single channels. Although determining the exact cortical source of an EEG signal is non-trivial, there is agreement that specific, recurring and temporarily stable scalp maps must reflect specific brain states that can be attributed to specific neuronal processes in well-described cortical sites or networks ( Michel & Koenig, 2018 ). These maps can be targeted in real-time in closed-loop applications ( Diaz Hernandez et al., 2016 ).
Studying or modulating the function of slow oscillations of a specific cortical site or network by means of stimulation requires that stimulation is synchronized with ongoing slow oscillatory activity within this site or network -i.e., stimulation must be timed to the local UPor DOWN-phase of the respective cortical site or network. Importantly, slow oscillations vary substantially with respect to the degree of their "localness ", i.e. their spatial extent on the scalp and within the brain. In fact, two distinct subtypes of slow oscillations Malerba et al., 2019 ;Mensen et al., 2016 ;Siclari et al., 2014 ) have been identified: spatially restricted "local " type-II slow oscillations with relatively low amplitudes, and widespread, high-amplitude type-I oscillations. Type-II oscillations are visible on only a few neighboring EEG electrodes (hence the term "local "). They are generated by corticocortical synchronization mechanisms and are subject to homeostatic decline across the night. Type-I oscillations involve many neighboring elec-trodes. They are generated by subcortical processes that depend on the arousal system, and they show no sign of homeostatic regulation. The distinction between spatially restricted ( "local ") vs. widespread slow oscillations thus allows identifying and targeting different neuronal synchronization processes and distinct homeostatic regulation mechanisms during sleep Siclari et al., 2014 ). However, this distinction does not inform about the specific cortical site or network that is most directly involved in generating a single, specific slow oscillation. Whether the specific slow oscillation is spatially restricted to the specific cortical target site or network, or whether it spans across many cortical sites might be of minor relevance for the effect of stimulation on the local cortical computation and the local synaptic processes. The local impact of stimulation is theorized to mainly depend on whether or not the targeted site or network is currently in a neuronal UP-or DOWNstate ( Vyazovskiy et al., 2009 ). These states might be best identified by means of the propagation of their electric field to the scalp, i.e. by means of their voltage distribution on the scalp ( Michel & Koenig, 2018 ).
We propose a novel closed-loop stimulation algorithm that predicts and targets upcoming local UP-and DOWN-states of slow oscillations with high temporal and topographic precision: the topographic targeting of slow oscillations (TOPOSO) algorithm. Local UP-/DOWN-states are here defined as peaks/troughs of scalp EEG oscillations between 0.5 to 2 Hz that are most prominent over a specific region of interest on the scalp (e.g. over electrode Fz, which would be stereotypical frontal slow oscillations , or electrode C4, which would be slow-oscillations in the right sensorimotor cortex ( Krugliakova et al., 2020 )). To target such UP-/DOWN-states, the TOPOSO algorithm continuously assesses the similarity between the current voltage distribution of the EEG on the scalp and the voltage distribution of precomputed template maps of the targeted UP-or DOWN-states. The algorithm aims to detect transitions into local UP-/DOWN-states based on the temporal evolution of the similarity between EEG scalp maps and template maps and on the wave-form of the EEG signal over the targeted locus. This approach may target both, spatially restricted type-II slow oscillations, as well as widespread type-I oscillation Malerba et al., 2019 ;Siclari et al., 2014 ). The algorithm is supposed to detect transitions into local UP-or DOWN-states with well defined scalp maps in near real time and to leave enough time to trigger stimulation at the actual peak of the upcoming UP-or DOWN-state. In simulations performed on pre-recorded data, we assessed whether using scalp maps in addition to single-channel data leads to fewer but more precise stimulations. In a sham-controlled within-subject experiment, we explored whether we are able to target auditory stimulations at local UP-states over different cortical regions (Fz, C4, CPz). We assessed the impact of auditory stimulation on the targeted local UP-state and explored whether stimulation would induce subsequent local slow oscillations over the targeted sites. The TOPOSO successfully detected upcoming local UP-states over frontal, sensorimotor, and centro-parietal regions and allowed for steering auditory stimulation accurately, leading to an initial brief enhancement of the target state. Following this brief enhancement of the target state, the stimulation used here elicited -due to its auditory nature -a standard frontal slow oscillation rather than local slow oscillations.

Aim and rationale
Local slow oscillations are generated by a highly coordinated back and forth between depolarized UP-and hyperpolarized DOWN-phases of the neurons within a specific, isolated cortical region or network ( Nir et al., 2011 ). Here, it is assumed that the electric fields induced by the coordinated UP-and DOWN-phases of these specific neurons yield scalp maps that have a high spatial similarity but show inverse polarities, i.e. scalp maps that are anticorrelated. Local slow oscillations should thus manifest as sequences of prominent, highly similar, anticor-related scalp maps with well-defined transitions between these states. Previous work indeed suggested that UP-and DOWN-states of auditory evoked frontal slow oscillation show highly similar but anticorrelated maps (r > | -.95|, see supplementary table S6 in Züst et al., 2019 ). During a local slow-oscillation, the correlation between EEG scalp maps and the predefined scalp map of a specific target state (e.g. an UP-state over the motor cortex) should thus initially be highly negative (preceding DOWN-state), but should rapidly transition to a highly positive correlation (target UP-state). This rapid transition should occur during a timewindow representative of 1 4 to 1 2 of the wavelength of slow-oscillations. By detecting such rapid transitions in real time, it should be possible to predict and target upcoming local-UP-or DOWN-states. Here, transitions are detected whenever the correlation between the current scalp EEG map and the scalp map of the predefined map of the target state is negative but is rapidly increasing in a slow-oscillation specific time window, and the voltage of the EEG over the target region is negative but increasing for transitions to UP-states, or positive but decreasing for transitions to DOWN-states.
The TOPOSO algorithm builds on the assumption that template maps, which are representative of specific targeted local slow oscillation UP-and DOWN-states, can be obtained from training data by post-hoc detecting slow oscillations in the respective EEG channel. Maps are generated by averaging the scalp maps of single UP-/DOWN states of only the most prominent (high-amplitude) slow oscillations that were posthoc identified over respective target electrodes (e.g. Fz, see Fig. 7 for examples of template maps; see chapter 2.3 for template generation). Template maps can be obtained either from sleep data of a baseline night of the same subject, or from sleep data of a representative sample of subjects. The resulting maps can be used to assess how the similarity between real-time EEG data and a specific map evolves in time. A rapid and consistent increase in similarity should indicate an upcoming local UP-or DOWN-state.
The TOPOSO algorithm detects a transition into an upcoming UP-(or DOWN-) state if all of the following conditions are fulfilled: (A) the similarity between the actual scalp EEG map and the scalp map of the target UP-(DOWN-) state is constantly increasing but (B) is still negative for the majority of the recent data samples; (C) the mean voltage over electrodes at the target site (e.g. Fz) is increasing (decreasing for DOWNstates) but (D) is still negative (positive) for the majority of the recent samples.
To detect transitions into UP-/DOWN-states, the TOPOSO algorithm analyzes the temporal evolution of the real time EEG in a data window with a duration that is based on the prototypical frequency of slow oscillations. Human slow oscillations peak at frequencies between 0.5-1.0 Hz ( Achermann & Borbély, 1997 ), which yields a duration of about 500 ms between peaks of consecutive UP-and DOWN-states at the upper frequency boundary. The time sequence between two states (e.g. from DOWN-to UP-state; see Fig. 1 ) can be divided in 4 time windows: (1) post-peak, (2) pre-zero-crossing (highlighted in Fig. 1 , left panel), (3) post-zero-crossing, and (4) pre-peak. The earliest possible time window for reliably detecting a transition is at the zero-crossing, i.e. by analyzing the pre-zero-crossing time window. At frequencies of 0.5-1 Hz, the pre-zero-crossing time window is expected to have a minimal duration of about 125 ms. This corresponds to 1/8th of the wavelength at 1 Hz. Therefore, the most recent 122 ms of real-time EEG data are used for detecting transitions into UP-/DOWN-states (61 samples at 500 Hz sampling rate).
The TOPOSO algorithm operates on unfiltered EEG data. Preprocessing only involves the following steps: removal of EOG-, EMG-, and artifact-laden EEG-channels, de-trending of each single channel, and rereferencing to the common average. Then, the relevant features are extracted at every data sample: the voltage over the target electrode (or the average voltage of a set of target electrodes), and the correlation of the scalp map with the template map.
We expected that both the absolute amplitudes of the EEG and the correlation between EEG scalp maps and template maps would vary be- Fig. 1. Visualization of the TOPOSO algorithm (a) and its implementation (b). a) the voltage over the target EEG channel (green) and the similarity between the scalp EEG and the template scalp map (template correlation; blue) for one slow oscillation. The DOWN-state, the transition between states, and the UP-state are highlighted. The gray bar indicates the time-window based on which the transition into the UP-state is detected. The criteria used to detect a transition are illustrated at the bottom: > 50% and > 75% indicate the percentages of samples within the time window that must meet each criterium for the algorithm to detect a transition into a local UP-state. The two scalp maps indicate the used EEG-measure to compute the feature (template correlation, focal voltage). b) sketch of the implementation of the algorithm for closed-loop applications. tween subjects (due to differences in skin and skull conductivity, head geometry, neuroanatomy, and the fit of EEG caps). To reduce the influence of interindividual differences in signal quality on algorithm performance, only the sign ( + /-) of the correlation/voltage at each time-point as well as the sign of the sample-to-sample change in correlation/voltage instead of absolute values is analyzed. Thus, the TOPOSO algorithm ignores the actual amplitude of the voltage and the magnitude of the correlation and uses exclusively the sign of these values and the sign of the relative change in these values.

Formal description
Put formally, a transition into an UP-or a DOWN-state is detected if all four of the following conditions are fulfilled at the same time, i.e., during the analysis of the time series of the n most recent samples of EEG data.
(A) The correlation corr (similarity) between the EEG (S) and the template map T is increasing for at least C 1 of the recent n samples: The correlation between the EEG (S) and the template map T is still negative for at least C 2 of the recent n samples: The voltage at the target site (referenced to the global average) is increasing for at least C 1 of the recent n samples: The voltage is still negative for at least C 2 of the recent n samples: Where n = number of samples (61) used for analysis, v i = the voltage over the target electrode at sample i, S i = the vector with the voltage distribution (scalp map) over all electrodes at sample i, T = the vector with the voltage distribution of the target state (template map), p = the polarity of the target state ( = + 1 for transitions to UP-states, = -1 for transitions to DOWN-states), C 1 and C 2 = pre-defined criteria. To find optimal parameters for C 1 and C 2 , we assessed how the TOPOSO algorithm would perform on pre-recorded EEG data for all possible combinations of C 1 and C 2 . For a detailed description of this procedure see chapter 2.6 Parameter optimization: evaluation of optimal detection criteria . For each parameter combination, we determined the average number of detected transitions into UP-and DOWN-states, the mean amplitude of the target states, and the time between the detection of a transition and the actual amplitude peak. Visual inspection of these descriptive statistics suggested that optimal parameters were C 1 = 75% and C 2 = 50%. The criteria were identical for the conditions regarding the voltage, and the conditions regarding the correlation between the EEG and the template maps. Hence, the criterion of C 1 = 75% was used for conditions (A) and (C), and a criterion of C 2 = 50% for conditions (B) and (D) (see chapter 2.5 Validation of computational rationale for the reasoning behind this). Importantly, optimal parameters for C 1 and C 2 were determined for frontal electrodes only (target electrode Fz) because we assumed that EEG data from frontal electrodes provide the best possible ground truth for the presence of slow oscillations. This assumption builds on the observation that slow oscillations originate most frequently over frontal regions . Parameters were kept identical for other, non-frontal sites to ensure that the algorithm always targets the same oscillatory phenomenon.

Procedure
To assess whether meaningful and distinct scalp maps for local UPand DOWN-states can be generated, we first extracted scalp maps focused on the following 12 electrodes/regions on the 10-20 grid: Fz, Cz, Pz, Oz, F5, F6, T7, T8, C5, C6, P5, P6 ( Table 1 ). Template maps for local UP-/DOWN-states were extracted from pre-recorded EEG data (for details about the data samples, see chapter 2.3.2).
First, EOG and EMG channels were removed and data were rereferenced to the global average, which allowed us to retrieve the original reference at Fz. Next, the target signal was extracted by averaging the voltage over electrodes centered around the site of interest (e.g. AF1, AFz, AF2, F3, Fz and F4 for the target Fz, Table 1 ). Using the average Note: The target signal for each target site was extracted by averaging the voltage over the electrodes centered around the site of interest. Using the average of a set of nearby electrodes instead of just one single electrode provides a more robust signal.
of a set of nearby electrodes instead of just one single electrode provides a more robust signal. The target signal was bandpass filtered at 0.15 -2 Hz. Then, all data segments containing non-rapid eye movement (NREM) sleep were selected. In these segments, we identified all data snippets between consecutive positive-to-negative zero crossings as potential slow oscillations if the snippets had a duration between 0.9 and 2 s (reflecting oscillations in the range between 0.5 to 1.11 Hz). Only candidate events with a trough-to-peak amplitude exceeding ⅔ of the trough-to-peak amplitudes of all candidate events were kept as slow oscillations. For each selected slow oscillation, we determined the negative-to-positive zero-crossing as the center of the oscillation.
To generate scalp templates for UP-and DOWN-states, we bandpass filtered the raw EEG signal from 0.3 to 35 Hz, re-referenced it to the global average, and then extracted ERPs centered on the negative-topositive zero-crossing for each of the previously identified slow oscillations. For the UP-state template, we then extracted the peak after the zero-crossing (about 0.5s later) in every identified slow oscillation. Similarly, for the DOWN-state template, we extracted the trough before the zero-crossing (about 0.5s before) in every slow oscillation. Scalp maps were computed by taking the average maps of all samples + /-40 ms around the trough/peak. The maps were normalized by dividing the voltage at each channel by the maximum absolute voltage of all channels.

Origin of EEG data
To create template maps for the detection of local UP-/DOWN-states, we used pre-recorded EEG data of NREM3 sleep. Data had been recorded during an afternoon nap in a sample of N = 39 participants (age = 19-32, M ± SD = 23.4 ± 3.5; 29 (74%) female) in a previous study on vocabulary learning during sleep ( Züst et al., 2019 ). All participants were mentally and physically healthy and right-handed. Subjects were restricted to 4 h of sleep the night before the experiment. Sleep recordings started between 12:40 and 14:50 and lasted about 90 min (M ± SD = 93.5 ± 33.1 min). Participants were played pairs of foreign words and German words via headphones while asleep. For further details on the study procedure, see ( Züst et al., 2019 ). Two subjects from the original study (N = 41) were excluded due to large signal drifts on a few electrodes.

Template validation
Visual inspection of the topographies of the UP-and DOWN-state templates that were extracted for the twelve target sites suggested that all templates reflected unique and highly distinct electrical fields ( Fig. 2 ,   Fig. 2. Topographies of each targeted UP-state (template map in normalized units, left) and the average EEG topography over all trials displayed from 0.4 s before to 0.4 s after the detection of a transition (t = 0), separately for each target site (ERP in μV). The EEG was averaged across + /-50 ms for each depicted time-point. The high similarity of the template map and the targeted brain state 200 ms (highlighted) after the detection of a transition suggests precise targeting of local UP-states. left panel). Inspection of the dipole fits for each template map confirmed that each template reflected a brain state that was most likely generated by a cortical dipole at the or close to the site of the target electrodes. Dipole fitting was performed for each template map assuming one single dipole. Fitting was done in fieldtrip ( Oostenveld et al., 2011 ), using the default boundary element method (bem) with the volume conduction model of the head that is provided by fieldtrip. This head model is based on the segmentation by Collins et al. ( Collins et al., 1998 ) and was constructed as reported in Oostenveld ( Oostenveld et al., 2003 ).

Validation of computational rationale
The TOPOSO algorithm builds on the assumption that a data window of 122 ms duration (61 samples of EEG data) is adequate for detecting transitions into UP-and DOWN-states in real-time. The algorithm is further based on the premises that the following parameters (respectively the signs of their values) are relevant features for detecting transitions into UP-/DOWN-states: the voltage at the target site, the sampleto-sample fluctuation of the voltage, the correlation between EEG and template maps, and the sample-to-sample fluctuation of the correlation.
When we developed TOPOSO, we wanted to assess the validity of the core assumptions of the algorithm and wanted to obtain first estimates for the optimal thresholds for detecting transitions into UP-/DOWNstates in realtime. To achieve this, we explored how the four relevant parameters on which TOPOSO operates evolve over time with respect to post-hoc detected transitions into UP-and DOWN-states. The computed parameters included (A) the percentage of samples in which the correlation between EEG scalp maps and the template map is increasing, (B) the percentage of samples where this correlation is still negative, (C) the percentage of samples where the voltage at the target site is increasing (or decreasing, for UP-vs. DOWN-states, respectively), and (D) the percentage of samples where the voltage is negative (or positive, for UP-vs. DOWN-states). The features were computed for data segments of 122 ms duration (61 samples) at a moving interval of 2 ms for a 4 s data window that was centered around the transition into UP-states as well into DOWN-states of post-hoc detected slow oscillations. Posthoc detected slow oscillations served as ground truth for the presence of UP-/DOWN-states. We used the time point of the zero crossing of the signal from the target electrode in these oscillations as ground truth for the transition into UP-/DOWN-states. The analysis was performed on the same data that were used to generate the templates (see chapter 2.3.2 Origin of EEG data ). We used the post-hoc detected slow oscillation events that we had used to extract the template maps (see chapter 2.3.1 Procedure ) as ground truth for the presence of UP-and DOWN-states. The analysis was performed for the targeting of frontal slow oscillations (Fz) only because slow oscillations tend to originate over prefrontal regions . EEG data derived from frontal electrodes thus provide the best possible ground truth for the presence of slow oscillations.
A visual inspection of the temporal evolution of our features revealed that the percentage of samples where the voltage (feature D) was positive (or negative) was maximal at the peak-time of the post-hoc defined UP-(or DOWN-) state. The same was true for percentage of samples where the correlation between EEG scalp maps and the target map was positive (feature B). More importantly, the percentage of samples where the sign of the voltage (feature D) was still negative (or positive) was about 50% at the time of the zero crossing of the DOWN-to-UP-state (or UP-to-DOWN) transition. The same was observed for the percentage of samples where the correlation with the template was still negative (feature B). This suggested that a threshold of 50% for the criterion C 2 of the TOPOSO algorithm (see 2.2 Formal description ) would be optimal. The percentage of samples where the sign of the sample-to-sample variation in the voltage (feature C) from the target site was positive (or negative), i.e., where the voltage was increasing (or decreasing), was maximal at the time of the transition from the DOWN-to the UP-state (or UP-to-DOWN). The same was true for the percentage of samples where the sample-to-sample variation in the correlation between EEG maps and the template map (feature A) was increasing. Importantly, the maximal values for the sample-to-sample variations of both the voltage and the correlation was about 70%. This indicated that a threshold of > 70% would be optimal for criterion C 1 . Finally, the temporal evolution of the features for the voltage and for the features of the correlation between EEG and template maps were highly similar, (features A and C, as well as features B and D). This suggested that identical thresholds for the criteria C 1 and C 2 can be used for the voltage and the correlation.

Parameter optimization: evaluation of optimal detection criteria
To find optimal thresholds for the detection criteria C 1 and C 2 , we performed simulations in which we applied TOPOSO to pre-recorded EEG data. We simulated how TOPOSO would perform with different combinations of thresholds for C 1 and C 2 . Thresholds ranged between 20% and 95% for each criterion (5% intervals), yielding 16 thresholds for each criterion and a total of 256 different threshold combinations (i.e., 256 simulations).
Simulations were performed on pre-recorded NREM sleep of the same data that were used to create the template maps for TOPOSO, i.e., the training data (for a description, see chapter 2.3.2 Origin of EEG data ). We preprocessed the pre-recorded EEG data to match the data as it would be processed in real-time (de-trending, re-referencing to global average; see as well chapter 3.1.2.1 Simulation of real-time detection of state transitions ). Simulations were performed for frontal electrodes (Fz) only, because slow oscillations originate most frequently over the prefrontal cortex . Frontal EEG data thus provide the best possible ground truth for the presence of slow oscillations.
For each simulation run, we extracted the following parameters averaged across all N = 39 datasets: the average number of detected transitions into UP-and DOWN-states, the average peak amplitude of the ensuing UP-/DOWN-state at the target site, and the average delay between detection of a state-transition and the actual peak time of the ensuing UP-/DOWN-state. We plotted these parameters for all possible threshold combinations for C 1 and C 2 . Visual inspection of these plots suggested that the thresholds C 1 = 75% and C 2 = 50% would be optimal for detecting a sufficient amount (mean events per minute of NREM sleep > 8) of transitions into high-amplitude (mean amplitude > 15 μV) UP-and DOWN-states with long enough delays (mean duration > 100 ms) between detection of the transition and the occurrence of the actual UP-/DOWN-states to allow use in real-time applications. We thus used these thresholds for our studies.

Validation on pre-recorded data
To assess the precision, reliability, and validity of the TOPOSO algorithm, we applied it to pre-recorded EEG data. We simulated a real-time data stream using pre-recorded sleep EEG data from an unpublished nap study and had our algorithm detect transitions into UP-states or DOWNstates. We did this separately for each of the 12 selected target sites. We then analyzed the EEG data centered around the time stamps of the detected transitions. We assessed whether the TOPOSO algorithm indeed detects time-points during which the brain transitions into local UP-or DOWN-states with scalp maps that match the template of the targeted states.
We further assessed whether using the similarity between scalp maps and template maps for detecting transitions into local UP-/DOWN-states (template-based algorithm) improves the topographic precision compared to an algorithm that only operates on a single EEG channel. To this aim, as a control condition, we modified the TOPOSO algorithm to only use the voltage of the EEG of the target site for detecting state transitions. We used this modified single-channel algorithm to detect transitions into UP-/DOWN-states in the same pre-recorded EEG data. Fig. 3. Event-related EEG activity relative to the detection of the transition (t = 0) into a local UP-state for each of the twelve target sites (color coded). Left panel: event-related potential (μV) at the target site; middle panel: correlation of the EEG with the template map; right panel: global field power (GFP in μV) of the EEG. The ERP and the correlation with the template map reveal a similar prediction for each of the twelve target sites. Grey shades mark the time window (100 ms -300 ms post transition) used for the analysis of the peak EEG.

Test sample
The algorithm was tested on stage NREM3 sleep obtained from an additional set of pre-recorded EEG data that had not been used to generate the template maps of target states (see chapter 2.3.2). This data has been collected during an afternoon nap in a previously unreported sample of N = 21 (age = 18-28, M ± SD = 21.8 ± 2.6; 17 (81%) female) mentally and physically healthy participants. All participants were right-handed. Participants were subjected to the same study protocol as the participants of the data used for template generation ( Züst et al., 2019 ).

Procedure 3.1.2.1. Simulation of real-time detection of state transitions.
We preprocessed the pre-recorded EEG data to match the data as it would be processed in real-time (de-trending, re-referencing to global average) and then applied the algorithm to all NREM3 segments of all data sets. This procedure was performed separately for each of the 12 selected target sites and for UP-vs. DOWN-states. All time points where the TOPOSO algorithm detected a transition into the specific UP-/DOWN-state were marked for later analysis. The TOPOSO algorithm tended to repeatedly detect the transition into the same state across multiple subsequent time points. Only the first time point of such sequences was selected for analysis. Any additionally marked events within the next 800 ms were discarded (duration of a fast slow oscillation at 1.2 Hz) to avoid repeatedly sampling the same events.
To assess how the TOPOSO algorithm performs compared to conventional algorithms that only use a single EEG channel (without topographic information) for detecting UP-/DOWN-states, we further ran simulations with a modified version of our algorithm that only uses the voltage of the target site for detecting state transitions. In this modified single-channel approach, only conditions C and D (see 2.2 Formal description of the algorithm ) had to be fulfilled for detecting a transition. We performed the same simulations (detection of UP-/DOWN-states at 12 selected target sites) as with the original version of our algorithm and compared the EEG between transitions detected between simulations. The same values were used for the criteria C 1 and C 2 for the TOPOSO algorithm and for the single-channel approach.

Analysis of the detected state transitions.
For each detected transition, we extracted the event-related EEG centered around + /-1 s of the transition. We computed the mean event-related potential (ERP), the mean correlation between the single-trial EEG and the template map, as well as the global field power (GFP; i.e., the spatial standard deviation at each sample ( Skrandies, 1990 )) of the trial-averaged ERP separately for each participant and each condition (UP-/DOWN-state and each site). These analyses were performed on bandpass filtered EEG signals (0.3 -35 Hz). No further preprocessing was done. Fig. 3 illustrates the grand averages across all participants for these three parameters for transitions into UP-states separately for each target site.

Successful detection of transitions into local UP-/DOWN-states
Visual inspection of ERP topographies revealed that the TOPOSO algorithm indeed detects transitions into the targeted local state ( Fig. 2 ; due to space limitations, figures only illustrate the results of UP-state targets. Results are reported for both, UP-and DOWN-state targets, in the text. Supplementary Figures 1-3 illustrate the results of DOWN-state targets).
The time courses of the EEG, the GFP of the mean EEG and the correlation between EEG and template map indicate that the target state peaked at about 200 ms after the detected transition ( Fig. 3 , Supplementary Figure 2 for DOWN-states). Interestingly, the transition was preceded by voltage distributions exactly opposing the target state. I.e., if the target state was a local peak, the detected transitions into this local peak were preceded by a local trough at the same target region at about -200 ms before the transition ( Fig. 3 , Supplementary Figure 2 for DOWN-states). Furthermore, the half-wave which followed the detected transition and which peaked at the target site lasted on average about 500 ms, indicating that the detected events are parts of oscillatory activity with a frequency of 1 Hz. Taken together, these observations provide strong evidence that the TOPOSO algorithm responds to events that represent UP-and DOWN-states of slow oscillations.
For both, the single-channel algorithm and the TOPOSO algorithm, statistical assessment of the mean response over a 200 ms time window between 0.1 and 0.3 s following the detection of transition revealed that the mean ERP of the corresponding target channel differed significantly from 0. This was the case for DOWN-state targets as well as for UP-state targets. The same pattern was found for the mean correlation between the EEG scalp map and the template map (all t(20) > 13, all p < .001).

Higher topographic precision than single-channel algorithm
The TOPOSO algorithm is more selective and more precise in predicting the targeted brain states than an algorithm that operates on the voltage of single, local EEG channels. This was suggested by direct comparisons of transitions detected with the TOPOSO algorithm vs. the modified algorithm that is based exclusively on the voltage of local EEG channels ( Fig. 4 , Supplementary Figure 3 for DOWN-states). The TOPOSO algorithm detected significantly fewer transitions into UP-/DOWN-states, but the UP-/DOWN-states that followed the transitions had higher amplitudes at the target site, stronger correlations with the target templates, and higher GFP compared to states that followed transitions detected with the EEG (all paired-sample t-tests: t(20) > 3.4, p < 0.003). ERPs, correlations, and the GFP averaged over the time from 100 to 300 ms post transition were compared separately for each state Fig. 4. Comparison between the template-based TOPOSO algorithm (TOPOSO) and a single-EEG-channel-based (single channel only: SC-only) algorithm for UP-state targeting. Mean voltage (ERP in μV) at the target site (mean over adjacent electrodes), correlation between EEG scalp map and template map, and global field power (GFP in μV), all averaged across the time window from 0.1. to 0.3 s after detection of a transition; number of predicted states per minute (UP-states/min). Each panel displays mean and standard error of the mean (error bars) for each target site. All paired-samples contrasts for each target were significant at p < .003.
(UP/DOWN) and each target site. The increased average GFP suggests that scalp maps of single detected events were on average more similar to each other, i.e. they were more homogeneous across detections, leading to a stronger electric field in the average ERP. The elevated correlations suggest that these maps were also more similar to the target state.
It is possible that TOPOSO and the single-channel algorithm differed with respect to the exact time-point at which targeted UP-/DOWN-states would peak. To assess whether such differences in timing could account for the observed differences in mean amplitude, we further extracted the peak amplitudes averaged from a time-window centered around the exact peak times of each target site and state for both algorithms. We replicated the original finding that peak amplitudes were larger for TOPOSO than for the single-channel based approach in all but one template (all t > 5.5 and all p < 0.001, except for T8: t = 1.17, p = 0.25). This strongly suggests that the reported differences between TOPOSO and the singlechannel approach were a result of higher topographic precision and consistency of TOPOSO, rather than differences in temporal precision or in the timing of peaks.

Discussion
We assessed whether our newly proposed TOPOSO algorithm could be used in real-time to predict and target stimulation at UP-and DOWNstates of local slow oscillations during sleep. To this aim, we performed simulations on pre-recorded EEG data in which we used our algorithm to target local UP-and DOWN-states over 12 different sites on the scalp.
We found that the TOPOSO algorithm detects transitions into brain states with scalp maps that are highly similar to the template maps of the targeted UP-/DOWN-states, and that are highly distinct from nontargeted templates ( Fig. 2 , Supplementary Figure 1 for DOWN-states). Importantly, these brain states peak at about 200 ms after detection of the transitions, which would provide enough time to trigger stimulation during the target state in real-time applications. The targeted brain-states have a duration of about 500 ms, which reflects half-waves of oscillatory events with a duration of ∼ 1 s or a frequency of ∼ 1 Hz, i.e. the frequency of human slow oscillations ( Achermann & Borbély, 1997 ). Hence the TOPOSO algorithm appears suitable for real-time applications targeting local slow oscillations during sleep.
In comparison to a single-channel based algorithm, the TOPOSO algorithm detects fewer transitions into target states, but the detected states are more homogeneous and more similar to the targeted states with respect to their scalp maps. Thus, due to its topographic specificity, the TOPOSO algorithm might be more suitable than conventional algorithms for closed-loop applications aimed at targeting local slow oscillations.
Whether TOPOSO generally outperforms conventional singlechannel based approaches with respect to topographic specificity and sensitivity remains to be tested. Here, we compared TOPOSO to a custom-made, single-channel based approach that exactly matches the computations of the TOPOSO algorithm except for the use of topographic information. This was done to demonstrate that adding topographic information improves topographic precision. We did not compare TOPOSO with the best possible versions of currently available single channel algorithms. It is possible that the topographic specificity of conventional, single-channel based algorithms could be improved to match the performance of TOPOSO. This might be achieved by applying more stringent selection criteria for detecting slow oscillations in the single-channel time series that is obtained from the site of interest. For example, the threshold that the amplitude of events in the single channel must exceed to qualify as slow oscillations could be increased. This might lead to the targeting of fewer, but more homogeneous local slow oscillations. Also, ensuring the presence of harmonic oscillations in the frequency of interest -for example by means of sine-wave fitting ( Cox et al., 2014 ) -might prevent the false targeting of nonoscillatory noise and artifacts. Finally, increasing phase accuracy, i.e., the precision at which the phase of interest (UP-vs. DOWN-state) is targeted in the single-channel data via the use of a phase-locked loop (PLL; Santostasi et al., 2016 ) could improve homogeneity of stimulation.
While conventional single-channel approaches might be tailored to match the topographic precision of TOPOSO, the strength of our algorithm lies in its theoretical foundation. TOPOSO builds on the broadly accepted assumption that recurring and temporarily quasi stable scalp maps -such as the local UP-and DOWN-states targeted here -reflect specific brain states that can be attributed to specific neuronal processes in well-described cortical sites or networks ( Michel & Koenig, 2018 ). Using real-time analyses of the temporal evolution of the entire electric field on the scalp instead of the voltage in only one channel seems much more valid for targeting such states. A further advantage of TOPOSO is the fact that it does not depend on explicit definitions of amplitude thresholds for detecting slow oscillations. This makes it suitable for targeting low-amplitude slow oscillations as they occur in REM sleep, during wakefulness ( Andrillon et al., 2021 ), or in SWS of the elderly ( Wunderlin et al., 2022 ).

Validation in a real-time application
To assess the usefulness of the TOPOSO algorithm in a real closedloop stimulation application, we performed a within-subject sham controlled study in which we tried to target UP-states of local slow oscillations over three distinct sites on the scalp. We tested whether the TOPOSO algorithm can be used in vivo in real-time for targeting auditory stimulation at local UP-states. The goal was to assess how precise the TOPOSO algorithm is at targeting local slow oscillations at the intended phase, i.e. the UP-state. A further aim was to investigate the immediate impact of auditory stimulation on the targeted local UP-state, and to assess the influence of auditory stimulation on ensuing slow oscillatory and spindle activity, i.e. whether stimulation would be followed by additional local slow oscillations and local spindles at the targeted site.
Local UP-states were targeted over the frontal (Fz), right central (C4), and centro-parietal (CPz) cortex in a within-subject sham-controlled study design. The frontal cortex was selected because the majority of slow oscillations tend to originate in prefrontal regions ( Finelli et al., 2001 ;Nir et al., 2011 ), because frontal slow oscillations have been proposed to be most relevant in memory consolidation ( Klinzing et al., 2019 ;Ngo, Martinetz, et al., 2013 ), because frontal slow oscillations tend to govern sensory processing and even learning during sleep ( Andrillon et al., 2016 ;Züst et al., 2019 ), and because most studies using phase-targeted closed-loop auditory stimulation focused on this region ( Cox et al., 2014 ;Göldi et al., 2019 ;Ngo, Claussen, et al., 2013 ;Ngo et al., 2015 ;Ngo, Martinetz, et al., 2013 ;Santostasi et al., 2016 ;Shimizu et al., 2018 ). The right-central electrode C4 was chosen due to its proximity to the sensorimotor cortex. Fattinger et al. reported that auditory stimulation targeted at the DOWN-state of slow oscillations detected over the left motor cortex (electrode C3) perturbed local but not global slow oscillatory activity at the targeted site ( Fattinger et al., 2017 ). Importantly, perturbation of local slow oscillations was associated with impaired performance in a right-hand motor learning on the next day. Krugliakova et al. further suggested that UP-state targeted stimulation focusing on slow oscillations over the right motor cortex (C4) globally enhanced delta, theta, and sigma activity but also induced local changes in delta-sigma coupling in the right hemisphere ( Krugliakova et al., 2020 ). These studies provide first evidence that local manipulation of sleep slow oscillations in the motor cortex is feasible and alters the local functions of sleep. The centro-parietal electrode CPz was selected because slow oscillations over this cortical region have been associated with absence of dreams during NREM sleep. Two studies investigating dreaming during NREM sleep revealed that humans are less likely to report dreams if wakened from NREM sleep that is dominated by high slow-wave activity over centroparietal regions ( Siclari et al., 2017. Targeting and manipulating slow oscillations over these regions might thus provide a means to alter the frequency, vividness, or even content of dreams during NREM sleep.

Implementation of the algorithm
Data was recorded using the BrainVision Recorder software v2.0 by Brain Products. This software provides a remote data access (RDA) server that allows streaming data in realtime (in 5-sample data blocks) via TCP/IP protocol.
The TOPOSO algorithm was implemented in MATLAB® and was running on a second computer that was connected to the recording computer via LAN cable. On this second computer, the "rda2ft " interface provided by fieldtrip ( Oostenveld et al., 2011 ) streamed the real-time data to a buffer, from which it was read into a MATLAB® instance which was running the detection algorithm. The TOPOSO algorithm continuously scanned the buffer for new data, and performed the necessary operations to detect transitions into UP-states of interest. Upon every detection of a transition, an event marker was written to a second fieldtrip buffer. A second MATLAB® instance monitored this second buffer in realtime and triggered stimulation according to the current condition (stimulation vs. sham, with the respective target site and their specific delay). Sound onset and the EEG-marker were timely paired. Unfortunately, the EEG recording system did not allow to eliminate all time jitters, with which a jitter of up to 40 ms remained.
Stimulation was carried out in blocks, i.e. stimulation targeted the same site (Fz, C4, CPz, sham) five times in sequence before moving to the next site. Once five stimulations were applied for the specific template (5 for each template in sham), or if more than 2 minutes passed without stimulation, the algorithm moved on to the next block. All 4 blocks were repeated for as long as possible, with shuffled block order for each repetition ( Fig. 5 ). This procedure ensured that a similar amount of stimulations was achieved for each condition within each participant independent of the absolute amount of stimulations. The auditory stimulus was a burst of pink 1/f noise of 50 ms duration, with a rising and falling ramp of 5 ms ( Ngo, Martinetz, et al., 2013 ). No sound was presented in the sham condition .
Each stimulus presentation was followed by a timeout of 2 s before the next sound could be played. Hence, the shortest possible time interval between consecutive stimulations was 2 s. This allowed for an unconfounded analysis of the impact of stimulation on the targeted slow oscillation UP-state and the ensuing slow oscillatory activity.
The average loop time, i.e. the time it took the TOPOSO algorithm to analyze the EEG data, detect a target event, and trigger stimulus presentation, was 98 ± 19 ms (M ± SD; for a detailed description of the loop time assessment, please see Supplementary Methods). Because the algorithm detected transitions into UP-or DOWN-states that peak about 200 ms after this transition, an additional delay of ∼ 100 ms was added to the loop time of 98 ms before playing the click noise to hit the peak of the target state. Importantly, the average delay between the transition time point and the actual UP-state peak seemed to vary between target sites. Simulations performed on the N = 21 pre-recorded datasets suggested that the average delay was 200 ms for Fz, 180 ms for C4, and 215 ms for CPz. Therefore a delay of 100 ms for Fz, 80 ms for C4, and 115 ms for CPz was added to the loop time of 98 ms before playing the click noise.

Data collection 4.1.2.3. Participants.
Twenty mentally and physically healthy subjects were recruited to participate in this study. The research protocol was approved by the institutional review board of the University of Bern, and informed consent was obtained from each participant. Eight participants failed to reach stable slow-wave sleep during the afternoon nap, leading to twelve remaining participants in the study (age = 23-31, M ± SD = 26.75 ± 2.45, 6 (50%) female).

Procedure.
A short prescreening was performed during recruiting to exclude candidates with mental or physical health issues from participation. Participants were asked to sleep not more than 4 hours in the night prior to the experiment and to send a text message at the time they went to bed and at the time they got up to confirm compliance. Furthermore, participants were asked to abstain from caffeine on the day of testing until after the sleep recording. Participants arrived at the lab between noon and 2 pm, where the study procedure was explained and they were asked to give informed written consent. Participants were outfitted with EEG caps and with in-ear headphones (Pioneer, type SE-CL502_L) and were then asked to get prepared for taking a 90 minutes nap in a portable bed in the electromagnetically and acoustically shielded EEG cabin. Before lights were turned off and participants were allowed to sleep, a hearing test was administered. In this test, short beeps and tones were played at random intervals and Fig. 5. Illustration of blocks of auditory stimulations targeting UP-states over different sites on the scalp (Fz, C4, CPz). Stimulation condition (Fz/C4/CPz) was switched after 5 successful stimulations in a given condition or if no stimulations occurred in more than 120 s. randomly on the left or right ear. Participants indicated on which ear they heard a tone by pressing the according buttons on a keyboard. Four different types of beeps of 50 ms duration were presented: a pink noise tone, and pure tones with a frequency of 500 Hz, 1000 Hz and 2000 Hz. Overall, 20 beeps in symmetrical steps between 15 and 45 dB(A) per frequency and per ear, leading to an overall number of 160 beeps, were presented. The hearing test was implemented with the software Presentation®. After the hearing test, the keyboard was removed and participants were asked to relax and, if possible, sleep. Participants were informed that a click-sound similar to the pink noise played during the hearing test would be presented during sleep. It was mentioned that stimulation only occurs during deep sleep and they therefore should not aim to hear anything, because focusing on pending auditory stimuli might hamper sleep quality. Afternoon naps started between 2 pm and 4 pm, and lasted about 85 min (M = 85.5, SD = 21.6). When participants displayed stable NREM2 with visible slow-wave activity, the experimenter initiated auditory stimulation. Stimulation was started in NREM2 sleep, for multiple reasons: First, online rating of sleep stages can be challenging due to interindividual differences and we wanted to avoid missing opportunities for stimulation due to a misclassification of the current sleep phase. Second, the TOPOSO algorithm usually only stimulates if slow wave activity is present in the EEG. Thus, running the algorithm does not lead to random stimulations if a participant does not display slow waves. Third, we knew from piloting and from experience with our previous studies ( Ruch et al., 2014 ;Züst et al., 2019 ) that auditory stimulation often enhances early slow wave activity and facilitates the progression into SWS. Finally, the initial stimulus intensity was below the participant's hearing threshold but was increased within the first 10 -20 stimulations. Stimulus presentation was stopped if the EEG revealed signs of arousal. When a subject returned to stable NREM2 sleep, auditory stimulation was resumed, typically starting with a ramp up of the signal intensity over the first 5 -10 stimulations. If a participant failed to (re-)enter stable NREM2 sleep after 80 mins, the EEG recording was stopped. Only participants with at least 10 valid stimulations per condition were included in the data analysis (n = 12).
To avoid that highly artifact laden or broken EEG channels could corrupt the temporal and topographic precision of TOPOSO, the experimenter constantly monitored the realtime data of all EEG channels, displayed on the recording computer (continuously updated overview of the most recent 30 s of data). This allowed identifying artifact laden or broken EEG channels. If the signal quality of a specific channel was constantly low, the experimenter excluded this channel from real time analysis via the user interface of TOPOSO (MATLAB® instance one). The experimenter further continuously monitored the user interface of TOPOSO. The interface displayed a continuously updated 20 s overview of the time series of the realtime EEG signal of the target site (average signal of all relevant channels) and of the correlation between EEG scalp maps and the template map. The interface further provided visual markers which indicated when TOPOSO had detected a target UP-state within the displayed time series. The experimenter thus could interrupt stimulation when either of the time series (realtime EEG, or correlation between EEG maps and template map) showed unusual patterns, or when the time points that were marked as UP-states did not align with peaks in these time series.
4.1.2.5. EEG/Polysomnography. EEG was recorded using 64 channel BrainCaps MR caps with sintered Ag/AgCl Multitrodes by EASYCAP ( www.easycap.de ) and two 32 channel amplifiers from BrainAmp ( www.brainproducts.com ). Two channels were used to assess eye movements, and one channel was used to assess the muscle tonus below the chin. The reference electrode was positioned at Fz, and the ground electrode at CPz. Impedances were kept < 20 k. The software BrainVision Recorder ( www.brainproducts.com ) was used to record the EEG data. All signals were sampled at 500 Hz. Online polysomnographic visualization was performed according to AASM guidelines using the OpenViBE environment ( Renard et al., 2010 ).

Data analysis 4.1.3.6. Offline sleep-scoring.
Offline sleep scoring was performed by two independent raters, according to AASM guidelines, using the software Polyman ( http://www.edfplus.info/ ). With a Cohen's K of .76, the rater agreement was substantial ( McHugh, 2012 ). For stimulus inclusion, only the distinction between deep NREM (NREM2, NREM3) and all other sleep stages (awake, NREM1, REM) was of interest. In 12 of 3569 epochs (0.34 %), the raters disagreed in a way that was potentially relevant for the inclusion of stimuli. In those 12 epochs, the score indicating the shallower sleep stage was used.

EEG pre-processing.
After removing EOG and EMG channels from the raw data, all EEG channels were re-referenced to the common average. Next, the 50 Hz line noise and its harmonics was removed, and bad channels were identified and interpolated using the PREP pipeline ( Bigdely-Shamlo et al., 2015 ) as implemented in eeglab ( Delorme & Makeig, 2004 ). The cleaned EEG data was then again referenced to the global average and was bandpass filtered between 0.25 and 100 Hz.
Artifact laden data segments were identified and marked for later exclusion, using a semi-automated algorithm that was implemented in the fieldtrip toolbox ( Oostenveld et al., 2011 ). Artifacts were identified based on high-frequency noise (if the boxcar-smoothed (window: 0.2 s) envelope of the 45-90 Hz frequency band exceeded 5 standard deviations in any of the channels), signal jumps (if the change in amplitude between two consecutive samples exceeded 30 standard deviations in any of channel), rogue channels, e.g. due to sweating (if the minimal difference in voltage of any channel with all other channels exceeded 4 standard deviations), and de-correlated signals (if the difference between the actual data in a channel and its spherical interpolation exceeded 4 standard deviations). Artifacts were padded by 0.5 s at both ends. The validity of this artifact detection pipeline was confirmed by visual inspection.
Finally, EEG data was epoched from 2 s before to 2 s after stimulus onset for further analysis. For each epoch, the time-course of the correlation between EEG scalp maps and template maps of the respective condition was computed for additional analyses.

Phase analysis.
To assess the accuracy of stimulation, the mean phase of the slow oscillation frequency band ( < 4 Hz) was estimated for the time of stimulus onset. To this aim, the phase values of the Hilbert transform of the low-pass filtered (4 Hz) signal was extracted. The phase across all samples from 20 ms before to 20 ms after stimulus onset were averaged for each trial. This was done separately for the average signal of the respective target EEG channels as well as of the correlation between the EEG and the template map. Then, the mean phase for each experimental condition was computed separately for each participant.

Current source density estimation.
Analyses of the poststimulus ERP, the time-frequency decomposed signal, the post-stimulus power spectral density, and the post-stimulus phase-amplitude coupling were performed on current source density (CSD) estimates. CSD has the benefit that it provides a reference free signal with enhanced spatial resolution and specificity ( Kayser & Tenke, 2015 ) compared to the raw EEG. CSD was estimated using the spherical spline method ( Perrin et al., 1989( Perrin et al., , 1990 with default parameters as implemented in the fieldtrip toolbox ( Oostenveld et al., 2011 ) for MATLAB®.

Time-frequency analysis.
Event-related spectral changes were compared between the different experimental conditions. To this aim, the spectral power was estimated from 2 Hz to 21 Hz at 1 Hz steps from 2 seconds before to 2 seconds after stimulus (40 ms steps, yielding a 25 Hz sampling rate) using discrete wavelet transformations. Transformations were performed with 3 wavelet cycles at the lowest frequency and a linear increase of 0.5 cycles per 1 Hz step to 12.5 cycles at the highest frequency. The resulting power time series were normalized for each frequency at the single-trial level by first z-standardizing the time-series at each frequency and then subtracting the mean normalized power from -2 to -1 seconds before stimulus onset. These standardized time-frequency decompositions were then averaged within each condition separately for each participant.

Analysis of phase-amplitude coupling.
Post-stimulus phaseamplitude coupling (PAC) comodulograms were compared between experimental conditions for the phase of frequencies from 0.6 to 5 Hz (at 0.2 Hz steps) and the amplitude of frequencies between 4 and 40 Hz (at 1 Hz steps). De-biased PAC values as suggested by van Driel et al. ( van Driel et al., 2015 ) were computed for each phase-amplitude combination.
Phase values and amplitude envelopes were extracted for the data from 0 to 2 s after stimulus onset at 20 ms intervals (yielding a 50 Hz sampling rate) using discrete wavelet transformations. For phases, transformations were performed with one cycle at the lowest frequency of 0.6 Hz and a linear increase of 0.2 cycles per 0.2 Hz step to 5.4 cycles at the highest frequency of 5 Hz. For amplitudes, transformations were performed using 3 cycles at the lowest frequency of 4 Hz with a linear increase of 0.5 cycles per 1 Hz step to 21 cycles at the highest frequency Table 3 Mean phase & 95% CI at stimulus onset (stimulation and sham) for the EEG at the target site and the for the correlation between EEG scalp maps and the template map, separately for each target site. of 40 Hz. The resulting PAC comodulograms were averaged within each condition separately for each subject.
4.1.3.13. Significance testing. For each dependent measure (ERP, timefrequency decomposition, and phase amplitude coupling), the impact of stimulation vs. sham was assessed separately for each target condition. Furthermore, the differential effects of frontal vs. right central vs. centro-parietal targeted stimulation were assessed by comparing the difference scores between stimulation vs. sham between all target sites using an omnibus test. Follow-up contrasts were performed between each target site in case the omnibus test yielded a significant difference. For the analysis of event-related potentials, topographic analyses of variance (TANOVA) were performed as proposed by Koenig and colleagues ( Koenig et al., 2011( Koenig et al., , 2013. Cluster-based corrections for multiple comparisons in time were performed using 1000 permutations. For all other analyses, mass univariate analyses (t-tests or ANOVAs) were performed with cluster-based corrections for multiple comparisons using 1000 permutations ( Maris & Oostenveld, 2007 ). Cluster-formation threshold was set at p < .05 for all analyses. All tests were two-sided, clusters were said to be significant at alpha < .05.

Precise targeting of the peak phase
First, we assessed how precise the TOPOSO algorithm was at targeting the peak phase, i.e. the peak of the respective local UP-states. We extracted the mean slow-wave phase ( < 4 Hz) for the ERP over the site of interest, as well as for the time-course of the correlation between the scalp map and the template map ( Fig. 6 ).
Phase distributions were significantly non-uniform for both the ERP and correlation with the template maps for all targets (all p < .01, Hodges-Ajne omnibus-tests ( Zar, 1999 ) as implemented in the Circ-Stat toolbox ( Berens, 2009 )). This suggests that the algorithm consistently targeted a specific phase. Stimulation preceded the peak by ∼30° (  Table 3 and Fig. 6 ) in all target conditions, both for the ERP and the correlation with the template map. See Table 3 for mean phases and 95% confidence intervals of the phase (confidence intervals were computed as suggested by ( Zar, 1999 ) and as implemented in the CircStat Toolbox ( Berens, 2009 ) for MATLAB®).

Stimulation temporarily enhances the targeted local UP-state
Previous studies suggest that closed-loop auditory stimulation targeting frontal UP-states briefly enhances the amplitude of the targeted state before inducing a frontal DOWN-state (e.g. Ngo et al., 2015 ;Ngo, Martinetz, et al., 2013 ). Here, we investigated whether this phenomenon can also be observed when non-frontal UP-states are targeted. To this aim, the following parameters were extracted for the first 200 ms following stimulus onset separately for each target site and state for each participant: mean amplitude at the target electrode averaged across all single trials, mean of the global field power of each single trial, topographic consistency reflecting the mean correlation between scalp maps of single trials and the average scalp map of these trials ( Koenig & Melie-García, 2010 ), as well as the mean correlation between the scalp EEG and the template maps ( Fig. 7 ). All but one parameter were significantly elevated after stimulation vs. sham for all target sites (all p < .035, except for the template correlation at CPz: p = .223). The fact that the Fig. 6. Slow oscillation phase at stimulation onset estimated for the EEG at the target site and for the time-course of the correlation between EEG scalp maps and template maps. Upper row (Target EEG): Roseplots of phase of the target ERP with mean phase of each subject at the target site (red), mean phase across all subjects at target site (dark grey; vector-length = phase-coherence), 95% confidence interval around the group mean (light grey). Lower row (Template Correlation): Roseplots of phase of the template correlation with mean phase of each subject at the target site (red), mean phase across all subjects at target site (dark grey; vector-length = phase-coherence), 95% confidence interval around mean (light grey). The rightmost column illustrates the correspondence between phase angle and slow oscillation states. The targeted UP-state is at 0°/360°. Fig. 7. EEG response to stimulation vs. sham: a) mean voltage (ERP in μV), b) correlation of EEG maps with the template map (Template-corr), c) global field power (field strength in μV), and d) the consistency of targeted maps (Topo. consistency) averaged across the first 200 ms post stimulus onset separately for each target condition (Fz, C4, CPz) and for stimulation vs. sham. All parameters except one were significantly increased after stimulation compared to sham for all target sites (all p < .035, except for the template correlation at CPz: p = .223).
algorithm precisely targeted states with specific voltage distributions (see previous chapter) and the finding that stimulation vs. sham enhanced not only the voltage at the target electrode, but the strength of the electric field (GFP) and the correlation between the scalp EEG and the respective template maps strongly suggest that auditory stimulation briefly enhanced the the targeted local UP-state.

Local stimulation induces a stereotypical auditory evoked slow oscillatory potential
Visual inspection of the temporal evolution of scalp maps ( Fig. 8 , bottom panel) and of the voltage of single channels for each experimental condition ( Fig. 8 , top panel) suggested that highly distinct states were targeted at stimulus onset (stimulation and sham condition), but that auditory stimulation vs. sham induced a stereotypical auditory evoked slow oscillatory potential. Stimulation in each condition was followed by a frontal DOWN-state at about 0.5 s and a frontal UP-state at about 1 s after stimulus onset.
To address whether stimulation had a significant impact on the EEG response within each of the stimulation conditions (Fz, C4, CPz), TANOVAs contrasting CSD estimates for stimulation vs. sham were performed. These analyses confirmed that stimulation induced distinct scalp maps starting from 0.28 s up to 1.89 s following stimulation onset for each template (Fz: 0.28-1.65 s, C4: 0.32-1.89 s, CPz: 0.37-1.7s, all p = .003) compared to sham.
Importantly, no interactions between targets and stimulation vs. sham were observed, i.e. the stimulation induced changes did not significantly differ between target sites. This was suggested by the fact that the omnibus TANOVA with the factor target (Fz vs. C4 vs. CPz) performed on the difference between stimulation vs. sham yielded no significant cluster. This suggests that stimulation induced a similar slow oscillatory pattern irrespective of the target site.
Note that Fig. 8 illustrates the results for ERPs computed on EEG data, even though statistics were performed on ERPs for CSD estimates. EEG data instead of CSD data are plotted because this allows direct com- Fig. 8. Event-related responses (ERPs) to stimulation vs. sham; Upper panels: ERP over target electrodes (left) and over frontal electrodes (right) for all target sites (Fz, C4, Cpz) and conditions (stimulation vs. sham). The small inset subplots provide the difference waveforms for stimulation vs. sham for each target site. The scalp maps illustrate the electrodes for which ERPs are plotted. The color code represents the target condition (red: Fz, green: C4, blue: CPz); Center panel: global field power (gfp) of the grand average of the ERPs for all target sites and conditions. Global field power shows a stronger peak for stimulation vs. sham immediately after stimulus onset (t = 0.1 s) as well as strong induced responses about 0.5 s, 1 s, and 1.5 s after stimulation vs. sham. Lower panel: scalp maps for all target sites and conditions; Scalp maps confirm successful targeting of the target states (left column, normalized units) at stimulus onset (t = 0 s; highlighted at t = 0.1 s). Scalp maps further suggest that stimulation but not sham was followed by a stereotypical auditory evoked slow oscillatory potential with a DOWN-state at t = 0.5 s, and an UP-state at 1 s after stimulus onset. The EEG was averaged across + /-50 ms for each depicted time-point. parison between scalp maps of the actual data and template maps of the target states. Furthermore, plotting EEG data instead of CSD data facilitates comparability between our findings and findings of previous studies on local slow oscillations (e.g. Fattinger et al., 2017 ). The same figure with CSD instead of EEG data is provided in the supplements (Supplementary Figure 4). The qualitative pattern of results was highly similar between EEG and CSD data.

Stimulation induces a spindle
Event-related time-frequency analyses on CSD estimates revealed that click noise stimulation induced significant increases in theta activity at about 0.5 s and in spindle activity at about 1 s following stimulation onset in all conditions (sig. cluster for Fz ranging from -0.04 to 1.3 s for 2-21 Hz, p = .002; two clusters for CPz ranging from -0.04 to 1.92 s, 2-22 Hz, both p < .012; two clusters for CPz ranging from 0.08 to 1.52 s, 2-21 Hz, both p < .014; Fig. 9 ). An ANOVA comparing the effect of stimulation vs. sham between target conditions yielded no significant cluster. This suggests that stimulation induced similar spectral changes across all three target sites.

Stimulation enhances post-stimulus phase-amplitude coupling
Post-stimulus coupling between the phase of slow oscillations and the amplitudes of higher frequencies was enhanced for stimulation vs. sham for all three target sites (p < .018; Fig. 10 ). For Fz, coupling was significantly enhanced for two clusters encompassing the phase of frequencies between 0.6 and 3.2 Hz and the amplitude for frequencies between 4-10 Hz (p = .018) and 12-19 Hz (p = .004). For C4, coupling was enhanced between phases for 0.4-3.6 Hz and amplitudes for 4-20 Hz (p = .002). For CPz, coupling was enhanced for phases between 0.6-3.8 Hz and amplitudes from 4-19 Hz (p = .002). Enhanced phase-amplitude coupling following stimulation vs. sham is trivial in that it was probably caused by the overall increase in activity in the slow oscillation, theta, and spindle bands that was induced by stimulation. Similar increases in phase-amplitude coupling would be expected for any kind of auditory stimulation, whether stimulation is phase-targeted or random.
Importantly, the enhanced phase-amplitude coupling following stimulation was not significantly different between target sites. An ANOVA with the factor target site (Fz, C4, CPz) performed on the difference between stimulation vs. sham yielded no significant clusters. This suggests that stimulation induced similar changes in cross-spectral interactions across all three target sites.

General discussion
We present a new closed-loop stimulation algorithm that allows targeting local, EEG-defined slow oscillation UP-and DOWN-states of human slow-wave sleep: the topographic targeting of slow oscillations algorithm (TOPOSO). The algorithm detects transitions into upcoming local UP-and DOWN-states based on the temporal evolution of the similarity between topographic maps of the real-time EEG and predefined template maps of the target states. In simulations on pre-recorded EEG data, the TOPOSO algorithm successfully targeted slow oscillatory UPand DOWN-states at 12 distinct target sites with high temporal precision and topographic specificity. Importantly, the algorithm targeted UP-and DOWN states with higher topographic precision than an approach which only operated on the voltage of a single EEG channel. As a consequence, the TOPOSO algorithm targeted fewer, but topographically more homogeneous states. A within-subject sham controlled nap-study with three different target sites (Frontal (Fz), Right Central (C4), Centro-Parietal (Cpz)) confirmed that the algorithm allows targeting stimulation at local UP-states over different sites on the scalp in real time in vivo. The TOPOSO algorithm thus opens up a field of new opportunities by allowing researchers and clinicians to target and modulate local slow oscillations in humans using any kind of stimulation.
The high topographic specificity of the TOPOSO algorithm could help improve the efficacy of existing sleep modulation applications. Cur-rent applications successfully use slow oscillation phase-targeted sensory stimulation to enhance SWS and to thereby improve the associated memory ( Ngo, Martinetz, et al., 2013 ;Ong et al., 2016Ong et al., , 2018, immune ( Besedovsky et al., 2017 ;Grimaldi et al., 2019 ), and endocrine functions , to boost consolidation of specific memories during sleep ( Göldi et al., 2019 ;Shimizu et al., 2018 ), and to alter plasticity in the motor cortex ( Fattinger et al., 2017 ). All these applications build on conventional closed-loop stimulation approaches which only operate on the voltage of single EEG channels and therefore target slow oscillations with heterogeneous topographies. Importantly, the topography of an electric field on the scalp mirrors the predominating neuronal network activity in the brain ( Michel & Koenig, 2018 ;Zanesco, 2020 ), i.e. the current global brain state. Due to its high specificity regarding both, the phase of slow oscillations, and the topography of the targeted electric field, the TOPOSO algorithm ensures that stimulation always targets a similar brain state. This was also suggested by a recent simulation study ( Wunderlin et al., 2022 ) which directly contrasted the performance of a modified version of the TOPOSO algorithm with the performance of the single-channel based algorithm that was developed by Ngo and colleagues ( Ngo, Martinetz, et al., 2013 ). In this study, TOPOSO targeted fontal slow oscillations with higher spatiotemporal precision compared to the conventional approach ( Wunderlin et al., 2022 ). This was observed in data obtained from elderly participants who generally show reduced slow-wave activity. Using TOPOSO instead of or in combination with conventional closed-loop algorithms could thus improve the impact of existing sleep modulation applications by a) ensuring that stimulation always targets the relevant brain state, and by b) reducing unwanted side effects induced by incorrect modulation of non-target states.
The TOPOSO algorithm could further be used to modulate slowoscillatory activity outside of NREM sleep. Although slow oscillations are a defining feature of SWS ( Iber et al., 2007 ), similar oscillations can occur in rapid eye movement (REM) sleep  and even during wakefulness ( Andrillon et al., 2021 ;Avvenuti et al., 2021 ;Brokaw et al., 2016 ;Frohlich et al., 2021 ;Sattari et al., 2019 ). Importantly, slow oscillations in the awake brain are a sign of reduced attention ( Andrillon et al., 2021 ) and alertness ( Quercia et al., 2018 ). They further serve as biomarker of neuropathology after brain injury ( Cassidy et al., 2020 ;Sarasso et al., 2020 ) or in epilepsy ( Lundstrom et al., 2019 ), and they are associated with various neurological and psychiatric conditions ( Frohlich et al., 2021 ). Slowoscillatory activity in the awake brain is thus a promising target for modulation in health and disease. Unfortunately, slow oscillations have much lower amplitudes in REM sleep and during wakefulness than in SWS (e.g. Andrillon et al., 2021 ). Conventional approaches for phase targeted closed-loop stimulation may fail during REM sleep and wakefulness because they detect slow oscillations based on their high amplitudes. The TOPOSO algorithm does not depend on specific amplitude thresholds for detecting slow oscillations and further ensures that targeted UP-and DOWN-states are topographically homogeneous. Consequently, Wunderlin et al. observed that a modified version of TOPOSO was more successful than a conventional approach at targeting the lowamplitude slow oscillations in sleep recordings obtained from elderly participants ( Wunderlin et al., 2022 ). TOPOSO thus seems more suitable than conventional methods for modulating low-amplitude slow oscillations in the awake brain and in REM sleep.
Furthermore, the TOPOSO algorithm opens new ways of customizing sleep modulation to specific sub-groups of the population or to single individuals who show slow oscillations with unique topographic characteristics. In fact, the TOPOSO algorithm is able to target slow oscillations with unique topographic characteristics because it uses predefined templates of the topographies of the targeted local UP-and DOWN-states. These templates can be generated from available sleep recordings that are representative of the target population, or even from recordings of single individuals. Customizing stimulation to specific subpopulations or individuals is important because the topography Fig. 9. Comparison of event related spectral power between sham and stimulation condition for all target sites. Left: spectral power averaged across all channels (arbitrary unit); Right: topographical distribution of theta and spindle power, time window selected for high power. Cluster-based statistical analyses revealed a significant enhancement of the spectral power following stimulation compared to sham for each target site from around 0-1.5s and from 2-22 Hz (all p < .014), but these enhancements were not significantly different between target sites. of slow oscillatory activity varies substantially and systematically between groups and individuals. For example, different individuals show distinct, stable, trait-like topographic distributions of slow oscillatory activity ( Markovic et al., 2018 ). Furthermore, the topography of slow oscillations changes systematically throughout adolescence ( Kurth et al., 2010( Kurth et al., , 2012Ringli & Huber, 2011 ) and again with aging ( Landolt & Borbély, 2001 ;Sprecher et al., 2016 ). Also, some clinical populations such as patients suffering from depression ( Tesler et al., 2016 ) show altered slow oscillation topographies. Addressing these individual differences will help to increase the precision of slow oscillation target- Fig. 10. Phase amplitude coupling (PAC) for stimulation and sham for all target conditions. Left: Comodulogram averaged across all channels; Right: topographical distribution of PAC selected for delta * sigma coupling and for delta * theta coupling. Cluster-analysis revealed a significantly enhanced coupling of the phase of slow oscillations and the amplitudes of higher frequencies for stimulation vs. sham (for all three target sites, p < .018), but this enhancement was not significantly different between the target sites.
Successful modulation of local slow oscillations will ultimately depend not only on precise targeting of relevant local UP-and DOWNstates, but also on the type of stimulation that is applied. Here, we explored how auditory stimulation alters local slow oscillations during sleep. In a sham-controlled nap study, auditory click noises were targeted at UP-states detected over the frontal, right sensorimotor, and centro-parietal cortex. Stimulation briefly enhanced the specific local UP-state. In fact, the amplitude at the target site, the strength of the electrical field on the scalp, and the topographic similarity between EEG scalp maps and the template maps of the respective target states were all increased during the first 200 ms following stimulation vs. sham. Whether this brief enhancement of the targeted UP-states is sufficient for altering or improving their functions remains to be tested. Importantly, stimulation then elicited a frontal slow oscillation. For all target sites, the targeted local UP-states were followed by a frontal DOWN-state at around 500 ms and a frontal upstate at about 900 ms after stimulus onset. This frontal slow oscillation was accompanied by a temporary increase in fronto-central theta power during the DOWN-state, and by elevated fronto-central spindle-activity during the UP-state. Earlier studies investigating auditory processing during sleep suggest that such frontal slow oscillations are the stereotypical brain response to auditory stimulation during sleep ( Andrillon et al., 2016 ;Andrillon & Kouider, 2020 ;Colrain & Campbell, 2007 ;Riedner et al., 2011 ;Ruch et al., 2014 ). This is also suggested by the finding that specific targeting of local slow oscillations did not lead to a change in any of the parameters that were assessed to study the neuronal response to auditory stimulation. None of the stimulus-induced changes in electrical potentials, spectral power, or phase-amplitude coupling differed significantly between target sites. We therefore conclude that entrainment of non-frontal, local slow oscillations might not be possible with auditory stimulation. Whether the induced frontal slow-oscillation represents a general sleep-preserving function of the brain that is triggered by any kind of sensory stimulation ( Andrillon et al., 2016 ;Halász, 2016 ;Laurino et al., 2019 ), or whether the initiation of frontal slow oscillations is specifically favored by the auditory pathway ( Bellesi et al., 2014 ) is beyond the scope of this paper. Of note, our observation that only the initial early response to stimulation (during the targeted UP-state) but not the late response (induced slow oscillation) was specific to the targeted site is consistent with the findings by Laurino et al. (2019) . These authors assessed how the sleeping brain responds to stimulation in different sensory modalities (auditory, visual, tactile). They observed that the early response to stimulation is specific to the sensory modality, but that all types of stimuli then induce a modality-independent frontal slow oscillation.
Here, we speculate that optimal modulation of local slow oscillations is achieved through the use of stimulation techniques that directly alter neuronal activity within the specific cortical site of interest. Such techniques could include multisensory (e.g. audiovisual) stimulation, sensory stimulation in the specific modality of the targeted sensori-motor cortical network ( Bar et al., 2020 ;Laurino et al., 2019 ), transcutaneous electrical nerve stimulation ( Ravan & Begnaud, 2019 ;Veldman et al., 2021 ), or transcranial electrical ( Ketz et al., 2018 ), electromagnetic ( Murphy et al., 2009 ), or even ultrasound stimulation ( Fomenko et al., 2018 ). Importantly, the TOPOSO algorithm allows steering any kind of stimulation for targeting local slow oscillations.
With the appropriate type of stimulation, the TOPOSO algorithm can be used to either enhance and entrain specific local slow oscillations, or to suppress them. Both enhancement and suppression might find use in different practical applications. Enhancing local slow oscillations should increase their specific function. This could, for example, help with recovery after brain injury. Animal research indeed suggests that artificial enhancement of local slow oscillations in the peri-infarct zone after stroke boosts recovery ( Facchin et al., 2020 ). Admittedly, boosting of local slow oscillations might be more difficult to achieve than suppression. This is suggested by the finding that auditory stimulation entrained stereotypical frontal instead of local, non-frontal slow oscillations in this study. Selective suppression of specific local slow oscillations could allow studying their function in general ( Crupi et al., 2009 ;Fattinger et al., 2017 ). Perturbing specific local UP-and DOWN-states could further find use in clinical applications where pathological subtypes of slow oscillations must be suppressed. In depression, for example, frontal slow oscillatory activity tends to be enhanced during sleep ( Tesler et al., 2016 ). Suppressing these frontal slow oscillations was found to have an antidepressant effect ( Landsness et al., 2011 ). The TOPOSO algorithm could provide a means to selectively suppress frontal slow oscillations while leaving other slow oscillatory activity intact. This could provide the desired antidepressant effect while producing fewer unwanted side effects than standard sleep deprivation regimes that suppress all slow oscillatory activity ( Giedke & Schwärzler, 2002 ). The TOPOSO algorithm could further be used for suppressing pathological slow oscillations in wakefulness after brain injury ( Cassidy et al., 2020 ;Sarasso et al., 2020 ) or in epilepsy ( Lundstrom et al., 2019 ).
The TOPOSO algorithm and the presented findings are not without limitations. Most importantly, TOPOSO identifies and targets local slow oscillations merely by the voltage distribution of the electric field on the scalp, not by the true underlying neuronal activity recorded from within the brain. Whether the local UP-and DOWN-states targeted by TOPOSO truly reflect periods of high vs. low neuronal activity ( "ON " vs. "OFF "-periods) of slow oscillations within the cortical sites of interest thus remains to be confirmed. Determining the exact cortical origin and cortical extent of slow oscillations would require recording of multi-unit activity by means of brain-implanted microelectrodes ( Nir et al., 2011 ). Fortunately, much evidence suggests that temporally quasi-stable voltage maps such as the ones targeted by TOPOSO are very likely to represent specific brain states in well-described cortical sites or networks (for a review, see Michel & Koenig, 2018 ). Furthermore, source dipole analyses that we performed for the template maps used in TOPOSO suggested that the targeted UP-/DOWN-states were generated in the cortex underneath the target electrode. Hence, there is indirect evidence to suggest that TOPOSO targets well-localized slow oscillations. Nevertheless, the local specificity of TOPOSO might be limited by the fact that the algorithm does not explicitly distinguish between spatially restricted ( "local ") type-II slow oscillations, and widespread "global " type-I oscillation. Type-II oscillations only occur at one or a few sites on the scalp, while "global " type-I slow oscillations are present in most sensors. TOPOSO may target both types of slow oscillations, as long as their peak activity is at the site of interest. Although spatially restricted vs. widespread slow oscillations are thought to mirror distinct generating mechanisms and different homeostatic regulation processes Siclari et al., 2014 ), they may be functionally equivalent with respect to their impact on local computations and synaptic processes within the site of interest. Hence, targeting both types of oscillations for studying and modulating their local impact in the brain seems reasonable. A rather technical limitation of our current work is that TOPOSO was validated on only one EEG system. In fact, the EEG data provided for the training of our algorithm, the data used for the simulation study, and the data acquired in the closed-loop stimulation study were all recorded with the same equipment and in the same electromagnetically shielded room. It is thus unclear how TOPOSO would perform on different EEG equipment and in different environments. Recordings with different systems or in unshielded rooms might call for heavy filtering and preprocessing of real-time data. This might affect the overall performance of the algorithm or require adjustment of the settings and parameters. The generalizability of the findings of our in-vivo validation study is limited by the small sample size of the study and by the fact that stimulation was administered during a relatively short afternoon nap. More stimulations across an entire night in a larger sample of participants might provide the statistical power that is necessary for finding subtle differences in the slow oscillatory activity that is induced by stimulations targeted at distinct local UP-states. Finally, the generalizability of our findings is limited by the fact that the simulations as well as the in-vivo stimulation were performed on afternoon naps in partially sleep-deprived participants. It is thus unclear how well the algorithm would perform on natural night sleep. Importantly, though, the algorithm is currently successfully used for targeting frontal UP-and DOWN-states during night sleep in several ongoing studies. Also, an adapted version of the algorithm was successfully validated in a simulation study performed on night sleep data obtained in elderly subjects ( Wunderlin et al., 2022 ).
Several potential improvements of the TOPOSO algorithm that significantly increase its usability deserve mentioning. First of all, the algorithm could be implemented in a high-performance software platform or in a microcontroller in order to speed up computation time. This would increase the temporal accuracy and thus the efficacy of stimulation and could even allow for real-time detection and targeting of local UP-and DOWN-states instead of targeting up-coming UP-or DOWN-states based on the detection of state transitions. This could -for example -be achieved by means of a phase-locked loop (PLL) (e.g., Santostasi et al., 2016 ) that operates on the time-resolved similarity (correlation) between EEG scalp maps and target template maps. TOPOSO could further be extended with the capability to generate target templates based on forward-projections of local slow-oscillations in the targeted cortical source. These forward projections could be performed in a standard volume conduction model or even in individualized models ( Akalin Acar & Makeig, 2013 ). This would allow TOPOSO to target any local slow oscil-lations using any kind of high-density EEG montage without having to first pre-compute the respective template maps based on existing sleep recordings that were obtained with the same setup.
In sum, we argued that studies and applications aiming at modulating local slow oscillations during human sleep so far used closed-loop stimulation algorithms that failed to consistently target local slow oscillatory activity. We therefore introduced and validated a new EEG-based closed-loop algorithm that allows precise topographic targeting of local slow oscillations (TOPOSO) on different sites on the scalp. As the TOPOSO algorithm allows to target local slow oscillations based on predefined templates, it will enable individualized targeting of slow oscillations in subpopulations with altered slow oscillatory activity. We used this algorithm in a closed-loop stimulation study and found that auditory stimulation targeted at local UP-states may briefly enhance the targeted state, but then induces frontal rather than local slow oscillations. Therefore, we suggest that future applications aiming at local slow oscillatory enhancements use stimulation modalities (tactile, olfactory, visual, gustatory stimulation; electric or magnetic non-invasive brain stimulation) that address the functional specialization of the cortical site of interest and thereby induce and entrain local slow oscillations.

Data availability
The relevant code and data for this research is available at the Open Science Framework ( https://osf.io/ecvq8/ ).

Declaration of Competing Interest
The authors have no conflicts of interest to declare.

Data availability
The relevant code and data for this research is available at the Open Science Framework ( https://osf.io/ecvq8/ ).