Zapit: Open Source Random-Access Photostimulation For Neuroscience

Optogenetic tools are indispensable for understanding the causal neural mechanisms underlying animal behaviour. While optogenetic actuators provide millisecond-precision control over genetically defined neural populations, successful optogenetic experiments also critically depend on associated hardware for targeted light delivery. Optic-fibres are suitable for certain experiments, however fibre implantation can be invasive and limits flexibility of spatial targeting. In contrast, random-access laser-scanning optogenetic systems provide far greater flexibility for targeting distributed cortical areas. However, these systems can be technically challenging to build, and at present no open source solution is available. Here we present ‘Zapit’, a complete open source platform for spatio-temporally precise random-access laser-scanning optogenetic experiments in head-fixed mice. We describe the system, quantify its performance, and show results from proof of principle cortical photoinhibition experiments in behaving mice.


Introduction
Optogenetics has become the preferred experimental tool for manipulating neural activity in systems neuroscience due to its high temporal precision, reversibility, and both genetically and spatially constrained impact of modulation (Boyden et al. 2005;O'Connor, Huber, and Svoboda 2009;Li et al. 2019;Emiliani et al. 2022).Currently, light delivery for activation of optogenetic actuators is predominantly achieved either via chronically implanted fibres (e.g.Mayrhofer et al. 2019;Babl, Rummell, and Sigurdsson 2019;Lohse et al. 2021;Duan et al. 2021;Emiliani et al. 2022), or by implanting a window over the cortical site (e.g.Schneider, Sundararajan, and Mooney 2018;Liu, Huberman, and Scanziani 2016).Whilst fiber optics allow for manipulation of neural activity in both head-fixed and freely moving behavioural paradigms, the size and fixed nature of implants restricts the approach to a predetermined and small number of sites.
In mice, the skull is thin enough (i.e.∼250 µm; Ghanbari et al. 2019) that light passes easily through it, and it is feasible to image the dorsal brain surface through the intact skull (Steinzeig, Molotkov, and Castrén 2017;Guo et al. 2014) of a head-fixed animal.Similarly, this optical access through the skull allows for flexible, random-access, optogenetic photostimulation across the dorsal cortical surface without the constraints imposed by permanently implanted fibres.
Various approaches have been employed for light delivery through the intact skull.A fibre optic can be mounted on a motorized micro-drive (Zatka-Haas et al. 2021), a digital micro-mirror device (DMD, Allen 2017) can project patterns on to the exposed brain to activate extended regions and generate arbitrary illumination patterns (e.g.Chong et al. 2020), or a pair of galvanometric scan mirror (galvos) can direct a focused laser beam (Guo et al. 2014;Li et al. 2016;Heindorf, Arber, and Keller 2018;Inagaki et al. 2018;Pinto et al. 2019;Keller, Roth, and Scanziani 2020;Esmaeili et al. 2021;Voitov and Mrsic-Flogel 2022;Pinto, Tank, and Brody 2022;Coen et al. 2023).
Of these solutions, the galvo-based option offers the best efficiency and utility/affordability trade-off: scanners are much faster than motorized drives and the required laser power is much lower than a DMD because only a single spot is stimulated at any one time, minimising power loss within the optical system.The high speed of the scanners means multiple points can be stimulated in close succession, allowing for effective silencing of multiple locations simultaneously.Although several groups have implemented the galvo-based technique, there remains no commercial or accessible open source solution for implementing it.
The last decade has seen widespread adoption of open source hardware tools in neuroscience, such as 'Open-Ephys' (Siegle et al. 2017), the 'Pulse-Pal' pulse generator (Sanders and Kepecs 2014), the 'Stimjim' programmable electrical stimulator (Cermak et al. 2019), as well as countless designs for light-sheet and multi-photon microscopes.Surprisingly, there exists no equivalent project for random-access photostimulation in head-fixed animals.Anyone wishing to implement such a system needs to build it from the ground up, which is time consuming and requires knowledge of of optics, real-time hardware control, and programming.
Here we present 'Zapit', an open source galvo-based photostimulation system.Zapit is the combination of a compact hardware design comprising easily acquired and affordable parts (around 15,000 GBP for a system built with a high-end laser), and software tools for calibration and stimulus delivery which are maintained by a community of developers and experimentalists.We demonstrate how Zapit allows for fast and easy integration of targeted cortical photostimulation in a set of proof of principle behavioural experiments.

Operating principle
Zapit is a combined hardware and software solution for galvo-based photostimulation of the mouse dorsal cortex.Whilst we provide a compact hardware design (see below), the software is flexible enough to cope with substantial variations to the hardware, which can be built entirely from off the shelf parts if desired.This opens up the technique to research groups who do not have access to a machining workshop.
We implemented a hardware design similar to that used in Pinto, Tank, and Brody (2022).A 470 nm laser is fed into an XY galvo scanner, and is then pointed down to the animal via a dichroic fold mirror.A f=100 mm scan lens focuses the beam onto the sample.This lens doubles as an objective, imaging the sample and any excited green fluorescence onto a camera via a tube lens (Fig. 1A).The galvo waveforms are shaped to minimise mechanical noise, but nonetheless we designed a sealed enclosure for the scanners (Fig. 1B).
The Zapit software comprises a user-friendly GUI for performing the two critical alignment steps (Fig. 1C): 1, Aligning the scanners with the camera, enabling the beam to point accurately to any desired location in the image, and 2, mapping stereotaxic coordinates onto the exposed skull.Calibration takes about a minute and, once calibrated, the system will place the beam in any desired location defined by stereotaxic coordinates.
A simple API allows the user to integrate stimulation into an experimental paradigm.The system supports stimulation of one or more points in a given trial; points are stimulated sequentially.In a trial with a single stimulation location, the laser is parked in one place and flashed on and off at 40 Hz with a 50% duty cycle.In a trial with two locations, the beam cycles between them at 40 Hz such that each point experiences a 50% duty cycle.In the case of ≥3 points, the beam hits each point at 40 Hz but the duty cycle drops below 50% and laser power is increased proportionately to maintain the same average power.All beam locations are defined in stereotaxic coordinates.There is a ramp down in intensity at trial end to limit rebound effects (Li et al. 2019).An optional (but highly recommended) blue LED masking light runs in synchrony with the laser.
Figure 1.Zapit system overview.A. System schematic.The unexpanded laser beam (cyan) is fed into the galvos then is directed down towards the sample by a dichroic mirror (dashed grey line).A lens focuses the laser beam onto the sample.The sample is imaged onto a camera using this same 'scan lens' as an objective and a tube lens in front of the camera.B. Custom enclosure.We have designed an enclosure to make construction of the system easy and provide a compact structure that can be easily mounted in a variety of ways.C. User-friendly GUI.All calibration operations are conducted using a GUI, which also has the ability to deliver test stimuli for testing.D. Photostimulation integrates with behavioral experiments.Stimuli can be integrated into experimental paradigms easily using the MATLAB API, a shared-memory Python bridge, or a TCP/IP communications protocol.This enables spatially-restrictive causal optogenetic manipulations in mice genetically-engineered to express opsin in defined neural populations

Hardware Design
We used ScannerMax Saturn 5 (available from Edmund Optics) for directing the beam.Images were acquired using a USB-3 Basler acA1920-40um.Whilst various lens combinations work, we chose a f=100 mm Plössl objective composed of two ThorLabs AC254-200-A (f=200 mm) achromats.A Plössl is a compound lens composed of two identical achromatic doublets arranged such that their positive (convex) surfaces are near touching.This arrangement has a focal length half that of one of the individual elements and has substantially reduced optical aberrations and distortions compared with a single achromatic doublet of equivalent focal length.The tube lens is an f=50 mm Plössl composed of two ThorLabs AC254-100-A (f=100 mm) achromats.We chose this combination because it has a magnification of 0.5 and allows the mouse brain to comfortably fit on the camera chip.The light source is a 473 nm, 75 mW, Coherent Obis laser.A ThorLabs MF252-39 dichroic and MD498 emission filter before the camera allows the sample to be visualised without bright laser light contaminating the image.The location of the beam is usually visible because the blue light elicits autofluorescence from most surfaces, and this passes through the emission filter.
A more complete parts list with suggestions for alternatives is available on GitHub.For example, we chose the Obis laser because of its reliability, fast ON/OFF times, and relatively high power, which is sufficient for maintaining effective average power across multiple (e.g.20) sequentially targeted locations.However, this laser is expensive.Researchers requiring only a small number of laser spots per trial could likely use a cheaper laser from our list.
Whilst our system can be constructed entirely from off-the-shelf parts, we chose to design a custom sealed enclosure in order to minimize footprint and scanner noise.A fold mirror placed before the camera keeps the system compact.The beam feeds directly into the scan head by mounting the laser at the entry window using a 90 degree cage-mounted fold mirror.Fibre-coupling is also possible but this would result in light loss, and also increase the NA of the excitation system.We wanted to avoid this, as the minuscule NA of our current arrangement makes minor focusing errors on the excitation path irrelevant.We modelled the system in Zemax and estimated the theoretical laser spot as having a PSF with a FWHM of 70 µm.This value is estimated using an f=150 mm objective, slightly longer than the 100 mm we eventually settled on, and a 0.8 mm diameter laser beam.We estimated the true PSF full width half max as 91 µm (Fig. 2).A larger input beam diameter or a shorter focal length objective would increase excitation NA and so decrease FWHM.The true size of the spot in the brain will be much larger due to scattering.This procedure yields an intensity curve resembling a cumulative Gaussian, which can be fitted as such and converted to a probability density function.Whilst we measure a beam size of under 100 µm FWHM, the true size of the spot on the brain surface is likely to be much larger.The beam will scatter as it goes through the cleared skull and then will scatter further as it enters the brain.B. Beam spot size across the field of view.Focusing the beam on a piece of paper elicits fluorescence which can be imaged with the camera.We acquired many such images whilst moving the beam over a grid of positions spanning an area roughly the size of a mouse brain.The size and shape of the beam is very similar across all positions, showing there is no change in the resolution of optical stimulation over the field of view.

Software Design: calibration
Calibration is a simple two-step procedure.First, the laser is aligned to the camera image.This is achieved by by scanning the beam over a grid of points and then conducting an affine transform between the intended and observed beam locations This is an automated procedure, initiated by a button-click in a user-friendly GUI (Fig. 3A).
Figure 3. Two-step system calibration using the Zapit GUI. A. Scanner calibration.The Zapit GUI displays a live image feed from the camera.In this example, we imaged a print-out of the Allen brain outline at the sample plane.In 'Point Mode', the user can manually click locations in the image FoV, and Zapit will target light to this location.However, when 'Uncalibrated', the actual beam location (bright point) does not match with the desired target location (red circle).'Run Calibration' initiates an automatic calibration routine to correct this targeting error.Zapit systematically moves the beam over a grid of points and conducts an affine transform between the camera-measured and intended beam positions.Once calibrated, the beam goes to the target position.B. Sample calibration.The user then defines the position of the skull in the FoV using two landmarks, such as bregma and bregma +3 mm.These coordinates can be marked onto the skull during a previous surgery using a stereotaxic frame.Whilst clicking these coordinates, a brain outline (blue) is dynamically positioned, scaled, and rotated, providing instant feedback on the calibration.Once confirmed, the brain outline will turn green.The user can then load in target points defined in coordinate space, and confirm correct targeting by stimulating the target locations ('Zap Site') The user then defines the position of the skull in the FoV using two landmarks, such as bregma and bregma +3 mm AP.The two coordinates are marked onto the skull during the clear skull cap and head plate surgery.Whilst clicking these coordinates, a brain outline is dynamically positioned, scaled, and rotated, providing instant feedback on the calibration (Fig. 3B).This process assumes the skull is parallel to the objective, which should be ensured during head plate implantation (see Methods) 2.4 Software Design: defining stimulus locations Locations to be stimulated are defined in stereotaxic space and stored in a human-readable stimulus configuration file, which can be generated using a GUI (Fig. 4A) or via direct editing of the text file (YAML).This coordinate space is based upon the Allen Atlas with bregma estimated at 5.4 mm AP, as done previously by Birman et al. 2023.Figure 4B shows an example of a finished stimulus set.
The stimulus configuration GUI allows the user to define general stimulation parameters in addition to stimulus locations.Note that the 'Laser Power' setting defines the time-averaged power in mW at the sample surface used for stimulation.In other words, if two points are being stimulated in a single trial and requested power is 2 mW then the laser would deliver 4 mW at the sample.A power meter receiving light from just one of those points would report an average power of 2 mW.

Running Experiments in MATLAB
Once the system is calibrated and a stimulus configuration file is loaded, Zapit's MATLAB API can be used to deliver precisely timed photo-stimulation (Fig. 5A).Different experiments require stimuli to be presented in different ways, or place specific demands on stimulus timing.We accommodate a variety of different approaches via Zapit's sendSamples function.
When photo-stimulus duration is not known in advance, we queue waveforms for the next stimulus to the NI DAQ, and either begin stimulation right away or defer it until a TTL trigger is received.The latter allows for precise timing of stimulus onset.Once started, the stimulus continues indefinitely until a software command is issued to stop it.Photo-stimulation ends with a gradual ramp-down in power (e.g. over a 250 ms time period).This limits large rebounds in activity, which are common following cessation of photoinhibition with light-sensitive opsins (Li et al. 2019).
The preceding approach is effective in some cases, but in others a precise stimulation duration is called for.In such cases, stimulus duration is defined in advance and, as before, the stimuli can be either software or hardware triggered.Fig. 5B demonstrates the timing precision of hardwaretriggered, fixed-duration, stimuli.Onset latency is about 0.5 ms with respect to the TTL trigger, with near zero jitter.Fixed-duration stimuli can also be presented with a fixed delay following the TTL pulse (Fig. 5C), allowing for precise stimulus alignment with different temporal epochs of a behavioural task.
Zapit has the capability to write a log file listing each stimulus presentation, so the order of events can be reconstructed post-hoc.This is particularly useful in scenarios where the user asked Zapit to produce randomly chosen stimuli.Finally, control trials are possible where the galvos move and the optional masking light is on, but the photostimulation laser is off.The following minimal code example shows how to present all available stimuli sequentially.

Running Experiments Using Other Programming Languages or Remote PCs
Although MATLAB is required to run the Zapit GUI and calibrate the system, experiments can be conducted using any desired programming language.Zapit can be controlled from either the local PC or a remote PC using TCP/IP communication.The Zapit zapit_tcp_bridge package contains Zapit clients for MATLAB, Python, and Bonsai.There is detailed documentation on the message protocol, allowing users to easily write clients in the language of their choice.The following code snippet shows how a running Zapit instance can be controlled via a MATLAB instance running on a different PC on the same network.Equivalent code exists for Python.In addition to TCP/IP, control via Python can also be achieved using the 'zapit-Python-Bridge' (installed via pip), which provides access to the local Zapit MATLAB API instance via shared memory.For example:

Beam Positioning Accuracy
In trials where ≥2 points are stimulated, the beam must be disabled (blanked) whilst it is traveling between locations (Fig. 6A).When the beam is left on, there is the possibility of off-target stimulation (Fig. 6B).We implemented blanking and power control using the built-in modulation facility of our Coherent Obis laser.For simplicity, we chose a fixed motion time of approximately 0.5 ms between any pair of positions.This was long enough to significantly reduce sound generated by the scanners during experiments.Like other system settings, this motion time may be adjusted by the end user.Figures 6C & D show that the beam is disabled during this period.The blanking period of the laser was manually tuned to perfectly correspond with the motion epoch.This timing was completely reliable across trials.

Unilateral optogenetic perturbation of ALM biases motor choices during perceptual discrimination
To verify the functionality of our photostimulation system we set out to replicate a well-known result -biasing directional motor-planning by perturbing anterolateral motor cortex (ALM; Guo et al. 2014).First, we trained head-fixed VGAT-ChR2-EYFP mice to discriminate bilateral whisker deflections and report perceptual decisions with directional licking following a short delay (Fig. 7A).On each trial, trains of air-puffs were simultaneously presented to the left and the right whiskers.The target lickport choice ('left' or 'right') was cued by the whisker stimulus side receiving the faster stimulation rate (freq.range: 0 -10 Hz).The target lickport dispensed a small water reward for correct choices (3 µl ).Trials where left and right whisker stimulation rate was equal were rewarded at chance.The stimulus presentation window (1 s) was followed by a delay (1 s) before mice were allowed to report their choice (Fig. 7B).Following task learning, we programmed Zapit to perturb left or right ALM while mice performed the task (Fig. 7C).We perturbed a third of trials and randomised perturbation location across left and right hemispheres within the same session.The perturbation was time-locked to the onset of the sensory cue and lasted until the beginning of the response window (Fig. 7B).
On trials without perturbation, behavioural discrimination showed clear adherence to the signed lateralised difference in whisker-stimulation rate.Mice performed with high choice accuracy when the whisker stimulus difference was large, and at chance level when the stimulation rate was matched bilaterally (Fig. 7E 'Laser OFF').However, behavioural decisions were markedly biased on ALM perturbation trials.Unilateral perturbation biased choices towards the ipsilateral lickport (Fig. 7E), consistent with suppression of contralateral motor processing (Guo et al. 2014).Increasing laser power resulted in incremental decreases in performance on contralateral whisker stimulation trials (Fig. 7F).Our results therefore demonstrate that the Zapit system can be used for flexible, targeted optogenetic manipulations of cortex and can produce reliable and specific effects in awake behaving mice contingent on both perturbation location and stimulus strength.

Bilateral multi-site and multi-power optogenetic perturbation in a visual decision making task
We next tested the performance of Zapit using bilateral photostimulation for multiple sites and multiple light powers in the same session.We trained VGAT-ChR2-eYFP mice on a visual change detection task (Orsolic et al. 2021), and tested the effect of perturbing primary visual cortex (V1), an area expected to influence visual guided behaviour, as well as a control area not expected to influence visual guided behaviour: primary somatosensory cortex (S1).In the same session we perturbed each of these areas 7% of the trials with either 2 mW or 4 mW laser power.
Mice were trained to be stationary on a running wheel while observing a drifting grating stimulus, whose speed fluctuated noisily every 50 ms around a geometric mean temporal frequency (TF) of 1 Hz (STD = 0.25 octaves), and to report a sustained increase in its speed by licking a central reward spout.The mice were motivated to react promptly upon detecting a change by limiting the time in which the reward was accessible to 2.15 s.Since changes in speed were often ambiguous, their timing unpredictable, and the change magnitude randomised, mice had to continuously track the visual stimulus for a prolonged duration (3-15.5 s) prior to the change (Fig. 8A).
On trials with perturbation of V1 or S1, Zapit began bilateral stimulation 250 ms prior to stimulus onset, and lasted until the end of the stimulus (whether ended by a mouse action, or expiration of the response window), and subsequently ramped down over 250 ms (Fig. 8A).Throughout the trial, the laser fluctuated according to a bilateral 40 Hz square pulse pattern with a 50% duty cycle.
We also presented a blue LED masking light on every trial to avoid mice being able to see the laser on laser trials.This masking light had the same stimulation profile (i.e., 40 Hz pulses) as the laser stimulation on optogenetic perturbation trials.receive a soy milk reward.On 14% of trials mice were stimulated with a 470 nm laser through the intact skull covered by a thin layer of transparent bone cement (i.e., sometimes referred to as skull cap).Laser trials were randomly interleaved, and stimulation parameters on the 14% of trials would be randomly selected to be over S1 or V1 and either with 2 mW or 4 mW.A blue LED masking light matching the stimulation profile of the laser was presented above the mouse on every trial to mask when laser trials were happening.B. Psychometric effect of perturbing S1 and V1 with Zapit at 2 or 4 mW for an example mouse (binomial mean and 95% CI).
Note the scaling of behavioural disruption with increased light power in V1, but not in the control area S1. C. Psychometric effect of perturbing S1 and V1 using Zapit at 2 or 4 mW across 5 mice (mean and 95% CI across mice, n = 5) using Zapit As expected, we observed robust deficits in animals' abilities to detect changes in temporal frequency of a drifting grating when perturbing activity in primary visual cortex (V1), which scaled with increasing light power (Fig. 8B,C).In contrast, there were no significant behavioural effects when perturbing activity in primary somatosensory cortex (S1) (Fig. 8B,C).We did observe a slight but non-significant flattening of the psychometric curve when stimulating S1 with a 4 mW laser however, possibly indicating that the laser stimulation may in some cases have affected activity in higher-order visual areas around 1.5 mm caudal to the stimulation target in S1 when light powers were high (Fig. 8C).
This demonstrates that Zapit can effectively perturb activity at multiple cortical areas at multiple light powers in the same session, permitting direct comparison between the effects of perturbing activity in distinct areas bilaterally.

Zapit is a complete and ready to use solution
Zapit is a complete and accessible solution for head-fixed scanner-based optogenetics.The provided CAD models for the enclosure are easy to machine and it is straightforward, even for a beginner, to build a system around this base.Our software is well-organised, well-documented, and tested.There is ample on-line documentation for software install and usage.Zapit has a multi-lab user-base, and will be maintained and updated by developers and experimentalists for the foreseeable future.All work will be shared rapidly via GitHub.We are not aware of any significant caveats to the system, beyond the obvious constraints imposed by sequential, point-based stimulation.In the interest of transparency, the software's GitHub page maintains a list of known obvious issues with the software.

Comparison to other approaches
There are other effective approaches for rapid programmatic photostimulation in head-fixed behavioural tasks: those based on digital micro-mirror devices (DMDs) or spatial lights modulators (SLM).These approaches are capable of activating extended, arbitrarily-shaped areas (Chong et al. 2020).DMD-based solutions, such as the Mightex Polygon, provide the fastest pattern-switching time but are very wasteful of light and so require a roughly 4 W laser to cover an area the size of mouse dorsal cortex.SLM-based solutions are more light efficient, but devices with high resolution are very expensive and are are slower than DMDs.Whilst scanner-based systems restrict photostimulation to a small number of points, this scenario is sufficient to enable a wide variety of interesting experiments.Scanner-based approaches provide the most cost-effective and compact solution.
Zapit is not designed for subcortical stimulation, as the focused beam scatters rapidly as it enters the brain.Tapered fibres provide a powerful alternative option for multi-area subcortical targeting along the dorsoventral axis, as they allow for targeting multiple regions along the fibre length by altering the angle of light entering the fibre (F.Pisanello et al. 2017;M. Pisanello et al. 2018).

Clear skull cap preparation
In order to clear the skull, a transparent glue or 'bone' cement (we use Super-Bond C & B) must be painted over the surface.We have not found it necessary to thin the skull of our mice, but simply apply this thin layer (about 200-300 µm) of transparent bone cement.Unsurprisingly, we have anecdotally observed that when bone cement is thick (0.5-1 mm), then we only see robust behavioural effects at high light powers (4 mW).Additionally, if the cement is too thin it can crack in a long term preparation.Guo et al. 2014 indicate around a 50% loss of light power as the laser passes through bone cement and skull.

Light power selection
The light powers used for optogenetic stimulation vary considerably between studies -even studies stimulating the same region with the same opsin.Although every experimental setup will be different and have different experimental constraints, we recommend that when using Zapit, to start at 1.5 -2 mW time-averaged light power as a default (when using VGAT-ChR2 mice).Behavioural effects can scale with light power (Figure 7F and 8C), and at 2 mW we consistently see strong behavioural effects when stimulating sensory areas like V1 (Figure 8), or frontal areas like ALM (Figure 7) when using Zapit.In testing Zapit, we have found anecdotal evidence that when using 2 mW stimulation, we can observe completely distinct behavioural affects in areas 1 mm apart.Furthermore, at 2 mW average light power with a nominal 91 µm X/Y PSF, and with an expected light loss of around 50% as the light traverses the skull and bone cement, heating of the neural tissue as a result of the light stimulation will be minimal -even at long term stimulation (Stujenske, Spellman, and Gordon 2015).When using transgenic lines expressing opsins brain wide (such as in VGAT-ChR2-eYFP mice), we note that stimulation with 4 mW or above should be used with caution, as it in some cases may cause off-target behavioural effects indicating either that the light scatters widely along cortex (Li et al. 2019), or that light affects structures below cortex (Babl, Rummell, and Sigurdsson 2019).

Masking of laser stimulation trials
Masking the mouse's ability to see when the laser is on is paramount for the interpretation of the effects on behaviour caused by Zapit stimulation.We recommend masking the laser by providing a color-matched light stimulation from LEDs above the mouse's head on every trial which matches the stimulation profile of the laser (e.g., 40 Hz sinusoid) together with keeping the box in which the mouse performs the task well-lit with an white LED strip.Zapit provides an analog signal suitable for driving a masking LED.Together, this masking approach appears to mask the ability of the mouse to see the laser stimulation with blue light.Extra caution should be taken when using longer wavelengths, such as yellow or red light, as the longer wavelength more easily travels through the brain tissue and hits the back of the retina, and can in certain cases be more difficult to mask (Danskin et al. 2015).

Good practice: measures to report when using Zapit
We encourage people who use Zapit (and similar setups) to report a minimal set of standardised parameters to aid replication, comparability and consistency across experiments and laboratories: • Average light power • Peak light power • Stimulation frequency and profile (e.g.40 Hz sinusoid), and duty cycle.
• Number of concurrent stimulation sites (i.e., number of stimulation sites effectively silenced simultaneously: single site bilaterally stimulated would be 2 in this case).• Laser stimulation duration • Laser ramp down duration (and whether this period is included in the light duration, or follows it) • Whether or not a masking light was used, and if so the parameters (i.e.color, frequency, etc.) • Percentage of trials with stimulation per area, per light power, and total number of trials with stimulation.

Future Plans
In the immediate future we plan to spend more time validating the system and expanding existing features.For example, we will further develop the stimulus configuration generator GUI to allow patterns of multiple points to be more easily created for a single trial, as currently this ability is rudimentary.Zapit has the capability to generate electrophysiology-friendly waveforms shaped to reduce the photoelectric effect.These waveforms have not yet been tested.We will test them and conduct electrophysiology-based validation experiments.In the longer term we are considering the following enhancements to the system: • The ability to perform near-real-time closed loop stimulation, as this feature is available with the laserGalvoControl project (Pinto et al. 2019).• Software tools to make it easier to re-position the head in the same location as previous sessions.
• Linking atlas generation to the brainglobe (Tyson et al. 2022) ecosystem and allowing different mouse atlases, or even atlases from different species.• Modifications as may be necessary to allow simultaneous functional imaging and Zapit stimulation.

In Closing
We hope Zapit is a tool that will grow and find uses outside of our institute and specialities.Potential new users are welcome to contact us for assistance in building or setting up the system.

Mice
All experiments were performed under the UK Animals (Scientific Procedures) Act of 1986 (PPL: PD867676F) following local ethical approval by the Sainsbury Wellcome Centre Animal Welfare Ethical Review Body.We used VGAT-ChR2-YFP mice (Jackson Laboratories, USA) for Zapit experimental proof of principle experiments.
4.2 Implantation of clear skull cap for optical access to the dorsal surface of the brain Implantation of a clear skull cap (i.e., thin layer of transparent bone cement (C & B Superbond)) covering the dorsal surface of the brain together with a head plate placed over the cerebellum was carried out under 1.5% isoflurane in O2, together with pre and post surgical administration of Meloxicam (5 mg/kg).To ensure the skull is parallel to the objective, the skull should be aligned by checking that bregma and lambda depths are even (i.e., <0.05-0.1 mm difference), as well as ± 2mm lateral from midline is even (i.e., <0.05-0.1 mm difference).This allowed optical access to the dorsal surface of the brain, while head-fixing the mice.To allow calibration of Zapit two small dots were made over bregma and +3 mm AP from bregma.Mice began habituation to the behavioural setup and water/food restriction >4 days after surgery.

Bilateral whisker frequency discrimination delayed-response task
Mice were head-fixed and positioned in a perspex tube.Bilateral somatosensory (whisker) stimuli were delivered using compressed air directed to the left and right whisker fields using two 3 mm air hose lines (121-6278; RS Components).Air-puff stimulation was delivered in the dorsoventral axis.The air pressure (2 bar) was maintained using a pressure regulator (703-6113; RS Components).Left/right air flow was gated using two solenoid values (EV-2-12; The West Group).Air puff stimuli consisted of trains of regularly spaced pulse sequences (0 -10 Hz).Each pulse duration was 20 ms and stimuli were presented for 1 s.The task (stimulus design, trial timing, lick detection, reward delivery etc.) was controlled using the MATLAB implementation of Bpod (Sanworks).
Mice were trained through operant conditioning to associate lateralised whisker stimulation with lateralised reward (e.g.stimulus left = lick left).Water rewards (3 µl ) were delivered to the target lickport on correct trials using a gravity fed water reservoir system, with left/right spout tubing gated via two solenoid pinch valves (161P011; NResearch).Mice were first trained on 10 Hz unilateral stimulus trials (i.e.trials with no distractor) with no delay-epoch.During this phase, mice could lick the lickport(s) immediately following stimulus presentation.Following learning, a motorised stage (XL-320 Dynamixel; Robitis) moved the lickport in/out to teach mice to withhold licking until cued.The period between stimulus presentation and presentation of the lickport was incrementally increased across training up to a maximal 2 s (1 s stimulus presentation, 1 s delay).Movement of the lickport stage provided a salient auditory sound to cue the onset of the response window.Following learning of the full delay task, bilateral stimulation trials were introduced.During bilateral training, mice received 9 distinct types of sensory trials corresponding to a '3 x 3' combinatorial matrix of 0, 5 and 10 Hz left and right whisker stimuli.The target lickport was cued by the whisker side receiving the faster stimulus sequence.The rewarded side was randomised on trials where left and right stimulation was matched.Following learning mice underwent unilateral optogenetic perturbation experiments.Two unilateral stimulation locations corresponding to anterolateral motor cortex (2.5 mm anterior, ±1.5 mm lateral from bregma; Guo et al. 2014).Photostimulation (duration: 2.2 s; average power: 2 mW) was delivered on 33% of trials and was randomised across left and right ALM.

Visual change detection task for proof of principle experiments using Zapit
The design of the behavioural task was as previously described in Orsolic et al. 2021.Mice were head-fixed and placed on a polystyrene wheel.Two monitors (21.5", 1920 x 1080, 60 Hz) were placed on each side of the mouse at approximately 20 cm from the mouse head.The monitors were gamma corrected to 40 cd/m 2 of maximum luminance using custom MATLAB scripts utilizing PsychToolbox-3.The stimulus presentation was controlled by custom written software in MATLAB utilizing PsychToolbox-3.The visual stimulus was a sinusoidal grating with the spatial frequency of 0.04 cycles per degree resulting in 3 grating periods shown on a screen.Each trial began with a presentation of a grey texture covering both screens.After a randomized delay (at least 3 s plus a random sample from an exponential distribution with the mean of 0.5 s), the baseline stimulus appeared.The temporal frequency (TF) of the grating was drawn every 50 ms (3 monitor frames) from a log-normal distribution, such that log 2 -transformed TF had the mean of 0 and standard deviation of 0.25 octaves and the geometric mean of 1 Hz.The direction of drift was randomized trial to trial between upward or downward drift.The sustained increase in TF, referred to in the text as change period, occurred after a randomized delay (3-15.5 s) from the start of baseline period and lasted for 2.15 s.Random 15% of trials were assigned as no-change trials and did not have a change period.
Mice were trained to report sustained increases in temporal frequency by licking the spout to trigger reward delivery (drop of soy milk).Licks that occurred outside of the change period are referred in the text as early licks.If mice moved on the wheel (movement exceeding 2.5 mm in a 50 ms window) in either direction, the trial was aborted.If mice did not lick within 2.15 s from the change onset, the trial was considered a miss trial.
The stages of behavioural training for mice on this task has previously been described in Orsolic et al. 2021.

Behavioural setup and data acquisition
Reward delivery (soya milk) was controlled by a solenoid pinch valve (161P011, NResearch, USA) and delivered to the mouse via a spout positioned in front of it.Mouse licking the spout was measured by a piezo element (TDK PS1550L40N) coupled to the spout and amplified with a custom-made amplifier system.Running wheel movement was measured with a rotary encoder (model Kübler) that was connected to the wheel axle.All behavioural data and events, such as piezo voltage trace, valve or change period on/off state, etc, were acquired via analog and digital channels on an NI PCI-6320 acquisition card and processed and saved using custom written code in LabVIEW (NI) and MATLAB (The MathWorks).

Figure 2 .
Figure 2. Resolution of the scanning system. A. Theoretical and measured X/Y PSF based on a f=150 mm objective lens and a 0.8 mm beam.The empirical data were obtained by translating the focused laser spot over the edge of a razor blade and measuring light intensity with a photodiode placed under the blade.This procedure yields an intensity curve resembling a cumulative Gaussian, which can be fitted as such and converted to a probability density function.Whilst we measure a beam size of under 100 µm FWHM, the true size of the spot on the brain surface is likely to be much larger.The beam will scatter as it goes through the cleared skull and then will scatter further as it enters the brain.B. Beam spot size across the field of view.Focusing the beam on a piece of paper elicits fluorescence which can be imaged with the camera.We acquired many such images whilst moving the beam over a grid of positions spanning an area roughly the size of a mouse brain.The size and shape of the beam is very similar across all positions, showing there is no change in the resolution of optical stimulation over the field of view.
function r u n T h r o u g h A l l S t i m P o i n t s% Present stimulus at each location for one second hZP = zapit .utils .getObject ; % Get API object from base workspace if hZP .isReadyToStim == false return end for ii = 1: length ( hZP .stimConfig .stimLocations ) % Does not wait for a hardware trigger : starts right away hZP .sendSamples ( ' conditionNum ' ,ii , ' h a r d w a r e T r i g g e r e d ' , false ) pause (1) % Software timing only hZP .stopOptoStim pause (0.3) % To allow the ramp -down to happen end end % r u n T h r o u g h A l l S t i m P o i n t s

Figure 4 .
Figure 4. Generating photostimulation conditions using the interactive stimulus editor. A. Screenshot of stimulus config editor.The user adds or modifies stimulus locations by clicking on the top-down view of the brain.Points can be added either freely ('unilateral' mode) or symmetrically on the left and right sides ('bilateral' mode).The laser power, stimulation frequency, and ramp-down time are set to default values for all stimuli using this GUI.The stimulus set is is saved as a human-readable text file.Laser power, ramp-down, and stimulation frequency can be altered on a trial by trial basis by editing this file.B. A stimulus set superimposed onto the dorsal brain surface.All squares with the same number are associated with a single trial and will be stimulated together.C. Fluorescence emitted from a 3D-printed mouse skull when stimulated by the trial patterns shown in panel B. Numbering of the sub-panels in C matches trial numbers in B.

Figure 5 .
Figure5.Reliable and precise photostimulation.A. The system was programmed to deliver a specific optogenetic stimulus (800 ms with 200 ms rampdown, 40 Hz).A photodiode was positioned at the sample plane to measure photostimulation output (black traces).We also measured the analog input signal sent to the laser (magenta).The inset shows a close up of the photodiode response and analog input signal aligned to the detected onset of the laser input signal (overlay of 50 repetitions).B Low latency and reliable hardwaretriggered photostimulation.Optogenetic stimulation (800 ms + 200 ms rampdown, 40 Hz) was triggered using a 100 ms hardware trigger (red trace).Data for each repetition were aligned to the hardware trigger onset.The inset on the right shows a close-up overlay of hardware (red) and photodiode (black) traces aligned to the hardware trigger onset (overlay of 50 repetitions).C Same as B, but showing the photostimulation response when a 1000 ms onset delay was added to the stimulation design.Samples were recorded at 100 kS/s using an oscilloscope (PicoScope)

%
Start the client , specifying the IP address of the Zapit server client = z a p i t _ t c p _ b r i d g e .TCPclient ( ' ip ' , ' 122.1 4.143.200 ') ; client .connect ; % present the last stimulus condition for a short period nCond = client .g e t N u m C o n d i t i o n s ; client .sendSamples ( ' co nd i ti on N um be r ' , nCond , ' h a r d w a r e T r i g g e r e d ' , false ) import z a p i t _ p y t h o n _ b r i d g e .bridge as zpb from time import sleep hZP = zpb .bridge () hZP .send_samples ( conditionNum = -1 , h a r d w a r e T r i g g e r e d = False ) sleep (0.75) hZP .s top_op to_sti m () sleep (0.5)

Figure 6 .
Figure 6.Beam pointing reproducibility and beam blanking.A. Beam positioning with blanking.The beam is cycled rapidly between three positions and disabled (blanked) whilst moving between positions.The size of the spots do not reflect stimulation area.B. Beam positioning without blanking.Leaving the beam on during the whole stimulation cycle risks activating off-target areas.The lines between points in this image are due to the beam travelling between points.C & D show in more detail that the beam is disabled during motion.The scanner position feedback trace from a single trial is shown in blue.The laser is pointed at a 1 cm diameter photodiode and the orange trace represents the signal from this sensor.When the orange trace is low the laser is off.The inset panel in C shows 100 overlaid trials to demonstrate reliability.

Figure 7 .
Figure 7. Optogenetic perturbation of ALM with Zapit biases directional licking during a delayedresponse perceptual discrimination task. A. Mice performed a bilateral whisker-guided frequency discrimination task.Trains of air-puffs were delivered simultaneously to the left and right whiskers.The target response was cued by the side receiving the faster stimulus rate.B. Trial timing schematic.The whisker stimulus presentation period (1 s) was followed by a short delay epoch (1 s).After the delay, a motorised stage moved the lickport forwards cuing the start of the response window.Left or right ALM was perturbed (2.2 s + 250 ms rampdown, 40 Hz rate, 2 mW time averaged power) during the stimulus and delay epochs on a third of trials.C. Unilateral perturbation was targeted to left and right anterior lateral motor cortex (ALM) in VGAT-ChR2-EYFP expressing mice.D. Example optogenetic perturbation experiment.The perturbation location and sensory stimulus for each trial are indicated by tick marks to the left of the axis.The grey shaded bar indicates the duration of the whisker stimulus (0 -1 s).The cyan bars indicate duration of perturbation.Individual licks are coloured as red (left licks) and blue (right licks) markers.Left vs Right choice is shown on the right-hand side.The plot shows the first 150 trials of a 398 trial session.E. Effect of ALM perturbation on task performance.Results are shown for an example mouse (left; 5 sessions) and across the group (right; 3 mice, 15 sessions).Discrimination performance is shown as a function of signed stimulus difference on control trials (black), left ALM perturbation (red) and right ALM perturbation (blue) trials.Data show the mean concatenated across sessions with error bars showing 95% binomial confidence intervals.F. Effect of laser power on perceptual errors.Perturbation of contralateral ALM impaired performance on unilateral whisker stimulation trials (11 sessions, 3 mice).Statistical tests were two-tailed Wilcoxon signed-rank tests, comparisons made with '0 mW' control trials.P-values are corrected for multiple comparisons.* P < 0.05; ** P < 0.01.Data show the mean and error bars show 95% CI across sessions.

Figure 8 .
Figure 8. Bilateral optogenetic perturbation of primary visual cortex with Zapit disrupts visual change detection.A.Schematic of task and optogentic stimulation parameters.VGAT-ChR2-eYFP mice were trained to detect and respond to a sustained increase in drifting speed (i.e., temporal frequency (TF)) of a grating.During the baseline period mice must refrain from movement while observing a stimulus fluctuating in TF every 50 ms and respond by licking only once the mean TF has increased.If they lick within the change period (Hit) they receive a soy milk reward.On 14% of trials mice were stimulated with a 470 nm laser through the intact skull covered by a thin layer of transparent bone cement (i.e., sometimes referred to as skull cap).Laser trials were randomly interleaved, and stimulation parameters on the 14% of trials would be randomly selected to be over S1 or V1 and either with 2 mW or 4 mW.A blue LED masking light matching the stimulation profile of the laser was presented above the mouse on every trial to mask when laser trials were happening.B. Psychometric effect of perturbing S1 and V1 with Zapit at 2 or 4 mW for an example mouse (binomial mean and 95% CI).Note the scaling of behavioural disruption with increased light power in V1, but not in the control area S1. C. Psychometric effect of perturbing S1 and V1 using Zapit at 2 or 4 mW across 5 mice (mean and 95% CI across mice, n = 5) using Zapit Acknowledgments We thank Andy Peters for providing us with a MATLAB script for displaying a top-down view of the Allen Atlas in stereotaxic coordinates, and inspiring us with the Neuropixels Trajectory Explorer (10.5281/zenodo.7043459).Dale Elgar from COSYS Ltd. did most of the enclosure design.Graeme McPhillips at the SWC Electronics Core Facility provided advice on construction of the electronics enclosure.We thank Morio Hamada and Ivan Voitov for providing feedback on the manuscript.This work was supported by Wellcome awards to T.D.M.F.(217211/Z/19/Z) and M.L. (224121/Z/21/Z).A.D. was supported by UKRI grant EP/Y008804/1.The Advanced Microscopy Facility and individual labs were also supported by the Sainsbury Wellcome Centre's core provided by Wellcome (219627/Z/19/Z) and the Gatsby Charitable Foundation (GAT3755).Availability Statement This project is developed entirely in the open: all code is available at github.com/Zapit-Optostim.Data available on request.