Monitoring neural activity during sleep/wake events in adult C. elegans by automated sleep detection and stimulation

Summary Sleep in adult C. elegans occurs spontaneously, making timing of individual sleep/wake state transitions unpredictable. This protocol presents a closed-loop system to automatically detect sleep state transitions, trigger stimulation, and record evoked neural responses. This allows users to assess functional consequences of behavioral states in an unbiased manner and identify state-dependent neuromodulation. This closed-loop system is flexible and can be configured to detect any visible events, such as behavior patterns or optical reporters, and measure corresponding evoked neural responses. For complete details on the use and execution of this protocol, please refer to Lawler et al. (2021).


SUMMARY
Sleep in adult C. elegans occurs spontaneously, making timing of individual sleep/wake state transitions unpredictable. This protocol presents a closedloop system to automatically detect sleep state transitions, trigger stimulation, and record evoked neural responses. This allows users to assess functional consequences of behavioral states in an unbiased manner and identify state-dependent neuromodulation. This closed-loop system is flexible and can be configured to detect any visible events, such as behavior patterns or optical reporters, and measure corresponding evoked neural responses. For complete details on the use and execution of this protocol, please refer to Lawler et al. (2021).

BEFORE YOU BEGIN
Construct the neural imaging system Timing: Several days to weeks prior to experimentation, depending on equipment availability A custom imaging and stimulation system controls illumination timing, image acquisition, sleep state identification, and stimulus delivery (Figure 1). Although a variety of equipment can accomplish these tasks, here we describe the construction of an inexpensive system using open-source hardware and software. An Arduino Nano microcontroller controls fluidic valves through a ValveLink 8.2 (AutoMate Scientific) valve controller and controls illumination sources for brightfield and fluorescent imaging via digital signals. The Arduino controller interacts with the camera to synchronize stimulation and image recording, as directed by open-source Micro-Manager software (Edelstein et al., 2014).
1. Build an Arduino controller with all necessary connections to the brightfield and fluorescent illumination sources, the camera, and to the valve controller (Figures 2A and 2B). a. Connect Arduino Nano and screw terminal breakout ( Figure 2C). Solder headers onto Nano if necessary. b. Connect BNC screw terminals (or equivalent connectors) for the following signals, connecting the negative terminal to ground (GND) and positive to the indicated pin number (Figure 2D).
iii. A1 to DB9_pin9 (valve 2) for optional outflow control. iv. Optionally connect other valve control wires as needed, such as A2 to DB9_pin4 (valve 3). Up to eight valves can be supported to deliver multiple stimuli. d. Recommended: secure all cables and components.
i. Attach Nano to ValveLink using velcro hook-and-loop fastener ( Figures 2E-2G), and any others such as a LED controller. ii. Route all cables and secure them to ensure stable connections, e.g., using tape, zip tie, or Velcro.
2. Connect valve cable (RCA or as needed by controller) to a 3-way actuated fluidic valve for stimulus selection at valve 1. 3. Connect valve cable (RCA or as needed by controller) to a pinch valve for outflow shutoff at valve 2. Alternatives: Other equipment can be used for each of the imaging system components, as long as any substitutes maintain the ability to control illumination timing, fluidic valves, and image acquisition. For example, the Valvelink controller can be replaced with an inexpensive multichannel relay module or MOSFET trigger switch module to actuate fluidic valves. In the configuration described, all inputs and outputs are TTL-compatible voltage signals (0-5 V). Substitution of different cameras and controllers may require modification of the open-source code, for example to invert the polarity of a control signal.
Install and configure software Note: This protocol was tested with MicroManager version 1.4.17. Use this version to ensure consistency of operation.

Prepare microfluidic equipment
Timing: 2-6 h for fabrication of new components; 30 min to clean and prepare reused components Experiments are conducted using microfluidic chambers that facilitate precise chemical stimulation and keep animals within the microscope field of view. For complete details regarding the design, fabrication, cleaning, and preparation of microfluidic devices for behavioral and neural imaging of C. elegans please refer to Lagoy and Albrecht (2015). For video protocols regarding the setup and use of microfluidic devices, please see Reilly et al. (2017). The reusable microfluidic device, reservoirs, and tubing should be fabricated in advance and cleaned prior to experimentation. 11. Prepare all components for the microfluidic system: a. Neural imaging microfluidic device made from cured poly(dimethyl siloxane) (PDMS) with dermal punched inlet and outlet channel holes ( Figure 3A Figures 3A and 3B). Cut glass slides to size (e.g., 25 3 40 mm) with a diamond scribe and grind holes (2 mm diameter) using a rotary tool and diamond-coated bit. c. Hydrophobic (fluorinated) glass bottom slide ( Figures 3A and 3C). Silanize glass with TFOCS by vapor deposition in a fume hood vacuum chamber (see Lagoy and Albrecht, 2015). Sealing hydrophobic PDMS microfluidic devices with hydrophobic glass reduces the risk of leakage. d. Completed microfluidic device, sandwiched between the top and bottom glass ( Figure 3B) and secured in a clamp ( Figure 3C).

OPEN ACCESS
e. Three solution reservoirs using 60 mL syringes for fluid storage, 3 mL syringes for fluid priming, 3-way Luer valves for flow control, and tubing attached ( Figure 3D). Two reservoirs (for saline buffer and copper chloride stimulus solution) have tubing attached for direct flow into the microfluidic device. One reservoir (for control solution) will connect to a 3-way electrically-actuated fluidic valve ( Figure 3E) for switching between flows during the automated neural imaging trials. Label each reservoir clearly for intended use. f. Worm loading syringe ( Figure 3F) consisting of a 1-mL syringe connected to 50 cm tubing and a metal end tube. g. Outflow tubing connected through an optional outlet pinch valve to a 10 mL or 30 mL syringe reservoir and 3 mL side syringe for priming via two 3-way Luer valves ( Figures 3G and 3H). The pinch valve allows automatic flow stoppage at the end of an experiment.
Note: Inlet tubing can be flexible Tygon or rigid Teflon. Consult Lagoy and Albrecht, 2015 for details. Teflon tubing is more inert and preferred for hydrophobic stimuli.
Note: Components can be reused after thorough cleaning. Flush with diH 2 O, 70% ethanol, then diH 2 O, and dry using an air stream. Microfluidic devices should be soaked in 70% ethanol for 1 h to overnight and can be reused dozens of times. Devices used with hydrophobic stimuli at high concentrations may require stronger cleaning, dedicated components, or more frequent replacement.  (1), two Luer valves (2), a priming syringe (3), tubing to the device (4), the outflow pinch valve (5), tubing to waste (6), and a waste container (7).

Prepare nematodes
Timing: 10-20 min, timed 16-24 h prior to experiment Maintain C. elegans under standard conditions on Nematode Growth Medium (NGM) plates and fed OP50 Escherichia coli bacteria (Stiernagle, 2006). For neural imaging of the ASH aversive sensory neuron, use a C. elegans strain expressing GCaMP in the ASH neuron such as: CX10979, kyEx2865 [Psra-6::GCaMP3; Pofm-1p::GFP] (Larsch et al., 2013). Each experiment uses a single young adult C. elegans. Pick several array-positive L4 stage hermaphrodite animals 16-24 h prior to the experiment and isolate them to a fresh seeded plate. Adjust timing as needed for the desired stage of testing.
Note: The closed-loop system is applicable to studying any neuron(s). Substitute an appropriate strain expressing GCaMP in the desired neurons. For other color indicators, such as red-emitting RCaMP, use an appropriate fluorescent excitation source and microscope filter set, and a brightfield illuminator that matches the emission filter color.
Note: When using animals larger or smaller than wild-type young adult hermaphrodites, such as males, older adults, younger larval stage animals, or some genetic mutants, use microfluidic devices scaled proportionally to body size for smooth locomotion and to prevent escape from the arena. This step prepares the microfluidic equipment and solutions for experimentation. For complete details regarding the design, fabrication, cleaning, and preparation of microfluidic devices for behavioral and neural imaging of C. elegans please refer to Lagoy and Albrecht (2015). For video protocols of microfluidic device setup and operation, see Reilly et al. (2017). This example uses Copper chloride solution to stimulate the ASH aversive neurons.

KEY RESOURCES
1. Clean microfluidic device and top and bottom glass pieces by rinsing sequentially with water and 70% ethanol, wiping with a lint-free wipe, then drying in an air stream. Remove any dust with transparent tape, then align and secure with binder clips or a microscope slide holder ( Figures 3B and 3C). 2. Place device in a vacuum desiccator for 30 min. 3. Prepare 200 mL of Saline buffer and use it to prepare 60 mL of Control buffer (1 mg/mL fluorescein) and 60 mL of Copper chloride stimulus solution (1 mM CuCl 2 ). 4. Attach 3 reservoirs to the reservoir rack stand above the microscope ( Figure 4A). 5. Fill each of the 3 reservoirs with their designated solutions (60 mL of Saline buffer, Control buffer, or Copper chloride solution) and purge all bubbles from the connected tubing using the priming syringe (see Reilly et al., 2017 and troubleshooting Note 1). Actuate the valve to fill all tubes connected to the 3-way fluidic valve. 6. Fill the waste reservoir with R10 mL Saline buffer and use the priming syringe to fill both the outflow waste tube and the outflow outlet tube with buffer (see Figures 3G and 3H Figures 4B and 4C). 9. Insert tubing or a blocking pin into the worm loading inlet. 10. Gently insert each reservoir's tubing into the appropriate inlet (Figures 1 and 4C).
a. Connect the control reservoir 3-way valve ( Figure 3E) ''normally-closed'' outlet to the ''con-trol1'' inlet and its ''normally-open'' outlet to the ''control2'' inlet. b. Insert tubing approximately 3 mm into the PDMS inlet hole (to 2/3 depth). c. Use ''drop-to-drop'' connections, in which a droplet hangs from the tubing end and is connected to a liquid droplet above the microfluidic port (see Lagoy and Albrecht, 2015). d. Remove any excess liquid from the glass by vacuum aspiration or paper towel. 11. Open the outflow valve to establish flow. View live images in the microscope and verify that no bubbles are present in the device channels (see troubleshooting Note 1). 12. Balance inlet flows.
a. Focus on the intersection of inlet channels (Figures 4C and 4D) and observe flow patterns while alternately activating and deactivating the 3-way stimulus valve. b. Adjust reservoir heights up or down so that flow from Saline buffer and Copper chloride solution are equal and flow from Control buffer enables complete switching between Saline buffer and Copper chloride solution into the downstream imaging area (see Figure 4D and troubleshooting Note 2).
CRITICAL: Avoid introducing bubbles into the device during device preparation (see also troubleshooting Note 1). Ensure that the outflow valve is open only when all device inlet a. Remove the blocking pin from the worm loading inlet and allow a small droplet to form by briefly opening the buffer reservoir valve. b. Insert the worm loading tubing with a drop-to-drop connection. c. Remove excess liquid from the glass by aspiration or paper towel. 19. Establish fluid flow in the microfluidic arena.
a. Open the outlet valve to resume flow. Typical flowrate is about 1 mL/s or 4 mL/h, and is proportional to the difference in fluid height between inlet and outlet reservoirs. b. Adjust flowrate by raising or lowering reservoirs. Behavior is generally insensitive to flowrate (Albrecht and Bargmann, 2011). 20. Insert worm into the microfluidic arena.
a. Verify that saline buffer is present in the imaging arena (deactivate stimulus valve if not). b. Apply gentle pressure to the worm loading syringe plunger until the animal enters the arena. 21. Monitor the animal for 1-2 min to ensure behavior is normal and the animal is healthy (see troubleshooting Note 3).

Set testing parameters and run experiment
Timing: 5-10 min setup, 12 h duration This step describes the final steps of setting experimental parameters to determine sleep/wake state prior to running the closed-loop script.
22. Capture a single image frame of the arena under brightfield illumination with the animal visible. 23. Using the ''ImageJ'' toolbar in ''Micro-Manager,'' import the image frame at 25% scale. 24. Using the rectangle tool, draw a box spanning the outermost points of the arena where the animal will roam. This selection box will be the area of interest used for analyzing animal movement. Record the dimensions (x, y, w, h) of the rectangle, visible in the ImageJ toolbar window ( Figure 5). 25. Open ''SleepDetection.ijm'' and edit the variables x, y, w, and h near the top to define the selected area of interest, then save the file.

OPEN ACCESS
26. Locate the ''User Defined Closed Loop Settings.txt'' file on the computer and set parameters as desired ( Figure 6). Detailed information on each parameter is available within the file and in the ''ClosedLoopSleepStim.bsh'' script. 27. Run the ''ClosedLoopSleepStim.bsh'' within Micro-Manager to initiate the experiment.
Note: Occasionally animals try to escape the microfluidic arena through the worm entry port (see troubleshooting Note 3). Most often this occurs at the beginning of the experiment, so it is advised to monitor progress during the first few minutes after loading the animals. Use the worm loading syringe to gently push the animal back into the field of view if the animal attempts to escape the arena, or load a new animal if necessary. Once the animal is well established in the arena, the experiment can run unattended.

EXPECTED OUTCOMES
Adult C. elegans sleep behavior varies greatly even across a population of genetically identical wildtype animals under no stimulation ( Figure 7A). On average, about 10%-30% of unstimulated wildtype adult C. elegans animals should be in a sleep state at any moment, and median sleep bout duration is about 1.5-2 min (Lawler et al., 2021). With a moderate stimulus (such as 1 mM CuCl 2 ), a typical 12 h experiment should yield 12-24 sleep/wake transitions or approximately one transition every 30-60 min ( Figure 7B). If sleep/wake event yield is too low with a stronger stimulus, sleep events can be induced via deoxygenation (such as using sodium sulfite, see Lawler et al., 2021). Many factors can influence sleep dynamics, including environmental conditions (see troubleshooting Note 4).
The closed-loop script organizes behavioral videos and neural stimulation sets into a designated save location. All behavioral videos are contained in ''TimeLapse'' folders separated between stimulations. All stimulus captures are labeled in ''Stimulus'' folders with the detected behavioral state indicated. Sleep state predictions were found to be 93.4% accurate compared to human observation (Lawler et al., 2021). It is recommended to verify correct identification of behavioral transitions prior to sleep state analysis. For example, view behavioral videos and verify that sleep bout videos show minimal motion and sleep-specific posture (Lawler et al., 2021) and awake videos do not include sleep periods (see troubleshooting Note 5).

QUANTIFICATION AND STATISTICAL ANALYSIS
To quantify neural fluorescence, NeuroTracker (Larsch et al., 2013) ImageJ software tracks the position of the neuron over time and integrates fluorescence intensity of the soma within a small integration box (available with usage instructions at https://github.com/albrechtLab/Neurotracker). Use active behavior tracking settings as animals frequently move during the stimulation period. Choose an integration box size that just encloses the neuron soma, typically 4 3 4 pixels or 6 3 6 pixels.
NeuroTracker outputs a text file containing neural tracking data over time for each animal, including centroid position, integrated fluorescence intensity, and background level. A MATLAB script ''Neu-roTrackerSummary.m'' can be used to read, organize, and visualize neural fluorescence data across individuals ( Figure 7C) or averaged across groups such as sleep and wake states ( Figure 7D). Neural fluorescence (F) is calculated by subtracting the background (median intensity of an annulus surrounding the neuron) from average fluorescence intensity in the integration box. To compare across animals with different GCaMP expression, intensity measurements are normalized to a baseline consisting of the first 4 s of each trial before stimulation (F 0 ). The normalized activity over baseline, DF/ F 0 = (F -F 0 )/F 0 , can be averaged across individuals and population groups. For statistical comparisons, it is recommended to reduce data per trial to metrics such as peak calcium activity, area-under-curve (AUC), baseline F 0 , rise time, and decay time. These values can then be compared statistically across sleep states, perturbations, or other experimental groups.

LIMITATIONS
Unlike lethargus states between well-timed larval stages, adult sleep events are not time synchronized and occur randomly. Since chemical stimulation is applied uniformly across the entire arena in the neural imaging device, the methods described above are limited to one animal at a time. Additionally, sleep state is determined by a whole-field image subtraction, necessitating one animal per image field. Due to this reduced throughput, it is advised to first determine the overall sleep response to new genetic or chemical perturbations using a high-throughput microfluidic population behavior assay (Lawler et al., 2021), then analyze neural responses as described here using identical conditions. Alternatively, timed stimulus pulses can be delivered and resulting neural responses can be grouped post hoc based on each animal's sleep state. However, while this method allows for Figure 6. Sample experiment settings file These sample settings define imaging resolution (bin 2), framerate (100 ms exposure = 10 frames/s), and illumination timing (20 ms for brightfield, 10 ms for fluorescence with 5 ms delay from exposure onset). Stimulation recordings capture 300 frames (or 30 s at 10 fps), and the stimulation program is a 10 s chemical pulse (valve 1 opens from frame 50-150 or from 5-15 s within each recording trial). The entire experiment lasts 12 h. Sleep state changes are monitored using a 10-s interval and changes must persist for 3 intervals (i.e., 30 s) to register a transition. After each stimulation trial, 15 min should elapse before triggering a new stimulation (regardless of any transitions within this time delay), and the next trigger shall begin following the opposite transition (i.e., Sleep-to-wake follows Wake-to-sleep).

OPEN ACCESS
analysis of many animals at once, it does not control for timing between state transitions and stimulation tests.
To monitor free-roaming behavior without camera tracking, a low-magnification (53) objective is used such that the entire 3 mm 3 3 mm microfluidic arena is contained within the field of view. Calcium imaging at this magnification is sufficient for tracking single neural activity, or a few neurons spaced at least 10-20 mm apart. This resolution is not sufficient for whole-brain imaging. Additionally, some neural imaging C. elegans strains may not show sufficient expression to be clearly visible at this magnification or may have low baseline activity. For example, newer GCaMP variants (6+) increase dynamic range by decreasing baseline fluorescence, making tracking of inactive neurons more difficult without additional markers, such as a stable red fluorescent protein expressed in the same neuron.
The sleep detection script relies on detection of movement across frames, and therefore may not be suitable for detecting sleep events in mutants that have overall movement deficiencies. Adjusting movement sensitivity parameters may be sufficient for accurate state detection (see troubleshooting Note 5). Alternatively, the image processing script can be altered to assess any type of optical reporter that does not rely on movement. For example, states and trigger events could be defined by fluorescent reporters expressed in neurons, muscles, or other cells. In this way, the closedloop sleep detection and stimulation system could be broadly adapted to automatically assess neural responses following any detectable biological phenomenon, such as a locomotory behavior, neural response, mating event, or a change in level or localization of a signaling molecule.

TROUBLESHOOTING Problem 1
Air bubbles enter or form in the microfluidic chamber (steps 5 and 11).  Lawler et al., 2021). Note that these data were obtained using a large population microfluidic device, not described in this protocol. (B) Example single animal behavior in a typical 10-h closed-loop experiment indicating automatically triggered neural recording trials. Sleep and awake states are indicated by black and gray shading. Recordings were triggered one minute after a sleep state change, followed by 15 min of rest (white shading). (C) Heatmap of individual ASH neural responses to 10 s stimulation with 1 mM CuCl 2 (gray bar), in sleeping and awake animals. (D) Average ASH neural responses in sleep and awake states from panel C (n = 18 sleep, 17 awake). Shading represents s.e.m. No change is observed in ASH sensory responses between the sleep and wake states, indicating a consistent sensory response. Other neurons may change in peak magnitude, duration, rise time, decay rate, or other metric across sleep states.

Potential solution
A common problem with microfluidic devices is the presence of air bubbles within the liquid channels, which affect fluid flow, animal behavior, and microscope imaging. Bubbles can either be present at the beginning of an experiment or form during the experiment. To avoid initial bubbles, the microfluidic devices should be degassed in a vacuum chamber before filling such that any bubbles present upon fluid inflow are absorbed into the gas-permeable PDMS material. Extended vacuum duration, and quickly loading fluid upon release from vacuum, will accelerate this process. Next, it is important to avoid flow of air bubbles from the tubing and Luer fittings. Thoroughly purge air from reservoirs and inlet tubing, using vigorous flicks of the Luer fittings to dislodge any bubbles, and make careful drop-to-drop connections at the inlets as described in Lagoy and Albrecht (2015) and Reilly et al. (2017). Finally, to avoid bubble growth during a long experiment, ensure that the chamber is kept at a net positive pressure relative to atmosphere by keeping the inlet and outlet reservoir liquid levels above the device. While it is possible to remove bubbles by pressurizing the chamber, it is usually faster to open, clean, reassemble, and refill the microfluidic device.

Problem 2
Fluids do not switch properly during stimulation (step 12).

Potential solution
Proper fluid switching ensures that the stimulus is delivered reliably to the animal regardless of its position within the arena. During the setup procedure, it is recommended to include a temporary stimulus solution containing fluorescein or other visible dye, and ensure that upon valve actuation the entire arena fills with stimulus solution (see Figure 4D). Imbalanced flow is indicated by a buffer stream at the top or bottom of the arena during valve actuation, or a stimulus stream without valve actuation. To balance flows, ensure that the tubing lengths and diameters are identical, and that reservoirs are positioned such that fluid heights are level. Slight adjustments in flow balance can be made by raising or lowering reservoirs. Note that any fluorescent dye in the stimulus or buffer solutions should be removed after flow balancing, as it can affect tracking of neural activity. One convenient method is to draw a small amount of dye (20-50 mL of 0.1 mg/mL fluorescein) into the tubing of either the stimulus or buffer reservoirs using the priming syringe. Flow balance can then be monitored and adjusted until the dye fluid has passed. Fluorescein added to the control fluid should never pass through the arena. Ensure that the control fluid only exits via the bypass channels around the arena, with equal stream width in the upper and lower channels as the valve is actuated.

Potential solution
Animals may try to escape the arena in search of food or other attractants. Physical barriers upstream and downstream keep the animal actively roaming in the field of view. Animals that escape through these barriers may be physically smaller than a young adult stage wild-type C. elegans. For example, mutants may grow more slowly and require more time to reach the desired size. Additionally, animals may escape if the device is not sealed properly or is damaged. Carefully check the device for damage, especially at the barriers using a stereomicroscope, and ensure all surfaces of the microfluidic device and glass pieces are fully cleaned of debris prior to assembly. Minimize syringe force when loading the animal, as overpressure may disrupt the seal between the device and the glass slide.
An animal may also escape the microfluidic arena through the worm loading port located upstream in the device, especially if fluid flow is slow or stopped. Ensure that sufficient downstream flow is present to keep animals within the micropost array of the arena. A typical flowrate of 1 mL/s is sufficient, corresponding to about 50 cm height between inlet and outlet reservoir levels. Monitor the beginning of each experiment, and if an animal enters or nears the worm loading port, gently apply pressure to the worm loading syringe to push the animal back into the micropost array.

Problem 4
The animal does not sleep (expected outcomes section).

Potential solution
Sleep in adult C. elegans is sensitive to many environmental factors and varies substantially across individuals. A lack of sleep may result from unintended stimulation to the animal. Stimulation from light (especially blue and ultraviolet light), chemical stimuli, and mechanical perturbations can limit sleep. Ensure that the animal is not exposed to any unnecessary blue/UV light, that buffers are freshly prepared, that animals are loaded into arenas filled with buffer (not stimulus), that flow through the microfluidic device is gentle, and that animals exhibit natural crawling movement. If animals do not sleep after the first sleep transition stimulation, the stimulus concentration may be too high. Additionally, rough handling of the animal prior to loading can also lead to a diminished sleep response.

Problem 5
The script does not correctly identify sleep states (expected outcomes section).

Potential solution
Sleep detection follows an image processing algorithm that may require adjustment based on image quality and lighting to correctly identify the animal. To determine adjustments, observe the result of each step in the segmentation process ''SleepDetection.ijm'' using the ImageJ software. For example, segmentation of the animal from the microfluidic environment requires thresholding, by default using Otsu's method to isolate the foreground (animal) from the background of the image. Depending on lighting conditions, other automatic or manual thresholding methods may be more effective. After thresholding, the script identifies a valid animal assuming a consistent pixel resolution to size the animal. The script by default expects an image resolution of 350 pixels/mm when at full scale (90 pixels/mm at 25% scale), and this parameter should be adjusted for other image resolutions or animal sizes.

RESOURCE AVAILABILITY
Lead contact Further information and requests for resources and reagents should be directed to Dirk R. Albrecht (dalbrecht@wpi.edu).
Materials availability C. elegans strains are available from the Caenorhabditis Genomics Center, or from the corresponding author of published works. Microfluidic design files are available upon request to the lead contact.