Main

In scattering tissues such as the mammalian brain, two-photon excitation microscopy (2PM) is the gold standard for recording cellular structure and function in noninvasive and physiologically relevant conditions in vivo1,2. However, the maximum penetration depth of two-photon microscopes is fundamentally limited by the onset of out-of-focus fluorescence near the surface with increasing excitation power, which for the mammalian brain prevents imaging beyond roughly 1 mm (ref. 3). Imaging approaches based on three-photon excitation microscopy (3PM) have shown potential for deep imaging beyond 1 mm with cellular resolution, owing to a substantially increased signal-to-background ratio (SBR) at depth and longer wavelength excitation4,5,6,7.

As in 2PM, however, with increasing imaging depths optical aberrations due to tissue heterogeneities and refractive index mismatches, and subtle motion artifacts due to the animal’s heartbeat, degrade image resolution and overall performance, and result in a loss of subcellular details. This has so far prohibited the resolution of fine neuronal processes, synapses and subcellular Ca2+ transients in deep cortical and subcortical areas of the mouse brain in vivo without using highly invasive methods such as gradient index lens implantation8 or cortical aspiration9. While optical aberrations can be measured and compensated by using adaptive optics (AO) methods10,11, previous implementations were predominantly based on 2PM and thus were limited in their effective imaging depth to at most 800 µm in the mouse brain12,13,14,15. Alternative approaches based on wavefront shaping have the potential to image even further into highly scattering media, but limited fields of view (FOV) of only tens of micrometers and/or fast decorrelation times have prohibited their useful application in realistic intravital conditions16,17,18.

A further challenge in in vivo deep brain imaging is that at large tissue depths, heart pulsation leads to intraframe motion artifacts that prevent frame averaging to enhance the signal-to-noise ratio (SNR), a standard technique that is essential to reliably resolve small structures such as dendrites and individual spines.

To address the above shortcomings, we developed a minimally invasive intravital imaging methodology based on 3PM, indirect AO correction and active electrocardiogram (ECG) gating to achieve aberration correction and near-diffraction-limited resolution up to a depth of over 1.4 mm in the mouse brain. This enabled us to resolve individual synapses down to roughly 900 µm in the cortex, and fine dendritic processes in the hippocampus at a depth of more than 1.4 mm. Furthermore, our noninvasive approach achieved in vivo functional characterization of fibrous astrocytes in the white matter and resolved Ca2+ transients in individual microdomains.

Results

3PM with ECG gating

Our intravital imaging method is based on a homebuilt 3P laser scanning microscope optimized for 1,300 nm excitation and the use of broad-bandwidth, low repetition-rate lasers (Fig. 1a and Extended Data Fig. 1). We optimized the 3P fluorescence signal by ensuring short-duration laser pulses (<50 fs) and efficient power delivery to the focal plane within the sample. Optimization of the in vivo fluorescence signal in 3PM is especially important to avoid laser-induced tissue heating or long-term tissue damage7,19,20,21.

Fig. 1: Schematic principle of ECG-gated AO 3PM.
figure 1

a, Illustration of the motion-corrected AO 3P microscope. Aberration correction is performed via a modal-based indirect wavefront sensing approach. Intravital motion artifacts are reduced with a real-time ECG-gated image acquisition scheme that synchronizes the Galvo scanners to the cardiac cycle of the mouse. b, 3PM at 1,300 nm excitation wavelength in EGFP–Thy1(M) mouse visual cortex and hippocampus. Left, 3D reconstruction of a 3P image stack of third-harmonic signal (cyan) and GFP-labeled neurons (green). Right, maximum intensity projection images at various depths in the cortex (Cx; top), corpus callosum (CC; middle) and CA1 region of the hippocampus (HPC; bottom). SBRs at different depths are displayed in the respective images. Scale bar, 20 μm. c, Comparison of intraframe motion artifacts for ECG-gated and nongated image acquisition at 701 μm depth. Standard deviation (s.d.) projection images of consecutively acquired frames with (top, right) and without (top, left) ECG gating. Arrows indicate high frame-to-frame variability resulting in artifacts without ECG gating. Yellow box shows overlay of two consecutively acquired frames (red and green). Bottom, pairwise two-dimensional cross-correlation between individual frames without (bottom, left) and with (bottom, right) ECG synchronization. Representative datasets obtained from n = 4 mice.

Source data

We first validated the deep-tissue capability of our 3P microscope by imaging neuronal structure and third-harmonic generation contrast along an entire cortical column and into the hippocampus up to 1.2 mm depth in a Thy1EGFP-M (EGFP, enhanced green fluorescent protein) mouse through a chronic glass window (Fig. 1b and Supplementary Video 1). We observed high SBRs, even at deep, subcortical layers below the white matter, while ensuring physiologically low (0.5–22 mW) average laser power and focal energies (<2 nJ) below previously established damage and heating thresholds7,21 (Extended Data Fig. 2).

Despite the high SBR as well as numerical aperture (NA) and thus spatial resolution of our 3P system, however, fine neuronal processes such as dendritic spines are sometimes only reliably resolved down to roughly 500 µm, and completely disappear below the highly scattering corpus callosum. One possible reason for this is residual physiological brain motion resulting from cardiac activities, which results in intraframe imaging artifacts that are difficult to correct during postprocessing (Supplementary Video 2). These distortions typically increase with depth and distance from the stabilizing cranial window and headbar, and can lead to image blurring when using frame averaging, as typically done to increase image SBR. Therefore, they present an inherent challenge for in vivo high-resolution intravital microscopy, especially at greater depth22.

To address this, we implemented a prospective image-gated acquisition scheme based on a field-programmable gate array (FPGA), which enables active synchronization of the scanners to the cardiac cycle in real time so that active scanning is paused during peaks of ECG recording. We found that this straightforward ECG-gating approach substantially reduced intraframe motion artifact down to the hippocampus (>1 mm depth), and was most useful at large tissue depths and for visualizing fine structures such as individual spines. Furthermore, temporal sequences of frames acquired with ECG gating were more correlated to one another than were non-gated frames, indicating higher temporal image stability (Fig. 1c, Supplementary Fig. 1 and Supplementary Video 2).

Compared to previous work that used ECG-triggered full frame acquisition23,24, our approach is independent of the chosen acquisition parameters, does not require additional postprocessing and can readily be applied to large-FOV scanning. While we note that our ECG gating effectively reduces the duty cycle of the image acquisition by 40–60% and works only with galvanometer-based scanners, which poses limitations for recordings of fast dynamics, it is also a considerably simpler and sample-independent solution compared to more elaborate active motion correction techniques25,26,27.

Modal-based sensorless AO for deep imaging

A major challenge in multiphoton microscopy is degradation of the excitation point spread function (PSF) due to optical aberrations. This is particularly problematic in 3PM, as the fluorescence depends nonlinearly on the focal intensity4. Furthermore, submicrometer structures such as dendrites and spines are smaller than the axial extent of the PSF, and thus become even more challenging to resolve. Optical aberrations further increase the axial extent of the PSF, which leads to overall low fluorescence signal from fine structures. While 3PM has been used for deep cortical and subcortical imaging5,7,28, these previous studies focused on cellular (functional) investigations that did not require subcellular details.

To restore near-diffraction-limited resolution in deep brain regions, we incorporated indirect AO to our intravital ECG-gated 3PM. Many indirect, ‘sensorless’ AO approaches have been developed for microscopy over the years, including so-called ‘modal’ methods29,30, where the aberrations are represented by a series of modes defined over the whole pupil, and various ‘pupil-segmented’ approaches31,32, in which the pupil is separated into a number of zones that are modulated separately. We chose indirect, modal-based AO30 as these approaches were predicted to be most robust in low-signal and high-noise conditions33 and are thus arguably best suited to push the depth limits in deep brain imaging, especially when combined with higher-order multiphoton microscopy34.

We developed a continuous membrane deformable mirror- (DM-) and modal-based AO optimization scheme with automatic shift correction (Supplementary Fig. 2) and integrated it into the hardware control of our 3PM. First, we validated the AO performance by correcting artificial aberrations in ex vivo brain slices (Supplementary Fig. 3). Next, we applied our method to in vivo 3P imaging of neuronal structures throughout the cerebral cortex of Thy-1 EGFP-M mice (Fig. 2a,b and Supplementary Figs. 46 and Supplementary Videos 3 and 4). Moreover, with AO correction we were able to observe hippocampus CA1 neurons and dendrites down to the stratum lacunosum moleculare in the dorsal hippocampus at roughly 1.45 mm depth (Fig. 2c–e, Extended Data Figs. 3 and 4 and Supplementary Videos 5 and 6).

Fig. 2: AO enables high-resolution 3P deep brain imaging.
figure 2

Indirect modal-based AO correction and ECG-gated 3PM at 1,300 nm excitation. a,c,e, Representative images showing dendrites and spines in (a) layer VI and (c,e) hippocampus of the in vivo mouse brain (EGFP–Thy1(M)) through a cranial window. Images were recorded with two different conditions: AO system (wavefront correction of system aberrations) and AO full (wavefront correction of system and brain tissue aberrations). Maximum intensity projection images with system and full aberration correction at layer VI in cortex (a) as well as hippocampus (c,e) (scale bar, 20 μm; on zoomed regions, 2 µm). White boxes in a indicate magnified views of spines. The white cross in a,c,e shows orthogonal view along dendrite. Respective wavefront maps for aberration correction are displayed in the top and bottom corners. Aberration measurement location for e was identical to c. b, Intensity profile along spines (right; white dotted line) and across dendrite (left; white cross), respectively, in cortical layer VI (a). Norm., normalized. d, Intensity profile along neuron somata (white dotted line in c) and across dendrite (white dotted line in e). f, Lateral resolution analysis of AO correction improvement. Spectral power map as a function of spatial frequency (wavenumber) at (left) layer VI of cortex (a) and (right) hippocampus (e). Middle, average radial profile of spectral power maps for maximum intensity images. g, Axial resolution analysis. Effective PSF of microscope inferred from beads in solution and compared to in vivo measurements performed on dendrites, with system and full AO at a depth of 653 μm (cortex), 822 μm (cortex), and 1,000 and 1,327 μm (hippocampus). For AO at 1,327 µm, the AO measurement was performed at 1,000 µm depth. The effective illumination NA was reduced at a greater depth to increase objective transmission. h, Spatial analysis of lateral (green) and axial (blue) intensity enhancement (AO on/AO off) with respect to distance from location of AO measurement in cortex (left) and hippocampus (right). Median values are shown as dots and top 75th and bottom 25th percentile as shadows. Dotted lines show exponential fits. The red box indicates the area where the intensity enhancement (AO on/AO off) <1. Same data as Extended Data Figs. 6 and 7 for Z35. i, Analysis of wavefront distortion (peak-to-valley (PV) and root-mean-square error (r.m.s.e.)) displayed on DM for aberration correction in cortex (C) and hippocampus (HPC) and pooled from Extended Data Fig. 8. Only datasets with <100 μm lateral off-set between cortex and hippocampus in the same animal were included in the analysis. Representative datasets obtained from several imaging sessions in n = 7 mice.

Source data

We observed substantial improvements in image quality and the spatial resolution due to AO correction. We directly measured up to fourfold improvement in effective axial resolution and about eightfold enhancements of fluorescence signals, as evidenced by axial intensity line plots and spectral power map analysis of lateral resolution (Fig. 2b,d,f,g and Supplementary Fig. 5). Here, higher spatial frequencies, k, were substantially restored by full AO correction, as can be seen by comparing the power in the spatial frequency distributions between full AO and systems AO correction. In addition, we note that the reported improvements in signal and resolution (AO full) are solely due to correction of tissue-induced aberration, since values are compared to the best possible performance of the microscope alone, including aberrations due to sample preparation (AO system).

With our 3P-AO scope, we were able to recover near-diffraction-limited performance at all imaging depths (Fig. 2g), and in particular to reliably resolve individual synapses down to roughly 900 µm in the cortex (Fig. 2a, Supplementary Fig. 4 and Supplementary Videos 3 and 4) and fine dendritic processes in the hippocampus at up to 1.4 mm depth (Fig. 2e, Supplementary Fig. 6, Extended Data Fig. 4 and Supplementary Video 6).

We also characterized the influence of the starting SBR on the AO performance and found that our AO routine led to signal enhancement even at low starting SBR (Extended Data Fig. 5). This is a distinctive asset of our nonsegmented, modal AO technique in which the entire pupil is modulated at once, since such a strategy leads to larger AO-induced signal changes compared to segmented AO strategies31,35,36. Therefore, they are likely to be more robust at, and therefore better suited for, the low SBR conditions typically encountered in deep-tissue imaging, consistent with previous findings33.

Spatial characterization of aberrations and AO performance

Our capability to sense aberrations and perform AO correction throughout entire cortical and subcortical regions allowed us to analyze spatial and depth-associated differences in aberrations and to characterize the isoplanatic patch (that is, the FOV over which a given correction yields an improvement in image signal). We found that the isoplanatic patch was substantially smaller in the lateral than axial dimension (Fig. 2h) and generally decreased with image depth between the cortex (Extended Data Fig. 6) and hippocampus (Extended Data Fig. 7). This suggests that (tissue) aberrations predominantly change laterally across the FOV, and accumulate less with depth, presumably because axial translation of the focus produces more common path aberrations than lateral displacements.

We further performed AO correction with varying Zernike (Z) mode numbers up to Z21, Z35 and Z60, respectively, and found that low-order correction (Z21) led to the highest mean signal enhancement across a large (360 × 360 µm) FOV. In contrast, higher-order Zernike mode correction (Z60) led to the highest local signal enhancement but overall reduced isoplanatic patch size, both laterally as well as axially (Extended Data Figs. 6e,f and 7e,f). Here we found that corrections up to Z35 represented the optimal trade-off between signal enhancement and isoplanatic patch size when imaging in deeper (>500 µm) brain regions over larger axial ranges (Supplementary Video 6). Our findings are relevant for choosing optimal AO strategies for a given imaging condition or desired performance with respect to FOV, depth, resolution enhancement and AO optimization speed. Being able to individually control Zernike modes and to quickly adjust to the desired correction order and number of Zernike modes is an advantage of our modal-based, sensorless AO strategy. Furthermore, this allows the total number of AO measurements to be optimized in terms of overall speed.

In general, we found that overall aberration magnitude and r.m.s.e were lower in the cortex than the hippocampus (Fig. 2i); however, individual Zernike mode amplitudes did not display a clear correlation with tissue depth or aberration class (Extended Data Fig. 8). Finally, we characterized bleaching rates at the power levels and pulse energies used during AO measurements and imaging, and found that even at the highest power levels used for high-resolution spine imaging, only negligible bleaching was observed (Extended Data Fig. 9).

As a further demonstration, we applied our method to thinned skull and full, intact skull preparations, which are optically challenging because of considerable bone-induced aberrations that normally restrict high-resolution imaging to the first hundred micrometers6,37. While we did observe improvements in image quality in these conditions to a maximum depth of 700 µm (Supplementary Figs. 7 and 8), the signal enhancement was restricted to small image regions around the point of AO measurement, probably because of strong differences in aberrations (small isoplanatic patch size) across the FOV.

Applications to astrocyte calcium imaging

Next, we explored the capability of our 3P-AO scope for an even more challenging application of multiphoton microscopy, namely in studying the physiology of glial cells that are notorious for low fluorescence in their fine processes and high photosensitivity38. Similar to neurons, astrocytes, the most abundant glial cell-type in the brain, constitute a diverse population of cells with morphological and functional heterogeneity across different brain areas39.

The two most prominent astrocyte populations, protoplasmic astrocytes and fibrous astrocytes, reside in gray- and white-matter areas, respectively (Fig. 3a). While protoplasmic astrocytes have been extensively investigated noninvasively in vivo in the upper cortical layers using common two-photon methods40, little is known about the Ca2+ signals of protoplasmic astrocytes and fibrous astrocytes located in deeper brain areas. The main hurdle in studying fibrous astrocytes has been their location among highly scattering myelinated fiber tracts deep within the brain (>800 µm) and the lack of a genetic tool-box to target these cells. Moreover, astrocytes are highly amenable to photoactivation, and prolonged exposure to high laser power can severely affect their physiology38,40,41,42,43.

Fig. 3: 3P-AO enables structural and functional imaging of astrocytes in vivo.
figure 3

a, Illustration of protoplasmic and fibrous astrocytes that reside in the gray and white matter, respectively. b, White matter astrocytic Ca2+-imaging. Left, median intensity time-series projection image (pseudocolored) of three fibrous astrocytes (A, B, C) in the corpus callosum (at a depth of 862 µm). Arrowheads show soma of astrocytes. Map of all active microdomains at baseline overlaid on median intensity projected image of astrocyte. Center, intensity versus time traces for five microdomains (corresponding to colors in left panel), showing characteristics of Ca2+ transients. Right, raster plots displaying duration and intensity of Ca2+ transients of all microdomains. c, Gray matter astrocytic Ca2+ imaging. Left, median intensity time-series projection image (pseudocolored) of two protoplasmic astrocytes in the layer 6 of the visual cortex (at a depth of 835 µm). Map of all active microdomains at baseline overlaid on median intensity projected image of astrocyte. Center, intensity versus time traces for five microdomains (corresponding to colors in the left panel), showing characteristics of Ca2+ transients. Right, raster plots displaying duration and intensity of Ca2+ transients of all microdomains. d, AO-enhanced astrocytic Ca2+-imaging. Left, median intensity time-series projection image (pseudocolored) of protoplasmic astrocyte in the cortex (at 784 µm deep). Map of active microdomains at baseline. Center, intensity versus time traces for five microdomains (corresponding to colors in left panel), showing characteristics of Ca2+ transients without AO (AO off) and full AO (AO on) correction. Right, raster plots displaying duration and intensity of Ca2+ transients without AO and full AO correction. e, Graph showing mean amplitude (Z score/SNR) for microdomain Ca2+ transients without AO and full AO correction; P value based on a nonparametric Kolmogorov–Smirnov unpaired two-sided t-test. Error bars denote s.e.m. Representative datasets shown from n = 3 mice, and n = 5 L5/6 protoplasmic cells (c), n = 4 fibrous cells (b) and n = 3 cells with AO (d). Scale bar in bd, 20 µm.

Source data

To further demonstrate our technical advancements, we used an adeno-associated virus-(AAV-) based viral approach to express the genetically encoded Ca2+ sensor GCaMP6f specifically in astrocytes, and used our 3P-AO microscope to in vivo record Ca2+ transients in fibrous astrocytes in the corpus callosum (Fig. 3b) and in deep-layer (layer V-VI) protoplasmic astrocytes (Fig. 3c, Supplementary Video 7 and Supplementary Fig. 9). Here, the use of AO was crucial to achieve high signal and SBR even under low laser excitation power, and enabled the detection of more active microdomains compared to experiments without aberration correction (Fig. 3d,e and Supplementary Videos 810). We note that the overall time of AO optimization was fast (<500 ms per independent Zernike mode) compared to Ca2+ dynamics lasting for several seconds in the astrocyte soma, which allowed us to use indirect AO on structures with functionally varying signal levels. We resolved Ca2+ transients in individual microdomains, which are linked to synaptic activity, and yielded high SNRs even at low power levels. Our approach enabled the discovery that, although fibrous astrocytes reside in the white matter and do not tend to form ‘regular’ synaptic contacts as seen in protoplasmic astrocytes, they still exhibit microdomain-like Ca2+ transients.

Discussion

In summary, by combining 3PM with active aberration correction and ECG gating, we advanced near-diffraction-limited in vivo brain imaging in mice to a depth of 1.4 mm. We note that with our AO strategy we obtained exceptionally high axial correction range, which so far was only thought to be achievable in more elaborate, multi-conjugate AO approaches44,45,46. This permits AO enhancements to be achieved in regions far away from the site of AO measurements and optimization. This can be advantageous, since it allows the use of cell soma for AO measurements that reside in different axial planes or cortical layers. Here, cell soma are more reliable targets for AO optimization, and allow the use of much lower excitation power compared to when dendrites or spines would need to be imaged for AO measurements.

While the acquisition speed in (deep) 3PM is in general limited to a few frames per second owing to limitations associated with laser power, pulse energy and sample physiology20, our independent modal-based optimization is sufficiently fast to be used on samples with slowly varying signal levels, including Ca2+ signals in astrocytes. This is an advantage of our method compared to other approaches18,36 that require fluorescence levels to stay constant over much longer time frames. Compared to direct AO methods, indirect AO optimization, since it is applied to the excitation light, is not sensitive to differences in (tissue) aberrations that might exist between the excitation and signal emission wavelengths, and not depth limited by the wavelength of the (shorter) fluorescence light.

On the application side, our methods allow investigation of biological questions such as layer-specific synaptic remodeling, which was previously restricted to the first three layers of the brain, required removal of overlying brain tissue9 or insertion of invasive, optical probes47. Furthermore, we showed the capability of our method to uncover the distinct physiology of astrocytes across different cortical layers and of a previously understudied population of subcortical white matter astrocytes. While we ensured that average laser power and focal pulse energies were well below any previously established damage and heating thresholds for neural imaging, we highlight the need for appropriate control experiments in biological applications to ensure minimal photodamage, phototoxicity or photoactivation. Apart from our chosen demonstrations, we believe that our intravital 3P-AO technology can be extended to other tissues and across various model organisms to investigate cellular structure and physiology (and pathophysiology) with minimal invasiveness. In the future, wavefront-shaping approaches16,17, which can correct for both multiple scattering and low-order aberrations simultaneously, will have great potential when combined with 3PM to maintain diffraction-limited performance and effective power delivery to the focus at even greater depths.

Methods

Excitation source

The 3P excitation source was a wavelength-tunable noncollinear optical parametric amplifier (Spectra Physics) pumped by a regenerative amplifier (Spirit, Spectra Physics) operated at 1,300 nm and 400 kHz. At this wavelength, the laser system delivered an output power of 470 mW with a pulse width of 32 fs. To compensate for group delay dispersion of the microscope optical components, we implemented a homebuilt single-prism pulse compressor48, which consisted of a N-SF11, 40 mm prism (PS855, Thorlabs) and two gold roof mirrors (HRS1015-M01, Thorlabs). For imaging in the hippocampus an alternative laser system was used (White Dwarf WD-1300, Class5Photonics), which was operated at 1,300 nm and 500 kHz, delivering 1 W of output power. Dispersion compensation was achieved via dispersive mirrors, which was included in the laser system. With these pulse compressors, roughly 45 fs (Spectra Physics) or 60 fs (Class5Photonics) pulses (deconvolved with a sech2 pulse shape) could be recovered at the objective focal plane, as measured by an intensity autocorrelator (Carpe, APE GmbH). The excitation power was modulated with a Pockels cell (360-40 LTA, ConOptics).

Custom-built AO multiphoton microscope

A schematic of the microscope set-up is shown in Extended Data Fig. 1. For AO correction the DM (for details, see below) was conjugated to the back focal plane of a high-NA objective (NA 1.05, ×25, XLPLN25XWMP2, Olympus) via a pair of relay lenses (for DM-Multi-3.5 (Boston Micromachines); L1, L2, 47-380, Edmund Optics; for DM97-15 (Alpao); L1, AC508-250-C; L2, AC254-75-C, Thorlabs) to galvanometers (GVS002, Thorlabs), which were conjugated to each other with a relay system of two paired lenses (lens L3, 47-380; Edmund Optics; L4, LE4950, Thorlabs). The galvometers, scan lens, tube lens and objective back focal plane were conjugated in a ‘4f’-configuration. The scan lens was composed of 2-inch lenses (AC508-100-C, Thorlabs) in Ploessl configuration and a broad-bandwidth tube lens (TL200-2P2, Thorlabs). The microscope head and detection unit were based on a Movable Objective Microscope (Sutter Instrument Company), and three-dimensional (3D) translation of the objective was achieved with an electronic micromanipulator translation stage (MP-285). The fluorescent signal was collected by the same objective, separated from the excitation path with a long-pass dichroic beam splitter (D1 FF76-875, AHF) and filtered with a near-infrared laser blocking filter (FF01-940/SP, Semrock). The THG and fluorescent signals were separated with a dichroic beam splitter (D2 T480lpxr, AHF), cleaned with optical filters (F1, FF01-432/36-30-D, Semrock; F2, ET525/70m-2p, AHF), respectively, and detected by a photomultiplier tube (Hamamatsu, H7422-40), amplified and low-pass filtered by a transimpedance amplifier (3.5 MHz bandwidth, 105× gain, Femto DHCPA-200). The amplified voltage signals were digitized at a sampling rate of 80 MHz by an A/D conversion module comprising a digitizer adapter (NI-5734, National Instruments) and an FPGA card (PXI-7961R, National Instruments). ScanImage 2016a (Vidrio Technologies49) running on MATLAB 2016a (MathWorks) was used to control image acquisition and custom modified to enable synchronization of the image acquisition to the laser pulse repetition rate, integrated by the FPGA to realize a scheme in which each voxel is illuminated by a single or constant multiple of laser pulses. Synchronization to the laser repetition rate also allowed the introduction of a signal sampling window (125 ns was found to be optimal) that ignores noisy samples where no signal was present, thus improving the SNR of the collected data.

DM calibration

For active wavefront modulation, two different continuous membrane DMs were used: a DM-Multi-3.5 (Boston Micromachines) and the DM97-15 (Alpao) with 140 and 97 actuators, respectively. Calibration and generation of a Zernike-to-Command control matrix (Z2C) was performed with a homebuilt Michelson-interferometer50 to calibrate the Boston-DM while the Alpao-DM was inhouse calibrated with a homebuilt Shack–Hartmann wavefront sensor, consisting of a sCMOS camera (C11440-22CU, ORCA Flash4.0, Hamamatsu) with a 20 × 20 microlens array (18-00197, SUSS MicroOptics) and custom-written control software (additionally the Alpao-DM was precalibrated in the factory). Continuous membrane DMs have nonlinear response behavior that results in the Z2C matrix being linear only around the empirically chosen amplitude range used for calibration. To ensure a reliable operation even outside this range, we characterized the effect of Zernike modes on the axial displacement of the PSF. Axial shifts of the image plane are problematic in modal-based AO correction as this can lead to changes of the metric value due to content change of the image rather due to change of the excitation PSF and hence can lead to sample dependent biases51. This may corrupt the optimization procedure and prevent convergence to an optimal solution. We observed that independent of the calibration procedure, both DMs showed cross-talk between spherical modes and defocus. Therefore, a look-up table was generated for the Z2C matrix after calibration that characterized the respective focal shift for the first, second and third-order spherical mode. For moderate mode amplitudes (roughly 60% of maximum r.m.s.e value) mode coupling was linear, therefore the focus shift for spherical modes could be compensated by applying the opposite focal shift directly to the DM using the Zernike defocus mode (Supplementary Fig. 2). However, due to nonlinear mode coupling this focus shift correction failed for large amplitudes. Hence, for large amplitude aberrations the axial focal shift of spherical modes was compensated by moving the microscope translation stage along the axial dimension. This approach was integrated into our inhouse custom-written indirect AO software (described below) and the axial translation was based on the generated focal shifts look-up table.

Modal-based indirect wavefront optimization

For wavefront optimization, a user-defined number (N) of Zernike modes were corrected independently and the DM wavefront was updated sequentially after optimization of each mode. For each mode, nine amplitude changes were applied during the first optimization round and five amplitude modulations during subsequent iterations. As a quality metric for the wavefront optimization we chose the mean intensity of user-defined structures of interest such as cell soma, as this showed the most robust performance in low SBR conditions. Furthermore, we found cell soma to be less prone to sample dependent biases51 and because of their brightness allowed using exceptionally low power during the AO routine. During optimization, the structures of interest were segmented and only the segmented image was analyzed. Segmentation was achieved by intensity thresholding the median filtered (3 × 3 pixel) image. Zernike modes were modulated in the following order: first spherical, second coma and third astigmatism followed by other modes. This modulation scheme was chosen because spherical and coma aberrations are common and known to have large amplitudes in in vivo cranial window imaging as they result from refractive index mismatches between layers and tilted surfaces, respectively52. In general, two to three AO iterations were performed before convergence of the optimization metric was observed. Hence, in total 9 N + (i − 1) × 5N or (i × 5N) measurements were performed (i, number of iterations) to find the optimal wavefront. Normally, tip/tilt and defocus modes were excluded from the correction scheme, however, at large depths (>1,000 µm) the defocus mode was included into the correction scheme to reposition the focal plane onto the object of interest after every iteration as vital functions of the animal could lead to translational brain motion and hence sample dependent biases. This can lead to an elongation of the PSF toward the brightest structure if it is not centered at the initial focal plane51.

Typical parameters for 3P-AO optimization

For indirect modal-based wavefront optimization the focal plane was positioned in the center of the brightest structure in the region of interest. For in vivo experiments, we chose neurons (Thy1-GFP mice) or astrocyte (expressing GCaMP6f) somata for indirect AO optimization. Typically, a 40 × 40 μm FOV was scanned with a 64 × 64 pixel resolution, resulting in a roughly 25 Hz acquisition rate during optimization. Independent mode optimization was essential for aberration measurement on dynamic astrocyte calcium signals. With an independent mode optimization scheme the fluorescent signal only needs to be stable over 5–9 amplitude modulations. These data could be acquired within around 250–450 ms, which is at least one order of magnitude faster than somatic astrocyte GCaMP dynamics (about 8.0 s, ref. 53). For cranial window preparations, typically 21–60 Zernike modes, excluding tip/tilt mode, were used for aberration correction and 2–3 iterations were performed. Hence, a total of 210–900 measurements were required for aberration measurement that resulted in an overall fluorescence acquisition time of 9–36 s at a 25 Hz frame rate. Acquisition parameters for AO optimization and imaging are summarized in Supplementary Table 2. To minimize brain heating and photobleaching during AO optimization, the excitation power was reduced substantially, approximately by 50%, so that only a dim signal of the large somata was visible. Using our measured parameters for the light attenuation lz at 1,300 nm in brain tissue (lz = 270 µm, cortex), lz = 101 µm (corpus callosum) and lz = 250 µm (hippocampus) the estimated focal energy Ef was roughly 1 nJ (Ef = Eo × exp(−z/lz), where z is depth from the surface) during wavefront optimization, which is within the established physiological pulse energy regime7 (Extended Data Fig. 2). We further characterized bleaching rates at the used power levels and pulse energies at depth, and found that even at highest pulse energies used (that is, roughly 0.9 nJ, corresponding to 3.55 mW (surface) at 630 µm deep), negligible bleaching (<10% fall off within 1,750 frames) was observed (Extended Data Fig. 9). Although we used physiological power and pulse energy regimes, aberration measurements were performed on a different astrocyte within the proximity of the astrocyte of interest used for functional recordings, to ensure physiological responses during the imaging period. Furthermore, to prevent experimental biases and activation of astrocytes during recording the order of AO correction (first AO off followed by AO on, or vice versa) was chosen randomly (Supplementary Videos 810). For structural imaging in Thy-1-EGFP mice, the wavefront correction and imaging was performed on the same cell somata. Furthermore, to increase the objective transmission at a greater depth, the effective illumination NA was reduced (NA of roughly 0.8), yielding slightly decreased resolution (Fig. 2g).

To minimize aberrations before AO optimization, the correction collar of the objective was adjusted to compensate for the refractive index mismatch of the cranial window. Furthermore, the cranial window was aligned orthogonal to the optical axis using an objective-like alignment tool that enabled alignment within <1° accuracy. The alignment tool was based on overlaying the reflection from the cranial window to a reference reflection of a surface perpendicular to the optical axis at >2 m distance.

ECG gating

Software development

ScanImage was custom modified to acquire images gated in real time to the physiological parameters of the mouse, such as breath and heart rate, which were monitored by a dedicated physiological monitoring system (ST2 75-1500, Harvard Apparatus). The ECG signal triggered a transistor–transistor logic (TTL) pause gate (generation of the gate is described below), which was used to modify the system’s laser clock that was fed into the FPGA through an auxiliary I/O connector block (SCB-19, National Instruments). When the state of the pause gate was set to high, this effectively halted the image acquisition task and the galvometers stopped at their current position. During this period, the Pockels cell was synchronously turned off via an external circuit-based AND gate to prevent extensive light exposure of the sample. Scanning continued once the pause gate was reset to low.

Hardware development

The ECG-triggered TTL pause gate was developed on an FPGA System-on-Chip platform (ZYBO Z7 ZYNQ-7010, Digilent) using the Verilog programming language on Vivado 2018. First, the analog ECG signal was scaled to the FPGA input range (0–1 V), using an operational amplifier to reduce the peak-to-peak amplitude of the signal and centering it at 0.5 V. Next, the ECG signal R wave peaks (the local highest amplitude in the ECG signals) of the cardiac cycle was taken as the base point to generate the pause gate. The status of the TTL pause gate was set to low within the time interval (tp − Δtpre, tp + Δtpost), where the R wave peak occurred at time tp (Supplementary Fig. 1a). The parameters Δtpre and Δtpost were manually adjustable in accordance with suppression of the motion artifacts in the images. In our experiments, Δtpre and Δtpost were set to 30 and 20% of the ECG-cycle period, resulting in an imaging duty cycle of 50%. In practice, it is hard to predict the exact occurrence time of the next R wave peak. Therefore, we continuously analyzed the last ten heartbeat cycles to predict the next R wave peak in real time. Furthermore, we developed an auto-tuning threshold algorithm that adapted the threshold levels to changing DC levels of the ECG signal.

Animals and ethics statement

This work followed the European Communities Council Directive (2010/63/EU) to minimize animal pain and discomfort. All procedures described in this paper were approved by EMBL’s committee for animal welfare and institutional animal care and use, under protocol number RP170001. Experiments were performed on male and female, 7–24-week-old C57Bl6/j or homozygous Thy1–EGFP-M (Jax no. 007788) transgenic mice from the EMBL Heidelberg core colonies. During the course of the study, mice were housed in groups of 1–5 in makrolon type 2L or 3H cages, in ventilated racks at room temperature and 50% humidity while kept in a 12/12 h light/dark cycle. Food and water were available ad libitum.

Stereotaxic viral vector delivery and cranial window implantation

For astrocyte-specific expression of GCaMP6f, the gfaABC1D-cyto-GCaMP6f expression construct (Addgene, catalog no. 52925) was subcloned into the AAV vector. rAAV serotypes 1 and 2 viral particles were generated as described previously54 and purified by AVB Sepharose affinity chromatography55 after titration with real-time PCR (each titer 1.0–6.0 × 1012 viral genomes per ml; TaqMan Assay, Applied Biosystems). For stereotaxic injection of rAAVs and the cranial window implantation, mice were anesthetized with isoflurane vapor mixed with O2 (5% for induction and 1–1.5% for maintenance). Anesthetized mice were subcutaneously injected with 1% xylocain (AstraZeneca) under the scalp as preincisional local anesthesia and placed in a stereotaxic frame (David Kopf Instruments, model 963). The skin and periosteum over the dorsal cranium were removed with fine forceps and scissors to expose the bone. A 4-mm diameter circular craniectomy was made over the visual cortex using a dental drill (Microtorque, Harvard Apparatus), centered at 2.5 mm posterior and 2.5 mm lateral to Bregma. Close care was taken to preserve the integrity of the dura and avoid bleeding. rAAV injections were performed at the center of the craniectomy using glass pipettes lowered to depths of 400, 800 and 1,200 μm, using a syringe at a rate of roughly 4 μl h−1. Roughly 300 nl were injected per spot. After injection, a round 4 mm coverslip (around 170 μm thick, disinfected with 70% ethanol) was placed over the craniectomy with a drop of saline between the glass and the dura. The craniectomy and cranial window were sealed using acrylic dental cement (Hager Werken Cyano Fast and Paladur acrylic powder), and a customized headbar was cemented to the skull for head fixation under the microscope. The skin wound around the surgical area was also closed with dental acrylic. After surgery, mice received pain relief (Metacam, Boehringer Ingelheim) and antibiotic (Baytril, Bayer) injections (subcutaneous, 0.1 and 0.5 mg ml−1, respectively, dosed 10 μl g−1 body weight). Mice were single housed after cranial window implantation and had a recovery period of at least 3 weeks before further experiments, for GCaMP6f expression and to resolve the inflammation associated with this surgery56.

Thinned skull and brain slice preparation

Skull thinning followed the same general steps as the cranial window implantation procedure described above. Once the skull was exposed, a round approximately 3 mm area centered at 2.5 mm posterior and 2.5 mm lateral to Bregma was thinned using a dental drill. The thinned area was deepened a few micrometers beyond the trabecular part of the bone and the thinned surface was leveled out with polishing dental drill bits, leaving roughly 25–30 μm of remaining bone tissue. The thickness of the thinned area was estimated by visualization of blood vessels through the progressively more transparent thinned skull.

Brain slices were generated by transcardially perfusing the animal with phosphate-buffered saline (PBS) followed by 4% paraformaldehyde to fixate the brain. Subsequently, the perfused brain was isolated and post-fixed in 4% paraformaldehyde for 24 h at 4 °C before being transferred to saline and stored at 4 °C until 300-μm-thick free-floating coronal slices were cut with a vibratome (Leica VT1200).

Imaging through the intact skull was performed through a glass cranial window implanted over the exposed intact bone. This preparation isolated the exposed bone from the environment. The surgical procedure followed the same general steps as the cranial window implantation procedure described above. Once the dorsal skull bone was exposed, a round 4 mm no. 0 coverslip was placed centered at 2.5 mm posterior and 2.5 mm lateral to Bregma, with a saline drop on the underside to fill the gaps between the glass and skull. The whole assembly and skin wound was sealed and fixed to the surrounding exposed skull with dental cement.

In vivo deep brain imaging

For in vivo imaging experiments, animals were head-fixed using a customized headbar and complement holder and the cranial window was aligned orthogonal to the optical axis using the method described above. For structural neuronal imaging, Thy1-EGFP mice were anesthetized with isoflurane (2% in oxygen, Harvard Apparatus) while for functional astrocyte imaging mice were kept under low anesthesia (isoflurane 1–1.5% in oxygen). Mice were positioned on a small animal physiological monitoring system (ST2 75-1500, Harvard Apparatus), which allowed maintenance of animal body temperature at 37.5 °C and to monitor physiological parameters, ECG signal and breath rate. During experiments, eyes were covered with eye ointment. Acquisition parameters for structural neuronal imaging and functional astrocyte Ca2+ imaging are summarized in Supplementary Tables 1 and 2. Here we note that imaging depth was reported as raw axial translation of the objective. Taking the refractive index difference between the coverslip, immersion media and various brain tissues into account4, the actual imaging depth is likely around 5–10% larger than the values reported. In general, the data shown in the figures are representative of several imaging sessions, which were repeated between 2 and 11 times each on 16 separate mice, all of which produced comparable data quality. The numbers of mice are indicated in the figure captions.

Image postprocessing and analysis

All image data shown represent raw, 3 × 3 or 3 × 3 × 3 median filtered images, as stated in the respective captions and summarized in Supplementary Table 1. To improve visibility of dim structures before AO correction a scaling factor was applied to images (also indicated in the figures). Slow image drifts due to translational brain motion were corrected by template-matching individual image frames. Structural neuronal images from Thy1-eGFP mice were registered by rigid body transformation with StackReg57 (ImageJ) while astrocyte time series were registered by translation with TurboReg (ImageJ).

For the spatial analysis of aberrations presented in Extended Data Figs. 6 and 7, the measured aberrations for the different AO conditions (AO off, AO system and AO on for Z21, Z35 and Z60; that is, for correction up to Zernike orders of 21, 35 and 60, respectively, excluding piston, tip and tilt), were analyzed. Aberration correction was performed in the cortex (430–830 μm) and hippocampus (920–1,200 μm) and image stacks for the different AO conditions were recorded over a 360 × 360 μm lateral FOV with varying depths (roughly 300–400 μm in cortex and 100–300 μm in hippocampus). As neuronal somata were used for spatial aberration analysis the axial extend of the FOV in the hippocampus was smaller compared to the cortex, as the CA1 region in the hippocampus only exhibited a small region were somata are located. In total, six datasets from both cortex and hippocampus from three mice were used for analysis.

To spatially analyze the AO intensity enhancement of aberration correction (AO on: AO system, AO Z21, Z35, Z60), the ratio of the mean intensity of each somata within a FOV (AO on/AO off) was calculated and analyzed with respect to the lateral and axial distance from the point of correction (that is, the somata on which the AO measurement was performed). In more detail, we carried out the analysis in the following way: AO Z21 was used as the reference for analysis. Somata were segmented using the open-source machine learning-based software Ilastik58. The rest of the analysis was conducted in MATLAB. Object detection of individual somata was achieved with the command ‘bwconncomp’ (generating connected components). Objects that were smaller than 100 pixels were discarded and the centroids of each somata object were determined using ‘regionprops’. To prevent bias, image stacks of all AO conditions were aligned in 3D to the reference stack (AO Z21) with ‘imregister’ (transfformtyp, translation). The mean intensity of the top 20% brightest pixels of the somata object labeled pixels was used to calculate the intensity ratio (AO on/AO off).

Automated extraction and analysis of astrocyte Ca2+ signals

Astrocytes’ Ca2+ signals were analyzed using a custom-built MATLAB-based machine learning algorithm called CaSCaDe (calcium signal classification and decoding, for details see ref. 38). Since CaSCaDe was designed for the analysis of 2PM data, here we incorporated the following changes to optimize the code for analyzing 3PM data: a 3D bandpass filter of 11 × 11 × 11 pixels was applied to the time-series image, the sum-intensity projected image was binarized using a threshold value of Ibg, the image was smoothed with a 31 × 31 pixels2 Gaussian filter and a standard deviation of 3 pixels. To generate a microdomain map, a watershed segmentation with more than two regional maxima was applied, and microdomains with an area of less than 5 × 5 pixels2 were considered as noise and discarded. A Ca2+ event was considered positive if it had an intensity value of 3 (a.u.) and it spanned more than four frames. A support vector machine was trained to further refine the detection of Ca2+ events. Then 75 features were extracted from raw and two smooth intensity profiles obtained using a Gaussian filter with sizes of 11 and 21 frames separately. Support vector machine training was performed using MATLAB on 4,300 fluorescence signals manually annotated as positive or negative.

Reporting Summary

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