{'fraction_non_alphanumeric': 0.033832177590454086, 'fraction_numerical': 0.01543521906904555, 'mean_word_length': 5.197493822802683, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Context-Dependent Representations of Movement in Drosophila Dopaminergic Reinforcement Pathways

Dopamine plays a central role in motivating and modifying behavior, serving to invigorate current behavioral performance and guide future actions through learning. Here we examine how this single neuromodulator can contribute to such diverse forms of behavioral modulation. By recording from the dopaminergic reinforcement pathways of the Drosophila mushroom body during active odor navigation, we reveal how their ongoing motor-associated activity relates to goal-directed behavior. We find that dopaminergic neurons correlate with different behavioral variables depending on the specific navigational strategy of an animal, such that the activity of these neurons preferentially reflects the actions most relevant to odor pursuit. Furthermore, we show that these motor correlates are translated to ongoing dopamine release and acutely perturbing dopaminergic signaling alters the strength of odor tracking. Context-dependent representations of movement and reinforcement cues are thus multiplexed within the mushroom body dopaminergic pathways, enabling them to coordinately influence both ongoing and future behavior.


Introduction
Neuromodulators confer flexibility to neural circuits, endowing animals with the ability to adapt to a complex and ever-changing world 1 . Across invertebrates and vertebrates alike, the neuromodulator dopamine influences diverse facets of behavior over different timescales. Dopamine has canonically been studied for its role in representing reward and stimuli predictive of reward, providing a teaching signal that drives learning [2][3][4] . Yet, loss of dopaminergic signaling also leads to pronounced motor and motivational deficits, highlighting a central role in both coordinating and invigorating an animal's actions [5][6][7][8][9] . Dopamine therefore subserves multiple seemingly disparate functions-shaping ongoing behavioral performance and modifying future behavior through learning.
How can a single neuromodulator exert such a broad influence on behavior? The diverse roles of dopamine could arise from functionally specialized and anatomically segregated circuits that each encode either reinforcement, motor, or motivational signals 6,10 . Alternatively, the same dopaminergic pathways could contribute to multiple forms of behavioral modulation. Indeed, recent recordings reveal that midbrain dopaminergic neurons responsive to rewards also display motor-associated activity as animals perform a learned task 11,12 . However, whether ongoing motor correlates in dopaminergic neurons simply encode motor kinematics, convey a motivational signal to promote reward-seeking behavior, or reflect the expectation of reward remains enigmatic [13][14][15] . Moreover, whether the multiplexed activity of dopaminergic neurons indicate that the same pathways can both rapidly shape online behavioral performance and instruct learning is unclear.
Here we took advantage of the concise circuitry of the mushroom body, the associative olfactory center of Drosophila, to gain insight into the dual representation of reward and motor activity by dopaminergic pathways. The mushroom body is richly innervated by dopaminergic neurons (DANs) whose segregated axonal projections target discrete, non overlapping compartments that tile the length of the mushroom body's output lobes 16 . DANs innervating different compartments convey the reinforcement signals that instruct learning, with distinct subsets activated in response to either reward or punishment [17][18][19][20][21][22][23][24] . Each compartment of the mushroom body lobe is also innervated by the dendrites of 1-3 mushroom body output neurons (MBONs). Local dopamine release within a compartment can therefore tune the strength of synaptic connections between the Kenyon cells that encode odor identity and the MBONs that bias behavior, enabling the same olfactory cue to drive either approach or avoidance depending on an animal's past experience 16,22,23,[25][26][27][28] . Recent studies have also revealed that the activity of specific mushroom body DANs correlates the spontaneous motor actions of an animal 26,[29][30][31] . The mushroom body therefore offers the opportunity to explore motor-related signaling in a simplified dopaminergic circuit with a defined role in reinforcement learning.
To gain insight into the nature of motor-associated activity in DANs, we devised methods to record from the mushroom body as animals actively pursued an appetitive odor plume in a virtual olfactory environment, allowing us to directly compare ongoing dopaminergic activity during spontaneous and purposive behavior and disambiguate whether their signaling relates to the sensory stimulus, motor kinematics, or represents a context dependent cue related to the task. We find that the same DANs responsive to reinforcement cues that instruct learning provide a rich representation of the moment-by-moment actions of an animal. Dopaminergic correlates of behavior, however, are not invariant but depend on the navigational strategy used for odor tracking, such that DANs preferentially represented the behavioral variables most relevant for pursuit. Together, our results suggest that rewards and purposive actions are encoded through comparable patterns of dopaminergic neuron activity and dopamine release, highlighting how the same neuromodulatory pathways can contribute to multiple forms of behavioral modulation over diverse timescales-conveying motivational signals to rapidly shape current behavior as well instructive signals to modify future behavior through learning.

Mushroom body DAN activity correlates with locomotion
To explore how dopaminergic pathways in the Drosophila mushroom body coordinately represent reward and movement, we monitored their activity in head-fixed animals walking on an air-supported, freely-rotating ball (Fig. 1A, Extended Data Fig. 1A). We expressed a synaptically localized calcium indicator GCaMP (sytGCaMP6s) under the tyrosine hydroxylase and dopa-decarboxylase drivers (TH/DDC), allowing us to visualize calcium influx in DAN axon terminals innervating the different compartments that tile the mushroom body lobes (Fig. 1A,B). We focused on the population of DANs targeting the γ lobe (γ2-γ5), as these respond to positive and negative contextual cues to instruct short-term associations 20,24,26 . Starved animals walking in the dark, in the absence of any overt stimuli, alternated between spontaneous bouts of locomotion and quiescence and when presented with a droplet of 1M sucrose, immediately ceased walking and consumed the sugar, allowing us to compare the activity evoked by reward and locomotion within the same trials (Fig. 1C).
As previously described, ingestion of sucrose evoked bidirectional changes in the γ lobe dopaminergic population 26 , activating the γ4 and γ5 DANs while suppressing the γ2 and γ3 DANs. Prior to and after sugar consumption, fluctuations in DAN activity were also observed that appeared to be temporally aligned to an animal's locomotion (Fig.  1C). The relative magnitude of these reward and motor-associated signals differed across DAN subsets, pointing to their functional specialization. While γ4 DANs were robustly activated by both sugar ingestion and locomotion, γ2 and γ3 DANs were activated only during walking and inhibited by reward ( Fig. 1C and Extended Data Fig. 1B). In contrast, sugar-evoked responses in the γ5 compartment were far larger than any motor-associated fluctuations ( Fig. 1C and Extended Data Fig. 1B). To characterize the locomotor-related activity of DANs, we therefore focused on the γ2, γ3, and γ4 subpopulations.
The dual representation of locomotion and reward within a compartment could arise either from heterogeneous classes of DANs that target the same compartment or from the multiplexed activity of individual neurons. Recent connectomic analyses indicate that the γ4 DANs can be divided into distinct subclasses based on their patterns of pre synaptic connectivity 32 , raising the possibility that they comprise a functionally diverse population. Using intersectional genetic drivers, we recorded from two morphologically distinct γ4 DAN subpopulations that could be distinguished by the axonal tract they follow to innervate the lobes (Extended Data Fig. 1D,E; MB312B, upper commissure; MB316B, lower commissure). While both subsets exhibited robust motor-associated activity, MB316B+ γ4 DANs also responded to sugar ingestion (Extended Data Fig. 1F-H). To further explore the multiplexed activity of the MB316B+ subpopulation, we used constrained nonnegative matrix factorization 33 to identify clusters of correlated pixels within the γ4 compartment, which presumably correspond to the individual axonal boutons of different neurons. Individual pixel clusters displayed both movement-and reward-related signals, an observation further corroborated by imaging of single MB312B+ and MB316B+ soma (Extended Data Fig. 2). Distinct DAN subclasses innervating the γ4 compartment thus appear to be functionally specialized, with a population selectively tuned to ongoing movement and a subset conveying multiplexed signals about locomotion and reward.
To assess whether the motor-associated activity of DANs can drive dopamine release, we expressed the genetically encoded dopamine sensor dLight1.3b 34 in Kenyon cells, their primary targets in the mushroom body (Fig. 1B,D). During bouts of locomotion, we observed rapid fluctuations in dLight signaling along the length of Kenyon cell axons that adhered to the compartmental organization of the γ lobe (Fig. 1B, Extended Data Fig.  1C, Supplementary Video 1). Dual recordings of DANs expressing the red calcium sensor jRGECO 35 and dLight in Kenyon cells demonstrated that dopamine release was highly correlated with DAN activity in the γ4 compartment, with comparable signals evoked by locomotion and reward (Fig. 1E,F). Despite the heterogeneity of γ4 DAN subclasses, we were unable to identify any functional topography or compartmental subdomains in either the activity of the broader DAN population labeled by TH/DDC or dLight signaling. Indeed, multiple clustering algorithms defined each compartment as a relatively homogenous functional unit ( Fig. 1B and Extended Data Fig. 1C). Examination of the Drosophila connectome reveals that different DAN subclasses have highly intermingled pre-synaptic terminals within the γ4 compartment 32 (Extended Data Fig. 1E), suggesting a potential basis the spatially homogenous patterns of dopamine release evoked by both locomotion and reward.

Differential encoding of behavior across compartments
While information about ongoing locomotion could be globally broadcast across the brain 30 , we observed that the DANs innervating different compartments reflected distinct facets of motor activity that unfolded over different timescales. For example, γ3 DAN activity consistently tracked the onset and offset of each bout of locomotion, independent of the heterogeneous kinematics of spontaneous movement ( Fig. 2A,B). In contrast, γ2 and γ4 DAN activity was highly variable even for bouts of walking that were indistinguishable by multiple behavioral metrics, both within and across individuals (  Supplementary Fig. 1). Conversely, although γ3 DAN activity faithfully reflected walking bouts enduring for tens of seconds, it only weakly tracked the rapid fluctuations in an animal's velocity during periods of continuous locomotion ( Fig. 2A, Extended Data Fig. 4A). Rather, increases in forward velocity were associated with increased γ4 activity and decreased γ2 activity, while increases in angular velocity (turning) were associated with increased γ2 and γ3 activity and decreased γ4 activity (Extended Data Fig. 4A-C). However, as observed for movement initiation, these relationships were inconsistent even within the same individuals (Extended Data Fig. 4A). Linear filters describing the moment-to-moment relationship between DAN activity and forward or angular velocity on average accounted for only a fraction of the variance in DAN activity during locomotion, but their predictive power varied widely between flies ( Fig. 2D-F, Extended Data Fig. 3G). Filters generated from multiple DANs accounted for significantly more of the variance than any single dopaminergic compartment (Extended Data Fig. 4G), suggesting that the ensemble activity of heterogenous DANs carries more information about an animal's ongoing behavior than an individual compartment.
During bouts of ongoing locomotion, the activity of different DANs was highly correlated on a sub-second time scale (Extended Data Fig. 4D-F). Yet, these intercompartmental relationships fluctuated rapidly (Extended Data Fig. 4D,H). Interestingly, the coordinated activity of DANs during locomotion partially mirror the responses of DANs evoked by sugar rewards or aversive shock 26 (Extended Data Fig. 4A-F, 5D), highlighting how the rich interconnectivity between compartments 16,26,32 may generate similar network states in response to both external reinforcements and ongoing behavior.

Recording DAN activity during active odor pursuit
Motor correlates in mammalian dopaminergic pathways have been proposed to reflect an animal's anticipation of reward or represent the motivation or vigor of goal-directed behaviors 5,7,10,11,[36][37][38][39][40] . The variable mapping between mushroom body DAN activity and apparently indistinguishable movements during spontaneous locomotion raised the possibility that these neuromodulatory pathways, likewise, do not simply encode the kinematics of locomotion, but may be shaped by an animal's behavioral context. To explore this possibility, we devised methods to record from DANs as flies were engaged in active pursuit of an appetitive odor plume.
A common navigational strategy employed by many insects, including Drosophila, is to reorient and increase their upwind velocity in response to an attractive olfactory cue, leading them to the odor source 41 . Indeed, flies freely walking in constant airflow displayed robust upwind tracking in response to a brief pulse of the food odor apple cider vinegar (ACV) (Supplementary Fig. 2A-E). To replicate odor-evoked tracking under the microscope, we used a closed-loop olfactory paradigm in which the heading of a tethered fly walking on an air-supported ball was yoked to the rotation of a tube carrying either a clean or odorized airstream, enabling an animal to control its orientation within an olfactory plume 28 (Fig. 3A, Supplementary Fig. 2G). Tethered flies could thus track an appetitive plume by reorienting and maintaining a steady upwind heading, resulting in a net upwind displacement towards the fictive odor source ( Fig. 3B and Supplementary Fig. 2D).
On average, the population of γ4 DANs was activated by brief pulses of ACV (Fig. 3D, Supplementary Video 2), consistent with their sensitivity to appetitive cues 18,20,26,31 (Fig.  1C,D and Extended Data Fig. 1B). However, odor-evoked responses were highly variable even between sequential odor presentations ("trials") within an individual animal (Fig.  3B,D). This variation appeared related to the concurrent behavioral response to the odor: γ4 DAN responses were strongest during trials when animals vigorously reoriented to track upwind and weaker when animals failed to alter their heading and continued to walk crosswind (Fig. 3B,F). Consequently, trial-by-trial, average γ4 DAN activity was correlated with the net distance an animal tracked upwind towards the fictive odor source (Fig. 3F, Extended Data Fig 5A,C). γ2 DAN activity also depended on an animal's behavioral response but in the opposite manner. These relationships were not apparent in clean air (Extended Data Fig. 5A-C), nor did they depend on differences in the efficacy of odor stimulation, as the magnitude of Kenyon cell responses was independent of the position of the odor tube (Extended Data Fig. 3H). Thus during active olfactory pursuit, mushroom body DANs neither solely represent the presence of an odor cue nor the kinematics of movement, but rather reflect the behavioral response to the stimulus.
In the closed-loop paradigm, flies tracked towards the fictive odor source predominantly by altering their heading to reorient in the upwind direction, rather than increasing their forward walking speed (Fig. 3C, Extended Data Fig. 5B,C). Interestingly, the moment-to-moment correlation between γ4 DAN activity and these behavioral variables was differentially strengthened as animals transitioned from walking in clean air to odor pursuit, with a notable change in the γ4 DAN-|heading| filter (Fig. 3E). Likewise, across trials, an animal's average heading but not its forward velocity was correlated with the γ4 DAN response and inversely correlated with the γ2 DAN response ( Fig. 3F and Extended Data Fig. 5A,D). Motor variables thus appear to be distinctly encoded by DANs as animals actively track an odor plume.

Context-dependent representations of odor-tracking behavior
The emergence of novel behavioral correlates during olfactory pursuit suggests that DAN representations of movement may depend on behavioral context. To explore this possibility, we altered the experimental conditions to induce flies to rely on a distinct navigational strategy to track towards the fictive odor source. By increasing the speed of the airflow, we observed that animals walked upwind almost continuously for several meters, even in the absence of odor (Fig. 4A), consistent with evidence that high airflow triggers positive anemotaxis in many insect species 42 . During these extended bouts of anemotaxis, the moment-to-moment correlations between γ2 and γ4 DAN activity and a fly's heading were strengthened compared to when animals walked in more circuitous paths in clean air under low airflow conditions (Extended Data Fig. 5G). Distinct behavioral correlates therefore arise as animals pursue a straight upwind trajectory, irrespective of whether tracking was elicited by high airflow or an appetitive odor.
Tethered flies walking upwind in high airflow responded to ACV by maintaining their current heading and transiently increasing their forward velocity (Fig. 4A,B, Extended Data Fig. 5F). As observed in the low airflow context, we found that as animals transitioned from walking in clean air to odor pursuit, the correlations between DAN activity and different behavioral variables changed, both in the structure of their moment-to-moment relationships captured by the linear filters (Fig. 4C) and in their averaged activity over the course of an odor trial (Fig. 4D). Notably, whereas in the low airflow context, the average γ4 DAN activity during the odor stimulus was predominantly correlated with changes in an animal's heading (Fig. 3F), in the high airflow context, it was more strongly correlated with an animal's forward velocity (Fig. 4D, Extended Data Fig. 5E, Supplementary Fig.  3A-D). These distinct relationships were apparent even if behavioral data was subsampled to have equivalent variance in low and high airflow regimes (Extended Data Fig. 5H,I). Despite the differential encoding of motor actions in low and high airflow, γ4 DAN activity remained well correlated with an animal's net upwind displacement in the odor plume across experimental conditions (Fig. 3F, 4D). Context-dependent correlations between DAN activity and behavior thus emerge as flies engage in different odor tracking strategies, with the behavioral metrics most relevant to odor pursuit selectively strengthened in each.

A simple model for odor pursuit
We sought to understand how the rapid remapping of DAN activity to behavior, captured by the changing linear filters, might give rise to these longer timescale relationships that emerge during olfactory navigation. We found that simply applying the best-fit linear filter to the experimentally measured behavior (Fig. 5A) could largely reproduce the trial-by-trial relationships between DAN activity, an animal's specific motor actions and the net distance it tracked towards the odor source (Fig. 5B,C). For example, the filters fit to γ4 DAN activity as animals walked in odor in low airflow gave rise to a strong correlation between the average γ4 DAN activity and a fly's heading, but a weaker correlation with its forward velocity, replicating the experimentally-observed relationships (Fig. 5B). Conversely, the filters fit to γ4 DAN activity in high airflow predicted a strong correlation with the average forward velocity of an animal tracking the odor plume, but not its heading (Fig. 5C). These relationships did not depend on the behavioral kinematics of odor pursuit as applying the low airflow filters to the high airflow behavioral data replicated the DAN-behavior correlations displayed in the low airflow context ( Fig. 5E and Extended Data Fig. 6B,D). Likewise, the high airflow filters were sufficient to reproduce the experimentally observed relationships when applied to the low airflow data ( Fig. 5D and Extended Data Fig. 6A,C), reinforcing that these context-dependent correlations depend principally on the distinct structure of the linear filters across conditions. Moreover, these relationships were not present if we used filters fit to DAN activity when animals walked in clean air (Extended Data Fig. 6E,F). The context-dependent restructuring of ongoing DAN-motor correlates thus naturally give rise to the longer timescale relationships we observe, ultimately strengthening the representation of actions that subserve odor navigation.
To further illuminate how the relationships between DAN activity and behavior unfolded over an odor trial, we calculated a cross-correlation matrix at various temporal offsets relative to the odor stimulus. This analysis supports our observations that the moment to-moment correlations between DAN activity and distinct behavioral variables were differentially strengthened as an animal entered the odor plume (Extended Data Fig. 7). Unexpectedly, the activity of some DANs became significantly correlated not only with an animal's current behavior, but also with its prospective tracking throughout the odor presentation (up to 8 sec into the future, Extended Data Fig. 7C,D). This anticipatory activity could not be explained by the possibility that animals maintain invariant trajectories within the odor plume, at least for the low airflow context, where the auto-correlation of their heading was predictive for < 3 sec and was similar in both clean air and odor (Extended Data Fig. 7B). A nested model quantifying how much the past, present, or future behavior contributed to predicting DAN activity further reinforced that DANs carry prospective signals (Extended Data Fig. 8A). In the low airflow context, while a fly's heading prior to odor onset had a negligible contribution to DAN activity, including current or future heading significantly improved the model's ability to predict γ4 activity in the initial epoch of an odor response (Extended Data Fig. 8B). In contrast, in the high airflow context, an animal's forward velocity, but not its heading, was the primary predictor of DAN activity in odor (Extended Data Fig. 8C). The anticipatory signaling of the mushroom body DANs further underscores that these pathways are not simply reporting on an animal's instantaneous experience, but appear to reflect context-dependent computations spanning multi-second timescales.

Satiety state coordinately modulates DAN activity and behavior
Our functional evidence that DANs preferentially correlate with the actions relevant to odor pursuit suggests that they may, like mammalian reinforcement pathways, reflect goal-directed behavior. Given that hunger represents a critical and conserved regulator of motivational drive, we explored how satiety state coordinately alters DAN activity and odor pursuit by measuring both in the low airflow context prior to (starved) and after consumption of sucrose (fed). Once sated, tethered animals walked with lower velocity and more frequently failed to reorient and steer upwind in response to ACV ( Fig. 6B and Supplementary Fig. 3E), mirroring the diminished odor attraction of fed freely moving flies ( Supplementary Fig. 2F) 43,44 . The dampened behavioral attraction to ACV in fed flies was accompanied by a corresponding attenuation of DAN responses (Fig. 6C).
Nevertheless, on a trial-by-trial basis, γ4 DAN responses remained significantly correlated with the change in an animal's heading in the odor plume (Fig. 6A,D), indicating that this population was still activated on the trials when a fed fly did reorient to walk upwind towards the odor source. Indeed, filters fit to DAN activity in starved or fed animals comparably predicted the longer timescale DAN-movement relationships observed in either satiety state (Extended Data Fig. 9). Thus γ4 DANs remained preferentially correlated with contextually-relevant behavioral variables irrespective of an animal's hunger state. While metabolic signaling pathways are thought to directly impinge onto DANs 43,45 , our results suggest that satiety state-dependent changes in DAN activity, at least in part, arise from the behavioral differences in starved and fed flies, underscoring the tight connection between internal state, locomotor activity, and motivational drive.

DAN activity influences ongoing behavior
The rapid context-dependent signaling of mushroom body dopaminergic pathways suggests that, beyond their established role in learning and memory, DANs may also acutely shape behavior. To test this possibility, we selectively expressed the light-gated anion channel, GtACR1, or cation channel, CsChrimson, in distinct subsets of DANs, allowing us to transiently inhibit or activate these populations during odor tracking in freely moving animals (Fig. 7A). To minimize the potential confounds of behavioral modulation due to learning, we examined odor pursuit in nominally naïve animals in response to a single brief episode of optogenetic illumination (Fig. 7B). The protocerebral anterior medial (PAM) DANs innervate multiple mushroom body compartments, including γ4, and their activation is sufficient to instruct appetitive odor associations 18,20,24,28 . Optogenetic inhibition of the entire cluster of PAM DANs, or just the MB312+ population of γ4 DANs, consistently suppressed attraction to ACV in starved flies ( Fig. 7A-C and Extended Data Fig. 10A, Supplementary Fig. 4A). In contrast, silencing the protocerebral posterior lateral (PPL) DANs that convey negative reinforcement during learning 17,19,21,28 had no impact on odor tracking. Conversely, optogenetic activation of PAM DANs increased the proportion of fed flies that tracked upwind towards an odor and even promoted upwind tracking in the absence of an odor stimulus ( Fig. 7D and Extended Data Fig. 10B, Supplementary Fig. 4B,C). Acute manipulation of DANs therefore bidirectionally modulates olfactory approach behaviors, in accord with more chronic perturbations 44,46 , with inhibition of PAM DANs suppressing the strong attraction of starved animals and their activation reversing the behavioral indifference of fed flies.

Discussion
In this study, we took advantage of the mushroom body's concise circuit architecture to explore the nature of movement-related activity in a population of dopaminergic neurons that instruct associative learning. While motor signals have been previously observed in the mushroom body DANs 26,29-31 , by developing methods to examine their activity as an animal was actively engaged in odor tracking, we gain new insight into these motor correlates and how they contribute to adaptive behavior. Although DANs provide a rich representation of a fly's ongoing behavior, several lines of evidence suggest these motor correlates do not simply reflect the kinematics of movement. First, the relationship between DAN activity and indistinguishable motor actions is not fixed but can rapidly change to reflect alterations to an animal's context. Indeed, distinct DAN-motor correlations emerged as animals transitioned from walking in clean air to active odor pursuit, such that the representation of actions most relevant to odor tracking in a particular context were selectively strengthened (Fig. 8). As a consequence, γ4 DAN activity consistently correlated with an animal's net upwind displacement towards the appetitive odor source on a given trial, irrespective of the specific navigational strategy used for tracking. Second, our analyses suggest how these moment-to-moment correlations give rise to longer timescale relationships, even extending beyond immediate behavior such that DANs carried information about an individual's prospective tracking within the odor plume. Finally, optogenetic perturbations of DAN activity acutely alters odor tracking, indicating that these pathways not only reflect but also modulate real-time behavior. Together, these data support a model in which DAN-motor correlates are dynamically tuned to the actions that subserve goal-directed and purposive behavior (Fig. 8), like seeking a food source, suggesting a fundamental connection between movement and motivation within these dopaminergic pathways.

Layered multiplexing of reward and motor signals
Our work supports emerging evidence that mushroom body DANs exhibit functional complexity beyond signaling rewards or punishments. DANs innervating different compartments reflect both external reinforcement cues 18,24,26 and motor variables, giving rise to a rich and distributed representation of an animal's ongoing experience through correlated patterns of activity across the population. The Drosophila connectome reveals how functional specialization within different DAN subsets may arise. Individual DANs display divergent patterns of synaptic connectivity 32 , integrating from an array of interneurons emanating from additional higher-order neuropils, feedback from MBONs innervating different compartments, as well as select ascending sensory pathways. The mushroom body DANs are thus wired into a highly interconnected network, poised to convey pre-processed signals that reflect an animal's external environment, internal state, motor actions, and motivations. The complexity of inputs to the DANs further suggests how their activity may be rapidly remapped to different behavioral actions depending on the context in which they are performed, either by inheriting context-dependent signals from their diverse presynaptic partners or reweighting these inputs in a context-dependent manner. Likewise, the highly recursive and integrative wiring of DANs suggests how both ingestion of a sucrose reward and tracking towards an appetitive odor source can generate comparable patterns of network activity.
Mirroring the multifaceted and complex functional representations, we find that the same DANs that instruct olfactory associations also acutely influence odor pursuit. These observations suggests that in Drosophila diverse forms of dopaminergic modulation may be subserved by the same neuronal pathways. Recent work suggests that mammalian striatal dopaminergic neurons display similar heterogenous and multiplexed activity in which representations of behavior and motivational cues are coupled with teaching signals 6,10-12 , further supporting that functional diversity may be an important principle allowing dopaminergic systems to guide diverse forms of adaptive behavior.

Diverse computational roles for dopamine
An important remaining question is whether and how the targets of the mushroom body DANs-Kenyon cells and MBONs-differentiate between dopamine signals evoked by external reinforcements or arising from behavior. While subsets of γ4 DANs appear functionally specialized, their axonal projections are intermingled throughout the compartment and form similar numbers of synapses with the main γ lobe Kenyon cells 32 . This synaptic organization suggests that ongoing release of dopamine during locomotion may engage the same synaptic plasticity mechanisms that drive memory formation, allowing both rewards and self-generated actions to similarly modulate behavior. Although the goal of reinforcement learning is to shape an animal's long-term decision-making policies 47 , short-term associations are required to solve the credit assignment problem and extract the causal relationship between an animal's actions and subsequent rewards. The combination of ongoing DAN activity during odor pursuit and rapid dopamine-dependent plasticity of the γ lobe offers a potential mechanism for storing such an eligibility trace of a fly's recent actions. For example, KC-to-MBON synapses activated by an odor during locomotion could be rendered sensitive to an ensuing reward, generating a short-term association useful for updating a fly's decision-making policy during odor navigation. Such a mechanism could underlie recent evidence for history-dependent odor tracking behavior 48 or facilitate pursuit of an odor plume. Indeed, optimization of a simulated mushroom body network for different tasks, including odor navigation, revealed highly distributed DAN activity patterns that covaried with multiple task-relevant variables, mirroring the multifaceted representations we experimentally observe 49 .
Optimal behavioral policies may not only emerge through learning but could be hard wired into the nervous system through evolution to assure appropriate adaptive behavior. The mushroom body's position at the nexus of sensory circuits conveying odor signals and the efferent MBON pathways that bias behavior makes it an optimal substrate for dopaminergic signaling to modulate olfactory behavior, whether based on an animal's past experience or its current context. Our data add to growing evidence that the mushroom body plays a role beyond associative learning 26,44,46 , suggesting dopaminergic modulation may act through multiple mechanisms that function over distinct timescales. Consistent with this notion, the Drosophila connectome reveals that DANs synapse directly onto MBONs 32,50 , providing a parallel route of communication that is mechanistically distinct from associative plasticity. Interestingly, the heterogenous subclasses of γ4 DANs differentially synapse onto the dendrites of three MBONs innervating the γ4 compartment 32 , suggesting an additional mechanism to expand the computational capacity of a single compartment and to shape moment-to-moment behavior.

Conservation of neuromodulatory mechanisms
Our work supports the basic correspondence of dopaminergic systems in insects and mammals, despite their separation by several hundred million years of evolutionary divergence. Dopamine acts upon circuits that display a fundamentally different architecture across these distant phyla yet can give rise to similar forms of learning and adaptive behavior. Whether the analogous roles of dopamine in insects and mammals reflect the basic conservation of neuromodulatory pathways or convergent evolution is not clear 51 . One possibility is that dopamine's evolutionary ancient role as a modulator of motor circuits 52 predisposed dopaminergic systems to acquire more specialized functions as brain complexity evolved, linking reward pursuit and reinforcement. Alternatively, the ubiquity of dopamine as a modulator of associative circuits could reflect similar computations arising repeatedly, potentially taking advantage of conserved receptor signaling pathways and molecular hardware. In either case, the coupling of reinforcement signals and locomotor representations in the same neuromodulatory system across divergent taxa suggests an inherent connection between them. By representing and invigorating motor actions and assigning value to sensory stimuli through learning, dopaminergic pathways allow animals to flexibly adapt their behavior over different timescales: acutely shaping moment-by moment movements to achieve short term goals and effecting persistent changes in behavior through learning.

Fly Husbandry
Flies were maintained on cornmeal-agar-molasses medium at 23-25°C, 60-70% relative humidity, under a 12-hour light/dark cycle and transferred to vials containing only a KimWipe soaked in 2 mL water (or 0.2 mM all-trans-retinal water for optogenetic experiments) 18-24 hours before all experiments. For optogenetic experiments, flies were grown on retinoid-free sugar-and-yeast-based food in complete darkness. 1-2-day-old females were transferred to conventional food containing 0.4 mM all-trans-retinal (Sigma #R2500) and placed in the dark for ≥24 hours.

Fly Stocks and Genotypes
All experiments were performed using 1-7-day-old females. For detailed fly stock sources and genotypes see Supplementary Table 1.

Fly Tethering and Dissection
For in vivo imaging of neural activity, flies were prepared as described previously 53 with minor modifications. Briefly, 3-7-day-old-females were anesthetized using CO 2 (<30 sec) and tethered to a specially designed holder dish. The fly was held in place with UV-curable glue (Loctite) applied to each eye and thorax and the proboscis was glued in an extended position. Care was taken to avoid glue contacting the antennae or aristae. After a <2-hour recovery period, the dish was filled with external saline (108 mM NaCl, 5 mM KCl, 2 mM CaCl2, 8.2 mM MgCl2, 4 mM NaHCO3, 1 mM NaH2PO4, 5 mM trehalose, 10 mM sucrose, 5 mM HEPES sodium salt, pH 7.5 with osmolarity adjusted to 275 mOsm) and the cuticle covering the dorsal portion of the head was removed. Muscle 16 and obstructing trachea were removed with care taken to keep the antennae and antennal nerves intact.

Two-Photon Functional Imaging
All functional imaging experiments were performed on an Ultima two-photon laser scanning microscope (Bruker Nanosystems) equipped with galvanometers driving a Chameleon Ultra II Ti:Sapphire laser. Emitted fluorescence was detected with either photomultiplier-tube or GaAsP photodiode (Hamamatsu) detectors. Images were acquired with an Olympus 40x, 0.8 numerical aperture objective at 512 pixels × 512 pixels resolution. For fast-scanning volumetric imaging in vivo (Extended Data Figure 2G), the laser was directed through an 8 kHz resonant scanning galvonometer and the objective was controlled by a piezo-electric Zfocus.

Image Processing
All image processing was performed using custom scripts in Matlab or FIJI/ImageJ (NIH). Compartment (DAN subpopulation)-specific activity was computed by averaging all fluorescence signal within a manually defined MB γ lobe compartment. All DAN>sytGCaMP6s signals are normalized (divided) by MB247(KC)>dsRed fluorescence within the same ROI. Data from all other functional imaging experiments are plotted as raw fluorescence on an arbitrary scale or normalized as indicated.

Tethered Locomotion
For tethered locomotion experiments, a spherical treadmill was designed based on previous studies 53 . Briefly, a 6.35 mm diameter ball was shaped from Last-A-Foam FR-4618 (General Plastics) by a custom-made steel concave file. The ball rested in an aluminum base with a concave hemisphere 6.75 mm in diameter with a 1mm channel drilled through the bottom and connected to an airflow. The ball was recorded at 60-61 fps using a Point Grey Firefly Camera (Firefly MV 0.3 MP Mono USB 2.0, Point Grey, FMVU-03MTM-CS) with Infinity Lens (94mm focal length) focused on the ball while being illuminated by infrared LED lights. Ball rotation was calculated in real time using FicTrac software 54 running on computers with ≥3GHz processors speeds.

Closed-loop arena
The heading of the fly, as calculated by FicTrac, was transmitted to an Arduino Mega via serial port. Custom Arduino code was used to translate heading into tube position controlled by motors described below. The closed-loop air-delivery system was custom designed using OnShape (www.onshape.com) and 3D printed using Visijet Crystal material at XHD resolution in a 3DSystems Projet 3510 HD Plus. O-ring OD and ID Gland surfaces were designed with excess material for printing then manually modified on a lathe for improved RMS [surface] finishing. 360° tube rotation was driven by a bipolar stepper motor (Pololu item #1206) controlled through a A4988 Stepper Motor Driver Carrier (Pololu #2980) coupled by a Dust-Free Timing Belt XL Series, 1/4" Width (McMaster-Carr, 1679K121, Trade No. 130×L025) to the rotating tube system, which rotated mounted on an Ultra-Corrosion-Resistant Stainless Steel Ball Bearing (3/4" Shaft Diameter, 1-5/8" OD, Mcmaster-Carr 5908K19). Air channel was kept airtight using oil resistant o-rings (1/16 Fractional Width, Dash Number 020, Mcmaster-Carr 2418T126). Motor rotation was measured by a rotary encoder (CUI Inc., AMT10 Series) that was used to correct for skipped steps.

Odor stimulation and airflow
Odor stimulation was achieved by directing a continuous stream of either 100 mL/min (low airflow conditions) or 400 mL/min (high airflow conditions) of clean air through a 2 mm diameter tube made of Visijet Crystal material directed at the fly's antenna. 10-20% of the total airstream was diverted through the headspace of a 500 mL bottle containing water. At a trigger, a custom-built solenoid valve controller system redirected the odor stream from the water bottle to a bottle containing the odorant, Apple Cider Vinegar (ACV, Heinz).

Sugar Feeding
For recordings involving sucrose, flies were tethered for imaging and locomotion as described above. Early during recovery from anesthesia, flies would often fully extend their proboscis before regaining other motor functions and at this point, glue was applied to the lateral sides of the proboscis with care taken to avoid glue contacting the distal proboscis, mouth parts, antennae, and aristae. As in all other tethered experiments, muscle 16 and obstructing trachea were removed with extra care taken to keep the antennal nerves and the esophagus intact. This approach allowed for flies to ingest sugar through their proboscis with minimal motion of the brain relative to the imaging plane. As a control for movement artifact in experiments recording GCaMP activity from all MB DANs, the stable fluorophore dsRed was expressed in the anatomically overlapping population of KCs and all DAN>sytGCaMP6s signals were normalized (divided) by MB247(KC)>dsRed fluorescence within the same ROI. In addition, this channel was monitored for movement artifact and trials that demonstrated changes in activity during sugar feeding beyond the range observed during spontaneous locomotion were excluded from analysis. For CNMF analysis of MB312B and MB316B flies (Extended Data Fig. 2A-D), occasional frames during sugar feeding demonstrated large movement artifacts. These frames were manually excluded and the neural activity at these timepoints was inferred using linear interpolation. For sucrose delivery, tethered flies were presented with nanoliter volumes of 1M sucrose via a Nanoject II Auto-Nanoliter Injector (Drummon, Cat. No. 3-000-204) positioned with a motorized micromanipulator (Scientifica). Red food coloring was added to the sucrose and the fly abdomens were inspected after each experiment to confirm sucrose ingestion.

Freely Moving Fly Behavior and Optogenetic Perturbations
Behavior in freely moving flies was assayed in a custom-built apparatus as described previously 28 .

Data Analysis and Presentation
Unless otherwise noted, all analyses, visualizations, representations, normalizations, and averaging of behavior and DAN activity were performed or generated using custom scripts in Matlab and/or ImageJ. The following Matlab functions were used to generate the parenthetical variables/images: imagesc (heatmaps), movcorr (running correlations), hist (histograms), kmeans (k-means clustering). All figures, illustrations, schematics, and cartoons were created using Adobe Illustrator CC.
To facilitate visual comparison of neural activity and behavior ( Figures 1C-E, 2A-C, 3B, 4A, Extended Data Figure 1F, 2, 3A,B,C,F, 4A-C, 8A, and Supplementary Fig. 3A-C,E) the behavioral variables of net motion and/or forward velocity were convolved by the biexponential rise and decay function of GCaMP6s (rise t 1/2 =175 ms and decay t 1/2 =550 ms), GCaMP6f (rise t 1/2 =50 ms and decay t 1/2 =150 ms), dLight (rise t 1/2 =10 ms and decay t 1/2 =100 ms), or jRGECO (rise t 1/2 =40 ms and decay t 1/2 =200 ms) and then multiplied by the mean of the top 10% of unconvolved behavioral variables for each trace (translated from radians/sec into mm/s according to the radius of the treadmill). In all other analyses the unconvolved behavioral data was used, as smoothing out the fine temporal structure of the signal could lead to the loss of relevant information within the data and introduce spurious temporal shifts.
Behavioral variables were captured at 60-61 frames/second while neural activity (fluorescence) was captured at 10 frames/sec. Due to electronic delays within the imaging system, however, frames were captured over a range of every 95-110 ms, creating irregular time stamps. To align these two distinct time-series, a standardized and regular time-series was generated for each trace containing 100 ms time bins (0, 100, 200, 300, etc.…). All behavioral or fluorescence data captured between these standardized cutoff points were averaged and assigned to the lower bound of the time bin. This allowed for neural and behavioral data to be aligned and meaningfully compared.
Comparisons of movement-and reward (sucrose)-related DAN activity and neurotransmitter release (Extended Data Figure 1B) were made by averaging normalized (ΔF/F o with F o = median trial fluorescence) sytGCaMP6s or dLight1.3b fluorescence during bouts of movement or during ingestion of 1M sucrose solution manually identified by concurrent digital video recording.
CNMF analysis was performed as follows: Frames with large motion artifacts were manually removed from the imaging stack, which was then motion corrected using non-rigid motion correction (NoRMCorre) 55 . ROIs were extracted using constrained non-negative matrix factorization (CNMF) 56 . Greedy and graph NMG initialization methods were used to extract ROIs corresponding to DAN presynaptic terminals and mushroom body compartments.
Instances of movement initiation ( Figure 2B, Extended Data Figure 3A-F, Supplementary  Figure 1) were identified in silico using a custom Matlab script that relied on a manually set cutoff to find inflection points in net motion after a prolonged pause (≥2 sec) followed by sustained movement (≥3 sec). Triggered average of parameters of behavior at the start of movement were normalized by dividing them by their average value during a given trial. Each individual behavioral trace was then aligned to generate the average, standard deviation, and 95% confidence interval and plotted on an arbitrary scale on an aligned set of axes. Relationships between DAN activity and different behavioral variables and relationships between different DANs during individual bouts of movement initiation were calculated by averaging the ΔF/F o signal over the period of t=1 to t=2.5 seconds relative to the onset of movement and averaging the behavioral variables (normalized as above by division by their average value) over the relevant time period. Net motion, forward velocity, and |angular velocity|: t=1 to t=3. |Lateral velocity|: t=0 to t=1. Proportion of time moving after start is calculated over a 10 sec period after initiation of locomotion.
Principal component analysis (PCA) of behavioral variables during movement onset ( Supplementary Fig. 1) was performed on the concatenation of net motion, forward velocity, |angular velocity|, and |lateral velocity| across a 4 second time window centered on instants of movement initiation (4 variables × 4 sec time window × 10 Hz sampling = 160 initial variables per start). All behaviors were z-scored over the 4 sec window prior to concatenation.
To identify bouts of movement and periods of quiescence, custom Matlab scripts used manually set cutoff values and the non-convolved net-motion recordings to perform an in silico identification of periods of walking and periods of not walking during trials. Walking/ still designations were then manually verified and time points of transition stored to be used in subsequent analyses.
Probability of accurate walking state prediction ( Figure 2C) was calculated as follows: Epochs of movement and quiescence were identified as above. All data from a single animal were concatenated and 20% of time points were randomly set aside (using Matlab function randperm) while the remaining 80% were used to train a multinomial logistic regression model (mnrval) to predict locomotor state from compartmentalized DAN activity. The model was then tested on the previously allocated 20% of time points. During testing, the model produced both a prediction of locomotor state and probability of accuracy. Predictions were compared with actual locomotor state and the probability of accuracy of correct predictions were averaged (with incorrect predictions assigned a value of zero). This process was repeated 100 times for each animal and the mean probability of accurate predictions was averaged across all 100 repetitions.
Increases in forward velocity and |angular velocity| (Extended Data Figure 4B,C) were calculated as follows: A custom Matlab script isolated local maxima in forward or |angular| acceleration during bouts of movement and the preceding point of acceleration=0 was then identified, and velocity and neural activity were then aligned to these time points. To exclude instances when animals altered both their forward and angular velocities, epochs in which the acceleration of the alternative behavioral variable rose beyond a manually set cutoff point were excluded. For plotting, behavior centered on these inflection points were z-score normalized by the average behavior over a time window from t=−2 to t=2. Neural activity was plotted as ΔF/F o with F o defined as neural activity from t=−1 to t=0. Behavior and neural activity were then aligned to generate the average and standard deviation of the given variable.
Linear filters were fit using standard linear regression in which the least squared error between true and predicted output was minimized to identify best-fit filters. Specifically, for a given DAN variable x (e.g., γ4) and behavioral variable y (e.g., forward velocity), we let the estimate y*(t) of behavior at time t be given by y*(t) = a(-τ)x(t-τ) + a(-τ+Δt)x(t-τ+Δt) + ... + a(τ-Δt)x(t+τ-Δt). We then found the a(-τ), ..., a(τ-Δt) that minimized the squared difference between y(t) and y*(t), averaged over all t within a given trial. Only timepoints during which the animal was walking were used in the fitting procedure. All filter fitting was performed using the scikit-learn package in Python.
The proportion of DAN variance explained by specific behavioral variables ( Figure 2F) was calculated using an adjusted R 2 value, (R 2 adj = 1 -(1 -R 2 )(n-1)/(n-p-1), where n is the number of valid timepoints used in the filter fit (i.e., the number of timepoints where the fly was locomoting), and p is the number of time points (free parameters) in the linear filter. This quantity adjusts for spurious increases in standard R 2 due to a large number of free parameters relative to data points. We chose this metric because it allowed us to capture individual variation in DAN variance explained by behavior across flies and trials without requiring us to hold out data for cross-validation (since many trials did not have sufficient data points to do so due to the limited amount of time the fly was walking). Negative R 2 values, which largely reflect a scarcity of data in an individual trial, were not plotted. Figure 4G) were made by fitting linear filters to 80% of trials and evaluating them on the held-out 20% of trials. Filters were defined as the best-fit weights in a weighted sum of either one or all DAN activity levels in the 8 seconds surrounding the timepoint of the behavior to be predicted (e.g., for single DANS imaged at 10 Hz, there were 80 weights to fit, and for all 4 DANS, 320 weights to fit). All trials used in fitting were aggregated before fitting due to the large number of weights in the 4-DAN filter, with a random 80/20 fitting/test split of trials repeated 50 times. For each split, filter weights were chosen to be those that minimized the squared difference between the true and predicted behavioral variable, averaged over all timepoints in all trials used for fitting. Filters were evaluated by calculating the R 2 between the true and filter-predicted behaviors in the 20% of held-out trials.

Predictions of behavioral variables from single and all DAN compartments (Extended Data
Partial correlations (Extended Data Figure 4F) were generated via custom Python scripts in the following way. To calculate the partial correlation between two variables x and y, conditioned on auxiliary variables z 1 , z 2 , ..., we first computed the best fit linear predictions x * and y * for x and y, respectively using z 1 , z 2 , ..., as the only predictors (in addition to an intercept term). The partial correlation between x and y given z 1 , z 2 , ..., was then computed as the Pearson correlation between (x -x * ) and (y -y * ). Both the net ball motion signal and the other DAN activities were included in the auxiliary variables.
Position of tethered flies on a fictive 2-dimensional plane was calculated by FicTrac software based on the diameter of the foam ball upon which the fly was walking, and representations of fictive walking trajectories were generated using custom written Matlab scripts.
Neural activity and behavior at odor onset were identified using the aligned internal timestamps generated with Bruker Nanosystems software or FicTrac software, respectively, and representations were generated using custom written Matlab scripts. For DAN activity, ΔF/F o was calculated with F o defined as the average normalized (see Image Processing) GCaMP fluorescence during a 10 second period immediately prior to odor onset. In air controls were similarly calculated except with a 15-second temporal offset.
Individual odor responses were aggregated from trials across multiple flies. Every fly was presented with at least 10 odor presentations, but trials in which FicTrac failed to continuously track the fly's movements throughout the period immediately preceding and through the entire odor presentation were excluded, as in these instances the animal was not maintained in the closed-loop virtual reality configuration. As a result, the number of trials from any individual fly included in the dataset ranged from 3 to 12. We therefore aggregated responses across animals to examine the relationship between changes in DAN activity and changes in different behavioral variables.
Relationships between averaged DAN activity and behavior during an odor trial were calculated as follows: Upwind displacement was divided by the individual fly's average walking speed in the 10 seconds prior to odor presentation and then calculated as the change in fictive position along the axis of airflow from the start of the odor plume (t=0) until the end of the odor plume (t=10). Changes in forward velocity or |heading| were calculated by subtracting the average forward velocity or |heading| during bouts of movement in the 10 second period preceding odor onset (t=−10 to t=0) from the average forward velocity or |heading| during bouts of movement occurring within the odor plume (t=2 to t=10, to account for any delays in odor delivery). Using shorter or longer time bins gave similar results. γ DAN ΔF/F o was averaged over t=2 to t=10 sec after odor onset with F o = average sytGCAMP6s activity during bouts of movement from t=−10 to t=0 seconds before the onset of odor. Relationships between averaged DAN activity and behavior as animals walked in clean air (Extended Data Figures 5A,B,E,F) were calculated similarly except over the 20 seconds preceding an odor stimulus. Subsampling of odor responses (Extended Data Figure 5H,I) was performed by serially excluding data below or above a manually set cutoff point until the variances of the behavioral variables in the two datasets was approximately equal.
Linear Model ( Figure 3E, 4C, 5 and Extended Data Figures 6, 9): Prior to filter fitting we z-scored normalized DAN activity within each compartment relative to the entire 5-minute trial. Forward velocity was normalized by dividing all timepoints by the median forward velocity computed during all identified walking periods in the trial. Absolute (unsigned) heading was measured in radians. We then considered either the 10 seconds prior to odor onset (in air) or the 10 seconds following odor onset (in odor). The average 10-second activity of each DAN subset across all trials was then subtracted from the DAN activity during each individual trial (either in or out of odor) to account for any rapid rise or fall during odor onset and allow the filters to better explain how behavior gives rise to the fluctuations around the mean response. Using the collection of 10-second windows aggregated across all odor pulses and trials for either the "in odor" or "in air" period we then fit 5-second linear filters predicting DAN activity from the two behavioral variables. Specifically, for each compartment we assumed DAN activity at time t, g(t), was a weighted sum of the forward velocity and absolute heading signals in a window extending 4 seconds prior to t and 1 second after. Mathematically, we let the estimate g * t = w h −4 h t−4 + w h −3.9 h t−3.9 + ... + w h 0.9 h t+0.9 + w h 1 h t+1 + w v −4 v t−4 + w v −3.9 v t−3.9 + ... + w v 0.9 v t+0.9 + w v 1 v t+1 where h and v are absolute heading and forward velocity, respectively. We chose all w's by minimizing the squared error (g(t) -g*(t)) 2 averaged across time, pulses, and trials. This yielded 5 seconds of absolute heading and forward velocity weights for each DAN compartment in each period ("in air" and "in odor"). We repeated this process across all conditions (low-flow, high-flow, fed). Experimentally-derived data was similarly normalized when directly compared with model-generated data. Figure 7) were generated in Python in the following way. For each 10-second odor pulse across all trials, all measured variables (DAN activity, heading, etc.) within the 20 sec time window surrounding the pulse onset were selected and stored (i.e., the window included the 10 seconds prior to the pulse and the 10 sec of the pulse itself). For each variable this generated an initial data matrix with the number of rows equal to the number of odor pulses across all trials and with 200 columns (20-seconds x the 10 Hz sampling). DAN activity was normalized for each pulse by subtracting and then dividing by the average fluorescence within this 20-second window. Forward velocity and heading were normalized by subtracting the forward velocity or heading, respectively, averaged over the first 10 seconds (the 10 seconds preceding the odor pulse onset). A correlation matrix between variables x and y across odor pulses was then generated by computing the Pearson correlations between x(t 1 ) and y(t 2 ) for all t 1 and t 2 spanning the 20-second window. P values were calculated as standard Pearson correlation p values using the scipy Python package.

Cross correlation matrices (Extended Data
The nested model analysis (Extended Data Figure 8) used linear models and significance levels for the increase in variance explained (as stepwise predictors were added) were computed using an F-test. Models were fit and analyzed using Python scripts and results were plotted in Matlab. Briefly, for a given condition (low or high airflow) and DAN compartment, each odor pulse was treated as a "trial". Across trials, we sought to predict DAN activity during the initial phase of odor presentation (γ 1-4 , time-averaged 1-4 seconds post odor onset) using combinations of the following predictors: |heading| time-averaged over the 10 sec prior to odor onset (h o ), initial Δforward velocity (time-averaged from 1-4 sec post odor onset, Δv 1-4 ), initial Δ|heading| (time-averaged from 1-4 sec post odor onset, Δh 1-4 ), and future Δ|heading| (time-averaged from 7-10 sec post odor onset, Δh 7-10 ). Windows were chosen based on the approximately 3-second heading autocorrelation time. We then proceeded with a stepwise regression: for a given condition and DAN compartment we first identified (using least-squares regression) the best linear prediction of initial DAN activity (γ 1-4 ) given h o alone. That is, we identified the parameter a in the model g* = ah o that minimized (γ 1-4 -γ*) 2 averaged over all trials/pulses. We next added initial forward velocity as a predictor by identifying the best-fit parameters a, b in the model γ* = ah o + bΔv [1][2][3][4] and recomputed the trial/pulse-averaged error. We repeated the procedure by sequentially adding in the remaining two predictors Δh 1-4 and Δh 7-10 and recomputing the corresponding error. This stepwise regression allowed us to evaluate whether the predictive power gained by adding in each new predictor was significant by comparing the explained variances of the model with and without the candidate predictor using an F-test.

Statistical analysis
All statistical analyses were performed using built in Matlab functions unless otherwise noted. Exact p values for every statistical test performed is listed in Supplementary Table 2. Pearson Correlation Coefficient and associated p-value: corrcoef One-way ANOVA followed by Tukey's multiple comparison test: anova1 and multcompare Fisher r-to-z transformation was calculated using http://vassarstats.net/rdiff.  Figure 1F, light lines) or closed-loop (CL) in clean air. ± 95% CI. OL: N=66 animals, 119 5-minute trials. CL: N=20 animals, 32 5-minute trials. (H) Comparison of γ Kenyon Cells activity during presentation of apple cider vinegar from indicated angles. Average ΔF/F o (dark line) ± 95% CI aligned to odor onset. Right: average ΔF/F o during odor presentation from indicated angles. N=16 animals, 3 odor presentations per orientation (total 144 odor presentations). One-way ANOVA followed by Tukey's multiple comparison test; no statistical significance observed.  Table 2). N=26 flies, 143 odor presentations. (E) Same analysis as in Figure 4D but offset by 15 sec such that flies were walking in clean air. N=22 flies, 52 odor presentations. (F) Same analysis as in Figure 4B but offset by 15 sec such that animals were walking in clean air. N=22 flies, 52 odor presentations. (G) Filters predicting DAN activity from |heading| (top) or forward velocity (bottom) as animals walked in clean air, under low (lighter) or high airflow (darker) conditions. ± 95% confidence interval obscured by thickness of the data line. (H) Average γ DAN ΔF/F o plotted as a function of upwind displacement (left), Δ|heading| (middle), and Δ forward velocity (right) during odor presentation from Fig. 3F however here data from the low airflow context was subsampled such that the variance of the Δ |heading| was statistically equal to that of the high airflow context. Top: distribution of range of behavior. Pearson coefficient (r) indicates where relationship between subsampled variables is significant (p<0.05 with Bonferroni, see Supplementary Table 2). N low airflow=135 odor presentations. (I) Same as (H) except when data from the high airflow context is subsampled such that the variance of the Δforward velocity was statistically equal to that of the low airflow context. N high airflow=50 odor presentations.  Table  2). N=26 flies, 143 odor presentations. Note the correlation between an animal's current and past or future forward velocity extend throughout the trial, while the correlation between an animal's current and past or future heading is < 3 sec. (C-D) Cross correlation matrix between forward velocity (left) or |heading| (right) and γ DAN activity during the 10 sec prior to odor onset and the 10 sec during odor presentation under low (C) and high (D) airflow conditions. Only relationships that are statistically significant by Pearson cross correlation (p<0.05, no Bonferroni correction, see Supplementary Table 2

Supplementary Material
Refer to Web version on PubMed Central for supplementary material.    Table 2). Fisher r-to-z transformation indicates significant differences in correlation coefficients for γ4-Δ|heading| and γ4-Δforward velocity relationship with z=−6.03. N=26 flies, 143 odor presentations.  Table 2). Fisher r-to-z transformation indicates significant differences in correlation coefficients with z=−7.43. Fisher r-to-z transformation also indicates significant differences in correlation coefficients for upwind displacement -Δforward velocity across the high and low airflow contexts with z=−3.89 but no significant differences in the correlation coefficients for upwind displacement -Δ| heading|. N=22 flies, 52 odor presentations. Linear filters predicting DAN activity using forward velocity (V f , left) or |heading| (|h|), right) in the odor plume (colored) and in clean air (black, dashed) over a 4 second window (zero mark indicates odor onset). N=22 flies, 52 odor presentations. (D) Average γ DAN ΔF/F o plotted as a function of net upwind displacement (left), average Δ|heading| (middle) and average Δforward velocity (right) during odor presentation. Pearson coefficient (r) indicated where relationship is significant (p<.01 with Bonferroni correction, see Supplementary Table 2). Fisher r-to-z transformation indicates significant differences in correlation coefficients for γ4-Δ|heading| and γ4-Δforward velocity relationship with z=4.46. Fisher r-to-z transformation indicates significant differences in correlation coefficients for γ4-Δ|heading| and γ4-Δforward velocity relationships across the high and low airflow contexts with z=−1.77 and z=−3.42, respectively. N=22 flies, 52 odor presentations.  Table  2). N=26 flies, 143 odor presentations. (C) Average predicted DAN activity plotted as a function of experimentally determined upwind displacement (left), average |heading| (middle), and average forward velocity (right) for each odor trial under high airflow conditions. Best fit line and Pearson correlation coefficient (r) indicated where relationship is statistically significant (p<.05 with Bonferroni correction, see Supplementary Table  2). N=22 flies, 52 odor presentations. (D) γ4 DAN activity predicted by applying the high airflow filters to low airflow behavioral data, plotted as a function of experimentally determined average |heading| (left) and average forward velocity (right) for each odor trial under low airflow conditions. Best fit line and Pearson correlation coefficient (r) indicated where relationship is statistically significant (p<.01 with Bonferroni correction, see Supplementary Table 2). N=26 flies, 143 odor presentations. (E) γ4 DAN activity predicted by applying the low airflow filters to high airflow behavioral data, plotted as a function of the experimentally-determined average |heading| (left) and average forward velocity (right) for each odor trial under high airflow conditions. Best fit line and Pearson correlation coefficient (r) indicated where relationship is statistically significant (p<.01 with Bonferroni correction, see Supplementary Table 2). N=22 flies, 52 odor presentations. Upwind displacement (left), average |heading| (middle), and average forward velocity (left) of animals prior to (black, starved) and after (maroon, fed) a sucrose meal. Paired two-sided t-test with Bonferroni correction, p<0.05 (*), see Supplementary Table 2. N=10 flies, 102 odor presentations (49 before and 53 after feeding). (C) Average DAN responses to ACV are altered after feeding. Paired two-sided t-test with Bonferroni correction, p<0.05 (*), see Supplementary Table 2, N=10 flies, 102 odor presentations (49 before and 53 after sugar feeding). (D) The relationships between γ DAN activity and behavior in different satiety states. Average z score normalized DAN activity plotted as a function of average |heading| (left), and average forward velocity (right) during odor presentation prior to (black) and after (maroon) feeding. Fisher r-to-z transformation indicates no significant differences in correlation coefficients for γ4-|heading| relationship across starved and fed animals with z=−0.51. Pearson correlation coefficient (r) indicated where relationship is statistically significant (p<0.02 with Bonferroni correction, see Supplementary Table 2). N=10 flies, 49-53 odor presentations.  (A) Schematic model showing how an animal's context, including whether it is walking spontaneously in clean air or engaged in active odor pursuit, the navigational strategy it employs, and its satiety state, shapes the moment-to-moment relationships between DAN activity and different behavioral variables (grey dial), giving rise to the longer timescale relationships in which DAN activity is preferentially tuned to the motor actions that subserve odor pursuit. An animal's context also coordinately influences behavior (thick grey arrows). Acute manipulation of DAN activity alters behavior, highlighting how the mushroom body dopaminergic system is embedded within a larger feedback loop (grey dashed arrow). (B) Schematic depicting how the model in (A) produces the behavior and neural activity we observe in the low (left) and high (right) airflow contexts. Under low airflow conditions (left), the γ4-|heading| relationship is selectively strengthened. When a fly encounters the odor, it reorients and elevated γ4 DAN activity promotes upwind tracking towards the odor source. Conversely, under high airflow conditions (right), the γ4 DAN activity-forward velocity relationship is selectively strengthened. When a fly encounters the odor, increased γ4 DAN activity also promotes upwind tracking towards the odor source despite a fly using different actions for pursuit.