A rise-to-threshold signal for a relative value deliberation

Whereas progress has been made in identifying neural signals related to rapid, cued decisions1–4, less is known about how brains guide and terminate more ethologically relevant deliberations, where an animal’s own behavior governs the options experienced over minutes5–8. Drosophila search for many seconds to minutes for egg-laying sites with high relative value9, 10 and neurons, called oviDNs, exist whose activity fulfills necessity and sufficiency criteria for initiating the egg-deposition motor program11. Here we show that oviDNs express a calcium signal that rises over seconds to minutes as a fly deliberates whether to lay an egg. The calcium signal dips when an egg is internally prepared (ovulated), rises at a rate related to the relative value of the current substrate being experienced, and reaches a consistent peak just prior to the abdomen bend for egg deposition. We provide perturbational evidence that the egg-deposition motor program is initiated once this signal hits a threshold and that sub-threshold variation in the signal regulates the time spent deliberating and, ultimately, the option chosen. These results argue that a rise-to-threshold signal guides Drosophila to lay eggs on substrate options with high relative value, with each egg-laying event representing a self-paced decision similar to real-world decisions made by humans and other mammals.

] dips during ovulation, rises for seconds to minutes, and peaks immediately before the abdomen bend for egg deposition. a, Behavioral sequence of egg laying. b, Imaging an egg expressing GCaMP3 in the body, over time. Steps correspond to panel a. Image contrast has been adjusted for display; insets show close ups, with over/under saturated pixels in red/blue. c, Progression of the behavioral sequence of egg laying. Grey lines connect events from a single egg-laying sequence in a single fly. d, Schematic of wheel for measuring neural activity and body posture during egg laying. e, A single oviDNb descending neuron traced from light-microscopy images. Arrow points to cell body. f, Images of oviDN and oviDN-like cell bodies in a single side of the brain labeled by the two driver lines used in this study. The fly's midline is on the left. g, oviDN ∆F/F and fly behavior during egg laying for two eggs laid by the same fly. ∆F/F is smoothed with a 2 s boxcar filter. Images show the z-projection of selected two-photon imaging slices. Labels a and b in images refer to oviDNa and oviDNb, respectively (oviDNa is partially obscured by oviDNb in the z-projection). h, Population-averaged oviDNb ∆F/F aligned to the end of the abdomen bend for egg laying (light gray shading is s.e.). Data associated with 43 imaging traces from 41 egg-laying events associated with 9 cells in 8 flies are shown. The number of traces exceeds the number of egg laying events by two because for two eggs we imaged the oviDNb on both sides of the brain. Behavioral events shown below. i, A schematic of abdomen bend. θ is body angle and length is neck to ovipositor distance. j-l, Mean oviDN ∆F/F and fly behavior aligned to events in behavioral sequence shown in panel h. Normalized length is the length as shown in panel i divided by the median length (Methods). Filled arrows point to the moment the abdomen bend for egg deposition is complete. A subsequent (stronger) bend is, presumably, for cleaning the ovipositor after egg deposition. m, oviDN ∆F/F during individual egg-laying events for 3 separate flies, smoothed with a 5 s boxcar filter. Mean in black. n, Mean oviDN ∆F/F during egg laying for all 7 flies that laid ≥ 3 eggs, smoothed with a 5 s boxcar filter. A single fly imaged with GCaMP7b is shown with a thicker grey line.
to the abdomen bend for egg deposition (Extended Data Fig. 6b). The GCaMP signal from both the ipsilateral oviDNa and the contralateral oviDNb showed a cross-correlation with a zero-lag peak with the oviDNb (Extended Data Fig. 6c-d), supporting a model where all four oviDNs in the oviDN-SS1 line exhibit the same first-order calcium dynamics during egg laying. During non-egg-laying periods the oviDN ∆F/F signal fluctuated, maintaining a correlation with abdomen movements and locomotor variables (Extended Data Fig. 7a-d). Approximately once every half hour, the oviDN ∆F/F signal reached the 0.35 level without ovulation having occurred prior and these moments were associated with abdomen bends that yielded no egg (Extended Data Fig. 7e).
oviDNs thus express a signal whose dynamics correlate tightly with the behavioral sequence of Drosophila egg laying. This discovery raises two key questions that we pursue further here. First, is the egg-deposition motor program triggered by oviDN activity hitting a threshold? Second, if an activity threshold indeed triggers egg deposition, is subthreshold oviDN activity modulated during the search period to increase the chance that threshold is reached on substrates of higher relative value?

Evidence for a threshold in oviDN [Ca 2+ ] activity triggering the egg-deposition motor program
To test whether the egg-deposition motor program is initiated when oviDNs hit a threshold, we coexpressed in them GCaMP7f and the light-gated ion channel, CsChrimson 32 . We then measured oviDN ∆F/F and fly behavior while providing 5 s long, high-intensity light pulses (Methods). Stimulations after ovulation typically yielded an abdomen bend and egg deposition (Fig. 2a, Supplementary Video 5). Of the 34 high-intensity stimulations after ovulation, 28 (82%) resulted in egg deposition. Of the 174 highintensity stimulations without a prior ovulation event, 4 (2%) resulted in eggs (Fig. 2b). In all 4 of those cases, the eggs were from the first stimulation pulse given to a fly and ovulation may have occurred prior to the imaging session. If we average [Ca 2+ ] and behavioral signals around the time of stimulations that yielded an egg, we observe an increase in ∆F/F in the oviDN alongside a synchronous abdomen bend and egg deposition with variable latency (Fig. 2c). Note that the peak in oviDN [Ca 2+ ] slightly lagged the initiation moment of the abdomen bend in these stimulation experiments. It is likely that with optogenetic light pulses, however, that [Ca 2+ ] at presynaptic zones--the relevant compartment for driving behavior-reaches threshold earlier than does [Ca 2+ ] at the soma, given that synapses are small and are expected to have faster [Ca 2+ ] dynamics than cell bodies 33 .
In our initial experiments, we stimulated the oviDNs at user-defined moments. In subsequent experiments, we performed regularly spaced stimulations in flies expressing or not expressing CsChrimson. Flies expressing CsChrimson bent their abdomen, on average, with regularly spaced stimulation, even as none of these stimulations resulted in an egg (Fig. 2d), whereas control flies did not bend their abdomen (Fig. 2e). We interpret this result--alongside the observation that flies tend to bend their abdomen when oviDN activity is spontaneously high without prior ovulation (Extended Data Fig.  7e)--to mean that flies initiate the egg-deposition motor program when oviDNs reach a high level of activity. If an egg is available in the uterus, egg deposition occurs, albeit with temporal variability that is perhaps related to sensory feedback signals in the uterus 24 or aspects of the motor sequence related to how eggs are released 25 . The temporal variability in egg deposition was qualitatively similar in optogenetically-stimulated (Fig. 2c) and spontaneous (Fig. 1h) egg laying in head-fixed flies.
Is the egg-deposition motor program initiated in an all-or-nothing fashion when oviDN activity crosses a threshold? To test this hypothesis, we stimulated oviDNs at a regular interval while cycling through four different intensities of light. We assigned each oviDN response to one of seven bins depending on the ∆F/F maximum on that stimulation pulse (Fig. 2f). For each bin, we also plotted how much the abdomen moved. We found that when the stimulation pulse caused the oviDN ∆F/F signal to exceed ~0. 35, the flies produced a large abdomen bend and when the stimulation pulse induced a smaller oviDN signal, there was not a large bend (Fig. 2g-h). This result was robust to how we binned ∆F/F responses (Extended Data Fig. 8). These data are consistent with the hypothesis that a threshold level of oviDN activity initiates the egg-deposition motor program in a yes/no fashion. It is intriguing that the threshold level for abdomen bending in these CsChrimson stimulation experiments is similar to the 0.35 ∆F/F value observed during spontaneous egg laying (Fig. 1l). Because the excitability of CsChrimson expressing neurons is likely to be different from neurons lacking an optogenetic opsin and we are only stimulating 2 of the 5 oviDNs per side, this correspondence is not guaranteed to be functionally meaningful.

Flies search for an egg-laying substrate with high relative value in the time period when the oviDN [Ca 2+ ] is rising
If an oviDN activity-threshold triggers initiation of the egg-deposition motor program, might substrate quality modulate oviDN activity to influence when threshold is reached and thus where an egg is laid?
We first analyzed the egg-laying behavior of freely walking Drosophila to better understand how flies use substrate experiences during the search period, i.e., the time period after ovulation and before eggdeposition is initiated, to guide egg-laying substrate choice. We placed flies in custom, high-throughput chambers for egg-laying with wells for two different substrate options (Fig. 3a, Extended Data Fig. 1b, Supplementary Video 6) (Methods). We focused on sucrose-based choice because sucrose is non-volatile and this allowed us to infer the timescale over which flies use past substrate experiences to guide egg laying on the current option, independently of the flies being able to smell, or otherwise sense, the previous option at a distance (see below).
Drosophila melanogaster, perhaps counterintuitively, lay most of their eggs on the substrate with the lower, not higher, concentration of sucrose 9,10 . In the wild, D. melanogaster prefer to lay eggs on rotting fruit 13 , and the bias to low sucrose in our assays may be because a soft substrate with high levels of ethanol and low levels of sucrose 16 mimics the rotting portion of the fruit where active fermentation is taking place (i.e., conversion of sugar to alcohol). We replicated past results that showed sucrose-based choice to be, remarkably, a relative-value decision 9,10 . That is, flies strongly bias egg laying to the lower of two sucrose options rather than preferring an absolute sucrose concentration. For example, they laid > 90% of eggs on the 0 mM option in 0 vs. 200 mM chambers and they laid > 90% of their eggs on the 200 mM option (the previously avoided substrate) in 200 vs. 500 mM chambers (Fig. 3b). Flies laid a similar total number of eggs in all chambers, regardless of whether the chambers had substrates with the same sucrose concentration in both wells (one option) or two different concentrations (two options) 9,10 ( Fig.  3c).
Although we did not collect images with sufficient spatial resolution to detect elongation and scrunching of the flies' abdomens in these chambers, we could still detect the onset of the search period by analyzing the locomotor trajectories of flies because Drosophila consistently stand still for ~1 min. when they ovulate (Extended Data Fig. 2b-c) (Methods). We could also denote the end of the search period as the moment at which an egg was half out of the ovipositor, which follows the final abdomen bend for egg laying by only a few seconds in these environments ( Fig. 1c) (Fig. 3a) (Methods). The duration of the search period was highly variable (Fig. 3d). The search almost always ended with flies laying an egg on the lower sucrose option, despite spending appreciable time on the higher option during the search epoch 10 (Fig. 3e). 95% (734 of 771) of eggs were laid on 0 mM while only 77% (592 of 771) of search periods started on 0 mM (p = 2.1e-25). Note that more search periods start on 0 mM because ovulation tends to occur soon after the previous egg-laying event (Extended Data Fig. 2a) and egg laying tends to occur on 0 mM. We also noticed that when flies started the search period on 500 mM, they frequently left the high-sucrose substrate while searching (83%, 149 of 179), but when flies started their search on 0 mM, they left the low-sucrose substrate less often (36%, 212 of 592) (p = 8.4e-29). Leaving a higher sucrose substrate more often at the onset of search is not an intrinsic property of the substrate because flies leave substrate islands at a similar rate in 500 vs. 500 and 0 vs. 0 mM chambers (299 of 528 = 57% and 441 of 895 = 49%, respectively). Flies thus retain information about the substrate options available to them from experiences outside of the current search period and use this information to regulate the search. We tested for the possibility of flies using spatial memories to guide their egg-laying behavior in our chambers, but we could not find supportive evidence (Extended Data Fig. 9). Flies probably use spatial rises. a, Y-position trajectory, and egg-deposition events from a single fly in a high-throughput egglaying choice chamber. b, Fraction of eggs on the lower sucrose option with 95% confidence interval. xaxis indicates sucrose concentration in mM. One dot is one fly. c, Eggs laid per fly. One dot is one fly. d, Each row represents a single egg-laying event in a 0 vs. 500 mM sucrose chamber, aligned to egg deposition, with the fly's speed indicated by the black intensity. Rows have been ordered based on the search duration. Start of the search period is indicated in magenta. 18 flies were tested, and one did not lay eggs. e, Same data as in panel d, but the substrate, 0 vs. 500 mM, that the fly was residing on is indicated with white and black pixels respectively. f-h, Mean egg-laying rate during the search period after a transition from higher to lower sucrose (lighter blues) or lower to higher sucrose (darker blues) in three separate sucrose choice conditions with 90% confidence interval shaded (Methods). 771 eggs from 17 flies (18 flies tested and 1 did not lay eggs), 1863 eggs from 42 flies (47 flies tested and 5 did not lay eggs), and 1345 eggs from 30 flies (30 flies tested), respectively. memories to guide egg-laying behavior in other contexts, but our experiments were conducted in darkness, in chambers where flies typically run around the chamber edges continuously (thigmotaxis), which likely promotes a non-spatial strategy. We also did not find evidence that flies were specifically pausing to feed on the higher sucrose substrate while searching, suggesting that in our experiments a competing feeding drive is not the reason for suppression of egg laying on higher sucrose substrates (Extended Data Fig. 9).
We noticed that flies would occasionally lay eggs on the higher sucrose option, specifically if a few minutes had elapsed since they last visited the preferred, lower sucrose option (Fig. 3a bottom, first two eggs). To quantify this observation, we calculated the egg-laying rate during the search period as a function of time since the last substrate transition (regardless of whether the last transition occurred in the current search period or prior) (Methods). Flies in 0 vs. 500 mM sucrose choice chambers strongly inhibited egg laying on 500 mM if they had visited the 0 mM option in the past ~2 min. (Fig. 3f). After ~2 min., the egg-laying rate on 500 mM began to increase gradually, approaching, albeit not completely, the egg-laying rate on 0 mM at the 2-hour time point. One interpretation of this egg-laying-rate plot is that the relative value of the 500 mM substrate gradually increases over time, eventually approaching the value of the 0 mM substrate, if 0 mM is not revisited. This phenomenon is also visible in 0 vs. 200 mM and 200 vs. 500 mM chambers ( Fig. 3g-h). The fact that the egg-laying rate takes ~10 s to reach its maximum value after a fly transitions to the higher relative value (lower sucrose) option ( Fig. 3f-h) is due, at least in part, to the fact that flies do not lay eggs on the ~2.5 mm plastic boundary between substrates (Extended Data Fig 10a-b) and also to the fact that there is a ~3 s delay between when flies bend their abdomen to lay an egg and when the egg is deposited (Extended Data Fig 10c, Fig. 1c). Thus, the fly's internal sense of relative value likely changes more rapidly after a transition than the slowly increasing egg-laying-rate curve would suggest.

The relative value of the current egg-laying option influences the subthreshold physiology of oviDNs to impact when threshold is reached
How might oviDN physiology guide flies to lay eggs on the option with higher relative value? Perhaps the rate of rise in oviDN [Ca 2+ ] during search is modulated by relative value (Fig. 4a)? If so, flies on a high relative-value substrate might show an oviDN [Ca 2+ ] signal that rises faster and thus hits threshold more quickly. Flies on a low relative-value substrate would have their [Ca 2+ ] rise more slowly, or even fall, affording the flies more time to find a better option before threshold is reached.
We analyzed oviDN ∆F/F changes for all substrate transitions on the wheel. On wheels with 0 and 500 mM sucrose options, we observed an increase in the average ∆F/F after flies walked onto the higher relative-value substrate (decrease in sucrose concentration) and a decrease after flies transitioned to the lower relative-value substrate (increase in sucrose concentration) (Fig. 4b). Note that flies often straddled the boundary between substrates (Extended Data Fig. 11a), which will cause the change in [Ca 2+ ] with substrate transitions to appear more gradual than it would be otherwise. The difference in ∆F/F on the two substrates was not explained by persistent differences in feeding or locomotor speed between the two options (Extended Data Fig. 11b-c). We observed similar changes in oviDN activity with substrate changes at the level of the oviDN membrane potential and spike rate (Extended Data Fig. 12).
If oviDN [Ca 2+ ] tracks the relative value of substrates, rather than just sucrose concentration, one might expect that oviDN activity would gradually increase on the 500 mM option, as that option slowly becomes more acceptable over several minutes. Indeed, when we split 500 to 0 mM substrate transitions into four groups--depending on the time spent on 500 mM prior to the transition--we found that the average, "baseline" ∆F/F on 500 mM became progressively higher. After > 3 min. on 500 mM, the mean ∆F/F on 500 and 0 mM became indistinguishable (Fig. 4c). It is intriguing that this slow increase in oviDN mean [Ca 2+ ] in flies residing on a 500 mM substrate occurs on a minutes timescale that roughly matches the timescale over which egg-laying rates recover in flies residing on 500 mM in free behavior (compare Fig. 4c with Fig. 3f). Consistent with the idea that oviDN [Ca 2+ ] tracks relative value and not   just sucrose concentration, the magnitude of the average ∆F/F changes during substrate transitions from 0 to 500, from 0 to 200, and from 200 to 500 mM were similar (Extended Data Fig. 13).
We hypothesize that excitatory inputs associated with the relative value of the current substrate interact with additional, more generic, excitatory drive associated with the search state. The generic inputs might start arriving to oviDNs after the search start arrow in Figure 1k, where one observes a small inflection in the oviDN ∆F/F. These two inputs ultimately drive the oviDNs to hit threshold, thus inducing egg laying. One prediction of this model is that the slope at which the oviDN [Ca 2+ ] signal approaches threshold should be shallower on the less valued substrate, because of reduced drive from the putative relative-value inputs, and steeper on the more valued substrates. Although the number of eggs available to analyze were very few, we did find, consistent with our hypothesis, that the mean slope of the oviDN ∆F/F rise-tothreshold was shallower on the lower relative-value substrate than the higher one (Fig. 4d) and this was also evident, to near statistical significance, in an analysis of individual traces (Fig. 4e). These data are inconsistent with an alternative hypothesis where the threshold's height is inversely related to relative value (Fig. 4d), for example. In free behavior, we would expect the slope of the subthreshold oviDN signal to show even more marked adjustments than those shown in Figure 4d, because, unlike head-fixed flies, freely walking flies transition between low and high relative-value substrates regularly during search.

Gentle hyperpolarization of oviDNs increases the search duration resulting in improved choice performance
Given the above framework for how the oviDN signal guides egg-laying substrate choice (Fig. 4a), we asked whether we could perturb oviDNs to induce flies to be more patient and make "better" choices. Flies lay eggs on the option with lower relative value (higher sucrose) if they have not visited the more valued option in the past ~2 min. (Fig. 3f-h). We hypothesized that if we could increase the time it takes for [Ca 2+ ] to reach threshold by gently hyperpolarizing all ten oviDNs, flies would have more time to encounter the higher relative-value option and may thus lay eggs on the higher value option even more often than normal. Anthropomorphizing, these flies might be considered as more patient, trading off decision speed for increased accuracy.
Expressing the human Kir2.1 34 potassium channel in oviDNs eliminates egg laying 11 (Fig. 5a), as does optogenetic inhibition restricted to the egg-laying assay period using the light-gated anion channel, GtACR1 35 (Fig. 5b, Extended Data Fig. 14). We presume that each of these perturbations prevents the oviDN signal from ever hitting threshold. We found a modified mouse Kir2.1 (hereafter Kir2.1*) that, when expressed in all ten oviDNs, still permits egg laying, albeit at lower average amounts (Fig. 5c). If we only consider flies that laid ≥ 5 eggs, the mean number of eggs per fly becomes more similar, 37 vs. 29, suggesting that Kir2.1* may prevent threshold from ever being reached in some individuals but not others. We used genetic-background matched control flies that expressed a non-conducting channel, Kir2.1*Mut, which differs from Kir2.1* by only 3 amino acids 36 . Kir2.1* and Kir2.1*Mut had been developed and used to hyperpolarize neurons in mice 36 ; we introduce the transgenes into flies here (Methods). A similar strategy of using Kir2.1 paired with a non-conducting control has been recently used in flies 37 , but in those experiments the human, not a modified mouse, isoform was used. Kir2.1* and Kir2.1*Mut gene expression was restricted to a 23-hour period prior to experiments (Methods). We performed whole-cell patch-clamp recordings from oviDNs and found that Kir2.1* expressing oviDNs were hyperpolarized by ~14 mV, on average, compared to Kir2.1*Mut expressing flies (Fig. 5d). This is a moderate hyperpolarization that still permitted most Kir2.1* expressing oviDNs to fire spikes with sufficient current injection (Extended Data Fig. 15a). This fact could explain why at least some Kir2.1* flies can lay eggs.
We tracked the x-y trajectories and egg-laying behavior of flies expressing Kir2.1* or Kir2.1*Mut in all ten oviDNs (using the oviDN-GAL4) in two-substrate-choice, free-behavior chambers. We observed a 2-3 fold increase in the search duration in Kir2.1* compared to Kir2.1*Mut flies when comparing the Non-egg-laying periods were defined as moments > 10 min from egg deposition. i, Fraction of eggs on the lower sucrose option with 95% confidence interval. Each dot is one fly. If the same plot shown is redone by examining only flies that laid ≥ 5 eggs then p = 2.6e-6. In panels c-i, tub > GAL80 ts was present in all flies to limit the time window over which Kir2.1* or Kir2.1*Mut transgenes were expressed (Methods).
distribution of individual traces by eye ( Fig. 5e-f) or when quantifying the median search duration (Fig.  5g). The increase in search duration cannot be attributed to a general increase in the fraction of time spent walking (Fig. 5h) or a broad defect in egg-laying-related motor functions (Extended Data Fig. 15b-c). An increase in search duration when all oviDNs are gently hyperpolarized is presumably related to [Ca 2+ ] taking longer to reach threshold in oviDNs. This increase in search duration was, remarkably, accompanied by a higher fraction of eggs laid on the substrate of higher relative value, i.e., an improvement in choice behavior (Fig. 5i). Note that flies expressing Kir2.1*Mut in oviDNs expressed a weaker baseline trend for laying eggs on low sucrose (Fig. 5i, right light grey bar) compared to Canton S flies (Fig. 3b); however, ~75-80% choice is comparable to the level exhibited by our empty-Gal4 controls (Fig. 5i, left light grey bar) and is a common preference level for many genotypes (data not shown from a second manuscript in preparation).

Discussion
We provide insight into the cellular mechanisms by which animals perform ethologically relevant, relative-value-based decisions. Specifically, dynamic modulation of oviDN [Ca 2+ ] over the course of many seconds to minutes determines when that neuron's activity hits a threshold and we propose that this process fundamentally regulates where flies lay eggs.  40 , one can imagine how a threshold might actually be implemented in presynaptic terminals. Alternatively, the oviDNs may transmit a graded signal to post-synaptic partners resulting in those neurons implementing the threshold. Future work will be needed to link the rise-to-threshold signal evident in the oviDN soma, mechanistically, to motor action.
A fly's decision of when and where to lay an egg resembles decisions that humans make, like when to stop browsing a menu and choose a dish at a restaurant. Both processes start with an initiation event: ovulation or the decision to have a meal. Next, the individual's own behavior reveals new options to the organism over time: more egg-laying substrates or more dishes. Finally, the decision process is terminated when one option is selected and the motor program to choose that option has begun. This structure would seem to apply broadly, to many natural decisions taken by animals and humans, and thus the principles by which the oviDN mediates Drosophila egg laying may prove relevant for understanding decision making more broadly, across contexts and species.
Rise-to-threshold signals have been linked to decision-making and action initiation in humans 41,42 , monkeys 4,43-46 , rodents 47-52 , zebrafish [53][54][55] , and insects 56-60 . These signals have been shown to rise, or hypothesized to rise, on the hundreds-of-milliseconds to seconds timescale. In the decision-making literature, some of the most influential work has focused on so-called "perceptual decisions", in which rising signals integrate sensory input so that an animal can report a percept 2,3 . More recently, neural signals associated with self-paced decisions have been studied [5][6][7][8] , but without definitive links to behavior yet. The oviDN signal we describe emphasizes several important features of how brains make decisions.
(1) Rise-to-threshold signals can underlie decisions that take minutes, not just seconds.
(2) Rise-tothreshold signals can cause behavior to start when threshold is crossed 50,59 ; they are not just a correlate of the decision-making process. (3) Rise-to-threshold signals can track the relative value of stimuli to guide their ramping rate, not just the sensory properties of those stimuli. (4) Rise-to-threshold signals underlie ethologically relevant, self-paced decisions--where options are encountered due to the animal's own actions--not just externally cued decisions. This latter finding is particularly important because it generalizes the rise-to-threshold mechanism to the vast swath of decisions that animals make where their own actions determine the options experienced.     The first and last bin always include all the data points below and above that bin, respectively. The curve in panel g appears more linear and less step-like than the others; however, it is expected that as one progressively shifts the center point of the bins, one will find a position where the central bin exactly straddles the putative threshold, yielding an intermediate y value for that bin. The fact that panels f and h appear more step like supports this explanation for panel g.

Figure Legends
Extended Data Fig. 9. Evidence against use of spatial information guiding search and against feeding-on-higher-sucrose-related suppression of egg deposition in our free behavior chambers. a, Schematic of a fly searching for an egg deposition site in a 0 vs. 500 mM chamber. ∆T0mM and ∆T500mM are all the intervals of time that a fly was transiting through 0 or 500 mM, respectively, during an egglaying search period. ∆Tlast_500mM is the last transit interval through 500 mM for eggs deposited on 0 mM. If a fly were positionally avoiding sucrose, ∆T500mM would be less than ∆T0mM. If a fly were to use spatial information during the search period--by taking a shortcut to get to the preferred 0 mM substrate at the end of a search--∆Tlast_500mM would be less than ∆T0mM and ∆T500mM. If a fly were feeding on the higher sucrose substrateand pausing as flies do when they feed 61 --∆T500mM would be larger than ∆T0mM. b-d, ∆Tlower_sucrose, ∆Thigher_sucrose, and ∆Tlast_higher_sucrose distributions for three different sucrose choice chambers. ∆Thigher_sucrose is not less than ∆Tlower_sucrose suggesting that flies are not positionally avoiding the higher sucrose option. ∆Tlast_higher_sucrose is not detectably smaller than ∆T0mM or ∆T500mM suggesting that flies are not taking a shortcut--and thus not manifesting use of spatial information--at the end of the search. It is possible that flies use spatial information to guide the search in conditions with less thigmotactic walking 62,63 and/or with visual landmarks 64 (all experiments in this study were conducted in darkness).
Note that use of spatial information is compatible with our time-domain model for egg laying and would just suggest that flies control the substrate upon which they are located and as such control the egg-laying drive that they experience. ∆Thigher_sucrose is not larger than ∆Tlower_sucrose indicating that flies are not pausing only on the higher sucrose substrate. We interpret this result to mean that flies are not suppressing egg deposition because of extensive feeding on the sucrose substrates. In addition, we did not notice additional proboscis extension on higher sucrose when we spent hours inspecting each egg to annotate the egg deposition time, probably because our flies are very well fed prior to entering the chamber (Methods). The 5-10 s bin in this analysis has a higher egg laying rate than in the analysis from panel a, suggesting that part of the delay in egg laying after a transition is due to flies not laying eggs on the plastic barrier. c, Mean locomotor speed. A ~3 s delay exists between when a fly pauses and bends its abdomen to lay an egg till when an egg is deposited. This ~3 s can explain why even the data in panel b do not show high egg laying rates in the 0-5 s bin. Analyzing the same data as in panels a-b. Fig. 11. Changes in oviDN ∆F/F during substrate transitions are not due to consistent, detectable changes in behavior. a, Probability that a fly's centroid is > 2 mm from the midline between substrates, aligned to detecting a transition from one substrate to the other.

Supplemental Tables
Supplementary Table 1. Genotypes for each experiment.
Supplementary Table 2. Conditions for each experiment.

Supplemental Videos
Supplementary Video 1. Individual egg-laying event of a fly expressing GCaMP3 in eggs. An egglaying event with the behavioral sequence occurring in a localized space was chosen so that it could be magnified. Video is compressed and played back at 5X speed.

Supplementary Video 2.
Three consecutive egg-laying events of a wild type fly in a sloped ceiling egglaying chamber (as in Extended Data Fig. 2a). Traces below movie are smoothed with a 5 s boxcar filter. Pink line is overlaid on fly to indicate the neck to ovipositor length and is only drawn in frames that passed the criteria described in the Methods. Video is compressed and played back at 1X speed.
Supplementary Video 3. Egg-laying event during two-photon imaging in a tethered fly expressing GCaMP7f in oviDNs (as in Fig. 1g left). ∆F/F and brain images are smoothed with a 2 s boxcar filter. Video is compressed and played back at 5X speed.

Supplementary Video 4.
Egg-laying event during two-photon imaging in a tethered fly expressing GCaMP7f in oviDNs (as in Fig. 1g right). ∆F/F and brain images are smoothed with a 2 s boxcar filter. Video is compressed and played back at 5X speed.

Supplementary Video 5.
Optogenetically stimulated egg-laying event and abdomen bends in a tethered fly expressing GCaMP7f and CsChrimson in oviDNs (as in Fig. 2a left). CsChrimson stimulations here were manually triggered. An orange dot in close-up of fly and orange line in 'fly position' trace both indicate stimulation periods. ∆F/F and brain images are smoothed with a 2 s boxcar filter. Video is compressed and played back at 5X speed.
Supplementary Video 6. Wild type flies in a high-throughput 0 (bottom) vs. 500 (top) mM egg-laying chamber. Video is compressed and sped up 60X by displaying only every 60 th frame. The analyzed movies for figures included all the frames and were therefore much smoother.

Methods
Flies. Flies were reared on a standard corn-meal medium at 25°C, ambient humidity, and a 12 h/12 h light/dark cycle unless otherwise noted. Genotypes and conditions for each experiment are described in Supplementary Table 1  Egg-laying chamber with sloped ceiling. We designed a new chamber for imaging egg laying in freely walking flies, which enforced flies to remain in a tarsi-down body posture over the agarose at all times. The flies could not tilt their bodies in this chamber and thus they could not walk on the side walls or ceiling. This constraint meant that the flies' bodies were always in the same general orientation, parallel to the imaging plane, throughout, allowing for quantitative measurements of postural parameters.
Chambers were made by sandwiching and tightly screwing layers of acrylic and 3D-printed plastic and then placing a glass ceiling (Extended Data Fig. 1a). The acrylic layers were laser-cut (VLS6.60, Universal Laser Systems). The side-wall layer was 3D-printed using the VisiJet M3 Crystal plastic material (Projet 3510 HD Plus, 3D Systems). The glass was treated with Sigmacote (Sigma-Aldrich) to make it slippery to a fly's tarsi--preventing any walking on the ceiling 65 . Glass was re-treated with Sigmacote after ~10 uses. The 3D-printed spacer layer incorporated a sloped edge that kept the fly completely parallel to the imaging plane by preventing access to the side of the chamber (Extended Data Fig. 1a). This allowed for quantitative measurements of body posture--e.g., the distance from neck to ovipositor--which would be distorted if the fly were able to tilt. The sloped ceiling design was inspired by a sloped floor plastic chamber 65 . A sloped floor does allow the fly to tilt and thus was not suitable for our application.
Chambers were used multiple times and washed prior to each use. Chambers were assembled with only the two bottom layers and then cooled at 4°C. Fresh substrate containing 1% agarose (SeaKem LE Agarose, Lonza), 0.8% acetic acid, and 1.6% ethanol was pipetted to completely fill the well ~5 hrs prior to each assay. Careful pipetting with only the two bottom layers assembled was critical to forming a flat layer of agarose--preventing the formation of a meniscus, which would allow the fly to tilt. Acetic acid and ethanol were included to help simulate a rotten fruit and generally promote egg laying 9 . After the agarose solution was solidified (~1 hr), the chamber was fully assembled, minus the glass ceiling, and equilibrated at room temperature.
Females were separated on their day of eclosion and group housed in vials. At age 3 to 6 days, ~20 females were exposed to ~20 Canton-S males in an empty bottle with wet yeast paste and a Kimwipe (Kimberly-Clark) soaked with 2 ml of water. The wet yeast paste was applied to the side of the bottle and was composed of 1-gram dry yeast (Fleischmann's) and 1.5 ml of 4.25 mM putrescine dihydrochloride in water. This treatment allowed females to mate and caused them to accumulate many eggs. Flies fed with yeast 66,9 or putricine 20 increase the number of eggs they develop. These eggs are retained by the flies during the treatment period because they lack a soft medium for egg deposition 9 . After ~24 hrs, individual gravid females were placed into chambers under gentle cold anesthesia from which they typically recovered within 30 s. The fly with the least ability to tilt (of 6 flies in individual chambers) was chosen to be imaged for a few hours in near-complete darkness (under a shroud) at ~24°C and 40-60% humidity.
For imaging of eggs inside the body, a 470 nm LED (pE-100, CoolLED) filtered twice (OD4 475 nm and OD4 500 nm shortpass, Edumund Optics) provided excitation light at 30 µW/mm. This excitation light arrived at the fly from below, after first passing through the agarose substrate. Videos were recorded at 10 fps with a 100 ms exposure time per frame, using an ORCA-Fusion C14440-20UP camera (Hamamatsu) equipped with a 15.5-20.4 mm Varifocal Lens (Computar) and two 510 nm longpass filters (Chroma). Representative stills (Fig. 1b) or videos (Extended Data Video 1) were selected.
For imaging body posture, 850 nm LEDs illuminated the arena from above, through a white acrylic diffuser (1 µW/mm 2 at the fly). Videos were recorded at 25 fps using a GS3-U3-41C6NIR-C Grasshopper camera (FLIR) equipped with a 15.5-20.4 mm Varifocal Lens and a 780 nm longpass filter (MidOpt). DeepLabCut 67 was used for offline tracking of body parts including the neck and ovipositor. DeepLabCut models were iteratively fine-tuned by identifying poorly tracked frames in iteration i and adding them to the training dataset for iteration i+1. A total of 1568 training frames were manually annotated. DeepLabCut output coordinates were filtered by setting coordinates to NaN if (1) the probability score was less than 0.95; or (2) the body part jumped more than an empirically determined distance in consecutive frames. 'Ovulation start' was defined as the first frame in which the abdomen appeared to begin the elongation process. 'Search start' was manually annotated as the first frame in which the abdomen returned to a stable neutral posture after ovulation. 'Abdomen bend complete' was manually annotated as the frame in which the bend to lay an egg was completed (abdomen maximally deflected). Identifying the frame in which the abdomen bend was completed was much easier than attempting to identify when then abdomen bend was initiated. Note that although flies bend their abdomen to deposit an egg, flies also bend their abdomen during our experiments for other reasons. 'Egg deposited' was manually annotated (with some computer assistance) as the first frame in which half the egg was visible (emerging from the ovipositor).
High-throughput egg-laying choice chamber. We designed a new chamber for studying egg-laying choice behavior with high-throughput. This chamber ensured the fly was nearly always in contact with an agarose egg-laying substrate option. The substrate the fly was on could be unambiguously defined by the fly's y-position and orientation. In previous egg-laying choice studies 19,10,68 , flies could walk on the side walls or ceiling and yet were assigned to a substrate beneath them during tracking, which makes it very hard to determine how previous substrate experiences influence the decision to lay an egg.
Chambers were made by sandwiching and tightly screwing layers of acrylic or Delrin plastic and then placing a glass ceiling (Extended Data Fig. 1b). Acrylic and Delrin plastic were laser-cut. The glass was treated with Sigmacote.
Chambers were used multiple times and washed prior to each use. Chambers were assembled without the glass ceiling and cooled at 4°C. 1 ml of fresh substrate containing 1% agarose, 0.8% acetic acid, and 1.6% ethanol was pipetted to fill the acrylic well and form a meniscus with the Delrin plastic spacer ~5 hrs prior to each assay. The meniscus ensured that the fly could not walk directly on the side (Delrin plastic) of the chamber and was inspired by plastic chambers with a sloped floor 65 . Quantitative measurements of body posture were not possible because flies could tilt by walking on the meniscus. Sucrose containing substrates were supplemented with the appropriate amount of sucrose. Acetic acid and ethanol were uniformly distributed in all substrates. After the agarose solution was solidified (~1 hr), the chamber was equilibrated at room temperature.
These egg-laying chambers and assay protocols were specifically designed to minimize the following confounds: (1) diffusion between substrate islands; (2) visual landmarks; (3) fly-to-fly communication; (4) olfactory landmarks; (5) temperature and humidity fluctuations; and (6) variability in fly rearing. Diffusion was minimized by a ~2.5 mm wide barrier between the substrate islands and by loading the agarose at 4°C. Visual cues were minimized by conducting the assay in near-complete darkness. 850 nm illumination, to which the fly visual system has no measurable sensitivity [69][70][71] , was provided from below for tracking (1 µW/mm 2 at the agarose beneath the fly). Fly-to-fly communication was minimized by assaying individual flies in isolated chambers separated by an opaque Delrin plastic spacer. Olfactory landmarks were minimized by using a non-volatile compound, sucrose, as the sole varying variable. Temperature and humidity were kept constant by conducting experiments in an environmental room (24°C with 40-60% humidity). Air exchange was made possible by four small ventilation holes in each barrier. Variability in fly rearing was minimized by controlling age, mating status, food history, and circadian time.
Females and males were separated on their day of eclosion and group housed in vials. At age 3 to 6 days at zeitgeber time (ZT) 6 (i.e., 6 hours after lights on), ~20 females were exposed to ~20 Canton-S males in an empty bottle with only wet yeast paste and a Kimwipe soaked with 2 ml of water. Putrescine was not added to the yeast paste in these experiments because we could always test sufficient flies wherein the additional eggs provided by feeding putrescine was not required. On the next day at ZT 8, individual females were placed into egg-laying chambers under gentle cold anesthesia. Images were acquired at 2 fps with a FMVU-03MTM-CS Firefly or FL3-U3-13Y3M-C Flea3 camera (FLIR) equipped with either a LM12HC (Kowa), HF12.5SA-1 (Fujinon), or CF12.5HA-1 (Fujinon) lens and a 780 nm longpass filter. The x-y position and orientation of each fly was extracted offline using Ctrax 72 . We assigned a fly's current substrate depending on whether its centroid was above or below the midline of the acrylic barrier. This simplification was appropriate because the ~2.5 mm acrylic barrier (a fly is ~2.5 mm long) practically prevented a fly from standing on both substrates simultaneously and a Canton-S fly spent only 1.5% of its time in an orientation where all tarsi were likely to be on the barrier. Note that flies do not lay eggs on the plastic barrier (or any plastic used in this study) because it is too hard. 'Egg deposition' was manually annotated (with some computer assistance) as the first frame in which half the egg was visible (emerging from the ovipositor). Annotations by an individual human annotator or across multiple human annotators were reproducible to ± 4 frames or ± 2 s. The 'search period' was determined as described in the section 'Automated estimation of search…'. . Controls for genotype were siblings of experimental flies that were treated identically except no light was provided from above. Controls for light were flies 'expressing' GtACR1 with an empty split or empty GAL4 driver. Additional controls for light with twice the intensity (57 µW/mm 2 ) provided ample assurance that light alone was not preventing egg laying (data not shown). 567 nm light was chosen to minimize overlap with the sensitivity of the fly visual system 69-71 while still stimulating GtACR1.

Construction of Kir2.1* and Kir2.1*Mut flies.
We screened a variety of reagents to find a way to gently hyperpolarize oviDNs. We serendipitously identified a Kir2.1* that, as inferred from our behavioral experiments (Fig. 5c), hyperpolarizes oviDNs more gently than the Kir2.1 traditionally used in flies 34,75,76 (Fig. 5a). A matched control, Kir2.1*Mut, that has a non-conducting channel facilitates quantitative comparisons. In theory, a 'low' level of light stimulating GtACR1/2 should also be able to gently hyperpolarize neurons 35,74 . However, (1) identical illumination of each fly was hard for us to practically achieve because multiple chambers were spread across a large area that needed to be evenly illuminated and flies can rotate their heads exposing neurons to more or less stimulation as a result; (2) illumination is hard to match between free behavior and tethered electrophysiology preparations; (3) a non-conducting control for GtACR1/2 does not currently exist, so separate controls for genotype and light are necessary; and (4) egg-laying assays would no longer be in the dark.

Automated estimation of search period in free behavior high-throughput choice chambers.
Since we did not have a high-resolution view of the abdomen in our high-throughput choice chambers (Extended Data Fig. 1c), we used locomotor speed as a proxy for search onset (Extended Data Fig. 2bc) and egg deposition as a proxy for abdomen bending to lay an egg (Fig. 1c). The end of the search period was the annotated moment of egg deposition (rather than the abdomen bend to lay the egg). The start of the search period was determined for each egg by smoothing the locomotor speed trace, prior to egg deposition, with an 18.5 s boxcar filter and identifying the first frame where this smoothed signal dropped below 0.1 mm/s. The minimum search duration was 18.5 s due to the length of the boxcar filter. These parameters were determined empirically to yield search onset times consistent with visual inspection of the data.
Calculation of egg-laying rates as a function of time since the last substrate transition in free behavior choice chambers. Egg-laying rates as a function of time (Figure 3f-h) were calculated as follows. Data from all flies tested in a given chamber type were combined prior to any calculations. First, we iterated through each time bin denoted on the x-axis and, for each bin, we counted the number of eggdeposition events that were assigned to that bin, #eggs(bin). Second, we iterated through the same time bins and counted the number of video frames in which flies were assigned to that bin, #frames(bin), during an egg-laying search period. Third, we iterated through the same time bins and counted the number of times flies changed assignment into that bin, #visits(bin), during an egg-laying search period (i.e., we did not keep incrementing the "visits" counter if the fly remained in a time bin from one frame to the next).
To get the mean egg-laying rate, we calculated #eggs/#frames for each bin. Since videos were recorded at 2 fps, we multiplied the value for each bin by 120 to convert to units of eggs/minute.
To get the confidence interval per bin, we used the Clopper-Pearson method ('exact' binomial confidence interval) to calculate the 90% confidence interval for #eggs/#visits for each bin. We then converted the confidence interval for each bin to units of eggs/minute by multiplying by 120*#visits/#frames per bin. Note the confidence interval cannot be directly calculated from #eggs/#frames because then the confidence interval would be dependent on the video framerate.
For these rate functions, search periods with duration less than 30 s were set to 30 s. This prevented very short search periods from introducing fluctuations in the rate curves (by contributing to the numerator and not contributing much to the denominator). As such, rate curves varied less from replicate-to-replicate or condition-to-condition. Note that search periods already had a minimum duration of 18.5 s as automatically generated by the search period calculation (Methods). Analyzing the data with no minimum search duration (or with other definitions of the search period) did not change any of the stated conclusions (data shown in a second manuscript in preparation). Binning the x-axis differently also did not qualitatively change any of our stated conclusions. Rate functions start off with low rates after a transition at least partially because flies do not lay eggs on the plastic barrier between substrates (Extended Data Figure 10a-b) and because flies are, by definition, walking (and not pausing to deposit an egg) during a transition (Extended Data Figure 10c).

Design of egg-laying wheel and setup under microscope.
We designed a wheel upon which tethered flies walked and laid eggs on agarose-based egg-laying substrates. The design was optimized to maximize a fly's ability to lay eggs and rotate the wheel.
The wheels were 3D-printed from VisiJet M3 Crystal plastic using a Projet 3510 HD Plus 3D printer (Extended Data Fig. 3a). A pivot (N-1D, Swiss Jewel) was press fit through the center hole and never removed. Wheels were washed prior to each use. Three wells were available for loading the same or different agarose-based substrates. Each well was separated by a 1 mm barrier. Wheels were loaded with fresh agarose substrates (as prepared for free behavior choice chambers) using a 3D-printed agaroseinjecting mold (VisiJet M3 Crystal material) that was cooled on ice (Extended Data Fig. 3b). Food coloring (HY-TOP assorted food coloring) was added at a dilution of 1:10,000 to the agarose solution prior to loading so wheel quality could be visualized. Wheels with any mixing between wells were discarded. Food coloring at 2.5 times this concentration or the presence of VisiJet M3 Crystal material did not affect choice in free behavior control experiments (Extended Data Fig. 3d). After the agarose was solidified, the wheel and pivot were suspended between two spring loaded bearings (VS-30, Swiss Jewel) that were threaded into clear acrylic that was press fit into a 3D-printed base (UMA-90 material printed on a Carbon DLS, Protolabs) (Extended Data Fig. 3c). This wheel assembly was stored in a custom humidification chamber to prevent the thin layer of agarose from drying and to allow the wheels to equilibrate to room temperature. Wheels were used within 2 hrs of preparation. When ready, a wheel assembly was secured in a small custom humidification chamber (~90% humidity) that sits under the microscope objective attached to a micromanipulator. The wheel-pivot combinations used in this study had weight 87.9 ± 0.3 mg (mean ± std) without agarose and 146.4 ± 0.8 mg with agarose. For reference, a single gravid female weights ~1.4 mg and a typical foam ball used for fly walking experiments 80,81 weighs 40 to 46 mg. Most of the wheel's weight is due to the agarose and the wells needed to hold it. A variety of lighter and less-prone-to-evaporation synthetic materials were screened in free behavior assays, but egg laying was suppressed on all of them.
The fly was viewed by two CM3-U3-13Y3M Chameleon cameras (from the sides) and one FMVU-03MTM-CS Firefly camera (from the front) (FLIR). Two 850 nm LEDs from the front-left and front-right illuminated the fly at 5 µW/mm 2 . Cameras were equipped with a 15.5-20.4 mm Varifocal Lens and either a 900 nm shortpass (Thorlabs) or 875 nm shortpass (Edmund Optics) filter to dampen visibility of the 925 nm two-photon excitation light. Cameras had an exposure time of 16 ms and were triggered synchronously using a single external trigger source at 25 fps (Arduino Uno, Arduino). A side facing camera recorded the fly and a single dot painted on the wheel. The dot was painted in a consistent location on the wheel that was defined by an embossed 3D-printed feature. The dot was tracked using DeepLabCut (1109 training frames, with training and filtering like the free behavior DeepLabCut model).
The dot position was converted to wheel degrees by fitting the set of all dot positions to a circle and then computing a wheel angle for each frame. A single frame in which the fly's centroid straddled the dot was used to convert the wheel angle to the fly's position on the wheel. This alignment consistently meant that the fly's neck was situated on the plastic-to-next-substrate boundary during a detected substrate transition. A second side facing camera was used for a close-up view of the fly's body. DeepLabCut was used to track body parts including the neck, ovipositor, and tip of the proboscis (2259 training frames, with training and filtering like the free behavior DeepLabCut model). 'Normalized length' was calculated by subtracting the x-coordinates of the neck and ovipositor in each frame and dividing by the median of this value for each recording (Fig. 1i). An absolute reference for length was not easy to include in the camera frame and therefore distance was measured about the median. For reference, the median length in free behavior was ~2.35 mm (Extended Data Fig. 2b-e). This metric for length was used since it can quantify both an elongated and a bent abdomen and is similar to the neck to ovipositor length measured in free behavior. Despite the similarity with free behavior length, we noticed, on average, a slight difference in the signature of abdomen bends (Extended Data Fig. 2d compared to Fig. 1l) possibly due to the curvature of the wheel. The 'body angle (°)' was the angle between the neck and ovipositor (Fig. 2i). Larger angles indicated a more bent abdomen. Although a fly must bend its abdomen to lay an egg, the magnitude of a physiologically relevant deflection of body angle (as measured in degrees) is not that large (Fig. 2i). 'Normalized neck to proboscis length' was calculated by determining the Euclidean distance between the tip of the proboscis and the neck in each frame and dividing by the median of this value for each recording. This underestimated the true deflection of the proboscis because the proboscis does not start at the neck. The neck was used as an origin point because it was easy to robustly track. The position of each tarsus was not able to be tracked, and the tarsi on the opposite side of the camera were often occluded by the body. A front facing camera was used to align the fly on the center of the wheel width. The body posture slightly varied from fly-to-fly due to slight differences in tethering. To achieve egg laying, it was very important to position the fly at a point on the wheel circumference, and at a vertical distance from wheel, that maximized perpendicular contact of the ovipositor to the substrate when the abdomen was bent while still allowing the fly to walk on the wheel. In some cases, flies had to be positioned close to the wheel which, unfortunately, decreased the dynamic range of abdomen bending. 104 flies were imaged, to collect the data displayed in Figure 1h. The majority of flies did not lay eggs because, among other considerations, it often takes flies several hours to start laying a "clutch" of eggs (even when freely behaving in a chamber) and we could not image conveniently for 18 hours to wait for a clutch to start.
Moments of distinct behaviors (as in Fig. 2h and Extended Data Fig. 4b) were annotated manually by inspecting the behavior videos while being blind to any neural signals (∆F/F). 'Ovulation start' was defined as the first frame in which the abdomen appeared to begin the elongation process. 'Abdomen at its longest' was the frame in which the abdomen was maximally stretched. 'Abdomen scrunch start' was the first frame in which the abdomen assumed a stable scrunched position. 'Search start' was defined as the first frame in which the abdomen returned to a stable neutral posture after ovulation. 'Abdomen bend complete' was defined as the frame in which the first bend prior to egg laying was complete (abdomen maximally deflected). 'Egg deposited' was defined as the frame in which half the egg was visible. 'Ovipositor cleaned' was defined as the frame in which the first abdomen bend following egg laying was complete.
For CsChrimson 32 optogenetics experiments, a 660 nm LED coupled to a 1 mm wide lightguide (M660F1 and M35L01, Thorlabs) was focused on the front, midpoint of the fly's head using a lens set (MAP10100100-A, Thorlabs). A wavelength at the very tail end of the sensitivity of the fly visual system 69-71 that could still stimulate CsChrimson was used to minimize light-related confounds. Two shortpass filters--OD4 550 nm and OD 4 575 nm (Edmund Optics)--minimized the ability of the LED light to enter the two-photon detector path, which collected the GCaMP signal. The incident area of the LED was adjusted to be wide enough (~3 mm diameter) to cover the whole front of the fly such that all CsChrimson expressing oviDN cell bodies and neurites in the brain (and likely in the thorax) could be stimulated. The LED intensity was controlled by adjusting the duty cycle of a 490 Hz PWM signal (Arduino Uno, Arduino) that was fed into an LED driver (T-Cube, Thorlabs). The CsChrimson stimulation intensity for Figure 2a-e was 641 µW/mm 2 . For Figure 2f-h intensities were 641, 159, 148 and 136 µW/mm 2 .

Treatment of flies for tethered experiments.
Females and males were collected on their day of eclosion and group housed together in standard corn-meal medium vials supplemented with 2.5 mM putrescine dihydrochloride and wet yeast paste. The wet yeast paste was applied to the side of the vial and was composed of 1-gram dry yeast and 1.5 ml of 4.25 mM putrescine dihydrochloride in water. At age ~5-6 days females were gravid because larvae occupied the corn-meal medium and there was no additional room to deposit eggs. This treatment was more convenient than the treatment used in free behavior choice experiments and was inspired by separate aspects of two studies 10,20 . Free behavior controls indicated that this treatment increased the number of eggs a fly laid without affecting choice behavior (Extended Data Fig. 3e).
For CsChrimson optogenetics experiments, flies were treated as above, but were kept in low white light (~3 nW/mm 2 measured at 660 nm) from egg to adulthood. At age ~5-6 days, ~20 females were exposed to Flies were anesthetized at ~4°C and tethered to a custom holder 82 , except where the back wall of the pyramid leading up to the fly was tilted at an angle instead of rising at 90° so as to allow more light from the brain to reach the objective 81 (Fig. 1d). The head was pitched forward during tethering to provide a view of the oviDN cell bodies. For electrophysiology, the head was inserted deeper into the holder for unobstructed access to the oviDNs with electrodes. Flies were attached to the holder with blue-light-cured glue (Bondic). The proboscis was gently extended, and the dorsal rostrum was glued to the head capsule. This prevented brain movement associated with proboscis extension while still allowing proboscis extension to be measured (albeit with a smaller dynamic range than natural proboscis extension). Extracellular saline solution was added to the holder well (bath) and a window was cut in the cuticle to expose the posterior side of the brain. The holder was stabilized with magnets above the egg-laying wheel inside a small custom humidification chamber.

Calcium imaging.
We used a two-photon microscope with a movable objective (Ultima IV, Bruker) and custom stage (Thorlabs, Siskiyou). The microscope was controlled by Prairie View software (Bruker) and was enclosed by a black shroud. A Chameleon Ultra II Ti:Sapphire femtosecond pulse laser (Coherent) filtered by a 715 nm longpass filter (Semrock) provided 925 nm two-photon excitation. Emission light from the brain was collected by a 16x/0.80 NA objective (16X W CFI75 LWD, Nikon), split by a 565 nm dichroic, and filtered by a 490 to 560 nm bandpass filter (Chroma) prior to entering GaAsP detectors (Hamamatsu). For CsChrimson optogenetics experiments, the emission light was split by a 525 nm dichroic and filtered by both a 490 to 510 nm bandpass and a 480 to 520 nm bandpass filter (Chroma) to prevent optogenetic stimulation light from entering the detector. A Piezo motor was used for volumetric scanning.
A range of optical zooms, z-slice number, z-slice separation, fields of view, laser powers (6 to 30 mW at the specimen), and frame rates (mean of 1.84 Hz) were used over the course of experiments on oviDN dynamics. Individual data traces were inspected by eye and the reported results were robust to the range of parameters used. All recordings had multiple z-slices within, above, and below the cell body permitting effective quantification of recordings with slight z-drift over hours of recording. For example, in Figure  1g, 14 z-slices were taken at 3 µm steps and only ~5-6 of the z-slices included fluorescence from the oviDNb cell body. The length of each recording (mean of 75 min) varied depending on (1) the perceived health of the fly; (2) the chance of future egg-laying events (which were higher if the fly had already laid an egg); (3) the amount of z-drift; and (4) the quality of the agarose wheel, which sometimes visibly dried over a period of hours. The experimenter was blind to correlations between the neural signal and behavior during the vast majority (~95%) of recordings. Flies were only excluded if a technical issue arose (e.g., errors synchronizing behavior with two-photon imaging or saline leaking from the holder). Only eggs with continuous two-photon imaging from 240 s before to 30 s after egg-deposition were analyzed.
For CsChrimson optogenetics experiments supporting a rise-to-threshold mechanism (Fig. 2f-h), twophoton imaging parameters were held relatively constant (mean framerate of 1.81 Hz, and two-photon laser power ~10.5 mW). CsChrimson stimulation intensities were determined in pilot experiments. Periodic stimulation cycling 4 intensities was applied for 5 s every 2 min. The experimenter was blind to correlations between the neural signal and behavior during all these recordings. Figure 2c, two-photon imaging data are only shown for 5 of the 9 flies, whereas the behavioral data are shown for all 9 flies. The 4 flies for whom we did not show imaging data had bleed-through artifacts in the GCaMP signal from the CsChrimson illumination LED because these data were collected prior to us optimizing the detection path for minimizing this artifact.

For CsChrimson optogenetics experiments in
Two-photon imaging frames were motion corrected using custom scripts from a previous study 81 or using CaImAn 84 . The ROIs for a cell body were drawn manually for each z-plane using the time-average of each z-plane. ROIs were drawn around the outer boundary of the cell body. The brighter of the two cell bodies in oviDN-SS1 was assigned to be oviDNb (Extended Data Fig. 6a). In a few cases, where the brighter cell was not obvious, ROIs encompassing both cell bodies were drawn and assigned to be oviDNb. For a given imaging volume timepoint, the individual pixel intensities in all the individual zplane ROIs for a given cell were pooled and averaged, Fcell(t). An identical average was done for a volume that appeared to be background, Fbackground(t). Prior to calculating the ∆F/F, we subtracted the background from the cell, Fcell_actual(t) = Fcell(t) -Fbackground(t). This eliminated non-cell-specific signal such as autofluorescence and constant detector background. This subtraction also made the ∆F/F robust to variations in the number of background pixels included in the ROIs drawn around the outside of a cell. ∆F/F was calculated using the formula, (Fcell_actual(t) -F0(t)) / F0(t), where F0(t) was the running mean of Fcell_actual(t) over a 20 min. window. The mean over a long timeframe was used to estimate a 'baseline', systematically, for the continuously fluctuating oviDN signal. A similar running mean 'baseline' estimate (albeit with a much shorter window) was used to quantify continuously fluctuating dopaminergic signals in mammals 85  Two-photon imaging-frame pulses, behavioral-camera frame triggers, and optogenetic LED triggers were all digitized at 10 kHz on a Digidata 1440A (Molecular Devices) and saved to a computer (Axoscope, Molecular Devices). To assign a timestamp to a volume scan, we identified the moment that the twophoton volume scan was half complete. To assign a timestamp to a behavioral camera frame, we used the beginning of the 16 ms camera exposure period. Calcium imaging were interpolated and behavioral data were down-sampled to a common 10 Hz array for all population analyses. Each 100 ms timepoint was assigned the calcium imaging and behavior data value from the closest previous respective timestamp (i.e., previous neighbor interpolation). A relatively large 100 ms time-base was chosen because faster sampling was unnecessary for the current analyses and would be computationally time-consuming given the 200+ hours of two-photon scanning collected. In the case of triggered averages, the zero point was the timestamp for the behavior camera frame with the behavior of interest or the frame with the onset of optogenetic stimulation. In the case of cross-correlations, the zero point was the timestamp of the first acquired two-photon volume.
Electrophysiology. We used the same two-photon microscope for calcium imaging and for patch-clamp electrophysiology. The microscope was controlled by either Prairie View (Bruker) or µManager 86 software. A 470 nm LED (pE-100, CoolLED) provided excitation through the objective to identify 2xEGFP or GCaMP7f positive neurons. An 850 nm LED coupled to a 400 µm wide lightguide (M850F2 and M28L01, Thorlabs) was focused on the fly's head to illuminate cells for patch-clamping. Both LEDs were turned off when recording electrophysiology data. A 40x/0.80 NA objective (LUMPLFLN 40XW, Olympus) and CoolSnapEZ CCD camera (Photometrics) were used for patch-clamping.
Cell bodies were exposed by breaching the neural lamella and perineural sheath using gentle application of 0.5% collagenase IV (Worthington) in extracellular to a small 30 µm x 30 µm area containing the cell bodies of interest 82 . Collagenase was applied with a 4 to 6 µm tip micropipette with 8 to 80 mm Hg positive pressure at ~30-32°C for ~3 min. Once the cell bodies were exposed, the bath was returned to ~19-21°C and flushed of collagenase.
Electrophysiological signals were acquired using a MultiClamp 700B amplifier (Molecular Devices). The electrophysiological signals and behavioral camera triggers were digitized at 10 kHz via a Digidata 1440A and saved to a computer (Clampex, Molecular Devices). The oviDN or oviDN-like subtype (Extended Data Fig. 6a) that was recorded from was not distinguished. Recordings were made without current injection (except for current step protocols) and the reported membrane voltage (Vm) was corrected for a 13 mV junction potential 82 . Spikes were identified by highpass filtering the Vm and finding peaks above a threshold that were separated in time by > 1 ms. Parameters for peak detection were varied from recording to recording based on visual inspection of the data, in which the action potentials were clear. We calculated the spike rate by counting the number of spikes in every 5 s interval (at 0.1 ms steps), dividing by 5, and assigning that value to the middle of the 5 s interval. Spike rate and Vm were thus both measured at 0.1 ms intervals. Data were aligned and analyzed identically to calcium imaging. The resting Vm was considered the first stable Vm after breaking into the whole-cell configuration (Fig.  5d, Extended Data Fig. 12a). We calculated a Vm with spikes removed by discarding (converting to NaNs) 150 ms of data centered on the peak of each spike (Extended Data Fig. 12c).
Electrophysiological recordings for Extended Data Figure 12 were analyzed only if (1) the cell was stably recorded for more than 3 minutes; (2) the Vm was below -43 mV at rest with no large drift or rapid fluctuations in the Vm that were non-physiological; (3) the fly walked for at least one wheel rotation; and (4) the cell spiked at least once. A total of 5 cells were rejected for not passing criteria 2, 3 and 4. 3 of these 5 were rejected for not passing criteria 2. A single cell was rejected for not passing criteria 3, indicating that flies were healthy in this preparation. A single cell passed the first 3 criteria but was rejected for not spiking (shown in Extended Data Fig. 12a). Cells that passed all 4 criteria were analyzed from the time the recording first stabilized to when the recording degraded or was terminated (mean = 41 min.).
Kir2.1* and Kir2.1*Mut flies were pre-treated as described for free behavior experiments, rather than as described for tethered experiments, so the transgene would be expressed as it was in free behavior. All recordings were done in vivo on the wheel. Recordings were analyzed if the Vm was below -43 mV at rest. Current step protocols were conducted with 5 pA increments with 1 s of current injection (Extended Data Fig. 15a).
Texas Red Fill. 100 mg/mL Texas Red (Dextran, Texas Red, 3000 MW, Lysine Fixable) (ThermoFisher Scientific) in patch-clamp intracellular saline (see above) lacking ATP, GTP, biocytin, or Alexa-568hydrazide-Na was backfilled into a patch pipette. The pipette was positioned near the cell body (without any collagenase application) and 2 to 5 pulses of 10 V (2 ms duration) were applied using an SD9 stimulator (Grass Instruments). All fills and anatomy were done with flies on the wheel under the twophoton microscope (as in Calcium imaging, except using a 40x/0.80 NA objective (LUMPLFLN 40XW, Olympus) and a 590 to 650 nm bandpass filter (Chroma) to filter emitted light prior to entering a 2 nd GaAsP detector (Hamamatsu)). Lighting with area smaller than the sensor was divided by the estimated illuminated area, rather than the area of the sensor.

Statistics.
We used the two-sided Wilcoxon rank sum test to calculate all p-values. Error bars are standard error of the mean unless otherwise described.
For egg-laying choice fractions (like Fig. 3c) grey bars show the fraction of eggs laid on the lower sucrose option after all eggs from all flies are pooled. Error bars indicate the 95% confidence interval of this fraction calculated using the Clopper-Pearson method ('exact' binomial confidence interval). Individual dots indicate individual flies.
P-values in the main text compare the number of trials with (or without) events in two separate groups. For a single group, trials with an event are treated as 1 and trials without an event are treated as 0. Then the two groups (each a set of 0 and 1) are compared using the two-sided Wilcoxon rank sum test (p-values calculated using two-sided Fisher's exact test are similar and similarly significant).
For all experiments, no data were excluded unless explicitly stated, and no statistical method was used to choose sample size.
Data Analysis Software. All data analyses and instrument control were done using MATLAB (MathWorks) unless otherwise specified. a Extended Data Figure 1. Free behavior chambers. 26   The first and last bin always include all the data points below and above that bin, respectively. The curve in panel g appears more linear and less step-like than the others; however, it is expected that as one progressively shifts the center point of the bins, one will find a position where the central bin exactly straddles the putative threshold, yielding an intermediate y value for that bin. The fact that panels f and h appear more step like supports this explanation for panel g. Extended Data Figure 9. Evidence against use of spatial information guiding search and against feeding-on-higher-sucrose-related suppression of egg deposition in our free behavior choice chambers. Fig. 9. Evidence against use of spatial information guiding search and against feeding-on-higher-sucrose-related suppression of egg deposition in our free behavior chambers. a, Schematic of a fly searching for an egg deposition site in a 0 vs. 500 mM chamber. ∆T0mM and ∆T500mM are all the intervals of time that a fly was transiting through 0 or 500 mM, respectively, during an egglaying search period. ∆Tlast_500mM is the last transit interval through 500 mM for eggs deposited on 0 mM. If a fly were positionally avoiding sucrose, ∆T500mM would be less than ∆T0mM. If a fly were to use spatial information during the search period--by taking a shortcut to get to the preferred 0 mM substrate at the end of a search--∆Tlast_500mM would be less than ∆T0mM and ∆T500mM. If a fly were feeding on the higher sucrose substrate -and pausing as flies do when they feed 61 --∆T500mM would be larger than ∆T0mM. b-d, ∆Tlower_sucrose, ∆Thigher_sucrose, and ∆Tlast_higher_sucrose distributions for three different sucrose choice chambers. ∆Thigher_sucrose is not less than ∆Tlower_sucrose suggesting that flies are not positionally avoiding the higher sucrose option. ∆Tlast_higher_sucrose is not detectably smaller than ∆T0mM or ∆T500mM suggesting that flies are not taking a shortcut--and thus not manifesting use of spatial information--at the end of the search. It is possible that flies use spatial information to guide the search in conditions with less thigmotactic walking 62,63 and/or with visual landmarks 64 (all experiments in this study were conducted in darkness).

Extended Data
Note that use of spatial information is compatible with our time-domain model for egg laying and would just suggest that flies control the substrate upon which they are located and as such control the egg-laying drive that they experience. ∆Thigher_sucrose is not larger than ∆Tlower_sucrose indicating that flies are not pausing only on the higher sucrose substrate. We interpret this result to mean that flies are not suppressing egg deposition because of extensive feeding on the sucrose substrates. In addition, we did not notice additional proboscis extension on higher sucrose when we spent hours inspecting each egg to annotate the egg deposition time, probably because our flies are very well fed prior to entering the chamber (Methods). The 5-10 s bin in this analysis has a higher egg laying rate than in the analysis from panel a, suggesting 11 that part of the delay in egg laying after a transition is due to flies not laying eggs on the plastic barrier. c, 12 Mean locomotor speed. A ~3 s delay exists between when a fly pauses and bends its abdomen to lay an 13 egg till when an egg is deposited. This ~3 s can explain why even the data in panel b do not show high 14 egg laying rates in the 0-5 s bin. Analyzing the same data as in panels a-b.   Genotype