Building an allocentric travelling direction signal via vector computation

Many behavioural tasks require the manipulation of mathematical vectors, but, outside of computational models1–7, it is not known how brains perform vector operations. Here we show how the Drosophila central complex, a region implicated in goal-directed navigation7–10, performs vector arithmetic. First, we describe a neural signal in the fan-shaped body that explicitly tracks the allocentric travelling angle of a fly, that is, the travelling angle in reference to external cues. Past work has identified neurons in Drosophila8,11–13 and mammals14 that track the heading angle of an animal referenced to external cues (for example, head direction cells), but this new signal illuminates how the sense of space is properly updated when travelling and heading angles differ (for example, when walking sideways). We then characterize a neuronal circuit that performs an egocentric-to-allocentric (that is, body-centred to world-centred) coordinate transformation and vector addition to compute the allocentric travelling direction. This circuit operates by mapping two-dimensional vectors onto sinusoidal patterns of activity across distinct neuronal populations, with the amplitude of the sinusoid representing the length of the vector and its phase representing the angle of the vector. The principles of this circuit may generalize to other brains and to domains beyond navigation where vector operations or reference-frame transformations are required. A neural circuit for implementing a coordinate transformation and 2D vector computation is described in Drosophila.


Beyond heading in the central complex
The Drosophila central complex includes the ellipsoid body, the protocerebral bridge and the fan-shaped body (Fig. 1a, b). Single EPG neurons have a mixed, input-output, 'dendritic' terminal in one wedge of the ellipsoid body and an 'axonal' terminal in one glomerulus of the protocerebral bridge 20,21 (Fig. 1b, two blue cells). In both walking 8,11,12 and flying 10,22 flies, the full population of EPG cells expresses a bump of calcium activity in the ellipsoid body, and copies of this bump in the left and right bridge. These three signals shift in concert along these structures, tracking the angular heading of the fly referenced to external cues 8,11,12 .
EPG cells represent one of a few dozen sets of columnar neurons in the central complex. Each columnar cell class tiles the ellipsoid body, the protocerebral bridge and/or the fan-shaped body. Individual columnar cells or neurite fields can be assigned an angular label between 0° and 360° based on their anatomical location 20,21 , with neighbouring neurites mapping to neighbouring angles. hDeltaB (h∆B) cells are a columnar class whose constituent cells have a 'dendritic' arbor in layer 3 of one fan-shaped body column and a mixed, input-output, 'axonal' arbor in layers 3, 4 and 5 of another column offset by half the width of the fan-shaped body 20 (Fig. 1b, two red cells). We created a split-Gal4 driver line for h∆B cells (Extended Data Fig. 1a-d) and a UAS-sytGCaMP7f responder line in which GCaMP7f is fused to the C terminus of synaptotagmin to bias GCaMP7f to presynaptic compartments 23 (Extended Data Fig. 1e, f). Imaging sytGCaMP7f fluorescence in h∆B cells of both walking (Extended Data Fig. 1n) and flying (see below) flies revealed a bump of activity that moves left-right along the fan-shaped body in coordination with the movements of the EPG bump around the ellipsoid body. Critically, however, the relative position of the h∆B and EPG bumps were often offset (Extended Data Fig. 1n), suggesting that the position of the h∆B bump might signal the travelling, rather than the heading, angle of the fly.

Computing the travelling angle
Next, we wanted to determine how the h∆B signal is built. As we show and consistent with past work in bees 7 , there exist sets of neurons that provide four motion-related inputs to the central complex. These inputs-L 1 , L 2 , L 3 and L 4 -represent the projections of the travelling vector of the fly (determined, for example, by optic flow) onto axes oriented ±45° (forward-right and forward-left) and ±135° (backward-right and backward-left) relative to the head of the fly 7 (Fig. 2a). The egocentric travelling direction of the fly can be computed by adding the four vectors defined by these projection lengths and angles. To turn the egocentric into an allocentric travelling direction, a coordinate transformation must be performed, and, as we also demonstrate, this is done by referencing the four projection or basis vectors to the allocentric heading, H, of the fly before taking the vector sum (Fig. 2b, right). The fly then computes its allocentric travelling direction by adding these four allocentric projection vectors with lengths L [1][2][3][4]

and angles H ± 45° and H ± 135°.
This vector sum can be performed by representing 2D vectors as sinusoids-a phasor representation-where the amplitudes and phases of the sinusoids match the lengths and angles, respectively, of the corresponding vectors. In such a representation, vectors are added by simply summing their corresponding sinusoids (Fig. 2c). Theoretical models using phasors have been proposed 2 , including for the fan-shaped body 7 , but here we provide a comprehensive experimental demonstration of their operation. Connectome-inspired conceptual models in Drosophila (conducted in parallel to our work) have also proposed how phasors could compute the travelling direction and speed of a fly 28 .

PFN d and PFN v cells encode vectors
The phasor model requires neuronal populations with sinusoidal activity patterns whose phases and amplitudes match the allocentric    (Fig. 2c). The sinusoidal shape of PFN bumps in the bridge may originate from the spatially sinusoidal dendritic density in a group of bridge interneurons called Delta7 (∆7) cells 21 , which are interposed between EPG cells and many downstream bridge cells, including PFN cells (Extended Data Fig. 3, Supplementary Text). The four, sinusoidal, PFN bumps in the bridge are poised to represent the four allocentric projection vectors from Fig. 2a, b, except that their phases are not offset by ±45° and ±135° relative to the EPG heading angle, H. Although PFN and EPG bumps share a common phase in the bridge, the projection anatomy of PFN cells from the bridge to the fan-shaped body provides a path for the PFN bumps to acquire ±45° and ±135° offsets from H. Corresponding PFN v and PFN d cells in the left and right bridge send projections to the fan-shaped body that are offset from each other by approximately ±1/8 of the extent of the fan-shaped body 21 (Fig. 3a,  b), equivalent to a ±45° angular offset. PFN d cells synapse onto both the axonal and the dendritic regions of the h∆B cells, but the input to the axonal region is anatomically dominant 20 (Fig. 3f, g). Assuming that the axonal input is thereby physiologically dominant, PFN d cells can promote h∆B axonal output at fan-shaped body locations that are offset by ±45° relative to the EPG heading signal in the bridge. PFN v cells project to the fan-shaped body with the same ±45° angular offset as PFN d cells, but PFN v cells target the h∆B dendrites, not axons, nearly exclusively 20 ( Fig. 3h, i). As described earlier, the axon terminal region of each h∆B cell is offset from its dendrites by half the width of the fan-shaped body, equivalent to an angular displacement of approximately 180° (Fig. 3f-i). The result of these two sets of shifts is that the PFN v cells in the left and right bridge promote h∆B axonal activity shifted by approximately ±135° relative to their common phase in the bridge. Thus, the anatomy suggests that the four PFN sinusoids in the bridge are transferred to the fan-shaped body with peaks at H ± 45° and H ± 135°, matching the angles of the allocentric projection vectors (Fig. 2). Furthermore, these sinusoids appear to be summed at the level of the h∆B axons.
To complete the phasor representation, the amplitudes of the PFN sinusoids should match the expected lengths of the corresponding allocentric projection vectors (L 1-4 in Fig. 2a). We found that the amplitudes of the PFN sinusoidal bumps across the bridge were strongly modulated by the egocentric travelling direction of the fly, that is, by the direction of optic flow. Specifically, the amplitude of each PFN sinusoid matched the projection of the inferred travelling direction of the fly (from optic flow) onto the four projection axes defined in Fig. 2b and

Model-data comparison
The phasor model predicts that the allocentric travelling direction can be determined by summing the four PFN sinusoids, because this is equivalent to summing the corresponding allocentric projection vectors ( Fig. 4a-d, Supplementary Video 1). To test this notion, we modelled the input to h∆B cells as four cosine functions shifted by the appropriate angles, representing the expected activity patterns of PFN cells across the fan-shaped body. We multiplied these cosines by the experimentally determined amplitudes measured at different angles of optic flow ( Fig. 3j-o) and summed the four amplitude-modulated and shifted sinusoids. The predicted travelling angle calculated in this manner is in excellent agreement with the angular location of the h∆B bump, measured experimentally (Fig. 4e, red circles). This prediction involves no free parameters, but it relies on an assumption that all four PFN types contribute equally to the total h∆B input. We can relax this assumption by adding the four sinusoids weighted by the average number of synapses from each PFN type onto the h∆B cells 20 (Methods). We can also extract the angles by which the PFN sinusoids are anatomically shifted between the bridge and the fan-shaped body from the hemibrain connectome 20 (Extended Data Figs. 5, 6), rather than using exactly ±45° and ±135°. The predicted bump location again agrees well with the measured position of the h∆B bump (Fig. 4e, green diamonds) (see Supplementary Text for more details).

Perturbations support the vector model
To test the vector model, we manipulated EPG, PFN d and PFN v activity while measuring the effect on the estimate of the travelling direction of the fly. For technical reasons, in these experiments, we imaged the bump position of PFR cells, rather than h∆B cells, in the fan-shaped body; PFR cells are a columnar cell class whose numerically dominant monosynaptic input is from h∆B cells 20  direction of the fly in flight (Extended Data Fig. 7a-e, Supplementary Video 2) and walking (Extended Data Fig. 7f-o), arguing that the PFR bump can serve as a proxy for the h∆B signal under our experimental conditions. We note that there were consistent, subtle differences between the h∆B and PFR signals (and PFR cells receive many more inputs than just from h∆B cells), implying that PFR and h∆B cells track different angular variables, although the PFR phase correlated strongly with the travelling direction of the fly here (see Supplementary Text). First, we inhibited EPG output 9 by expressing shibire ts , which abolishes recycling of synaptic vesicles at high temperatures 29 , in EPG cells. Without EPG input, the PFN d , PFN v , h∆B and PFR bumps should all be untethered from external cues and unable to track the allocentric travelling angle (Fig. 5a). We measured the PFR bump in persistently walking flies where, unlike in flying flies, it was rare to observe large deviations of the h∆B or PFR phase from the angular position of a closed-loop visual cue or the EPG phase (Extended Data Fig. 7f-j). With the EPG cells silenced, we still observed a bump in PFR cells but its phase did not effectively track the angular position of the closed-loop cue ( Fig. 5b-d). Thus, EPG input is indeed necessary for the travelling signal to be yoked to the external world.
Second, we expressed a K + channel, Kir2.1 (ref. 30 ), in PFN v cells, with the aim of tonically inhibiting these cells and thus decreasing the contribution of the backward-facing PFN v sinusoids or vectors to the computation of the travelling direction (Fig. 5e). This perturbation yielded an increase in the phase alignment between the EPG and PFR bumps in tethered, flying flies in the context of no optic flow ( Fig. 5f-h), consistent with our model. Third, we used the two-photon laser to optogenetically activate GtACR1 Clchannels 31,32 in LNO1 cells 33 ). b, When a fly travels backward, both PFN d sinusoids have a small amplitude and both PFN v sinusoids have a large amplitude, leading the sum, that is, the h∆B vector (red), to point backward, or opposite the heading direction. c, When a fly travels to the right, the PFN d sinusoid of the right bridge (PFN dR ) and the PFN v sinusoid of the left bridge (PFN vL ) have a larger amplitude than their counterparts on the opposite side of the bridge, leading the sum, that is, the h∆B vector (red), to point rightward. d, Same as panel a-a fly moving forward-but after the fly has turned clockwise by 90°. This turn rotates all the vectors (that is, the reference frame) by 90° inside the brain. e, Data from Fig. 1h (black bars) and model (diamonds and circles) (see main text). The grey, dashed unity line indicates a match between the optic flow direction and the EPG-h∆B phase.

Article
probably inhibitory (Extended Data Fig. 4), inputs to PFN v cells in the noduli 20 . This perturbation should disinhibit the PFN v cells, increasing the amplitudes of their sinusoids, opposite to the previous perturbation (Fig. 5i). This manipulation drove the PFR bump to be approximately 180° offset from the EPG bump ( Fig. 5j-l), consistent with our model.
Last, we silenced PFN d cells by perturbing one of their strongest inputs: the SpsP cells. There are two SpsP cells per side, each innervating all of the ipsilateral PFN d cells, and the vast majority of SpsP output synapses (more than 80%) target PFN d cells 20 . Because the tuning of SpsP cells to translational optic flow is opposite that of the PFN d cells, suggesting inhibition (Extended Data Fig. 4d-f), we optogenetically activated SpsP cells (with csChrimson 34 ) to reduce the amplitude of the front-facing PFN d sinusoids or vectors. This perturbation drove the PFR bump to be offset by 180°, on average, from the EPG bump ( Fig. 5m-p), consistent with this manipulation effectively shortening the two front-facing vectors (Fig. 5m).

Tuning for speed
If the h∆B or PFR bumps were to accurately track the travelling vector (angle + speed) of the fly, rather than just the travelling direction, we would expect the amplitude of their sinusoidal activity profiles to scale with speed (Extended Data Figs. 7,8). Indeed, both the PFR cells and the h∆B cells showed a measurable increase in bump amplitude with faster speeds of optic flow, but this modulation was focused to frontal-travel directions (Extended Data Fig. 8f-i, v-x). Different speed modulation across different travel directions complicates the interpretation of h∆B cells as encoding a full travelling vector, but non-uniform speed tuning across travelling directions could be corrected with additional modulation between the h∆B cells and putative downstream path integrators.

Discussion
Whether mammalian brains have neurons that are tuned to the allocentric travelling direction of an animal as in Drosophila is still unknown. Although a defined population of neurons tuned to travelling direction has yet to be highlighted in mammals 35,36 , such cells could have been missed because their activity would loosely resemble that of the head-direction cells outside a task in which the animal is required to sidestep or walk backwards.   Neurons are often modelled as summing their synaptic inputs, but the heading inputs that PFN cells receive from the EPG system appear to be multiplied by the self-motion (for example, optic flow) input, resulting in an amplitude or gain modulation. Multiplicative or gain-modulated responses appear in classic computational models for how neurons in area 7a of the primate parietal cortex might implement a coordinate transformation 1,4,5 , alongside similar proposals in mammalian navigation 37,38 . The Drosophila circuit described here strongly resembles aspects of the classic models of the parietal cortex (Extended Data Fig. 9). Units that multiply their inputs are also at the core of the 'attention' mechanism used, for example, in machine-based language processing 39 . Our experimental evidence for input multiplication in a biological network may indicate that real neural circuits have greater potential for computation than is generally appreciated.
We describe a travelling direction signal and how it is built; related results and conclusions appear in a parallel study 40 . The mechanisms that we describe for calculating the travelling direction are robust to left-right rotations of the head (Extended Data Fig. 10, Supplementary Text) and to the possibility of the allocentric projection vectors being non-orthogonal (Extended Data Figs. 4-6, Supplementary Text). It is possible that the travelling signal of h∆B cells is compared with a goal-travelling direction to drive turns that keep a fly along a desired trajectory 9,10 . Augmented with an appropriate speed signal (or if the fly generally travels forward relative to its body), the h∆B signal could also be integrated over time to form a spatial-vector memory via path integration 7,28 (see Supplementary Text). There are hundreds more PFN cells beyond the 40 PFN d and 20 PFN v cells studied here 20 , and thus the central complex could readily convert other angular variables from egocentric to allocentric coordinates via the algorithm described here. Because many sensory, motor and cognitive processes can be formalized in the language of linear algebra and vector spaces, defining a neuronal circuit for vector computation may open the door to better understanding of several previously enigmatic circuits and neuronal activity patterns across multiple nervous systems.

Online content
Any methods, additional references, Nature Research reporting summaries, source data, extended data, supplementary information, acknowledgements, peer review information; details of author contributions and competing interests; and statements of data and code availability are available at https://doi.org/10.1038/s41586-021-04067-0.

Fly husbandry
Flies were raised at 25 °C with a 12-h light and 12-h dark cycle. In all experiments, we studied female Drosophila melanogaster that were 2-6 days old. Flies were randomly selected for all of experiments. We excluded flies that appeared unhealthy at the time of tethering as well as flies that did not fly longer than 20 s in flight experiments. This meant excluding fewer than 5% of flies for most genotypes. However, in the perturbational experiments shown in Fig. 5e-p, many flies flew poorly-perhaps because these genotypes all expressed five to six transgenes that can affect overall health and flight vigour-and we had to exclude approximately 70% of flies due to poor tethered flight behaviour (that is, would not maintain continuous flight for more than 5-s bouts). The 30% of flies tested in these genotypes flew in bouts that ranged from 20 s to many minutes, allowing us to make the necessary EPG-PFR signal comparisons (discussed below). Flies in optogenetic experiments were shielded from green and red light during rearing by placing the fly vials in a box with blue gel filters (Tokyo Blue, Rosco) on the walls. After eclosion, 2 days or more before experiments, we transferred these flies to vials with food that contained 400 µM all-trans-retinal.

Cell-type acronyms and naming conventions
Each cell type is described in the order of 'names in this paper (in hemibrain v1.1 if different)', 'names used in ref. 33 ', 'description of acronym', 'references in which cell type is studied or defined' and 'total cell number (in hemibrain v1.1)', separated by em dashes.

Distinguishing PFR subtypes in Gal4 lines
The hemibrain connectome 20 defines two subtypes of PFR cells 21 : PFR_a cells and PFR_b cells, which differ in the details of their projections and connectivity in the fan-shaped body. Both PFR_a cells and PFR_b cells are columnar cells that project from the protocerebral bridge to the fan-shaped body. On the basis of the connectome 20 , PFR_a cells and PFR_b cells that innervate four of the bridge glomeruli project to the fan-shaped body in the same way, and PFR_a cells and PFR_b cells that innervate 12 other bridge glomeruli project to the fan-shaped body in a slightly different way. We used this fact to interrogate the MultiColor Flip-Out (MCFO) single-cell anatomical dataset 44 from the FlyLight Generation 1 MCFO Collection to quantify the ratio of each PFR subtype in the two Gal4 driver lines that we used for targeting transgenes to PFR cells. For the driver line 37G12, we found that 10 out of 13 cells in the MCFO data had an innervation pattern that is consistent with PFR_a but not PFR_b, and the innervation patterns of the other three cells were indistinguishable between the two subtypes. For the driver line VT005534, we found that two out of three cells in the MCFO data were consistent with them being PFR_a cells and not PFR_b cells, and the third cell had an anatomy that did not allow us to distinguish between subtypes. We observed no cell whose projection pattern matched PFR_b but not PFR_a. These results argue that the majority of the PFR cells targeted by the two Gal4 driver lines that we used are PFR_a cells.

Fly preparation and setup
As described previously, we glued flies to a custom stage for imaging during flight 24 and to a slightly different custom stage-which allows for more emission light to be collected by the objective-for imaging during walking 11 . Dissection and imaging protocols followed previous studies 11 . For tethered flight experiments, each fly was illuminated with 850-nm LEDs with two fibre optics from behind 24 . A Prosilica GE680 camera attached to a fixed-focus Infinistix lens (94-mm working distance, ×1.0 magnification; Infinity) imaged the wing-stroke envelope of a fly at 80-100 Hz. The lens also held an OD4 875-nm shortpass filter (Edmund Optics) to block the two-photon excitation laser (925 nm). This camera was connected to a computer that tracked the left and right wing beat amplitude (L-R WBA) of the fly with custom software developed by A. Straw (https://github.com/motmot/strokelitude) 24 . Two analogue voltages were output in real time by this software and the difference between the L-R WBA was used to control the angular position of the bright dot on the LED arena in the closed-loop experiments (described below). For tethered walking experiments, we followed protocols previously described 11 .

LED arena and visual stimuli
We used a cylindrical LED arena display system 45 with blue (465 nm) LEDs (BM-10B88MD, Betlux Electronics). The arena was 81° high and wrapped around 270° of the azimuth, with each pixel subtending approximately 1.875°. To minimize blue light from the LEDs inducing noise in the photomultiplier tubes of the microscope, we reduced the LED intensities, over most of the arena, by covering the LEDs with five sheets of blue gel (Tokyo Blue, Rosco). Over the 16 pixels at the very top of the arena (top approximately 30°), we only placed two gel sheets, so that the closed-loop dot at the top of the arena was brighter than the optic flow dots at the bottom, which may have helped to promote that the fly interpret the bright blue dot as a celestial cue (like the sun) and the optic flow at the bottom as ground or side motion. During flight experiments, we held the arena in an approximately 66° pitched-back position, so that the vertical and horizontal axes of the LED matched the major ommatidial axes of the eye 27 . During walking experiments, we typically presented a tall vertical bar-rather than a small dot-in closed loop and we tilted the arena by only approximately 30° because the ball physically occludes the ventral visual field and a shallower arena tilt made it more likely that the fly could see the closed-loop stimulus over all 270° of the azimuthal positions that it could take.
We adapted past approaches for generating optic flow (starfield) stimuli 26,27 . In brief, we populated a virtual 3D world with 45, randomly positioned spheres (2.3 cm in diameter) per cubic metre. The spheres were bright on a dark background. We only rendered spheres that were within 2 m of the fly because spheres further away contributed only minimally to the observed motion and, if rendered, would have overpopulated the visual field with bright pixels. We then calculated the angular projection of each sphere onto the head of the fly and used this projection to determine the pattern to display on the LED arena on each frame. To prevent the size of each sphere from being infinitely large as it approached the fly, we limited each diameter of the sphere on the arena to be no larger than 7. 7 and 8 where we tested multiple speeds as indicated (ranging from 8.75 to 70 cm/s). Although we report on the translation speed of the virtual fly in metric units, the optic flow experienced by insects translating at 35 cm/s will vary dramatically depending on the clutter of the local environment. We believe that the optic flow stimuli that we presented in our study are potentially in an ethologically relevant range because (1) our virtual fly translated at speeds that bracket observed flight speeds in natural environments [46][47][48] and (2) cells sensitive to optic flow reported here responded with progressively increasing activity to the presented stimuli/speeds rather than immediately saturating or showing no detectable responses (for example, Extended Data Fig. 8). That said, our stimuli simulated a dense visual environment and it will be important to test our results in the context of reduced visual clutter in future work.
In flight experiments with a closed-loop dot (Figs. 1, 3c-e, Extended Data Figs. 1g-m, 2, 3e, h, 4b-f, i, 7b-e), the dot subtended 3.75° by 3.75° and was located approximately 34° above the midline of the arena. We used the difference of the L-R WBAs to control the azimuthal velocity of the bright dot on the LED arena. That is, when the R WBA is smaller than the amplitude WBA (indicating that the fly is attempting to turn to the right), the dot rotated to the left, and vice versa. The negative-feedback closed-loop gain was set to 7.3° per second per degree change in L-R WBA. In initial experiments, we set the gain to 5.5° per second and we have lumped those data in with the data at 7.3° per second in Fig. 1f and Extended Data Fig. 1g-m because we did not observe obvious differences in any of our analyses. In closed-loop walking experiments with a visual stimulus ( Fig. 5b-d, Extended Data Fig. 7f-o), the bright bar was 11.25° wide and spanned the entire height of the arena. We directly linked the azimuthal position of the bright bar on the LED arena to the azimuthal position of the ball under the fly using Fictrac 11,49 , as previously described. This closed loop set up mimics the visual experience of a fly with a bright cue at visual infinity, like the sun. We did not provide translational stimuli in closed loop in this paper.

Calcium imaging
We used a two-photon microscope with a moveable objective (Ultima IV, Bruker). The two-photon laser (Chameleon Ultra II Ti:Sapphire, Coherent) was tuned to 1,000-1,010 nm for simultaneous imaging of GCaMP6m and jRGECO1a (Fig. 3c-e, Extended Data Fig. 2), and was otherwise tuned to 925 nm in all of the other imaging experiments. We used a ×40/0.8 NA objective (Olympus) or ×16/0.8 NA objective (Nikon) for all imaging experiments. The laser intensity at the back aperture was 30-40 mW for walking experiments and 40-80 mW for flight experiments. Because of light loss through the objective and the fact that the platform to which the fly was attached blocks roughly half the light from reaching the fly, we estimated an illumination intensity, at the fly, of approximately 16-32 mW for flight experiments. In walking experiments, the platform to which we attached the fly blocks less light and we expected an illumination intensity, at the fly, of approximately 24-32 mW. A 575-nm dichroic split the emission light. A 490-560-nm bandpass filter (Chroma) was used for the green channel PMT and a 590-650-nm bandpass filter (Chroma) was used for the red channel PMT. We recorded all imaging data using three to five z-slices, with a Piezo objective mover (Bruker Ext. Range Piezo), at a volumetric rate of 4-10 Hz. We perfused the brain with extracellular saline composed of (in mM) 103 NaCl, 3 KCl, 5 N-Tris(hydroxymethyl) methyl-2-aminoethanesulfonic acid (TES), 10 trehalose, 10 glucose, 2 sucrose, 26 NaHCO 3 , 1 NaH 2 PO 4 , 1.5 CaCl 2 , 4 MgCl 2 , and bubbled with 95% O 2 /5% CO 2 . The saline had a pH of approximately 7.3 and an osmolarity of approximately 280 mOsm. We controlled the temperature of the bath by flowing the saline through a Peltier device and measured the temperature of the bath with a thermistor (CL-100, Warner Instruments).

Optogenetic stimulation
In the optogenetic experiments in Fig. 5j-l, we used the two-photon laser tuned to 925 nm to excite GtACR1, with the same scanning light being used to excite GCaMP. To excite CsChrimson in the optogenetic experiments ( Fig. 5n-p, Extended Data Fig. 7k-o), we focused a 617-nm laser (M617F2, Thorlabs) on to the front, middle of the head of the fly with a custom lens set (M15L01 and MAP10100100-A, Thorlabs). We placed two bandpass filters (et620/60 m, Chroma) in the two-photon emission path of the microscope to minimize any of the optogenetic light being measured by the photomultiplier tubes. In flight experiments ( Fig. 5n-p), we used pulse-width modulation at 490 Hz (Arduino Mega board) with a duty cycle of 0.8 to change the intensity of the 617-nm laser. We measured the intensity of the laser at the head of the fly to be 20.8 µW. In the experiments in which we triggered backwards walking via activation of csChrimson (Extended Data Fig. 7k-o) in lobula columnar neurons, the duty cycle of the red light was 0.7 and the effective light intensity was 18.2 µW.
In Fig. 5j-l, for two main reasons, rather than directly exciting PFN v cells, we optogenetically inhibited the LNO1 inputs to PFN v cells. First, [Ca 2+ ] imaging revealed opposite responses to our optic flow stimuli in the two cell types (Extended Data Fig. 4a-c), arguing for a sign-inverting synapse between them. Second, we tried optogenetically activating the PFN v cells directly (data not shown), which yielded more variable movements of the PFR bump. We believe that stimulating LNO1 cells yielded more consistent effects on the PFR bump because there are only two LNO1 cells per side and they synapse uniformly on all PFN v cells within a tiny neuropil (the second layer of the nodulus) on their side 20 . The majority of the synaptic output of LNO1 cells goes to PFN v cells in the nodulus, with each LNO1 cell on average forming approximately 655 synapses on PFN v cells 20 . Stimulating GtACR1 in a small volume probably made homogeneous activation of the PFN v population more feasible.
Similarly, in Fig. 5m-p, rather than directly silencing PFN d cells, we optogenetically excited SpsP cells to inhibit PFN d cells. Exciting SpsP cells was likely to be an effective way to inhibit PFN d cells for two reasons. First, [Ca 2+ ] imaging revealed sign-inverted responses to our optic flow stimuli in the two cell types (Extended Data Fig. 4d-h), arguing for sign-inverting synapses existing between them. Second, approximately 80% of SpsP synapses are to PFN d cells in the bridge, with each SpsP cell forming approximately 563 synapses on PFN d cells 20 , on average. In addition, stimulating CsChrimson in four copies of SpsP cells probably makes homogeneous inhibition of the PFN d population more feasible than via direct optogenetic inhibition of the PFN d cells (where some PFN d cells might be more inhibited than others depending on the expression level of the opsin and the light delivery details).

Data analysis
Data acquisition and alignment. All data were digitized by a Digidata 1440 (Molecular Devices) at 10 kHz, except for the two-photon images, which were acquired using PrairieView (Bruker) at varying frequencies and saved as tiff files for later analysis. We used the frame triggers associated with our imaging frames (from Prairie View), recorded on Digidata 1440, to carefully align behavioural measurements with [Ca 2+ ] imaging measurements.
Experimental structure. For Fig. 1d-f and Extended Data Fig. 1g-m, each fly performed tethered flight while in control of a bright dot in closed loop. Each recording was split into two segments, where we first presented a static starfield for 90 s, followed by progressive optic flow for 90 s.
For Fig. 1g-i, we presented each fly with a closed-loop dot throughout. We presented four blocks of six translational optic flow stimuli (six translational plus two rotational) per block, shown in a pseudorandom order. Each 4-s optic flow stimulus was preceded and followed by 4 s of optic flow that mimics forward travel, which ensured that the EPG and h∆B (or PFR) bumps were aligned-for a stable 'baseline'-before and after each tested optic flow stimulus. We presented 4 s of a static starfield between each repetition of the above three patterns. We used the same protocol for Extended Data Fig. 7b-e (35 cm/s column), but we presented two yaw-rotation optic flow stimuli to each block, whose data we did not analyse for this paper.
For For Fig. 5b-d, each fly was presented with a tall bright bar in a closed loop throughout. EPG > Shibire ts flies experienced both 25 °C and 34 °C trials in these experiments and we waited approximately 5 min after the bath temperature reached 34 °C before imaging in the EPG-silenced condition so as to increase the likelihood of thorough vesicle depletion. Recording durations ranged from 6 to 8 min.
For Fig. 5f-h, j-l, flies performed tethered flight in the context of a dark (unlit) visual display. We recorded data for approximately 1-4 min and if the fly was flying robustly, we collected a second dataset from the same fly.
For Fig. 5n-p, flies performed tethered flight in the context of a dark (unlit) visual display. We recorded data for 2-6 min, and if the fly was flying robustly, we collected a second dataset from the same fly. We presented 12-s red-light pulses to activate csChrimson every roughly 20 s.
For Extended Data Figs. 1e, f, 4b, c, e, f (SpsP rows) and i (PFN v cells in the noduli, SpsP cells and LNO1 cells), we presented each fly with a closed-loop dot throughout. We presented four blocks of eight optic flow stimuli (six translational plus two rotational) per block, shown in a pseudorandom order. Each optic flow stimulus was preceded by 4 s of a static starfield, followed by 4 s of optic flow at different directions, and ending with 4 s of static starfield.
For Extended Data Fig. 1i, j (EPG > GCaMP6m walking data), each fly was walking in the dark for the first 2.5 min of the recording and was presented with a tall bright bar in closed loop for the second 2.5 min of the recording. We recorded data for 5 min, with up to three 5-min datasets collected per fly.
For Extended Data Figs. 1n-p, 4j-q, each fly was walking in the dark. We recorded data for 5-10 min, with up to three 10-min datasets collected per fly.
For Extended Data Fig. 2e, f, we presented each fly with a closed-loop dot throughout. We presented four blocks of three translational optic flow per block, shown in a pseudorandom order. Each stimulus was preceded by 1. For Extended Data Fig. 7f-j, each fly was presented with a tall bright bar in closed loop for the first 5 min of the recording and was walking in the dark for the second 5 min of the recording. We recorded data for 10 min, with up to three 10-min datasets collected per fly.
For Extended Data Fig. 7k-o, each fly was presented with a tall bright bar in closed loop throughout. We recorded data for 7-10 min, with up to three datasets collected per fly. We presented 4-s red-light pulses to activate csChrimson every 1-3 min.
Image registration. Before quantifying fluorescence intensities, imaging frames were registered in Python by translating each frame in the x and y plane to best match the time-averaged frame for each z-plane. Multiple recordings from the same fly were registered to the same time-averaged template if the positional shift between recordings was small.

Defining regions of interest.
To analyse calcium imaging data, we defined regions of interest (ROIs) in Fiji and Python for each glomerulus (protocerebral bridge), wedge (ellipsoid body) or column (fan-shaped body). For the bridge data, we defined ROIs by manually delineating each glomerulus from the registered time-averaged image of each z-plane (Fig. 2, Extended Data Figs. 2, 3, 4e-h PFN d row, 4i PFN d cells and PFN v cells in the bridge, 4j-k, 4n-o, 5, 8a-e, j-m, r-u), as previously described 11 . Because single SpsP neurons innervate the entire left or right side of the protocerebral bridge (Extended Data Fig. 4e, f (SpsP row), p-q), when imaging them, we treated the entire left bridge as one ROI and the entire right bridge as another. When imaging PFN cells or LNO1 cells in the noduli (Extended Data Fig. 4b, c, i, l-m), we treated the entire left nodulus as one ROI and the entire right nodulus as another.
For ellipsoid body imaging (Figs. 1, 5, Extended Data Figs. 1, 7), we defined ROIs by first outlining the region of each z-slice that corresponded to the ellipsoid body. We then radially subdivided the ellipsoid body into 16 equal wedges radiating from a manually defined centre, as previously described 8 . For fan-shaped body imaging (Figs. 1, 5, Extended Data Figs. 1, 7, 8f-i, n-q, v-x), we defined ROIs by first outlining the region in each z-slice that corresponded to the fan-shaped body. We then defined two boundary lines delineating the left and right edges of the fan-shaped body. When these two edge lines were extended down, they met at an intersection point beneath the fan-shaped body. We subdivided the angle generated by thus intersecting the two fan-shaped body edges-which corresponds to the overall angular width of the fan-shape d body region-into 16, equally spaced, angular subdivisions radi ating from the intersection point. We assigned pixels to one of the 16 fan-shaped body columns based on the pixel needing to (1) reside in the overall fan-shaped region and (2) reside in the radiating angular region associated with the column of interest.
Calculating fluorescence intensities. We used ROIs, defined above, as the unit for calculating fluorescent intensities (see above). If pixels from multiple z-planes corresponded to the same ROI (for example, the same column in the fan-shaped body), as defined above, then we grouped pixels from the multiple z-planes together for generating a single fluorescence signal for that ROI. For each ROI, we calculated the mean pixel value at each time point and then used three different methods for normalization. We call the first method ∆F/F 0 (Fig. 3d, e, j-r, Extended Data Figs. 1e, f (phase-nulled bump shape), 3, 4i (PFN d and PFN d cells in the bridge), j, l, n, p, 5,8), where F 0 is the mean of the lowest 5% of raw fluorescence values in a given ROI over time and ∆F is F -F 0 . We call the second method normalized ∆F/F 0 (Figs. 1, 3c, 5, Extended Data Figs. 1e, f (heatmap), g-p, 2, 7), which uses this equation: (F -F 0 )/ (F max -F 0 ), where F 0 was still the mean of the lowest 5% of raw fluorescence values in a given ROI over time and F max was defined as the mean of the top 3% of raw values in a given ROI over time. This metric normalizes the fluorescence intensity of each glomerulus, wedge or column ROI to its own minimum and maximum and makes the assumption that each column, wedge or glomerulus has the same dynamic range as the others in the structure, with intensity differences arising from technical variation in the expression of the indicator or from the number of cells expressing the indicator within a column or wedge. We used this method to estimate the phase of heading or travelling signals where it seemed reasonable to make the above assumption for accurately estimating the phase of a bump in a structure. We call the third method z-score normalized ∆F/F 0 (Extended Data Figs. 4b-h, i (signals in the noduli and SpsP cells), k, m, o, q) where we show how many standard deviations each time point's signal is away from the mean. We calculated the signal as ∆F/F 0 and then we z-normalized the signal. We used this method to estimate the asymmetry of neural responses to optic flow in the bridge or noduli, where it seemed sensible to normalize the baseline asymmetry (when there are no visual stimuli) to zero. Importantly, none of the conclusions presented in this paper rely on the normalization method used for visualizing and analysing the data.

Calculating the phase of bumps and aligning phase across structures.
To calculate the phase of the joint movement of the calcium bumps in the left and right protocerebral bridge, we first converted the raw bridge signal into a 16-18-point vector, with each glomerulus' signal normalized as described above. Then, for each time point, we took a Fourier transform of this vector and used the phase at a period of eight glomeruli to define the phase of the bumps, as previously described 11 . To calculate phase of the EPG bump in the ellipsoid body, we computed the population vector average of the 16-point activity vector, as previously described 8 . To calculate the phase of the h∆B and PFR bumps in the fan-shaped body, we computed the population vector average like in the ellipsoid body, using the following mapping of fan-shaped body columns to ellipsoid body wedges. The leftmost column in the fan-shaped body corresponded to the wedge at the very bottom of the ellipsoid body, just to the left of the vertical bisecting line; the rightmost column in the fan-shaped body corresponded to the wedge at the very bottom of the ellipsoid body, just to the right of the vertical bisecting line. We then numbered the fan-shaped body columns 1 to 16, from left to right, just like we numbered the ellipsoid body wedges clockwise around that structure 8 . This mapping is meant to match the expected mapping of signals from anatomy, described previously 21 , and as further discussed immediately below.
To align the EPG phase in the ellipsoid body with the h∆B phase or the PFR phase in the fan-shaped body, we used the approach just described (Figs. 1, 5, Extended Data Figs. 1, 7). To align the EPG and PFN d and PFN v phase signals in the protocerebral bridge ( Fig. 3c-e, Extended Data  Figs. 2, 3), we used the fact that these neuron populations commonly innervate 14 of 18 glomeruli in the protocerebral bridge, which allows for an obvious alignment anchor, as done previously 11 . To calculate the offset between the phase of neural bumps and the angular position of a cue (bright bar or dot) rotating in angular closed loop on our visual display, we computed the circular mean of the difference between the neural phase and the cue angle during the time points when the cue was visible to the fly. We used this difference to provide a constant (non-time-varying) offset to the neural phase signal such that the difference between the phase and cue angles was minimized across the whole measurement window of relevance. This approach is needed because of the past finding that phase signals in the central complex have variable offset angles to the angular position of cues in the external world across flies (and sometimes across time within a fly) 8,11 . To calculate the phase offset between neural bump position and visual cue angle, we did not analyse time points when the fly was not flying in all of our flight experiments (Figs. 1-5, Extended Data Figs. 1-5, 7, 8 except panels 8h, p, x) nor did we analyse time points when the fly was standing in walking experiments (Fig. 5c, d, Extended Data Fig. 1o, p). For a fly to be detected as standing, the forward speed needed to be less than 2 mm/s, the sideslip speed less than 2 mm/s, and the turning speed less than 30°/s. We also excluded the first 10 s of each period in Fig. 1f to minimize the impact of a changing visual stimulus on the offset estimate.
Comparing data acquired at different sampling rates or with a time lag. When comparing two-photon imaging data (collected at approximately 5-10 Hz) and behavioural (flight turns or ball walking) data (collected at 50-100 Hz) for the same fly, we subsampled the behavioural data to the imaging frame rate by computing the mean of behavioural signals during the time window in which each imaging data point was collected (Figs. 1f, 5b-d, Extended Data Figs. 1g-j, 4j-q, 7m-o), as previously described 11 .
Although we collected both the EPG signal in the ellipsoid body and the h∆B (or PFR) signal in the fan-shaped body at the same frame rate, the precise time points in which these two signals were sampled were slightly different because the piezo drive that moves the objective had to travel from the higher fan-shaped body z-levels to the lower ellipsoid body z-levels. Importantly, each z-slice in a such volumetric time series was associated with its own trigger time and we could use this fact to more accurately align the fan-shaped body and ellipsoid body phase signals to each other. Specifically, when comparing EPG and h∆B (or PFR) bump positions over time, we first created a common 10 Hz (100-ms interval) time base. We then assigned phase estimates from the two structures or cell types to this common time base by linearly interpolating each time series (using its specific z-slice triggers), and we used these interpolated time points, on the common time base, for calculating the phase differences between EPG and h∆B cells, or EPG and PFR cells (Fig. 1g-i, Extended Data Figs. 1p, 7c-e, m-o). For the histograms and other analyses in Figs. 1g, 5g, h, k, l, o, p, Extended Data Figs. 1l, m, n-p, 7g-j, we simply subtracted the EPG phase and the h∆B phase or the PFR phase measured in each frame, without temporal interpolation. None of our conclusions are altered if we change the interpolation interval or do not interpolate. Fig. 1n-p, we detected time segments where flies walked in three different, broad travelling directions (forward, rightward and leftward). Forward walking segments were defined by the flies having a forward velocity between +3 and +10 mm/s and a sideslip velocity between −2 and +2 mm/s. Sideward walking segments were defined by the flies having a forward walking velocity between +2 and -10 mm/s and a sideslip velocity between +3 and +10 mm/s to the relevant side.

Sideslip and backward walking analysis. In Extended Data
We expressed CsChrimson in a group of lobula columnar neurons, LC16, whose activation with red light has been shown to induce flies to walk backward (Extended Data Fig. 7k-o, more details in 'Optogenetic stimulation') 50 . Consistent with previous studies in free walking flies 50 , we also observed variable backward walking behaviours mixed with sideward walking and turning in our tethered preparation. To test whether the PFR phase separates from the EPG phase when a fly walks backward, we analysed optogenetic activation trials based on the following three criteria being met. First, the backward walking speed needed to be larger than 6 mm/s. Second, the duration of continuous backward walking (defined by backward walking speed being above 0.5 mm/s) needed to be longer than 1 s. Third, during the backward walking period, the sideward walking velocity needed to be biased towards one direction; the fraction of optogenetic trials in which the sideward velocity was clearly either positive or negative exceeded 80%. We included this third criterion so that we could split optogenetic trials into those where the PFR phase should have moved to the right and those in which it should have moved to the left in the fan-shaped body (Extended Data Fig. 7k-o).
Phase nulling. To compute the time-averaged shape of the bump in PFN and EPG cells, we followed previous methods 11 . In brief, we (1) computationally rotated each frame by the estimated phase of the bump on that frame, such that the bump peak was at the same location on all frames, and then (2) averaged together the signal from all frames to get an averaged bump, whose shape we could analyse via fits to sinusoids (Fig. 3, Extended Data Figs. 3, 5, 8a). In this phase nulling process, we first interpolated the GCaMP signal from each frame to 1/10 of a glomerulus, column, or wedge with a cubic spline. We then shifted this interpolated signal by the phase angle calculated for that frame. In both the ellipsoid body and the fan-shaped body (Extended Data Fig. 1e, f), we performed a circular shift, such the signals wrapped around the edges of the fan-shaped body. In the protocerebral bridge, we performed this circular shift independently for the left and right bridge. For the protocerebral bridge data, we subsampled the spatially interpolated GCaMP signal back to a 16-glomerulus vector before plotting the data (Fig. 3, Extended Data Figs. 3, 5, 8a) so as to more accurately reflect, in our averaged signals, what the actual signal in the brain looked like.
To compute the cell-averaged shape of the EPG-to-Δ7 synapse number across the glomeruli of the bridge in Extended Data Fig. 3, we followed a similar protocol to the one described above for the imaging data. We treated the EPG-to-Δ7 synapse number profile of each ∆7 cell as the equivalent of one imaging frame, with the synapse number of each glomerulus the equivalent of the fluorescence intensity of a single glomerulus from that frame. The rest of the steps-calculating phase, interpolation, shifting, averaging and subsampling-were the same as those described above.

Statistics and reproducibility
We performed unpaired two-tailed t-tests (Fig. 5d, h, Extended Data Fig. 1h, i, l, m, 7d, j) and Watson-Williams multi-sample tests (two-tailed; Fig. 5l, p, Extended Data Fig. 1p, 2g, 7i, o). See the related figures and captions for details. All experiments discussed in the paper were conducted once at the conditions shown; no experimental replicate was excluded. For most experiments, data across multiple days were collected and the data across days were consistent. In immunohistochemistry plots (Extended Data Fig. 1a-c), two brains were imaged, but only one is shown. Both imaged brains showed the same qualitative pattern of staining. Note also the fly exclusion criteria described in Fly Husbandry.
In Fig. 5d, the P values are 2.7 × 10 −5 , 6.2 × 10 −6 and 1.5 × 10 −4 comparing the fourth column (from left) with the first, second and third columns, respectively. The P values are 1.6 × 10 −6 , 2.4 × 10 −7 and 1.3 × 10 −5 comparing the seventh column (from left) with the first, fifth and sixth columns, respectively. In Fig. 5h, the P values are 1.1 × 10 −7 and 9.9 × 10 −8 comparing the third column (from left) with the first and second columns, respectively. The P values are 1.5 × 10 −5 and 6.9 × 10 −6 comparing the fifth column (from left) with the first and fourth columns, respectively. In Fig. 5l, the P values are 7.0 × 10 −8 and 2.8 × 10 −8 comparing the third column (from left) with the first and second columns, respectively. The P values are 4.0 × 10 −4 and 2.5 × 10 −4 comparing the fifth column (from left) with the first and fourth columns, respectively. In Fig. 5p, the P values are 2.0 × 10 −6 and 6.6 × 10 −4 comparing the third column (from left) with the first and second columns, respectively.
For Fig. 1i, to test whether the h∆B bump tracks the allocentric travelling direction (data fall on the diagonal line) better than tracking the allocentric heading direction (data fall on the horizonal line at zero), we calculated the mean circular squared difference between the data and the diagonal line versus the data and the horizontal line at zero. The result was 106 deg 2 for the diagonal line and 11,807 deg 2 for the horizontal line at zero, demonstrating that the h∆B bump tracks the allocentric travelling direction of the fly better than the allocentric heading direction.
All of the sinusoidal fits throughout the paper had three free parameters: baseline, amplitude and phase.
For fitting sinusoids to the activity bumps shown in Fig. 3d, e and Extended Data Fig. 3h, the left-bridge and right-bridge data were fit to sinusoids separately because their amplitudes could vary independently. The period of each sinusoidal fit was eight glomeruli, with the first and ninth glomeruli set to the same value (Extended Data Fig. 5). Reduced χ 2 tests were performed to test goodness of the fit. χ 2 values per degrees of freedom ranged between 0.17 and 0.83 for all PFN fits, between 0.05 and 0.13 for all PFR fits, and between 0.24 and 1.91 for all EPG fits. The corresponding P values ranged between 0.53 and 0.98 for all PFN fits, between 0.98 and 0.99 for all PFR fits, and between 0.08 and 0.95 for all EPG fits. These fit results mean that we cannot reject the hypothesis that the data are from an underlying sinusoidal distribution of activity.
For fitting sinusoids to the tuning curves in Fig. 3k, l, n, o, q, r, χ 2 per degrees of freedom were between 0.15 to 1.20 giving P values between 0.31 and 0.93. Again, the hypothesis that these data are generated by a sinusoidal distribution cannot be rejected. Although the EPG amplitude tuning curves to optic flow (Fig. 3q, r) fit well to sinusoids, the amplitude parameters of the fits were very small compared with the baseline parameters. For Fig. 3q, the amplitude and baseline parameters were 0.040 and 0.73 (unit: ∆F/F 0 ), respectively. For Fig. 3r, the amplitude and baseline parameters were 0.024 and 0.76 (unit: ∆F/F 0 ), respectively. By contrast, for the PFN signals in Fig. 3k, l, n, o, the amplitude parameters were 0.69, 0.69, 0.30 and 0.33 and the baseline parameters were 0.90, 0.90, 0.43 and 0.42, respectively. We thus concluded that the PFN v and PFN d sinusoidal activity patterns in the bridge are strongly modulated by optic flow, whereas the EPG activity pattern is very weakly modulated by optic flow.
The data points in Fig. 3d, e, k, l, n, o, q, r and Extended Data Fig. 3h, were fit to sinusoids using the method of variance-weighted least squares. All other fits to sinusoids used the method of least squares.
For Extended Data Fig. 7d, the null hypothesis is that the PFR bump tracks the allocentric travelling direction (data fall on the diagonal line) equally well than tracking the allocentric heading direction (data fall on the horizonal line at zero). We calculated the mean circular squared difference between the data and the diagonal line versus the data and the horizontal line at zero for the 35 cm/s column. The result is 549 deg 2 for the diagonal line and 7,710 deg 2 for the horizontal line at zero. Thus, the PFR bump tracks the allocentric travelling direction of the fly better than the allocentric heading direction in these experiments.

Modelling
We constructed a model, based heavily on the data, to test whether the observed PFN activity profiles could provide summed input to h∆B neurons that would induce the h∆B bump of activity to indicate the travelling angle of the fly. Neurons in the model are labelled by an angle θ that indicates their position along the fan-shaped body. In reality, this angle takes discrete values corresponding to the columns of the fan-shaped body, but, to simplify the notation, we use a continuous label here. The allocentric heading angle of the fly is denoted by H.
The data argue that the PFN activity profiles in the bridge have a sinusoidal shape (Fig. 3d, e, Extended Data Fig. 3) with phases locked to the phase of the EPG bumps (Extended Data Fig. 2), and that the projections of the PFN cells from the bridge to the fan-shaped body result in anatomically shifted inputs to the h∆B cells (Fig. 3f-i,  Extended Data Fig. 6). The phase of the EPG bump tracks the inverse of the heading angle of the fly, H, meaning that when the fly turns clockwise, for example, the bump rotates counterclockwise (when looking at the ellipsoid body from the rear). (To make things hopefully less confusing with regard to this minus sign, we flipped the orientation of the horizontal axis in some of our figures.) On the basis of these observations, we model the PFN activity profiles in the fan-shaped body as where i = 1, 2, 3, 4 refers to right-bridge PFN d , left-bridge PFN d , right-bridge PFN v and left-bridge PFN v cells, and a i and c i are parameters reflecting amplitude-dependent and amplitude-independent offsets (that is, mean levels) of the sinusoidal activity patterns (Extended Data Fig. 8). A i is the amplitude of the sinusoid for PFN i , which depends on the egocentric travelling angle (that is, simulated optic flow; Fig. 3j-o). The angles ϕ are the shifts in the PFN projections from the bridge to the h∆B cells ( Fig. 3f-i, Extended Data Fig. 6). The total input to the h∆B cells, which we call θ h∆BInput( ), is given by the sum of the PFN activities weighted by factors g i that reflect the strengths of the PFN connections to the h∆B cells: The h∆B bump will appear at the value of θ for which this summed input is maximal, which occurs at The prediction of the model is that this angle should be equal to the negative of the allocentric travelling angle. Many of the parameters of the model do not appear in this expression, and the overall scale of the g i values for the different PFN cells cancels in the above ratio. We obtained the amplitude factors, A i , directly from the data. For this purpose, we could use the amplitudes measured in the protocerebral bridge (Fig. 3j-o) with good results, but we chose instead to use the measurements from the noduli (Extended Data Fig. 4a-h), which is the site of the sensory input that drives the amplitude modulation of the PFN cells. Although the noduli do not have a columnar structure and thus can only provide a measure of mean activity for a given PFN type, we took advantage of the fact that the mean and amplitude of the PFN sinusoids in the bridge show virtually identical modulation (Extended Data Fig. 8) to infer the amplitudes A i . We divided the measured amplitudes by their averages across all the measured simulated motion directions for each PFN type to correct for possible expression and imaging differences.
We set the remaining parameters in the above expression for θ max in two ways (both results are shown in Fig. 4e). First, we assumed that the four values of g were the same, meaning equal weighting of the four PFN types, and we took the angles ϕ to be 45°, −45°, −135° and 135°. This resulted in a 'fit' to the data that involves assumptions, but no free parameters (Fig. 4e, red circles). To avoid these assumptions, we also used values of these two sets of parameters extracted from a connectome-based analysis 20 (Extended Data Fig. 6). On average, right (left) PFN d cells make 257.3 (260.7) synapses onto the 'axonal' region of the h∆B cells and 164.4 (162.7) onto the 'dendritic' region. Because these regions are 180° apart, implying a subtraction of sinusoidal signals, we took the strengths of these inputs to be g 1 = 257.3 − 164.4 = 92.9 and g 2 = 260.7 − 162.7 = 98. Right (left) PFN v cells synapse onto the 'dendritic' regions with, on average, 67.0 and 74.3 synapses, and we used these numbers as the values of g 3 and g 4 . This assumes that there is no appreciable attenuation between the dendritic and axonal regions of the h∆B cells. The angles ϕ, up to an overall rotation that we chose to bring these angles in approximate alignment with the set of angles used above, were extracted from the hemibrain data by the procedure shown in Extended Data Fig. 6 and were taken to be 44.5°, −41.5°, −131.5° and 136.5°. This generated the second set of model results shown in Fig. 4e (green diamonds).

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

Data availability
Data for all of the main figures are available on Dropbox (https://www. dropbox.com/sh/p8bqwavlsyl9ppv/AABz2-vda4Q3gukXqp8Ba2Gw a?dl=0). Other data are available on request from the corresponding author.

Code availability
The analysis code has been deposited on GitHub (https://github.com/ Cheng-Lyu/TravelingDirectionPaper_code). Fig. 1 | Characterizing the anatomy and physiology of h∆B  cells, showing that sytGCaMP and RGECO1a yield similar EPG phase estimates in the ellipsoid body, quantifying the EPG phase tracking of the closed loop dot, and evidence that the h∆B phase tracks the fly's traveling direction in walking flies. a, At least sixteen somas are labeled by the h∆B split-Gal4 line used in this paper. By comparison, the hemibrain connectome (v1.1) reports nineteen h∆B cells 20 . b, GFP expression of the h∆B split Gal4 in the fan-shaped body. c, Same as panel b, but not showing the anti-nc82 neuropil stain. d, h∆B cells from hemibrain connectome v1.1 20 . e, Top, h∆B GCaMP7f signal in a tethered, flying fly experiencing optic-flow (in the time window bracketed by the vertical dashed lines) with foci of expansion that simulate the following directions of travel: 180° (backward), −120°, −60°, 0° (forward), 60°, 120°. Bottom, Phase-nulled and averaged h∆B activity patterns in the fanshaped body, calculated from the above [Ca 2+ ] signals in the last 2.5 s of optic flow presentation. Population means with s.e.m. are shown. f, Same as panel e, but with h∆B sytGCaMP7f signal. Note that the single-bump structure in the sytGCaMP7f signal is clearer than the structure in the cytoplasmic GCaMP7f signal, which is consistent with sytGCaMP7f biasing GCaMP to axonal compartments of h∆Bs. g, Probability distributions of the difference between the EPG phase and the bright dot's angular position, without and with optic flow. h, Circular standard deviation of the EPG phase -dot position distributions, without and with optic flow. Two-tailed unpaired t-test was performed. i, Correlations between the angular velocities of the EPG phase and the visual landmark position under different conditions. The first two columns use the same data as in panels g and h. The third and fourth columns use data from simultaneous GCaMP7f imaging of EPG cells and PFR cells in tetheredflying flies with a closed-loop dot. The fifth column use data from GCaMP6m imaging of EPG cells in tethered-walking flies with a closed-loop bar. Two-tailed one sample t-tests were performed against zero. P values are 1.7e-3, 1.3e-4, 5.3e-4, 1.2e-5 and 3.6e-4 comparing each column (from left to right) to zero, respectively. The relatively low, but significantly different from zero, r values show that the EPG phase tracks, even if poorly, the rotation of the landmark. The EPG phase measured in walking experiments tracks the closed-loop stimulus better than in tethered flight. See Main Text for possible technical reasons for why one would observe this difference. The fact that EPG-phase tracking of the closed loop dot is better when we co-imaged EPG cells and PFR cells compared to when we imaged EPG cells and h∆Bs argues that the flies' genetic background (and thus how reliably flies perform tethered flight) can also quantitatively impact these measures. j, Angular-velocity correlations of the EPG phase and the visual landmark position under different conditions as a function of the time-lag between the two velocity signals. Same data as in panel i, but data with and without optic flow are lumped together. Correlation is highest at 290 ms, 260 ms and 375 ms for the three panels from left to right, respectively. Thus, we used time lags of 275 ms (mean of 290 and 260) and 375 ms for calculating the correlations in flight and walking experiments in panel i, respectively. k, Probability distribution of the angular position of the dot on the arena. Same data as in panels g and h, but data with and without optic flow are lumped together. We tested the uniformity of the distribution across angles using reduced χ2 test. P value is > 0.995, meaning that we cannot reject the hypothesis that the dot position is not evenly distributed on the arena. l, Circular standard deviation of the EPG phase minus the h∆B phase distributions, without and with optic flow. Same data as in panels g, h. Twotailed unpaired t-test was performed. P value equals 1.3e-6. m, Correlations between the EPG phase and the h∆B phase. Same data as in panels g, h and l. Two-tailed unpaired t-test was performed. P value equals 3.9e .66 when comparing any experimental group with 0°. Note that we only collected a full EPG-PFN, dual-imaging data set with optic flow (moving dots) with PFN v cells because, for reasons that are not fully clear, the jRGECO1a signal was too weak in PFN d cells to properly estimate the PFN d phase outside of the context of stationary dots (i.e., during optic flow). When imaging PFN d cells with a split-Gal4 driver and with GCaMP rather than with jRGECO1a (e.g., Fig. 3j-l), the signal is much brighter.

Extended Data Fig. 3 | ∆7 cells are poised to help create sinusoidally shaped activity bumps in PFN d , PFN v , and PFR cells in the protocerebral bridge.
Connectivity data are based on those in neuPrint 20 , hemibrain:v1.1. a, Two ∆7 cells from neuPrint reveal a graded increase and decrease in dendritic density across the bridge. b, Synapse-number matrix for detected synapses from EPG cells to ∆7 cells in the protocerebral bridge. Each row represents one ∆7 cell. c, Same data as in panel b, but plotting each ∆7 cell separately. d, Phase-nulled EPG-to-∆7 synapse # across the glomeruli of the bridge, averaged across all 42 ∆7 cells, based on the data in panel c. The anatomical input strength from EPG cells to ∆7 cells is sinusoidally modulated across the bridge. e, Transforming the EPG activity pattern across the bridge (blue) into a predicted ∆7 activity pattern (green, bottom row) based on the synaptic density profile in panel c (schematized in the middle). We first calculated the dot product between the EPG activity vector and each ∆7 cell's EPG-to-∆7 synapse-number vector (panel c). Then, for each glomerulus, we averaged the dot-product-output for all of the ∆7 cells that have axonal terminals in that glomerulus, thus creating the predicted activity value for that glomerulus. (The size of each green square here schematizes the # of synapses from EPG cells to the ∆7 cell of that type in that column; the intensity of each ∆7 row indicates the expected output strength of each ∆7 cell type, after being driven by the EPG signal above.) We plot the inverted, predicted activity output from ∆7 cells in the bottom row (green) because ∆7 cells are glutamatergic 43 and glutamatergic neurons in the Drosophila central nervous system typically inhibit their postsynaptic targets (via Glu-Cl channels). After inverting the ∆7 activity one can then imagine simply averaging the ∆7 predicted-activity row with the EPG activity-with some relative weighting for the ∆7 and EPG curvesto generate the net drive to the many downstream neurons that receive both EPG and ∆7 input 20 , like PFN cells. Note that the EPG activity bumps are slightly narrower than the sinusoidal fits whereas the ∆7 activity bumps are slightly wider than the sinusoidal fits. f, Same as panel e, but using the phase-nulled, averaged EPG GCaMP activity pattern from a previous study 11 . Note although the EPG bump is narrower in these data from walking flies than in panel e from flying flies, the shape of the predicted ∆7 output remains similar. g, Same as panel e, but starting with (imagined) EPG activity where there is only one active glomerulus on each side of the bridge. Note that the shape of the predicted ∆7 output remains similar to that in panels e, f. h, Measured, phase-nulled activity profiles from PFN d , PFN v and PFR cells. Thin lines: individual flies. Thick lines: population average. All three activity patterns conform well to their sinusoidal fits (gray dashed lines) (see Methods for goodness of fit). We hypothesize that the sinusoidal activity patterns in bridge columnar cells like PFN d , PFN v , PFR cells arises from the combined impact of EPG and ∆7 input. In other words, we posit that ∆7 cells 'sinusoidalize' the EPG bumps in the bridge -that is, they function to broaden and smoothen the EPG input to the bridge, to create two sinusoidally shaped bumps in their recipient cells, with these bumps often functioning as explicit, 2D vector signals in the fan-shaped body.  20 , hemibrain:v1.1. a, The previously described mapping between EPG dendritic locations in the ellipsoid body and axonal-terminal locations in the bridge 21 . Numbers ordered based on the location of each EPG cell in the ellipsoid body. b, EPG cells divide the ellipsoid body into 16 wedges, each 22.5° wide. Each glomerulus in the bridge inherits its angle, in our analysis here, based on the EPG projection pattern shown in panel a. The angles of the outer two bridge glomeruli-which do not receive standard EPG input, but only EPGt input 20 -were inferred to have angles equal to the middle two glomeruli (0° and 22.5°, respectively) based on how other cell types (e.g., PEN cells) innervate the bridge, as discussed in past work 11 . This angular assignment maintains a 45° step size between adjacent glomeruli on each side of the bridge, which seems natural due to symmetry considerations. (Note that EPGt cells map from the ellipsoid body to the outer two glomeruli of the bridge with a small angular offset compared to the pattern set up by the EPG cells that target the central 16 glomeruli-as reported by other studies 28 -a caveat that slightly complicates our angular assignments; however, EPGt cells receive extensive axonal input in the bridge that has the potential to align their output signals with the rest of the bridge system.) Glomeruli are numbered 1 to 18 from left to right, to aid the comparisons made below. c, Two ∆7 cells from neuPrint (and past work 21 ) reveal that the axonal terminals of each ∆7 cell are 8-glomeruli apart (#5→#13 for cell A and #2→#10→#18 for cell B). This anatomy argues that any two glomeruli 8 apart, such as #5 and #13, will experience ∆7 output of equal strength. Compelling physiological evidence for this statement is available in the [Ca 2+ ] signals of the PEN2 (equivalently, PEN_b) columnar cell class in the bridge, which is a strong anatomical recipient of ∆7 synapses 20 and shows [Ca 2+ ] activity across the bridge-clearly dissociable from the activity in EPG cells-with consistently equal signal strength at glomeruli spaced 8 apart, perfectly following the ∆7 anatomical prediction (orange trace in Fig. 3d and data points in Extended Data Fig. 2i from ref. 15 ). Note that in the EPG indexing, shown in panel b, glomeruli #5 and #13, as examples, have angular indices that are not identical, but differ by 22.5°. d, Angles assigned to each bridge glomerulus based on the ∆7 axonal anatomy. Because the ∆7 output anatomy requires that any two glomeruli 8 apart, across the whole bridge, have the same angular index assignment, this results in a situation where all neighboring glomeruli have angular assignments that are separated by 45°. Note that almost all neighboring glomeruli are separated by 45° in the EPG mapping as well, except that, critically, in the EPG mapping the middle two glomeruli are separated by only 22.5°. This discontinuity is not evident in the ∆7 output. To create an angular indexing of the bridge for ∆7s that accommodates the anatomical constraints just described-i.e., one that incorporates an additional 22.5° in the bridge representation of angular space and thus 'erases' the EPG discontinuity-we shifted the angular index for each glomerulus on the left bridge leftward by 11.25° relative to the EPG indexing and we shifted the angular index for each glomerulus on the right bridge rightward by 11.25° relative to the EPG indexing. e, The EPG indexing in panels a, b predicts that EPG activity in the left bridge (#2→#9) will be left-shifted by 22.5° compared to EPG activity in the right bridge (#10→#17). Indeed, when we overlapped the left-and right-bridge EPG signals we found the two curves are detectably offset from each other. f, To quantify the data from panel e, for each imaging frame in which the fly was flying, we calculated the phase of the EPG bump in the left and right bridge separately (via a population-vector average) and took the difference of these two angles (black bars: population mean and s.e.m.). We then averaged this angular difference across all analyzed frames for the same fly. For EPG cells, this angular difference should be -22.5° if it follows the EPG indexing in panel b and it should be 0° if the activity follows the ∆7 indexing in panel d. Across a population of 9 flies, we found the angular difference is close to -22.5°, but shifted toward 0° by 4.6°, consistent with the fact that the EPG signal itself receives strong anatomical input from the ∆7s and thus could be modulated in its shape to follow the ∆7 indexing, in principle 20 . It seems that the ∆7 feedback to EPG cells reshapes its signal, but incompletely. g, h, Same as panel e, but analyzing the PFN d and PFN v activity in the bridge. Because PFN cells only innervate the outer 8 glomeruli in each side of the bridge (unlike EPG cells, which innervate the inner 8), we compared glomeruli #1→#8 in the left bridge overlapped with glomeruli #11→#18 in the right bridge here (the middle two glomeruli contain no signal for PFN cells). i, Same as panel f, but analyzing the PFN d and PFN v activity in the bridge. Black bars: population mean and s.e.m. Note that because PFN d and PFN v cells innervate (and thus we can only analyze) the outer 8 glomeruli of the bridge, the angular difference in phase estimates between the left-and right-bridge activity should be +67.5° if it follows the EPG indexing (panel b) and +90° if it follows the ∆7 indexing (panel d). We found that the average angular difference in both PFN d and PFN v cells is intermediate between +67.5° and +90°, consistent with PFNs receiving functional inputs from both EPG cells and ∆7 cells. We use the angular offsets measured in this panel as the basis for slightly adjusting the PFN d and PFN v angular indices in the bridge to an intermediate value between the EPG and ∆7 indexing options, described above. We believe that this approach represents the most careful way to combine the known anatomy and physiology to determine the azimuthal angle that each PFN cell signals with its activity in driving the h∆B neurites in the fan-shaped body, which we analyze in the next figure. j, Angles assigned to each bridge glomerulus for PFN d cells, based on the EPG indices from panel b and the physiologically determined adjustment required, based on the measurements in panel i. k, Same as panel j, but for PFN v cells. Fig. 6 | Computing the angular shift implemented by the PFN-to-h∆B connections. Connectivity data and cell-type names are based on those in neuPrint 20 , hemibrain:v1.1. a, The anatomical angle of each PFN v cell is indicated based on which glomerulus it inervates in the protocerebral bridge, using the indexing described in Extended Data Fig. 5k. b, Same as panel a, but for PFN d cells, using the indexing described in Extended Data Fig. 5j. c, Synapse-number matrix for detected synapses from PFN v cells to h∆B cells in the fan-shaped body. Note that the two stripes in the heatmap represent PFN v cells synapsing onto the dendritic regions of h∆B cells. d, Same as panel c, but for synapses from PFN d cells to h∆B cells. Note that two of the five stripes in the heatmap represent PFN d cells synapsing onto the dendritic regions of h∆B cells, whereas the other, brighter, three stripes represent PFN d cell synapsing onto the axons of h∆B cells. The average # of synapses that each h∆B compartment (axon vs. dendrite) receives from PFN cells is indicated on the bottom. e, Because h∆B cells are postsynaptic to both PFN v and PFN d cells that project to the fan-shaped body from both sides of the bridge (panels c, d), each h∆B cell can be assigned an anatomical angle in four potential ways. To calculate the angle for an h∆B cell through its connection with the left-bridge PFN v cells, for example, we averaged the anatomical angles of all the left-bridge PFN v cells that connect to the h∆B cell in question, weighted by the number of synapses from that PFN v cell to the h∆B cell. f, The anatomical angle of each h∆B cell calculated based on its monosynaptic inputs from left-bridge PFN v s using the method described in panel e and data in panel c. g, Same as panel f, but calculations were made with right-bridge PFN v inputs to h∆B cells. h, Same as panel f, but calculations were made with left-bridge PFN d inputs to h∆B cells, using only the synapses formed on the axonal terminals of h∆B cells. (We test the impact of this assumption-of complete functional dominance of PFN d axonal synapses to h∆B cells-below.) i, Same as panel f, but calculations were made with right-bridge PFN d inputs to h∆B cells, using only axonal synapses. j, For each h∆B cell, we calculated the angular difference between the mean left-bridge PFN d input and the mean right-bridge PFN d inputs (i.e., the difference between data points in panels h and i) and we plot a histogram of those values. k-m, Same as j for the cell types indicated. n, The anatomically predicted angles for the coordinate axes of the four PFN vectors, as projected to the fan-shaped body and interpreted by h∆B axons and dendrites, calculated by averaging the histogram values in panels j-m, respectively. o, Same as panel n, but including all synapses from PFN d to h∆B cells, not just the axonal ones as in panel n. We weigh dendritic and axonal synapses by PFN d to h∆B cells equally in the panel e calculation. Note that the angles between four coordinate-frame axes do not change very much when also including the dendritic synapses from PFN d to h∆B cells, likely because they are less numerous than the axonal ones and the impact of the dendritic angles also seem to cancel out in their net effect (compare panels o and n). p, Same as panel n, but using the EPG indexing from Extended Data Fig. 5 instead of the adjusted PFN v and PFN d indexing. Note that the EPG indexing makes the front angle between the left-and right-bridge PFN d axes smaller. The same is true for the back angle between the left-and right-bridge PFN v axes. q, Same as panel n, but using the ∆7 indexing from Extended Data Fig. 5 instead of the PFN v and PFN d indexing. Note that the ∆7 indexing makes the front and back angles broader than 90°, when used in isolation. This analysis suggests that EPG and ∆7 inputs to PFNs are perfectly weighted to create axes that are orthogonal in our experiments in flying flies and also raise the possibility that orthogonality of this 4-vector system can be dynamically modulated via changing the weights of EPG and ∆7 inputs to PFNs (see Supplementary Text). Fig. 7 | PFR neurons track a variable similar to allocentric traveling direction in walking and flying flies. a, Schematics of two example EPG cells, two example PFR cells and two example h∆B cells, which are the anatomically dominant input to PFRs. b, Sample GCaMP7f frames of the EPG bump in the ellipsoid body and the PFR bump in the fan-shaped body. c, Top, EPG (blue) and PFR (purple) GCaMP7f signal in a tethered, flying fly experiencing optic-flow (in the time window bracketed by the vertical dashed lines) with foci of expansion that simulate the following directions of travel: 180° (backward), −120°, −60°, 0° (forward), 60°, 120°, 180° (backward; repeated data). Third row, EPG and PFR phases extracted from the above [Ca 2+ ] signals. Fourth row, circular-mean phase difference between EPG cells and PFR cells. Bottom two rows, average of left-minus-right and left-plus-right wingbeat amplitude. Single fly means: light gray. Population means: black. Dotted rectangle indicates a repeated-data column. d, EPG -PFR phase as a function of the egocentric traveling direction simulated by the optic flow, at three different speeds. Circular means were calculated in the last 2.5 s of optic flow presentation. Gray: individual fly circular means. Black: population circular mean and s.e.m. Dotted rectangle indicates a repeated-data column. (See Methods for how we calculate the optic flow speed.) Note that the data points deviate slightly from the unity line in a manner that means that the PFR phase is slightly shifted away from the traveling direction indicated by the optic flow and toward a frontal heading direction. The h∆B data in Fig. 1h does not show this deviation from unity. We performed two-tailed one-sample t-tests against the diagonal line for data points in the ±60° and ±120° columns for the 35 cm/s data from PFR cells here and the 35 cm/s data from h∆B cells in Fig. 1h. For the PFR results on the left of panel d, P values are 4.7e-5, 4.7e-5, 5.4e-4 and 9.1e-3 for the −120°, −60°, +60° and +120° columns, respectively. For the h∆B results in Fig. 1h, P values are 0.39, 0.88, 0.058 and 0.44 for the −120°, −60°, +60° and +120° columns, respectively. e, PFR phase as a function of the inferred allocentric traveling direction, calculated by assuming that the EPG phase indicates allocentric heading direction and adding to this angle, at every sample point, the optic-flow angle. Gray: individual fly means. Black: population mean. In panels d and e, data from the middle column (35cm/s) were the same as in panel c. f, Tethered, walking, [Ca 2+ ]-imaging setup with a bright blue bar that rotates in closed loop with the fly's turns. g, Sample time series of simultaneously imaged EPG and PFR bumps in a tethered, walking fly. Top two traces show [Ca 2+ ] signals. Third trace shows the phase estimates of the two bumps. Bottom trace shows the forward speed of the fly. h, Probability distributions of the EPG -PFR phase in walking and standing flies. Thin lines: single flies. Thick line: population mean. i, Circular mean of the EPG -PFR phase in walking and standing flies. Watson-Williams multi-sample tests, P>0.63 when comparing any experimental group with 0°. Gray dots: single fly values. Black bars: population means ± s.e.m. j, Same as panel i, but plotting circular standard deviation. Two-tailed unpaired t-tests were performed. P value equals 0.042. k, Tethered-walking setup where we used a 617 nm LED focused on the center of the fly's head to optogenetically trigger backward walking via activation of LC16 visual neurons expressing CsChrimson 50 (Methods). l, An example 2D trajectory of optogenetically triggered backward walking. An arrow is shown every ~0.1 seconds. Red arrows indicate backward walking during the red-light pulse; blue arrows indicate the 1.2 s before the red light turned on. m, Left, time series of EPG (blue) and PFR (purple) bumps and phase-estimates from the trajectory in panel l. Right, time series of forward velocity, sideslip velocity and the difference between the PFR and EPG phase in the trajectory shown in panel l. The ∆F/F heatmap range is more compressed here than in other plots because the PFR signal strength typically dips when the fly initiates backward walking (a phenomenon whose mechanism we have not yet explored). Nevertheless, clear moments where the PFR phase separates from the EPG phase are evident, even after the PFR signal strength has recovered, in this sample trace (and in others). n, Time series of the mean forward velocity, mean sideslip velocity and the circular mean of the difference between the PFR and EPG phase during backward walking, grouped by optogenetic trials in which the fly walked to the back left (left panel) or to the back right (right panel). The sign of PFR-EPG phase deviations seen here, in walking, are consistent with the signs observed in flight, for the same directions of backward-left and backward-right travel. Thin lines and gray dots: individual trials. Thick line and black dot: population mean (circular mean for bottom row). o, Circular mean and s.e.m. of the peak EPG -PFR phase during triggered left-backward and right-backward walking bouts (0.6 s to 1.4 s after the dashed lines in panel n). Watson-Williams multi-sample tests were performed and P value equals 1.6e-6.

Corresponding author(s): Gaby Maimon
Last updated by author(s): Sep 6, 2021 Reporting Summary Nature Portfolio wishes to improve the reproducibility of the work that we publish. This form provides structure for consistency and transparency in reporting. For further information on Nature Portfolio policies, see our Editorial Policies and the Editorial Policy Checklist.

Statistics
For all statistical analyses, confirm that the following items are present in the figure legend, table legend, main text, or Methods section.

n/a Confirmed
The exact sample size (n) for each experimental group/condition, given as a discrete number and unit of measurement A statement on whether measurements were taken from distinct samples or whether the same sample was measured repeatedly The statistical test(s) used AND whether they are one-or two-sided Only common tests should be described solely by name; describe more complex techniques in the Methods section.
A description of all covariates tested A description of any assumptions or corrections, such as tests of normality and adjustment for multiple comparisons A full description of the statistical parameters including central tendency (e.g. means) or other basic estimates (e.g. regression coefficient) AND variation (e.g. standard deviation) or associated estimates of uncertainty (e.g. confidence intervals) For null hypothesis testing, the test statistic (e.g. F, t, r) with confidence intervals, effect sizes, degrees of freedom and P value noted

Software and code
Policy information about availability of computer code Data collection Behavioral and visual stimulus data were recorded as voltages on a Digidata 1440 (Molecular Devices) I/O board. Two-photon imaging data were collected using PrairieView 5.4 (Bruker). Floating ball positions were measured using Fictrac v1. Wing tracking was conducted with Strokelitude (https://github.com/motmot/strokelitude).

Data analysis
Two photon imaging data were pre-processed using Fiji (to define regions of interest, version: 2.1.0/1.53c). All data were analyzed with custom code in python 2.7 and 3.6. Analysis code is deposited on github (https://github.com/Cheng-Lyu/TravelingDirectionPaper_code).
For manuscripts utilizing custom algorithms or software that are central to the research but not yet described in published literature, software must be made available to editors and reviewers. We strongly encourage code deposition in a community repository (e.g. GitHub). See the Nature Portfolio guidelines for submitting code & software for further information.

Data
Policy information about availability of data All manuscripts must include a data availability statement. This statement should provide the following information, where applicable: -Accession codes, unique identifiers, or web links for publicly available datasets -A description of any restrictions on data availability -For clinical datasets or third party data, please ensure that the statement adheres to our policy Data for main Figures are available on Dropbox (https://www.dropbox.com/sh/p8bqwavlsyl9ppv/AABz2-vda4Q3gukXqp8Ba2Gwa?dl=0). Other data are available upon request.