Main

The real world is ever dynamically changing, requiring humans and other animals to rapidly switch between different behavioural modes. For example, when a wild rodent is foraging for food, it occasionally needs to avoid predators and decide towards which burrow to escape, therefore switching dynamically between foraging, predator avoidance and decision-making. However, the neural basis of behaviour is typically studied while the animal is performing one behavioural task at a time, and little is known about how brain circuits rapidly switch between different natural behaviours. Navigation is a complex, dynamic natural behaviour that enables the testing of behavioural switches. It requires the animal to know its own location within the environment, while also paying attention to abrupt events—such as the appearance of unexpected obstacles, predators or conspecifics; the animal may therefore also need to assess the distance to ‘things out there’. The animal’s position is encoded by hippocampal place cells10,11,12,13; however, this coding has been studied mostly in empty, stationary set-ups that do not imitate the rich dynamism of real-world navigation. There have also been a number of studies that investigated the representation of ‘things out there’ by neurons in the hippocampal formation and surrounding structures15,16,17,18,19,20,21,22,23, but these were all studied under static conditions, without examining dynamic behavioural switches. Here we set out to investigate how brief natural attentional switches to ‘things out there’, which are essential for real-life navigation, affect the representation of space in the hippocampus during navigation. We aimed to test several hypotheses regarding how hippocampal circuits may encode position and distance to ‘things out there’ during dynamic navigation: (1) hippocampal activity always encodes only position; (2) hippocampal activity switches between pure position and pure distance representations; (3) hippocampal activity always multiplexes position and distance information; (4) hippocampal activity switches from a position code to a conjunctive representation of distance by position upon a behavioural need. As we show below, our results are most consistent with hypothesis 4.

Encoding of distance during brief attentional switches

We trained pairs of Egyptian fruit bats to fly together in a long 135 m linear tunnel between two landing balls, where food was given. The bats alternated between two behavioural modes (Methods): (1) solo: only one bat flew alone, or was >40 m away from the other bat (Fig. 1a (left)); or (2) cross-over: the two bats flew towards each other from opposite directions at <40 m (Fig. 1a (right)). The bats took off from the balls non-synchronously at random timing relative to each other, creating intermingled solo and cross-over flights, which were distributed approximately uniformly along the tunnel (Fig. 1b,c and Extended Data Fig. 1). During cross-overs, the bats bypassed each other at a very high relative speed of around 14 m s−1 (the sum of both bats’ speeds; the speeds of individual bats are shown in Extended Data Table 1) and, therefore, had to be attentive to avoid collision between one another. To measure the bats’ attention, we recorded their echolocation clicks (sonar signals), because many bat species have been shown to increase echolocation click rate when attention is needed; thus, echolocation provides an index of the bat’s moment-to-moment attention1,2,3,4,5,6,7,8,9. Indeed, we found that, during cross-overs, the bats increased their echolocation click rate by around fourfold and click amplitude by around twofold (Fig. 1d,e and Extended Data Fig. 2c), with this echolocation profile being uniform along the entire tunnel (Fig. 1f and Extended Data Fig. 2d). In all of the bats, the increase was rapid (about 1 s), and constituted a switch between two distinct behavioural phases (Extended Data Fig. 2b). This increase in click rate suggests that the bats were highly attentive during these demanding cross-over flights. In the rare cases of near collisions, the bats exhibited fewer echolocation clicks (Extended Data Fig. 2e–g), suggesting that a low click rate indicates a lapse of attention, which may lead to collisions. This provides further support for the link between echolocation rate and attention.

Fig. 1: Set-up and behavioural task.
figure 1

a, The experimental set-up. Bats flew in pairs and alternated between two behavioural modes: solo (left) and cross-over (right). b, Example behaviour (4 min of the full session that is shown in Extended Data Fig. 1a). The blue and orange lines show the positions of the recorded bat and the other bat, respectively; the pink circles show cross-over events; pink rectangles show cross-over flights (±40 m distance around cross-over events); grey rectangles show solo flights. c, The distribution of behavioural coverage along the tunnel in an example session: solo (left) and cross-over (right) flight is shown separately for the two flight directions (dir.) (dark and light coloured, stacked). The light grey vertical rectangles show the areas in which cross-overs were not analysed (Methods). d, Echolocation example. Top, the audio signal during one cross-over flight for the recorded bat (blue) and for the other bat (orange) as a function of the interbat distance (negative/positive distances: bats flying towards/away from each other). Bottom, raster plot showing the echolocation clicks of the recorded bat (blue dots) for the 50 cross-overs in this session (one flight direction). Note that Egyptian fruit bats emit pairs of clicks5. SNR, signal-to-noise ratio. e, The population average echolocation click rate (left) and click amplitude (right) for bat 2299 (n = 11 sessions) during cross-over flight (data are mean ± s.d. (pink shading), with the s.d. computed over all behavioural data in each distance bin) and solo flight (data are mean ± s.d.). Scale bar, the mean distance flown in 1 s. f, 2D click rate maps for interbat distance (x axis) by position (y axis) for the two flight directions for all sessions of bat 2299, coloured from zero (blue) to peak click rate (red; value indicated). Note that the click rate increased before cross-over, similarly along all of the positions (see the vertical band).

Source data

The use of a very large environment enabled us to examine these fast behavioural switches, because (1) bats fly very fast in large environments, allowing for very rapid switches; (2) the large space allowed for a substantial baseline before and after the cross-overs; and (3) it allowed the bats to perform cross-overs at multiple positions, therefore enabling us to disentangle distance from position. We used a wireless electrophysiology device to record the activity of 430 neurons from dorsal hippocampal area CA1 of four bats during flight (Extended Data Fig. 3a,b and Extended Data Table 1; 389 putative pyramidal cells, 41 putative interneurons; we analysed the data separately for the two flight directions: 693 valid pyramidal cells × directions, 74 valid interneurons × directions; Methods). On the basis of the solo flights, we classified 88.5% of the pyramidal cells as significant place cells (n = 613 cells × directions exhibited significant positional modulation of firing rate). Place cells exhibited multiple place fields in this long track (mean ± s.d., 3.03 ± 1.81 place fields per direction), with variable field sizes (Extended Data Fig. 3c–g), consistent with our previous report14.

During cross-overs, a subpopulation of hippocampal neurons showed significant modulation of their firing rate at specific interbat distances, exhibiting either enhanced or suppressed firing (Fig. 2a). We started by analysing the one-dimensional (1D) tuning to interbat distance, irrespective of position along the tunnel: 18.0% of the pyramidal neurons and 39.2% of the interneurons were classified as significantly tuned to distance (pyramidal, n= 125 cells × directions; interneurons, n= 29 cells × directions; Fig. 2b–d and Extended Data Fig. 4a); we refer to cells showing 1D distance modulation as 1D distance cells. This classification was based on three main criteria: (1) rigid spike shuffling for cross-over flights, which preserves the spiking pattern but dissociates it from behaviour; (2) shuffling compared to firing expected from solo flights to account for the place tuning (Extended Data Fig. 5); and (3) stability of the distance tuning (Extended Data Fig. 4b and Methods). These criteria ensured the detection of significant and stable distance tuning that did not result from the place tuning. The distance modulation was very prominent (Extended Data Fig. 4c; mean z-scored peak enhancement compared with the firing expected from solo: z = 7.18 (pyramidal cells) and z = 7.17 (interneurons)). The distance tuning could not be explained by speed changes during cross-overs (Extended Data Fig. 6), nor by direct responses to individual echolocation clicks (Extended Data Fig. 7a–d). Moreover, the distance tuning did not reflect coding of the absolute position of the other bat but, rather, reflected genuine coding of the interbat distance (Extended Data Fig. 8f (right)). In fact, almost no neurons showed significant tuning to the other bat’s position in this behavioural paradigm (Extended Data Fig. 8a; 1.2% of the cells were significant at a 1% significance level: binomial test, P = 0.34). The finding that hippocampal neurons encode distance information during cross-overs rules out hypothesis 1, which suggested that there is only pure position coding in the hippocampus.

Fig. 2: Hippocampal CA1 neurons represent the distance to another bat upon brief attentional switches during navigation.
figure 2

a, Examples of 1D distance neurons. nco represents the number of cross-overs. For each cell, the top row shows the tuning curve for 1D distance (pink line) and shuffles (shading). Horizontal lines denote significant enhancement (green) or suppression (brown). In the middle row, the left plot shows the recorded bat position (y axis) and interbat distance (x axis) during cross-overs (grey; the two flight directions yield positive versus negative slopes of the grey lines), with spikes overlaid (pink dots); the centre plot shows the spike raster during solo flights (grey, behaviour; black dots, spikes), showing position (y axis) versus time in the session (x axis; the solo raster has holes in which cross-overs occurred; Extended Data Figs. 1d and 3c); and the right plot shows place tuning during solo flights (black) and during cross-over flights (pink). The bottom row shows the 2D firing-rate map of position (y axis) by interbat distance (x axis), coloured from zero (blue) to peak firing rate (red; value indicated). bd, Population summary of all significant 1D distance neurons for putative pyramidal neurons (n = 125) and interneurons (n = 29). b, Top, the mean of z-scored distance tuning curves. A raster of z-scored tuning curves is shown separately for pyramidal neurons (middle) and interneurons (bottom), sorted by peak distance. c, Top, the fraction of cells with significant distance enhancement, as a function of interbat distance. Significantly enhanced and suppressed bins for pyramidal neurons (middle) and interneurons (bottom) are shown. d, Top, the distribution of enhancement response onset (the distance at which the tuning crossed 90% of the shuffle distribution). The response onset for pyramidal neurons (middle) and interneurons (bottom) is shown. Inset, pyramidal cells sorted by onset distance (separately for enhancement and suppression). eg, Attentional modulation of distance tuning, comparing higher-click-rate flights (purple, high attention) with lower-click-rate flights (pink, low attention). e, Example cells: 1D distance tuning curves. f, The average population tuning curves (each cell was normalized to its peak firing rate computed using all flights) for all 1D distance neurons (right) and all cells significantly modulated by click rate (left). g, The peak firing rate (normalized as described in f), for high- and low-click-rate flights (purple and pink), plotted for 1D distance neurons (right; one-tailed t-test: t = 2.47, P = 0.009, n = 37 cells × directions), and neurons that were significantly modulated by click rate (left; one-tailed t-test: t = 6.44, P = 3.72 × 10−5, n = 11). For f and g, data are mean ± s.e.m.

Source data

Across the population, 1D distance-coding cells showed significant modulation at many interbat distances, with over-representation of cells tuned to short distances (Fig. 2b–d; see Extended Data Fig. 4a for individual animals). The response onset of most neurons occurred early: 70.4% of the pyramidal neurons and 93.1% of the interneurons started responding before the cross-over event (Fig. 2d; sign test for the enhancement response onset compared to zero distance: pyramidal neurons, P = 1.27 × 10−4, n = 109 cells × directions; interneurons, P = 3.05 × 10−5, n = 16 cells × directions). Notably, the neuronal distance signal started at a similar interbat distance as the attention signal, indexed by an increased rate of echolocation clicks (the response onset in Fig. 2d starts at approximately −20 m, similar to the initial increase in click rate: Fig. 1e) but the neuronal responses ended later—many pyramidal cells were distance tuned also after the cross-over event (interbat distance > 0), when the echolocation click rate had returned to the baseline. This might be explained as follows: (1) while most neurons were ‘switched on’ by attention before the cross-over event, these cells continued firing for some time, and then other neurons became active after cross-over due to network reverberations or neuromodulators. (2) Some pyramidal cells with late activity may have been released from inhibition (Fig. 2c; the bottom ~20 pyramidal cells show suppression followed by enhancement), which could stem from interneurons being most strongly active before and around the cross-over event (compare pyramidal cells and interneurons in Fig. 2b–d (top)). (3) Population activity both before and after cross-over could represent neuronal sequences24,25,26, perhaps reflecting memory encoding of the entire cross-over event. (4) Finally, it might be behaviourally relevant to represent the distance from the other bat also after the cross-over event because the other bat could perform a U-turn after the cross-over and fly back towards the recorded bat (indeed, we observed such U-turns occasionally in the experiment). Furthermore, bats can directly sense the distance to the other bat behind their back using echolocation, which spreads also backwards5,27; or they can estimate the distance to the other bat after cross-over using path integration by relying on the bats’ fixed speed.

The distance tuning was generally uncorrelated between the two flight directions (Extended Data Fig. 4h–j) and was also uncorrelated between positive and negative distances (Extended Data Fig. 4k). This suggests that the distance-tuned neurons did not encode absolute distance but, rather, encoded distance and direction. Thus, these neurons could be interpreted as vectorial distance cells (other types of vectorial cells in the hippocampal formation were described previously18,19,21,23).

To explicitly test whether attention modulates the 1D distance tuning, we performed several analyses. First, we bisected the cross-over flights into those with lower attention versus those with higher attention (lower versus higher click rate), and found that cells with 1D distance tuning exhibited stronger responses during high-attention flights (Fig. 2e–g and Extended Data Fig. 7e; bisection was performed for entire cross-over flights; we included here only cells recorded simultaneously with audio; Methods). As distance tuning could not be explained by direct responses to echolocation clicks (Extended Data Fig. 7a–d), these results suggest that 1D distance neurons are modulated by high-level cognitive variables, such as attention, arousal or an enhanced state of active sensing.

Second, to experimentally test the effect of attention, we trained one pair of bats to perform an additional behaviour—tracking—in which the two bats flew in the same direction at a short interbat distance (Extended Data Fig. 9a (cyan and turquoise rectangles) and Methods). We reasoned that, as the relative speed during tracking was near-zero (in contrast to cross-over, for which it was around 14 m s−1), tracking requires lower attention than cross-over. Indeed, bats echolocated at much lower rates during tracking (Extended Data Fig. 9b), suggesting that tracking requires less attention. During tracking flights, CA1 neurons preserved their place tuning, but did not preserve their distance tuning; in fact, distance tuning was largely absent during tracking (Extended Data Fig. 9). This suggests that only when attention is strongly required—during cross-overs, but not during tracking—CA1 neurons encode the interbat distance.

Third and finally, in another pair of bats, after the end of the regular behavioural session, we conducted a second session in which the recorded bat flew with an alternative partner bat. We reasoned that, during collision avoidance (cross-over), it is important to attend to the other bat and represent its distance irrespective of the other bat’s identity. Indeed, distance tuning was largely preserved between the two sessions with different partners (Extended Data Fig. 10). This suggests that the observed distance tuning (Fig. 2) is probably not social but, rather, is related to collision avoidance.

Conjunctive 2D coding of distance by position

Next, we considered the 2D tuning of neurons to distance by position. As the vast majority of CA1 pyramidal neurons in the long tunnel were place cells14 (Extended Data Table 1), we started by analysing the distance tuning curve separately within each place field. Half of the place fields (49.3%, 301 out of 611) were significantly modulated by the interbat distance, showing enhancement, suppression or both (see Fig. 3a and Extended Data Fig. 11a for examples and Fig. 3b for the population). Interestingly, different place fields of the same neuron could exhibit different distance tuning (Fig. 3a (cell 331) and Extended Data Fig. 11a (cell 287)); we return to this issue below. Overall, place cells encoded the position of the bat when flying alone but, during cross-overs, they conjunctively encoded distance by position, and then switched back to their position coding after the two bats passed each other (Fig. 3a). As the bats flew very fast, these switches between different representations were extremely fast—as fast as 100–200 ms (Fig. 3c and Extended Data Fig. 11e).

Fig. 3: Conjunctive representation of interbat distance by position.
figure 3

a, Examples of three neurons. For each cell, the middle and right plots are as described in Fig. 2a, and the left plot shows the 1D distance tuning curves within different place fields (colours correspond to different place fields, marked by vertical coloured lines on the left of the centre plot). Place fields here and elsewhere were defined on the basis of solo data. Shading shows cross-over shuffles; horizontal green and brown lines show bins with significant enhancement and suppression, respectively. b, The percentages of different types of distance modulation within place fields for neurons with different numbers of place fields. Compound modulation indicates tuning with both significant enhancement and suppression (for example, cell 234 (blue) in a). c, The distribution of neuronal switch times of the distance tuning. Top, the rise time (dark green) and fall time (light green; stacked) for place fields with significantly enhanced distance tuning curves. n = 143. Bottom, the fall time (dark brown) and rise time (light brown) for place fields with significantly suppressed distance tuning curves. n = 62. Only a subset of the fields was valid for analysis here (Methods). d, Examples of two neurons with significant enhancement outside their place fields (within an interfield), plotted as described in a. The vertical lines on the left of the centre panel mark place fields (black) and interfields (peach). The black arrows indicate spikes contributing to distance tuning within the interfield; note that there were barely any spikes in the same position during solo flights (see the solo raster on the right). e, Population summary: distance bins that were significantly enhanced (green) or suppressed (brown) within place fields (n = 301 fields) and interfields (n = 59) sorted by distance-tuning peak. f, 2D distance by position tuning: patch analysis. Examples of cells with significant 2D patches are plotted as described in Fig. 2a without the raw data panels. The outlines show significant 2D patches (enhancement (green); suppression (brown)). The vertical black lines show place fields. g, Summary of different functional classes of pyramidal cells (numbers denote cells × directions). Place cells are shown in grey. The thick black curve encompasses the total number of distance-modulated cells (n = 384, 55.4% of all pyramidal cells).

Source data

Interestingly, significant distance tuning was also seen outside of place fields, in areas defined as interfields (n = 59 interfields showed significant responses, out of 87 interfields valid for analysis; Fig. 3d and Extended Data Fig. 12a (black arrows) and Methods). These distance-tuned responses in interfield areas were very strong compared with the low firing rate during solo flights (Extended Data Fig. 12d). This type of distance response might be explained by the presence of subthreshold place fields28, which are enhanced by incoming distance inputs and rendered suprathreshold, therefore creating a distance-by-position response. Overall, the distance-tuned place fields and interfields spanned a wide range of distances, with an over-representation of short interbat distances (Fig. 3e and Extended Data Figs. 11c and 12c).

We further examined the existence of significant 2D distance-by-position modulation of firing rate irrespective of place field definitions. We used cluster analysis (Methods) and identified ‘2D patches’ in the 2D distance-by-position firing-rate maps, which were significantly enhanced or suppressed relative to solo (see Fig. 3f for examples and Extended Data Fig. 12f for the population; 9.7% of the significant patches occurred outside of place fields; Fig. 3f (cell 314) and Extended Data Fig. 12e). When considering collectively cells with 2D distance modulation (neurons with significant patches, or significant tuning within-field or interfield; Fig. 3g (purple ellipse)) and cells with 1D distance modulation (Fig. 3g (pink ellipse)), the majority of pyramidal cells in CA1 were significantly modulated by the interbat distance during cross-overs (55.4%, n = 384/693 cells × directions; Fig. 3g (thick black line)). The existence of 2D distance-by-position patches rules out hypothesis 2—which suggested a switch between pure position coding and pure distance coding—because both signals were conjunctively encoded during cross-overs. In fact, there are two versions of hypothesis 2—(1) separate populations of neurons encode position and distance, or (2) single neurons switch between purely representing position and purely representing distance—and our results ruled out both options.

Two remaining hypotheses may underlie the results presented so far: hypotheses 3 and 4. Hypothesis 3 suggests multiplexing of position and distance information by the neurons—that is, the neurons exhibit 2D distance-by-position tuning, and are continuously ready to process both of these incoming information streams. Hypothesis 4 suggests that individual hippocampal neurons exhibit switching from position coding during navigation to conjunctive coding of distance by position during collision-avoidance behaviour. We believe that hypothesis 4, that is, switching, is more probable because we found that (1) during cross-overs, the position tuning changed significantly compared with solo flight (Fig. 4a), accompanied by a small but significant decrease in spatial information (Fig. 4b); furthermore, there was a substantial increase in the position decoding error at short interbat distances, when we used the solo-based tuning for decoding (Fig. 4c). Importantly, the changes in the position tuning (Fig. 4a–c) could not be explained by changes in the firing rate because there was no prominent change in the average firing rate during cross-overs (Fig. 4d). This suggests that the distance information comes partially at the expense of the position tuning, as expected from a switch. (2) The rise time of neuronal responses during cross-over was independent of the flight speed (Extended Data Fig. 6k). This is consistent with a neural switch rather than multiplexing, because flight through a static multiplexed tuning curve of distance by position should have yielded a faster rise time at a higher flight speed, which we did not observe (Extended Data Fig. 6k; t-test: t = 0.84, P = 0.41; n = 120 neurons). By contrast, for a neuronal switch, we expect that the switch time will have a fixed duration irrespective of velocity, consistent with our results. (3) The neuronal modulation was extremely rapid (Fig. 3c and Extended Data Fig. 11e), consistent with a neuronal switch. (4) Most neurons responded in sync at similar distances (Fig. 2b–d), and this was particularly prominent in each animal separately (Extended Data Fig. 4a). (5) These highly visual bats probably see each other from much greater distances than 20 m (refs. 29,30), and yet they exhibited a substantial behavioural and attentional switch at a distance of −20 m (Fig. 1d–f), and the neurons mostly started responding at −20 m (Fig. 2d), which seems to be more consistent with a switch, or gating of neuronal coding. (6) Hippocampal neurons did not always encode distance-by-position information; during tracking, the distance coding was almost absent (Extended Data Fig. 9). This is inconsistent with multiplexing of information, and more consistent with neuronal switching that is based on behavioural and attentional demands. However, in contrast to the switching notion, neurons also exhibited a diversity of preferred distances, consistent with multiplexing of information rather than with a network-level switch. Thus, the data are partially consistent with both hypothesis 3 (multiplexing) and hypothesis 4 (neural switching).

Fig. 4: Simultaneous decoding of interbat distance and position.
figure 4

ad, Change of position tuning during cross-overs. a, The average Pearson correlation between position tuning during solo and during cross-over flights, computed in 10-m distance bins (Methods). Data are mean ± s.e.m. (pink). n = 613 place cells × directions. Note the correlations decreased when bats approached each other, indicating a change in position tuning. The grey curve was computed as described for the pink curve, using solo projected on cross-over shuffles. b, Spatial information (mean ± s.e.m.; n = 613 place cells × directions) for the position-tuning curves computed during cross-over flights (pink), and for solo projected on cross-over shuffles (grey). c, Position decoding error as a function of distance during cross-over (pink; mean ± s.e.m.; n = 16 sessions) and chance level (grey). Note the increased decoding error at short distances. d, Firing rate (normalized to the peak of each cell) as a function of distance during cross-over for all place cells. Data are mean ± s.e.m. n = 613 place cells × directions. e,f, Simultaneous decoding of the interbat distance and position during cross-over flights. e, Examples of two flights (columns). Top, real position (black) and decoded position (blue) versus time. Bottom, real and decoded interbat distance. f, Confusion matrices (pooled over all sessions with ≥10 cells recorded simultaneously; n = 16 sessions). Left, the probability of decoded positions (y axis) for each real position (x axis), normalized to the uniform chance probability Pchance = 1/nbins (colour bar). Right, the same for the interbat distance. The diagonal structure in these matrices indicates accurate and unbiased decoding. g,h, The decoding error of interbat distance for different click-rate quartiles (q1–q4, quartiles of low click rate to high click rate) for one example session (g) (n = 146, n = 134, n = 146 and n = 151 decoding time windows for q1–q4) or pooled over all nine sessions that had audio recordings and ≥10 cells (h) (n = 998, n = 1,051, n = 1,074 and n = 1,063 decoding time windows for q1–q4). Note that the decoding error decreased as the click rate increased (q4, maximal click rate, that is, maximal attention; click rate is a proxy of attention). Data are mean ± s.e.m. Statistical analysis was performed using analysis of variance with post hoc correction for multiple comparisons: *P < 0.05, **P < 0.01, ***P < 0.001, ****P < 0.0001; no asterisks, not significant. See Extended Data Fig. 13c for the exact P values, violin plots and Kruskal–Wallis tests.

Source data

Next, we examined whether the distance-by-position representation enables decoding simultaneously the interbat distance and the position of the bat during cross-overs. We were able to simultaneously decode both variables using relatively small cell numbers (Fig. 4e,f and Extended Data Fig. 13; n = 10–22 simultaneously recorded cells; Methods). The interbat distance was decoded above chance at all ±40 m distances (Fig. 4f (right) and Extended Data Fig. 13b), although decoding was better at short interbat distances of ±20 m. Interestingly, when dividing the cross-over data to attention levels on the basis of the bat’s echolocation click rate, we found that the distance decoding error decreased as the click rate increased, that is, as the attention increased (Fig. 4g,h and Extended Data Fig. 13c,d). This suggests that, on a trial-by-trial basis, hippocampal neurons encode distance information more precisely when the recorded bat is more attentive to the other bat.

Coding of distance by position is non-separable

We next examined in more detail the nature of the conjunctive 2D distance-by-position coding. In many place cells, different place fields of the same neuron were modulated differently by the interbat distance (Figs. 3a (cell 331) and 5a). Indeed, over the population of place cells, the distance-tuning correlations between place fields of the same neuron were widely distributed around zero (Fig. 5b (pink)), and were only marginally different from the across-cell shuffle distribution (Fig. 5b (grey); there was a slight over-representation of cells with high correlations; Kolmogorov–Smirnov test, P = 0.016). Consistent with this, the correlation of distance tuning between pairs of place fields was independent of the difference in their positions along the tunnel (Fig. 5c (left); Pearson r = −0.08, P = 0.31). This lack of correlation between different fields could not be explained by differences in behaviour along the tunnel because (1) both echolocation profiles and flight velocity were nearly constant along the tunnel (Fig. 1f and Extended Data Fig. 6c); (2) there was no correlation between the difference (contrast index) of the echolocation click rate within pairs of place fields of the same neuron, and the distance-tuning correlations of these fields (Fig. 5d); and (3) simultaneously recorded neurons often showed very different distance tuning at the same position (Fig. 5c (right); note the wide distribution of correlations for small position difference between fields), despite the same underlying behaviour. Taken together, these results indicate that different place fields of the same neuron exhibited almost independent distance tuning, suggesting a non-separable 2D distance-by-position coding—the 2D coding could not be described by a multiplication of the two 1D marginals, that is, by a multiplication of the tuning curves for distance and for position. This finding may imply modularity, whereby different distance computations are performed at different place fields.

Fig. 5: The representation of distance by position is complex and non-separable.
figure 5

ad, Different distance tuning across different place fields. a, Example cell. Note the two place fields showed opposite distance modulation. b, The distribution of Pearson correlations between the 1D distance tuning curves of pairs of place fields of the same cell (pink; n = 170 pairs; the inclusion criteria are described in the Methods), or place fields of different simultaneously recorded cells (grey, cell shuffling; n= 2,479 pairs). c, Pearson correlations between the 1D distance tuning curves of pairs of place fields of the same cell (left) or of simultaneously recorded different cells (right), plotted versus the position difference between the place-field peaks (Pearson correlations of the scatters are indicated). d, Pearson correlations between the 1D distance tuning curves of pairs of place fields of the same cell (y axis) and the contrast index of echolocation click rate during cross-over within these pairs of place fields (x axis; contrast index = (CRfield1 − CRfield2) / (CRfield1 + CRfield2), where CR is the click rate). n= 79 pairs of place fields recorded with audio. eg, SVD analysis shows non-separable distance-by-position coding. e, Example neurons with varying degrees of non-separability. Top, 2D firing rate map of position (y axis) by interbat distance (x axis), cropped and completed for the SVD analysis (Methods); λ and α (non-separability indices) are indicated: higher values denote non-separable cells; neurons are sorted by λ. Bottom, histograms of shuffle distributions (grey) and real values (red lines) for λ (left) and α (right). Cell 96 is separable (two place fields show same distance tuning), the other five cells are significantly non-separable (different distance modulations at different positions). f, The distributions of λ and α across all cells in the SVD analysis (n = 262 cells × directions; inclusion criteria are described in the Methods). Grey, non-significant cells (n = 189 cells × directions). Red, significantly non-separable cells (n = 73 cells × directions). g, Non-separability indices λ and α versus the number of place fields of the cell (only place fields within the SVD rectangular maps were included; n = 237 place cells × directions). Spearman correlation ρ values are indicated. The black dots show the median; and the black lines are kernel density plots. h,i, The functional advantage of non-separability: theoretical analysis of distance decoding for simulated neurons. h, Mean decoding error (left) and catastrophic decoding error (right, 99th percentile of errors), plotted on a log scale as a function of the interbat distance, separately for simulated populations of cells with different non-separability values, λ (different colours). Grey, chance-level decoding. i, Mean decoding error (left, colour-coded) and catastrophic decoding error (right) as a function of the number of neurons used for decoding and the non-separability index, λ.

Source data

To further characterize the non-separability of the 2D distance-by-position coding of CA1 neurons, we performed a singular value decomposition (SVD) analysis31,32 (Fig. 5e–g, Extended Data Fig. 14 and Methods). This standard analysis enables us to determine whether a 2D map is separable (Fig. 5e (cell 96)) or is more complex (non-separable cells; Fig. 5e (five rightmost cells)). We quantified the non-separability using two SVD indices (λ and α, where higher values indicate stronger non-separability; Methods), and compared it to shuffles: this revealed that 27.9% of the pyramidal cells tuned to distance were significantly non-separable (Fig. 5f). Dimensionality analysis showed that some of the non-separable cells required more than four dimensions to describe their 2D distance-by-position maps (Extended Data Fig. 14d,e; mean, 2.25 dimensions), highlighting the complexity of their 2D tuning. This non-separability could not be explained by spike-sorting quality, nor by the very small inhomogeneities in click rate or flight speed (details are provided in the legend of Extended Data Fig. 14) (Fig. 1f and Extended Data Fig. 6c). Moreover, we found that place cells with a higher number of place fields were more likely to have higher non-separability indices (Fig. 5g).

Although non-separable complex tuning has been found also in other brain areas31,32,33,34,35,36, it remained unclear whether such tuning offers any functional advantage. A previous theoretical study showed that conjunctive 2D representation of two variables is more efficient than two separate 1D representations (by separate neuronal populations), especially when fast computations are needed for the two variables simultaneously37. However, that study did not examine specifically whether a non-separable conjunctive 2D representation is useful. To investigate the possible advantage of such non-separable coding in the hippocampus, we simulated populations of place cells with the same distance modulations but with different degrees of non-separability (Extended Data Fig. 15a). We then decoded the interbat distance from each population, and found that higher levels of non-separability led to lower decoding errors (Fig. 5h and Extended Data Fig. 15b,d,f). Furthermore, increasing the non-separability of the cells was equivalent to increasing the population size—that is, the same decoding error can be achieved with fewer neurons if their tuning is non-separable (Fig. 5i and Extended Data Fig. 15c,e,g). This suggests that the non-separable distance-by-position tuning yields a more efficient encoding of distance.

Discussion

Here we studied naturalistic behavioural switches between navigation and collision avoidance in flying bats, and found three key results: (1) more than half of the hippocampal place cells encoded conjunctively distance-by-position information (Fig. 3)—switching very rapidly (as fast as 100 ms) from a position representation to a distance-by-position representation (Fig. 3c and Extended Data Fig. 11e). Crucially, these rapid switches occurred at the level of single neurons. (2) The distance tuning was modulated by the bat’s sonar-guided attention (Figs. 2e–g and  4g,h and Extended Data Fig. 13c,d). (3) Finally, we found that, for many cells, the distance-by-position tuning was non-separable—an individual neuron could exhibit different distance modulation at different positions along the tunnel; specifically, different place fields of the same neuron exhibited very different distance tuning (Figs. 3a and 5). This may suggest modularity of hippocampal processing across different place fields. Simulations of a theoretical model showed that such non-separable neuronal code leads to better encoding of distance information (Fig. 5h,i). Our results are fundamentally distinct from previous reports (for details, see the ‘Additional discussion’ section in the Methods).

We propose that the non-separable code could be formed by independent position and distance inputs arriving to CA1 (Extended Data Fig. 16). Specifically, we previously proposed that the multiple place fields of a single CA1 neuron arise from different dendrites receiving independent position inputs14 (Extended Data Fig. 16 (grey); inputs from CA3 or medial entorhinal cortex). Here we speculate that there are also independent distance inputs, with a variety of different distance modulation profiles, that arrive at CA1 (for example, from the lateral entorhinal cortex or from the subiculum through the medial entorhinal cortex), as well as inputs that carry attention or context signals (Extended Data Fig. 16). These converging streams are combined in CA1, generating multiple place fields with different distance modulations, similar to what we found experimentally. This model suggests a key computational role for dendrites in generating the complex distance-by-position tuning observed in CA1.

Overall, our results suggest that, during a natural behavioural switch, the same hippocampal neurons can switch between two different types of neural codes very rapidly and flexibly, reflecting the animal’s behavioural needs. This dynamic view of hippocampal function calls for future dynamic experiments designed to further elucidate how the hippocampus supports flexible natural behaviours.

Methods

Bats and behavioural set-up

Bats

Four adult male Egyptian fruit bats, Rousettus aegyptiacus, were included in this study for electrophysiological recordings (weight, 160–175 g). No randomization or blinding was applied in this study. Sample size was not predetermined; the number of animals is standard for studies in this research field. Information on the individual bats is summarized in Extended Data Table 1. An additional four bats were used for the behavioural assay as partners. All of the bats in this paper were caught as adults in the wild (in Israel). All experimental procedures were approved by the Institutional Animal Care and Use Committee of the Weizmann Institute of Science.

Set-up

Bats flew in pairs (two bats together in each experiment) in a long straight tunnel (135 m × 2.3 m × 2.35 m (length, width, height); Fig. 1a). This flight tunnel was part of a longer 200 m tunnel, and the 135 m straight part was blocked by an opaque curtain. The bats flew between two landing balls that were located at the two ends of the tunnel, at a distance of 125 m from each other. On these balls, the bats could rest and receive food. The tunnel was uniformly illuminated (illuminance level: 5 lux). To ensure that the bats were aware of their position, 10 unique landmarks were distributed randomly along the tunnel, and were positioned at fixed locations across all of the experiments.

Training

The bats were initially pretrained for ~2 weeks (15–20 min per day) to fly alone between two landing balls in small-scale environments (either a flight room of ~6 × 5 m, or a short ~6 m segment of the flight tunnel), with the aim of getting used to handling by humans, and learning to directly fly between the two landing balls. The bats were then introduced individually to the long tunnel (135 m) with three training aims: first, getting the bats used to the experimental set-up; second, enhancing flight stamina; and third, training them to fly direct flights between the landing balls without performing U-turns. Once they reached good flight performance (which took around 1–2 weeks), they were introduced to their partner and flew together in the tunnel for about 1 week before surgery.

After training, the bats were implanted with a microdrive for electrophysiological recordings in the dorsal hippocampal area CA1 (see below). Each experimental session started and ended with sleep sessions (each sleep session lasting 5–10 min). For the sleep sessions, the bat was placed alone inside a small covered cage which was positioned on the floor in a quiet location inside the tunnel.

Behavioural paradigm

A pair of bats flew together in the tunnel, performing direct flights between two landing balls. We considered two different behavioural modes (Fig. 1a,b and Extended Data Fig. 1): (1) Solo flights, in which one bat was flying alone and the other bat was resting, or when the distance between the bats was >40 m. (2) Cross-over flights, in which the two bats flew towards each other with an interbat distance of within ±40 m (for more details, see the ‘Extracting flights and dividing data to different behavioural modes’ section below). During cross-overs, the bats had to be attentive to avoid collision with the other bat as this is a relatively narrow tunnel and because the bats crossed each other at a very high combined relative speed of around 14 m s−1 (see Extended Data Table 1 for the speeds of individual bats). Although collision avoidance is a very natural behaviour for bats, it was by no means trivial—we actually had a few collisions or near-collisions between the bats during training, as well as during the experiments themselves (Extended Data Fig. 2g), emphasizing that the need to pay attention was not hypothetical.

The experimenters timed the bats’ take-offs from the two balls at both ends of the tunnel to create a nearly uniform coverage of cross-overs along the tunnel, which was roughly randomly distributed over time (Fig. 1c and Extended Data Fig. 1). The experimenters stood near to the landing balls at the two ends of the tunnel, and did not enter the central 125 m behavioural zone. The bats flew in total 13.14 ± 3.50 km per session (mean ± s.d.; the distance per bat is shown in Extended Data Table 1); the behavioural session lasted around 1.5–2 h.

For one pair of bats, we had two additional behavioural modes (recorded bat no. 30; Extended Data Table 1). (1) Tracking mode: the two bats flew in the same direction with a short interbat distance (one bat tracked the other with an interbat distance of less than ±20 m; Extended Data Fig. 9). (2) Obstacle-avoidance mode: in the middle of the session, we introduced a stationary obstacle (vertical pole) inside the tunnel, which the bats had to avoid colliding with. As we decided to focus here on cross-over behaviours with other bats, we removed epochs near to this stationary obstacle for those cells that showed significant modulation by the obstacle (this resulted in the removal of 0.49% of the flight data for the cells recorded with obstacle).

In another bat pair, we conducted an additional session in which we switched the partner bat. In the first session, the recorded bat (bat no. 2299) was flying with his usual partner for a full session of 1.5–2 h (session a), then it rested ~40–60 min and we then ran the experiment again with an alternative partner for another ~1 h (session b). The recorded bat was familiar with both the usual partner and the alternative partner before surgery. As this was a very long and physically demanding experiment for the recorded bat (the recorded bat flew 21.85 ± 2.07 km per day in these two sessions together (mean ± s.d.), while carrying the recording-devices on its head), we succeeded to run this two-session experiment for only 3 days. A comparison of neural recordings from these two sessions is shown in Extended Data Fig. 10.

The use of a long flight tunnel in our experiment was crucial for several reasons: (1) in such a large-scale set-up, the bats fly very fast, which enabled us to investigate hippocampal neural activity during fast behavioural switches. (2) As we knew that the bats respond to each other at a distance of approximately −20 m before cross-over (Fig. 1d,e), and as we wanted to record also baseline activity before that (for comparison), this required defining a large symmetric window of ±40 m as the cross-over flight, which necessitated a large-scale environment. (3) To examine the response to interbat distance irrespective of position, we needed to disentangle distance from position in the experiment, which required having cross-over events at different locations in the tunnel (Fig. 1c and Extended Data Fig. 1). This required a long tunnel. (4) As in large-scale environments there are multiple place fields for each place cell14, it enabled us to test whether different place fields of the same neuron exhibit different distance tuning (Fig. 5). This would not have been possible in small environments, in which typically only one place field is observed for each place cell14.

Animal localization system

We tracked the position of the bats using wireless radio-frequency localization tags (weight, 6.6 g, including battery; BeSpoon), which received and transmitted signals to an array of 14 ground-based antennas that were distributed around the tunnel. A spherical estimation of the tag’s distance from each antenna was computed on the basis of the time interval between the signal transmission and arrival. The position of the bat in 3D was then estimated using the intersection of these spheres from all of the antennas. This localization method yielded a good precision of around 9 cm in the longitudinal and lateral axes of the tunnel14, but the vertical precision was poorer, and we therefore did not use the height measurements for analysis. Each bat had his own tag with a unique ID; the position of each bat was computed at a sample rate of 12.8 Hz or 16 Hz. Both tags were synchronized to the neural recordings using a non-periodic sequence of TTL pulses (precision of <1 ms).

Extracting flights and dividing data to different behavioural modes

All data in this study were analysed using MATLAB. Location data from the localization system were processed as described in ref. 14. In brief, we first removed outliers (defined as data points that were far away (>2 m) perpendicularly from the tunnel’s midline, or data with unreasonably high speed (>20 m s−1)). We then linearized the data by projecting the valid positional data onto the long 1D axis of the tunnel. We then filled short gaps where data were missing, as described in ref. 14. Finally, the positional data were upsampled to 100 Hz.

We analysed only flight epochs, and excluded data from take-offs and landings: flight epochs were detected based on: (1) speed (>2 m s−1), and (2) distance from the landing balls (>3 m from the balls). In the cases in which the bat performed a U-turn in the middle of the tunnel, we discarded an extra 3 m before and after the U-turn event (beyond the 2 m s−1 speed threshold) to avoid contamination by possible ‘U-turn coding’.

We further divided the data to distinct behavioural modes on the basis of the localization data of the two bats and their flight direction:

  1. (1)

    Solo flights: the recorded bat was flying while the other bat was resting, or both bats were flying and the interbat distance was >40 m. The 40 m threshold was taken because bats are probably not attentive to the other bat at large distances of >40 m (see the next paragraph), and we therefore considered such large distances as if the bat was flying alone. Short solo flights that lasted less than 2 s (corresponding to around 14 m) were discarded from the analysis.

  2. (2)

    Cross-overs: the bats flew in opposite directions and passed each other. The cross-over event was defined as the point of interbat distance = 0, with the distance measured along the long axis of the tunnel. As cross-overs are momentary events, we considered a distance-window of ±40 m around each cross-over event, which we defined as a cross-over flight. The bats increased their echolocation rate at distances between −20 m and 0 m (Fig. 1d–f and Extended Data Fig. 2), which suggests that they are attending to the other bat at these distances1,2,3,4,5,6,7,8,9,38,39,40,41; to enable the analysis of an extra baseline, we considered a larger and symmetrical distance window of ±40 m, which enabled us to detect neuronal modulations and their return to baseline activity. Cross-overs that occurred less than 8 m from the landing balls were excluded from the analysis to avoid effects of landing and take-off (see the light grey vertical rectangles in Fig. 1c and Extended Data Fig. 1b,e). Furthermore, we excluded cross-over flights in which the two bats did not fly in opposite directions for at least 5 m before and 5 m after the cross-over event. Most of the valid cross-over flights were long (median, 80 m, which is also the maximum possible length of a cross-over flight, given our ±40 m analysis window); however, cross-over events that were close to landing balls or U-turns resulted in cross-over flights that were shorter than 80 m (mean cross-over flight length: 74.84 ± 11.36 m (mean ± s.d.); minimal length 20.77 m).

  3. (3)

    Tracking: the two bats flew in the same direction with an interbat distance of less than ±20 m. We further divided the tracking epochs to flights in which the recorded bat was following the other bat (interbat distance between −20 m and 0 m) and when the recoded bat was leading (interbat distance between 0 m and 20 m). Tracking behaviour was analysed only in bat no. 30, which was trained to perform many tracking flights: these analyses are shown in Extended Data Fig. 9. In all of the other bats we had only a few or no tracking flights during the session, and they were therefore not analysed.

Audio recording and click detection

Audio recording

In Egyptian fruit bats, echolocation consists of pairs of very short ultrasonic clicks5,6. To detect these clicks, we recorded the audio signal using an on-board audio logger with an ultrasonic microphone. As there is a limit to the weight that bats can carry, in most experiments we could not record simultaneously the audio signal (audio logger) together with the neuronal recordings (neural logger) and position (positioning tag). Thus, in two bat pairs (recorded bat–partner no.: 2336–2331 and 2389–2387) we recorded the audio signal separately in some of the days instead of recording neuronal data. For bat 30, audio was recorded using a different audio-logger device and therefore its click amplitude was not comparable with the other bats and was not analysed in Extended Data Fig. 2c (the click rate from bat 30 appears only in Extended Data Fig. 9b). In our last bat pair (recorded bat–partner no.: 2299–2331), a new miniature version of the data logger was developed, which enabled us to record simultaneously both the neuronal activity and the audio signal. Together, behavioural analyses of the bats’ echolocation were performed on n = 6 bats (Extended Data Figs. 2c and 9b), and analyses combing simultaneously recorded neural data and echolocation data were performed on one bat (bat no. 2299; Figs. 2e–g and 4g,h and Extended Data Figs. 7 and 13c,d). For all of the audio recordings, with all devices, audio signals were filtered online (in hardware) between 4–40 kHz, and were recorded at a 100 kHz sample rate (this frequency range covers most of the energy of the echolocation clicks of this bat species6).

Click detection

Detection of echolocation clicks emitted during flight was performed offline as follows: we first further high-pass-filtered the audio signal at 10 kHz, as the echolocation clicks of this species do not contain energy below 10 kHz6. We then normalized the signal by its mean absolute deviation (MAD) over the entire session—transforming the amplitude to a SNR. We then used an amplitude threshold of 50 MADs (that is, SNR = 50), which detected clicks reliably, together with several time-domain criteria on the basis of known properties of the sonar clicks of this bat species6: (1) duration of click of 30–2,500 μs; (2) maximum rise time of 500 μs; and (3) minimum inter-click interval of 10 ms. We also used a frequency criterion, consisting of a minimum energy ratio of 10 dB between a high-frequency band (18–40 kHz) and a low-frequency band (5–12 kHz). As we recorded audio signals from both bats, we could remove clicks originating from the other bat by estimating their expected time-of-arrival to the recorded bat’s microphone using the interbat distance (measured using the localization system) divided by the speed of sound: this enabled us to discard low-amplitude clicks (SNR = 50–200) emitted by the other bat, which were detected on the recorded bat’s microphone at these estimated timings ±3 ms (Extended Data Fig. 2a). In the bat with simultaneous audio and neural recordings, we also manually curated the detected clicks to further improve the click detection (1.77% manually added clicks, 0.01% removed clicks).

Surgery and neural recording techniques

All of the surgical procedures were performed as described previously14. In brief, after completion of training, bats were implanted with either a 4-tetrode microdrive (weight, 2.1 g; Neuralynx), or a 16-tetrode microdrive (weight, 3.4 g; modified from ref. 42), loaded with tetrodes, with each tetrode constructed from four strands of insulated wire (17.8 μm diameter platinum-iridium wire). Tetrodes were gold-plated to reduce the wire impedance to 0.3 MΩ (at 1 kHz). The microdrive was implanted above the right dorsal hippocampus (3.0–3.6 mm lateral to the midline and 5.8 mm anterior to the transverse sinus that runs between the posterior part of the cortex and the cerebellum); the craniotomy was then covered with an inert silicone elastomer (Kwik-Sil or Kwik-Cast). During the implantation surgery, we used an injectable anaesthesia cocktail composed of medetomidine (0.25 mg kg−1), midazolam (2.5 mg kg−1) and fentanyl (0.025 mg kg−1), and added supplemental injections as needed, based on the bat’s breathing and heart-rate43. The microdrive was attached to the skull with bone screws, using a layer of adhesive (Super-Bond C&B) followed by dental acrylic. We attached the ground wire from the microdrive to a bone-screw that touched the dura in the skull’s frontal plate.

After surgery, the tetrodes were slowly lowered towards the CA1 pyramidal layer; positioning of tetrodes in the layer was provisionally performed on the basis of the presence of high-frequency field oscillations (ripples) and associated neuronal firing, and was later verified histologically (Extended Data Fig. 3a). For each bat, one tetrode was left in an electrically quiet zone and served as a reference, and the remaining tetrodes served as recording probes.

During recordings, a wireless neural-recording device (neural-logger; 16-channels or 64-channels, Deuteron Technologies) was attached to a connector on the microdrive. Signals from all channels were amplified (×200) and bandpass filtered (1–7,000 Hz), and were then sampled continuously at 31.25 or 32 kHz per channel, and stored on board the neural-logger. During subsequent processing, the neural recording was further high-pass filtered with a 600 Hz cut-off for spikes, creating a spike bandwidth of 600–7,000 Hz, and then a voltage threshold was used for extracting 1 ms spike waveforms.

Histology

Histology was performed as described previously14. In brief, at the end of recordings, the bats were anaesthetized, and electrolytic lesions (DC positive current of 30 μA, 15-s duration) were made to assist in the precise reconstruction of tetrode positions. The bat was then given an overdose of sodium pentobarbital and, with tetrodes left in situ, was perfused transcardially using 4% paraformaldehyde or 4.5% Histofix. The brain was removed and thin coronal sections were cut at 30 μm intervals. The sections were Nissl-stained with cresyl violet and were photographed to determine the locations of tetrode tracks in the dorsal CA1 (Extended Data Fig. 3a). Recording sites were all located in the dorsal CA1 (except for one tetrode from one bat, which was possibly placed in CA2, that was also included in the dataset), and spanned the entire extent of the proximo-distal axis of CA1.

Spike sorting

Spike-sorting procedures were similar to those described previously13,14. In brief, spike waveforms were sorted manually using Plexon Offline Sorter, on the basis of their relative amplitudes on different channels of each tetrode. Data from all the behavioural sessions and sleep sessions from the same recording day were spike-sorted together. Well-isolated clusters of spikes were manually selected, and a refractory period (<2 ms) in the interspike-interval histogram was verified. Spike sorting was performed in consecutive time windows to allow for drift correction of the spike clusters.

In total, we recorded 499 well-isolated CA1 neurons from 4 bats. We further analysed only 430 neurons that were valid for analysis (see the inclusion-criteria below). Out of the 430 valid neurons, we detected 389 putative pyramidal neurons (90.5% of the cells; based on average firing rate <5 Hz during the entire recording session), and 41 putative interneurons (9.5%; firing rate ≥5 Hz). As hippocampal place cells are known to remap between movement directions in a linear track14,44,45 (Extended Data Fig. 3g), we separated all analyses into flight directions and considered each direction independently. Cells × directions were defined as valid for analysis on the basis of the following behavioural and neuronal inclusion criteria: (1) 10 or more cross-overs per flight direction; and (2) or (3), where: (2) a minimum of 50 spikes per direction during solo flights; (3) a minimum of 30 spikes per direction during cross-over flights. This resulted in 693 pyramidal cells × directions and 74 interneurons × directions that were valid for analysis in this paper.

Statistics

Unless otherwise noted, for all the pairwise comparisons, we used two-tailed (two-sided) statistical tests, with a probability threshold of P = 0.05. All correlations were based on a two-tailed Pearson’s correlation coefficient (except for a few cases in which we used non-parametric Spearman correlations, if the scatters were clearly non-Gaussian). We used two-sample Kolmogorov–Smirnov tests to compare distribution shapes. To determine the significance of place tuning and of distance tuning, we compared the real data with shuffled data (see below). When plotting shuffle tuning curves for neurons, we always plotted 5–95% of the shuffle tuning curves.

Position tuning, field detection and place cells classification

Position tuning

As explained above, we performed all analyses in this Article separately for the two flight directions. Tuning curves for 1D position (place tuning) were computed by counting the number of spikes and the time spent in each spatial bin (0.5 m bins). Bins with a time spent of <0.8 s were discarded from the analysis (corresponding to around 11 flights passing through that bin). Spike-count maps and time-spent maps were then smoothed (Gaussian kernel σ = 3 bins = 1.5 m), and we then divided, bin by bin, the smoothed 1D spike-count map by the smoothed 1D time-spent map. We computed the spatial information (SI) as follows: \({\rm{SI}}\left(\frac{{\rm{bits}}}{{\rm{spike}}}\right)=\sum _{{\rm{i}}}{p}_{i}\left(\frac{{r}_{i}}{\bar{r}}\right){\log }_{2}\left(\frac{{r}_{i}}{\bar{r}}\right)\), where ri is the firing rate of the cell in the ith bin, pi is the probability of the bat to be in this bin and \(\bar{r}\) is the mean firing rate of the cell.

Place cell classification

Place cells were classified using data from solo flights on the basis of the following inclusion criteria: (1) significant spatial information compared to shuffle (>99% of the shuffles): to shuffle the spike train, we rigidly and circularly shifted in time the spikes of each flight, using a uniform random shift; the value of the shift differed randomly between individual flights, so each shuffle consisted of a unique set of temporal shifts across the set of flights. We performed 1,000 such shuffles. (2) Spatial information was >0.25 bits per spike. (3) The cell emitted ≥50 spikes during solo flights. (4) The cell had at least one significant place field, as described next.

Place field detection

Place fields were detected during solo flights similarly to our previous study14: (1) First, we extracted local peaks in the firing rate map, with a peak rate of >0.5 Hz. (2) To remove small local peaks ‘riding’ on a large field, we searched for shallow ‘dips’, that is, cases in which the dip between two adjacent peaks was >50% of the firing rate of the larger peak, and then disregarded the lower peak. (3) We next defined the field width as the zone in which the firing rate was ≥20% of the peak firing rate of that place field. (4) Field stability criterion: we required at least five different laps with spikes to have occurred inside the place field, or 20% of the laps with spikes—whichever is larger. (5) Field significance criterion: to capture clear distinct fields, we treated a place field as significant only if it had significant spatial information in its local area, near the place field. To quantify this, we focused on the local area surrounding the place field (the width of the field itself plus 50% of the field’s width in each direction), and calculated the spatial information in this local area for the real spikes, and also for 1,000 shuffles (same rigid shuffling of spikes as above). We considered the field to be significant only if it had spatial information of >95% of the shuffles in the same local area.

1D distance tuning and classification of 1D distance cells

Distance tuning

Tuning curves for the 1D distance between the bats were computed by counting the number of spikes in each distance bin (2 m bins), and dividing it by the time spent in each bin. Bins with a time spent of <0.4 s were discarded from the analysis. The tuning curves were next smoothed (rectangular window of 3 bins). Note that the 1D interbat distance along the tunnel axis was highly correlated with the Euclidean distance between the bats and with the time to cross-over (Extended Data Fig. 4d–g; mean Pearson correlation: r = 0.99999 and r = 0.9987, respectively), so any of these variables could be used to analyse the data; for consistency with the 1D position coding, we focused on the 1D interbat distance along the tunnel.

Shuffles for distance tuning

For classifying neurons as 1D distance cells, we computed two types of shuffles, and required the neuron to be significant according to both types of shuffles: (1) cross-over data shuffle: this shuffle was aimed to test whether during cross-overs the neuron showed enhanced or suppressed distance responses relative to the cross-over data. We performed 10,000 rigid spike shuffles for the flight data, as we did for the place cell classification above, but here used the data from the cross-over flights. (2) Solo projected on cross-over shuffle: owing to the prominent position coding in the hippocampus, this shuffle was aimed to test whether during cross-overs the neuron showed enhanced or suppressed distance-responses relative to the expected response from the solo data. We performed 10,000 shuffles in which we projected the solo spikes onto the cross-over behavioural data as follows (illustrated in Extended Data Fig. 5a). For each cross-over flight, we pooled all of the solo flights that occurred within the same position in the tunnel and, for each shuffle, we randomly picked one solo flight out of this pool (Extended Data Fig. 5a (i and ii)). We then computed what should be the projected interbat distance of each spike that occurred during this solo flight on the basis of the cross-over flight data (using linear interpolation; Extended Data Fig. 5a (ii and iii)). This yielded 2D distance by position shuffle datasets of spikes that occurred during solo, projected onto the cross-over behaviour (Extended Data Fig. 5a (iv)). This entire process was repeated 10,000 times, creating nearly unique shuffle datasets (across cells, 99.99% of shuffles were based on unique sets of solo flights). This shuffle conserves the spiking statistics of the neuron and its position tuning. This shuffling procedure reflects the null hypothesis that the expected firing pattern of the neuron is driven only by the position along the tunnel, without exhibiting any tuning to interbat distance.

Significant bins

To detect significant 1D distance modulation of firing rate, we looked for bins along the interbat distance axis, which exhibited significantly high or significantly low firing rate compared with both types of shuffles. This was done as follows: we first smoothed with a three-bin rectangular window the real distance tuning curve and all of the shuffled tuning curves (this smoothing was performed to avoid detection of transient increase or decrease in firing rate). We next computed the percentile of each bin from the real distance tuning curve compared with the shuffles’ values for the same bin. To correct for multiple comparisons for the number of bins, we computed the average response width, and required the following corrected critical-value: \(\frac{\alpha }{{N}_{{\rm{total}}{\rm{bins}}}}\times {N}_{{\rm{bins}}{\rm{in}}{\rm{width}}}\), where: α = 5% (the standard critical-value significance criterion, before correction (95% shuffling)); Ntotal bins = 40 (total number of 2 m bins of distance within the ±40 m distance range); and Nbins in width = 4 (average response width = 4 bins = 8 m). This resulted in αcorrected = 0.5% (two-sided), that is, we considered the firing rate in this bin to be significant if it was above the 99.5% percentile or below the 0.5% percentile of the shuffles. To prevent edge effects, we removed significant bins from the edges of the ±40 m range (that is, if the first or last bin were significant). Moreover, in each of the shuffles, we considered bins to be significant only if they had at least one additional significant neighbouring bin (that is, we required ≥2 adjacent significant bins; single significant bins were discarded). Finally, we considered a bin to be significant only if it was significant at the 99.5% level according to both types of shuffles (cross-over shuffle, and solo projected on cross-over shuffle). This requirement to be significant according to two fundamentally different shuffling procedures ensured that only robust distance tuning would be detected.

Defining 1D distance cells

1D distance cells (cells with significant 1D distance tuning) were defined by analysing the 1D distance tuning, using the following criteria: (1) the 1D tuning had significant distance bins above or below both types of shuffles (as described above). (2) The cell emitted ≥30 spikes during cross-overs in that flight-direction. (3) Stability of the tuning curve: Pearson correlation of r ≥ 0.3 between distance tuning curves computed in even flights and odd flights. We note that most of the cells with significant 1D distance tuning were not purely tuned only to distance, but rather had complex 2D tuning to distance by position (Figs. 3a,g and 5).

Control for movement-related responses

During cross-overs, bats tended to slightly lower their speed and slightly deviate laterally to avoid colliding with each other (Extended Data Fig. 6b,c (speed and velocity Y, respectively)). To test whether the distance modulation of the neurons is genuine and is not due to neuronal responses to these movements, we reasoned that we can compute the tuning to these movement variables during solo flights to disentangle it from the cross-over effects: if a cell is modulated by a movement variable, we expect to see the same movement-related modulation both during solo and during cross-over flights. We considered three movement-related variables that could potentially modulate the firing rate of the cells—we focused on speed and velocity because previous studies have shown that some hippocampal neurons are sensitive to movement speed or to manoeuvring44,46: (1) speed: \(S=\sqrt{({{V}_{X}}^{2}+{{V}_{Y}}^{2})}\) where VX is the velocity along the long axis of the tunnel, X, and VY is the velocity along the lateral axis of the tunnel, Y (see Extended Data Fig. 6a for an illustration of the X,Y axes); (2) VY, velocity in the Y axis, reflecting deviation (manoeuvring) in the lateral axis of the tunnel; and (3) SY, speed in the Y axis (absolute Y velocity, irrespective of the direction of the deviation). The positional resolution along the Z axis was not high enough to analyse behavioural modulations in Z, but observations during the experiment indicated that the deviations in Z were small.

For each movement variable, we built solo tuning curves and cross-over tuning curves (Extended Data Fig. 6d–f). To compare between solo and cross-over, we limited the data from which we built both tuning curves to include the same range of flight speeds in both cases; the range was set to 5–95% of the flight speeds during cross-overs, computed separately for each bat. We computed the tuning curves as described above (see the ‘1D distance tuning and classification of 1D distance cells’ section), using bin sizes of 0.2 m s−1 for velocity Y and speed and 0.1 m s−1 for speed Y. To evaluate the significance, we used 10,000 circular shuffles of the spikes as follows: we concatenated all of the in-flight spikes across all of the flights (separately for solo and cross-over flights), and we then rigidly shifted the times of all of the spikes by a random time interval in a circular manner (with the end of the session wrapped to the beginning). For each shuffle, we computed velocity tuning and speed tuning as for the real data. We then fitted a linear function to these tuning curves for both the solo and cross-over data, as well as for their shuffles, as velocity and speed modulations were found to be approximately linear in the hippocampal formation47,48. We defined cells as significantly modulated by velocity or speed if the slope of the linear fit was >97.5% percentile or <2.5% percentile of those seen in the shuffles (with significance assessed separately for the solo and for the cross-over conditions; Extended Data Fig. 6g–i). In total, we performed 6 linear fits = 3 movement variables (S, VY, SY) × 2 behavioural modes (solo, cross-overs). We considered a cell to be movement-modulated by one of the variables if it was significantly modulated by this movement variable both in solo and in cross-over, and had the same slope direction of the tuning during both solo and cross-over. The results of these control analyses are shown and further elaborated in Extended Data Fig. 6 – which ruled out any major contribution by velocity or speed.

Control for sensory or motor responses to the echolocation clicks

To exclude the possibility that the observed distance tuning during cross-over is directly linked to the echolocation clicks—that is, reflects a direct sensory neuronal response to the clicks themselves (auditory responses) or a motor neuronal activity before individual clicks—we used the solo flights as a control. As during the solo flights bats also emit echolocation clicks (albeit at a lower rate; Fig. 1e (black error bar) and Extended Data Fig. 2b), we tested whether the neurons show any auditory/motor response to the clicks when appearing outside of the context of cross-overs, and examined whether such responses could explain the distance tuning observed during cross-overs. To this end, we computed click-triggered responses during solo flights at ±200 ms around each click, using 10 ms bins, and averaged the responses across clicks (Extended Data Fig. 7a (bottom, black lines)). We compared each click-triggered response to 10,000 shuffles (rigid circular shuffling of spikes within the ±200 ms time window around each click, similar to the shuffling described above for place tuning), and considered a bin to be significant if it was above the 99.5% percentile or below the 0.5% percentile of the shuffles (corrected for multiple comparisons as described above, assuming 4 bins = 40 ms for the minimal duration of sensory/motor response). To exclude transient and unreliable responses, we considered only modulations that were significant in two or more consecutive bins. This analysis was performed on all of the 1D distance cells that were recorded simultaneously with audio (n= 41 cells × directions). The results of these control analyses are shown in Extended Data Fig. 7a–d and they strongly argue against the possibility that the 1D distance tuning could be explained by sensory or motor responses to clicks.

Modulation of the 1D distance tuning curve by attention

To test how attention modulates the distance tuning curves and firing rates of the neurons during cross-overs, we used the increase in echolocation click rate as an index of attention1,2,3,4,5,6,7,8,9,38,39,40,41. For 1D distance cells that were recorded simultaneously with audio (which was performed in one bat), we divided the cross-over flights into two equally sized groups according to the click rate (median bisection). This yielded two sets of flights: flights with high click rate versus flights with low click rate (reflecting high versus low attention). We then computed the tuning curves separately for these two sets of flights (as done above for the full 1D tuning curves). The separation to flights with high and low click rates was based on the mean click rate in a distance window between −15 to 0 m (this distance window matches the typical region in which the click rate was increased during cross-overs; Fig. 1e and Extended Data Fig. 2c). Click-rate tuning curves were computed for each individual cross-over flight (using a bin size of 2 m and smoothing by a Gaussian kernel with σ = 1.5 bins). We included in this analysis only valid flights that met the following criteria: (1) the flight had enough continuous distance data (from −25 to 5 m with no gaps; 4.4% of the flights were excluded); (2) the peak click rate was greater than 10 Hz—this threshold was used to exclude rare atypical cases of very sparse use of echolocation (on average 2.56 flights per direction per session were excluded, 5.6% of the flights in total); and (3) more than twofold change in sonar click rate during cross-over relative to the preceding minimum—here we removed atypical flights with almost no modulation of sonar click rate along the cross-over flight (this excluded 2.8% of the flights).

After applying these criteria for valid flights, we included in this analysis only cells that had 20 or more valid cross-over flights, and 30 or more spikes in high-attention trials or low-attention trials (similar to the requirement of 30 spikes in the main analysis of 1D distance tuning). This left for analysis n = 37 cells × directions out of the n= 41 total 1D distance cells that were recorded simultaneously with audio.

To examine the difference between the tuning curves in high-attention versus low-attention flights, we focused on a window of ±10 m around the peak firing rate of each cell (peak firing rate of the 1D distance tuning curve using all cross-over flights), and computed within this window two quantities: (1) the rate difference of the peak firing rates between the high-attention tuning curve and the low-attention tuning-curve, and (2) the rate difference of the mean firing rates between the two tuning curves. For significance, we divided randomly 10,000 times the cross-over flights into two groups, and computed the same two quantities, resulting in two shuffle distributions (Extended Data Fig. 7e (bottom row)). Cells that were higher than the 95th percentile in one of these shuffle distributions were defined as significantly attention modulated (n = 11 cells × directions, comprising 29.7% of the cells in this analysis; see Fig. 2e and Extended Data Fig. 7e for examples and Fig. 2f,g for the population).

Testing for position representation of the other bat

To test whether during cross-overs there is representation of the position of the other bat in world coordinates (that is, representation of the other bat’s allocentric position)—as opposed to representation of the distance from the other bat—we computed the corresponding 1D tuning curve: the firing rate of the neuron as a function of the position of the other bat (using the same procedure as described above for the tuning curve for self position). We defined a cell to be significantly tuned for position of the other bat if it passed the following criteria: (1) criteria identical to those used for determining position tuning for self place cells: (i) significant spatial information (99% percentile) compared to shuffles; (ii) spatial information was >0.25 bits per spike. (2) Criteria identical to those used for determining distance tuning during cross-over, as here the analysis was done during cross-over flights: (i) the cell emitted ≥30 spikes during cross-over flights; (ii) stability of the tuning-curve over even and odd flights: Pearson correlation of r ≥ 0.3 between these tuning curves. The results of these control analyses are shown and further elaborated in Extended Data Fig. 8, ruling out the possibility that, in this particular experiment, the bat’s hippocampal CA1 cells represented the position of the other bat; rather, the neurons represented the distance to it.

Distance tuning within place fields and between place fields (within interfields)

Computation of the 1D distance tuning curves within place fields (Fig. 3a and Extended Data Fig. 11a) was performed on the cross-over data, using only segments of behavioural data and neuronal data that occurred within the place field (the place field was defined during solo-flights, as described above). For computing the 1D distance tuning curves in interfield areas (between place fields), the interfield area was defined as follows: after we expanded each place field by 50% of its width to both sides (thus adding extra margins), the remaining areas between these expansions were defined as interfields. These extra margins were removed to prevent leakage of spikes from the adjacent place fields into the interfield. We then computed the 1D distance tuning curves for data within fields/interfields in the same way as it was computed for the entire cross-over data (described above), with small modifications to account for the smaller amount of data available within fields/interfields: (1) we used larger distance bins (2.6667 m; 30 bins); and (2) we discarded bins with less than 0.1 s time spent. To include place fields and interfields with good coverage and reliable spiking, we analysed only tuning curves with at least 30 spikes (as in the 1D tuning curve) and for which at least 80% of the distance bins were valid (above the minimal time spent of 0.1 s). Note that most interfields had, by definition, a small number of spikes, and their tuning could therefore not be analysed reliably (n = 87 interfields were valid for analysis). The resulting 1D tuning curves were based on 20.87 ± 6.55 flights per place field and 29.41 ± 12.38 flights per interfield (mean ± s.d., across all place fields or interfields).

Significant bins

To identify significant bins in these tuning curves (within fields/interfields), we performed a similar analysis as described above for the full cross-over data, but with slight modifications to account for the smaller amount of data. After finding the significant bins in both types of shuffles as described above (cross-over rigid shuffles and solo projected on cross-over shuffles), we removed significant bins at the edges of the distance range. We then considered a bin to be significant if it was significant in one type of shuffle (above the 99.5% percentile or below the 0.5% percentile of the shuffles, that is, corrected for multiple comparisons as described above), and was also above the 95% percentile or below the 5% percentile of the other type of shuffle. We required that the number of flights that contributed to a significant distance field (the consecutive set of significant bins) was at least two flights. The number of flights differed between narrow and wide fields; across the population, the mean number of flights per distance field was 8.13 ± 4.12 (mean ± s.d.).

Switch time

To quantify how rapidly place cells can change their representation from representing position to representing distance by position (Fig. 3c and Extended Data Fig. 11e), we analysed switch times for individual place fields. We first recomputed the tuning curve within the place field in terms of time to cross-over rather than interbat distance (using the same number of bins). As time to cross-over and interbat distance are highly correlated (Extended Data Fig. 4d,e; Pearson r= 0.9987 ± 0.0009 (mean ± s.d.)), the tuning curves were highly similar to each other. We next created a shuffle distribution using the cross-over rigid shuffling (as above), and computed the median of these shuffles per time bin. We upsampled (×10) both the real data and the median shuffle tuning curves to get finer temporal resolution. We next computed the time difference between the time point at which the real data crossed the median of the shuffle, and the time point of the first significant bin, and defined this time difference as the rise time for enhancement and fall time for suppression (Fig. 3c (dark green in the top plot and dark brown in the bottom plot)). Similarly, we defined the time difference between the time point of the last significant bin and the time point at which the data subsequently crossed the median of the shuffle as the fall time for enhancement and rise time for suppression (Fig. 3c (light green at the top and light brown at the bottom; see the arrows)). We computed these switch times only for tuning-curves with one significant enhancement or one significant suppression (not both), and only when the modulation crossed the median shuffle on both sides, resulting in n = 204 fields (out of a total of n = 303 significant fields), of which n = 143 were enhancement tuning curves and n = 61 were suppression tuning curves.

Distance-tuning correlations between place fields

In Fig. 5b,c (correlations of distance tunings between place fields), we excluded pairs of tuning curves if both place fields did not have significant distance modulations to avoid correlating small random noises, or if the position gap between the place fields was smaller than half their average width to avoid ‘leaking’ of spikes from one field to the other.

2D firing rate maps for distance by position, and patch analysis

Firing rate maps

2D firing-rate maps for interbat distance by position were computed by counting spikes and time spent in each 2D bin (bin size: 3 × 3 m), which resulted in two 2D maps—a spike-count map and a time-spent map. Bins with time spent <0.2 s were discarded from the analysis, unless an adjacent bin was visited. We smoothed the spike map and the time-spent map with a 2D Gaussian kernel (σ = 1.5 bins = 4.5 m). The 2D firing rate map was then computed by dividing bin by bin the smoothed spike-count map by the smoothed time-spent map. Note that identical binning and smoothing were also used for plotting 2D distance-by-position maps of click rate and velocity (Fig. 1f and Extended Data Figs. 2d and 6b,c).

Patch analysis

To find regions in the 2D firing-rate maps for distance by position that were significantly modulated (significant 2D patches; Fig. 3f and Extended Data Fig. 12e,f), we used cluster-based analysis49,50. This method, which is widely used for analysing data from functional magnetic resonance imaging and electroencephalography experiments, searches for contiguous groups of significantly modulated bins or pixels. First, we compared the firing rates in each bin of the real 2D map with the firing rates in the same bin in all 10,000 shuffle maps (using solo projected on cross-over shuffling; see Extended Data Fig. 5c for examples of shuffle maps), and computed the P value for each bin on the basis of its percentile compared with all the shuffle maps. Here we used the solo projected on cross-over shuffle because it accounts for the prominent position coding in the hippocampus, and it reflects the null hypothesis of how a neuron would have responded if it was only place-tuned and was not modulated by the interbat distance (see above for the description of this shuffling; Extended Data Fig. 5a,c). Second, neighbouring bins that passed a significance threshold of P > 0.995 were clustered together as enhancement clusters, and neighbouring bins that passed a threshold of P < 0.005 were clustered together as suppression clusters. For each cluster, we computed the surprise values for each bin (surprise was defined as –log10[P] for suppression clusters and –log10[1 − P] for enhancement clusters). We then summed the surprise values over all of the bins in that cluster to get the cluster score. We did this entire procedure (first and second step) both for the data 2D map and for all 10,000 shuffle 2D maps (treating each shuffle map as if it was a data map). Third and finally, we then compared the cluster scores in the data 2D map with the distribution of the highest cluster score in each shuffle 2D map (separately for enhancement and suppression). We considered clusters that were ranked above the 95% percentile compared with the shuffle as significant 2D patches. We then considered only 2D patches that passed additional two criteria, both of which were aimed to accept only patches that were based on enough behavioural-data: (1) at least 2 s of total flight time inside the 2D patch; and (2) on average at least 0.15 s of flight time for each bin in the patch (3 × 3 m bins). Moreover, we used three spike-based criteria for enhancement patches only (not for suppression patches)—these criteria were aimed to accept only enhancement patches that contained enough spikes: (1) at least 20 spikes inside the 2D patch, (2) average of at least 0.5 spikes per bin, and (3) at least 3 flights with spikes inside the 2D patch. We performed this analysis on all of the pyramidal cells that had a peak firing rate of ≥2 Hz in their 2D map (n = 607 cells × directions). Applying all the above criteria enabled us to conduct the analysis only on cells with reliable behavioural coverage and robust firing rates. Note that the patches were generally quite localized along the distance axis (the median distance patch width was 24.6 m for enhancement patches and 18.5 m for suppression patches, with the median taken over the maximum distance width for each patch; the median over the average width for each patch was 16.9 m for enhancement patches and 12.3 m for suppression patches).

Defining 2D distance-by-position cells

A cell was defined as a significant 2D distance-by-position cell if either: (1) it had significant modulation of firing rate within a place field or interfield (see above; Fig. 3a,d and Extended Data Figs. 11 and 12a–d); or (2) it had a significant patch within the 2D distance by position map (see above; Fig. 3f and Extended Data Fig. 12e,f). These were the n = 366 cells × directions that were marked as cells with 2D distance by position tuning in Fig. 3g (purple ellipse).

Decoding analysis

We simultaneously decoded the interbat distance and the position of the bat during cross-overs (Fig. 4e–h and Extended Data Fig. 13) using a Bayesian maximum-likelihood decoder11,51. Decoding was performed for each flight direction separately. We performed leave-one-out cross-validation, in which each cross-over flight served as test data, while the remaining flights were used to build the 2D firing-rate map for each cell (train data). We analysed only sessions with ≥10 simultaneously recorded cells (16 sessions; n = 13.19 ± 3.08 cells per session (mean ± s.d.); for the decoding analysis, we included all cells without any exclusion criteria).

The decoded position and interbat distance at every moment were those that maximized the log-likelihood function, assuming Poisson firing, that is, maximized:

$$A({x}_{D},{x}_{P}| \{{{\bf{n}}}_{i}\})=\mathop{\sum }\limits_{i=1}^{N}{n}_{i}\log [\tau {f}_{DP,i}({x}_{D},{x}_{P})]-\tau \mathop{\sum }\limits_{i=1}^{N}{f}_{DP,i}({x}_{D},{x}_{P})+\log [P({x}_{D},{x}_{P})]$$

The term on the left denotes the log-likelihood of the bat being located in a specific combination of (distance, position) = (xD,xP) given the observation of a vector of {ni} spikes in each of the N neurons. On the right, the first term corresponds to a sum of the log of the spatial tunings of all neurons (that is, \({f}_{DP,i}({x}_{D},{x}_{P})\)), weighted by their activity (ni) in the integration window τ, that is, the time bin used for decoding (we used τ = 1 s, with a 250 ms overlap: a relatively long time window, which was used due to the relatively small number of neurons). The second term corresponds to a correction for unequal coverage of the neuronal representation in different locations. The third term on the right side corresponds to the prior for the decoding (P(xD,xP)), which is needed due to the non-perfectly-uniform behaviour (time spent in the 2D distance by position space). The decoded position and distance coordinates were then taken as the combination that maximizes A(xD,xP|{ni}), that is, the maximum of the log-likelihood function.

In Fig. 4c, we used the same type of decoding, but instead of using the 2D firing-rate map we used the 1D position tuning computed based on the solo flights to decode the position during cross-over flights (Fig. 4c (pink)). Chance error was estimated by computing the median difference between the actual (real) positions and 100 random positions, which were sampled from the experimentally measured behaviour of the animal, to account for non-homogeneous behaviour (Fig. 4c (grey)).

In Fig. 4a–d, we used a 10 m distance sliding-window (2 m steps), and computed position tuning curves during cross-over flights separately for each distance window. These were then used to compute correlations with solo position tuning (Fig. 4a), spatial information (Fig. 4b) and mean normalized firing rate (Fig. 4d).

SVD analysis

To quantify the non-separability of the 2D distance-by-position coding, we performed a singular value decomposition (SVD) analysis on the 2D distance by position firing-rate map, denoted here by the matrix M. This is a standard analysis performed in neuroscience to assess the separability of 2D coding31,32,33,36,52. In this analysis, we decompose the matrix M (throughout this analysis, the matrix M was always mean-subtracted before the SVD decomposition):

$$M=U\times S\times {V}^{T}$$

Here U and V are matrices containing the singular vectors corresponding to the position and distance axes, respectively, and S is a diagonal matrix with non-negative singular values (sj in descending order); the superscript T denotes matrix transpose. This analysis enabled us to test whether the matrix M, namely the 2D distance by position firing-rate map, is completely separable, which means that it equals the first column vector in U multiplied by the first column vector in V × s1 (see Extended Data Fig. 14a (cell 117), where the first dimension, that is, the multiplication of the first two vectors, is almost identical to the original matrix); otherwise the matrix M is non-separable and requires additional terms, each being a product of vectors from U and V scaled by the corresponding sj (Extended Data Fig. 14a (cells 325 and 235)). We computed two types of measures to quantify the non-separability, based on the singular values. These measures, λ and α, were: (1) λ is the exponential decay fitted to the singular values: \({s}_{j}=a\times {e}^{\frac{-j}{\lambda }}\). For separable cells, the decay is fast, that is, λ is small, whereas, for non-separable cells, λ is large. (2) \(\alpha =1-\frac{{s}_{1}^{2}}{\mathop{\sum }\limits_{j=1}^{n}{s}_{j}^{2}}\): the fraction of variation in M that is not captured by the first singular value s1. For separable cells the first singular value is large relative to the subsequent singular values, and therefore α is close to zero; by contrast, non-separable cells have larger values of α (ref. 31). Note that these two measures, λ and α, are highly correlated among themselves (Pearson r = 0.98, P = 7.1 × 10–172, n= 262 cells × directions).

As SVD analysis requires a rectangular matrix M, and our 2D firing-rate maps were non-rectangular (see the 2D distance by position maps in Fig. 2a), we cropped our 2D map along the position axis (y) such that in each row we will have at least 80% valid distance bins (80% of the ±40 m range). We computed the 2D firing rate map again using only spikes and behavioural data that occurred within this cropped position area (this cropping is the reason for the smaller y-range (positions) of the maps in Fig. 5e as compared to Fig. 2a). To create a full rectangular map as SVD requires (that is, to fill non-visited bins in the 2D map) we used the following iterative procedure to estimate the matrix entries while not adding any excess non-separability: (1) we initially filled-in the empty bins on the basis of the local mean firing rate of the neighbouring bins; this created a full matrix, Mfirst iteration. (2) We next computed the SVD for this new full matrix Mfirst iteration, and changed the values of the original empty bins to values computed from the first 10 singular values and vectors, resulting in a new matrix, Msecond iteration (using a large number of 10 singular values ensured that this estimation procedure would not restrict the map dimensionality). We then computed the sum of squared differences between the current matrix Msecond iteration and matrix Mfirst iteration. (3) We iteratively continued to change the values of these bins by computing the SVD and building a new matrix Mi, and then computing the sum-of-squared-differences between the current matrix Mi and the previous matrix Mi − 1, until reaching convergence (sum of squared difference smaller than 0.001). The final matrix used in this analysis was referred to as MSVD, which is rectangular and has no empty bins.

We conducted SVD analysis only on pyramidal cells with significant distance modulation either in 1D or 2D that met the following criteria. Criteria on behavioural coverage: (1) the length of the position axis of the cropped rectangle was ≥45 m. (2) The largest position gap between adjacent cross-over flights was <10 m (that is, there were no large ‘holes’ in the behavioural coverage). (3) The number of cross-overs in the cropped map was >10. Criteria on spiking: (4) the number of spikes in the cropped map was >30. (5) The peak firing rate in the cropped 2D map was >2 Hz. Applying these criteria enabled us to conduct the analysis only on cells with reliable behavioural coverage and robust firing rates (n = 262 cells × directions).

To assess the significance of λ and α, we used as shuffles our 2D matrices from the solo projected on cross-over shuffle (see above; and see examples in Extended Data Fig. 5c). These maps were cropped and filled in the same way as the data map, and as by definition they exhibit only position tuning, we multiplied each row of the 2D matrix by the 1D distance tuning of the cell (Extended Data Fig. 14c (bottom panel in each shuffle); multiplied map). This results in matrices with the same behavioural data, the same spike statistics and the same 1D distance tuning as in the real data, but these ‘multiplied maps’ are almost separable, and any non-separability that we would measure in them must therefore arise from non-uniform coverage of bat behaviour or from noisy spiking. Thus, by comparing the 2D data maps to these shuffles, we can test whether the detected non-separability in the cell’s 2D data map is genuine, or whether it originates from noisy spiking or from non-homogenous behaviour. Cells were defined as significantly non-separable cells if both their λ and α were above the 95% percentile of the shuffle distribution, and their rounded projection dimension was ≥1 in the cross-validation test (see below).

Cross-validated SVD

We also performed a cross-validated SVD analysis to assess the dimensionality of the matrix53 (Extended Data Fig. 14d). Here we divided the bins in the matrix MSVD into train bins (90%) and test bins (10%, which were randomly picked for each of the 1,000 iterations of the cross-validation). We first set the values of the 10% test bins to the average value of the entire matrix MSVD. We then used SVD to reconstruct this matrix (90% real data, 10% set to the mean value) with increasing cumulative dimensions (for example, cumulative dimension 2 = U1 × s1 × V1T + U2 × s2 × V2T; x axis in the bottom left panel of each cell in Extended Data Fig. 14d). We iteratively changed the test bins using the same method as described above for filling-in the empty bins, until reaching convergence. We next computed (separately for the test and the train bins) the mean squared error between the values of the original bins and the values in the new reconstructed matrix using different cumulative dimensions. For the training bins, it is guaranteed that the error decreases as we add more dimensions (that is, as we increase the cumulative dimension). However, for the test bins, the error will decrease only if the added dimension indeed describes the data; thus, at some point, the error will start to increase when adding more dimensions because the additional dimensions are over-fitted to the training portion of the data, and therefore effectively add noise. We therefore define the cumulative dimension with the minimal test error as the meaningful dimension of the data (Extended Data Fig. 14d (bottom left panel in each cell): minimum of red curves). Finally, to remove any non-separability that may result from the non-uniform behavioural coverage, we carried out the same procedure also for the median map of the solo projected on cross-over shuffles (Extended Data Fig. 14d (right column for each cell)). Then, to assess the real dimensionality of our data, excluding the behavioural dimensionality, we computed the projection dimension: for each of the 2D matrices—the cross-over data matrix and the solo-median matrix—we took only the meaningful vectors from U and V (all of the vectors until and including the meaningful dimension); and projected the vectors of the solo median map out of these data vectors. This results in a subspace that is orthogonal to the solo median map space and therefore does not contain the behavioural dimensionality anymore:

$${U}_{p}={U}_{{\rm{data}}}-\left({U}_{{\rm{solo}}}\times {U}_{{\rm{solo}}}^{T}\right)\times {U}_{{\rm{data}}}$$
$${V}_{p}={V}_{{\rm{data}}}-\left({V}_{{\rm{solo}}}\times {V}_{{\rm{solo}}}^{T}\right)\times {V}_{{\rm{data}}}$$

where Udata and Vdata are matrices containing the meaningful vectors of the data, and Usolo and Vsolo are matrices containing the meaningful vectors of the solo median map. Then, the projection dimension of the data excluding the behavioural dimensionality was computed as the minimum of the sum of the normalized projected vectors:

$${\rm{projection}}\,{\rm{dimension}}=\min \left(\mathop{\sum }\limits_{i=1}^{N}{U}_{{p}_{i}}^{2},\mathop{\sum }\limits_{i=1}^{N}{V}_{{p}_{i}}^{2}\right)$$

Model of 2D distance by position maps, and decoding the model’s simulations

To assess the possible functional role of the observed non-separable maps (Figs. 3a and 5), we created populations of neurons with simulated distance by position maps, and systematically studied the effect of map separability on decoding performance. All of the simulations were conducted using MATLAB.

In our simulations, the bin size was 0.5 m both for the distance coordinate (xD, interbat distance; between ±40 m) and for the position coordinate (xP, position in the tunnel; between 0–130 m; we simulated the 130 m that were effectively covered by the bats). We note that below we make repeated use of the gamma distribution, defined by a shape parameter k and a scale parameter θ, to fit the model to the empirical data. The 2D distance by position map of neuron i is denoted below by fDP,i(xD,xP).

Position encoding

Position tunings were generated using a similar procedure as in our previous work14, with slight modifications of the parameters to fit the current experimental dataset. In brief, for each model neuron, we randomly picked a position coverage value from a gamma distribution that was fit to the data (kcoverage = 1.76, θcoverage = 0.18); if this sample value was larger than 0.8, we resampled. Next, we sampled field sizes from a gamma distribution fitted to the data (kfield-size = 4.62, θfield-size = 2.68 m), adding fields until the cumulative (total) sizes of all fields reached the coverage value. This number of place fields is denoted nfield. Then, the field locations were randomly and uniformly distributed along the environment, with no overlaps. To avoid distorting the uniform distribution of fields near the boundaries of the environment, we allowed fields to be located anywhere and we truncated them at the boundaries. This procedure created cells with multiple place fields, where the sizes of the fields of the same neuron were broadly distributed, as seen in the experimental data.

Distance modulation

Distance modulation profiles were generated as follows. For each neuron, the number of distinct distance profiles was set to ndis = nfield × xsep (rounded up, where xsep is a parameter controlling the degree of non-separability). We varied xsep between 0.2 and 1 in jumps of 0.2 (Extended Data Fig. 15a (columns)). Each field was assigned with one of the ndis modulation profiles. When ndis = 1, all fields undergo the same distance modulation (maximal separability), and when ndis = nfields, each field undergoes different distance modulation (maximal non-separability). We generated ndis sets of field-modulation values: distance modulation was enhancing/suppressing/not modulated with a probability of 0.38/0.20/0.42, respectively (numbers fitted to the experimental data). Across the population, the average number of fields that underwent distance modulation was independent of xsep because the probabilities (0.38/0.20/0.42) were independent of xsep. The centre location of each distance-modulation profile was sampled from a Gaussian distribution (µ = 0 and σ = 16.8 m; fitted to the experimental data), and the profile width was sampled from a uniform distribution between 4.3–12.9 m (the average of that distribution was matched to the experimental data). When a field is enhanced/suppressed, the firing rate in the region modulated by the distance coordinate was multiplied by a factor sampled from a gamma distribution (kenhance = 9.98, θenhance = 0.32; ksuppress = 0.39, θsuppress = 0.17; fitted to the experimental data).

We also added 2D distance-by-position modulation irrespective of place fields (Extended Data Fig. 15a (hotspots)), to reflect better the experimental data, where activation hotspots were found in the interfield analysis (Fig. 3d and Extended Data Fig. 12a) and in the patch analysis (Fig. 3f and Extended Data Fig. 12e,f). The distance-by-position firing rate map of each neuron had a hotspot with probability (xsep − 0.2)/0.8 (that is, no hotspots when xsep = 0.2 and one hotspot for each neuron when xsep = 1). The size, position and increase in firing rate of the hotspot was sampled similarly to the distance enhancement modulation profile. The position of the hotspot centre was sampled uniformly.

Quantifying the non-separability of maps

The parameter xsep enabled us to create 2D distance-by-position maps fDP,i(xD, xP) with differing non-separability levels (Extended Data Fig. 15a (columns)). After maps were generated, we computed for each 2D map the non-separability indices of the SVD analysis, λ and α, as we did for the experimental maps (Fig. 5e–g; see the definitions of λ and α in the ‘SVD analysis’ section above).

Generating spike counts for decoding analysis

We assumed that the animal starts each iteration (each ‘simulation-trial’) at a position xP = x0P in the tunnel (between 0 and 130 m) at a distance xD = x0D from the other bat (between ±40 m). Both animals fly at a speed of v = 8 m s−1 for a time interval Δt = 500 ms, in opposite directions. The expected spike count of the neuron during that trial is based on the bat’s trajectory through the 2D map fDP,i(xD, xP), and is given by:

$${m}_{i}=\frac{{m}_{0}}{\Delta t}{\int }_{0}^{\Delta t}{f}_{DP,i}({x}_{0D}+2vt,{x}_{0P}+vt){\rm{d}}t$$

where m0 is the in-field expected spike count without distance modulation: we used m0 = 5 in all our simulations, as in ref. 14. The factor 2 in x0D + 2vt reflects the double distance travelled when each of the two bats flies at a speed v towards the other. The actual spike count in each trial was drawn from a Poisson distribution with rate mi, and is denoted below as ni.

Decoding

We employed two commonly used types of decoders: a maximum-likelihood decoder and a population vector decoder.

For the maximum likelihood (ML) decoder, we computed the log-likelihood for each neuron, and summed over the N neurons11,14,51:

$${A}_{{\rm{ML}}}\left({x}_{D},{x}_{P}| \left\{{n}_{i}\right\}\right)=\mathop{\sum }\limits_{i=1}^{N}{n}_{i}\log [{m}_{0}\,{f}_{DP,i}({x}_{D},{x}_{P})]-{m}_{0}\mathop{\sum }\limits_{i=1}^{N}{f}_{DP,i}({x}_{D},{x}_{P})$$

The term on the left side denotes the log-likelihood of the simulated bat being located in a specific combination of (distance, position) = (xD, xP) given the observation of a set of {ni} spikes in each of the neurons i. On the right side, the first term corresponds to a sum of the log of the spatial tunings of all neurons, weighted by their activity; the second term corresponds to a correction for unequal coverage of the neuronal representation in different locations. This equation is very similar to the equation used for decoding the data, with the main difference being that here we created a uniform coverage and therefore did not include a term for the prior. This is an approximation of the likelihood function, where the decoder knows each neuron’s firing rate map (that is, fDP,i(xD, xP)), but it does not rely on continuously computing a convolution of the firing rate map with the animal’s motion and the other animal’s motion. The decoded position and distance coordinates were then taken as the combination that maximizes AML(xD, xP|{ni}), that is, the maximum of the log-likelihood function.

We considered population sizes N between 20 and 200 neurons, in jumps of 20. For each value of xsep and N, we generated 250 random populations. For each population, decoding was done in 41 equally spaced distances (between ±40 m) and 11 equally spaced positions (between 0 and 130 m), that is, 451 combinations of distance by position; we used a larger number of distances as in this study we focused on the distance modulation. For each distance-by-position combination, spike counts were randomly generated five times. Decoding errors were computed after grouping the data in three different ways: (1) based on the non-separability parameter used to generate the maps, xsep (Extended Data Fig. 15d,e); (2) based on the λ value of the SVD analysis computed post hoc for each population (Fig. 5h,i); and (3) based on the α value of the SVD analysis computed post hoc (Extended Data Fig. 15b,c). All three groupings yielded similar results and similar conclusions from the decoder simulations.

Population vector (PV) decoder: the classical PV decoder54,55 was adapted to the case in which the stimulus space (that is, the environment) is not circular, and in which neurons can represent more than one location and distance. In each trial, we computed the following sum over the N neurons:

$${A}_{{\rm{PV}}}\left({x}_{D},{x}_{P}| \left\{{{\rm{n}}}_{i}\right\}\right)=\mathop{\sum }\limits_{i=1}^{N}{n}_{i}\log [{m}_{0}\,{f}_{DP,i}({x}_{D},{x}_{P})]$$

The decoded location was then taken as the one that maximizes \({A}_{{\rm{PV}}}({x}_{D},{x}_{P}| \{{{\rm{n}}}_{i}\})\).

Additional discussion

Our results are distinct from previous reports. (1) Two studies tested how brief switches in the environment affect hippocampal activity56,57: these studies used non-ethological manipulations such as teleportation56 or rotating-platform57, whereas here we focused on natural behavioural switches. Moreover, these two studies56,57 reported switching between two position maps, whereas here we found switching from position representation to distance-by-position representation. Furthermore, both studies found that different place cells encode the two different position maps at different time points, whereas in our data, the same cells encoded conjunctively distance by position at the same time. (2) Our results are also different from studies that examined hippocampal spatial representation in response to objects that were moved within the arena between trials, but remained stationary within a trial and, therefore, did not evoke a behavioural switch15,16. They found neurons that exhibited spatial tuning either with respect to the room or to object coordinates, but not to both conjunctively, whereas, in our data, the same cells encoded conjunctively distance by position at the same time. (3) Our results are fundamentally different from classical remapping studies58,59, in which the hippocampus exhibits different position maps when the animal explores different environments in two different sessions. In such studies, there is no behavioural switch at all, because it typically takes a very long time (timescales of minutes) to transfer the animal between the different sessions and, therefore, such studies are not designed to examine rapid behavioural and neuronal switches, as we did here (with timescales as fast as ~100 ms). (4) Our results are also different from our previous findings of encoding of distance to a stationary goal19, as here we focused on representation of a moving conspecific, which required a very rapid switch of attention, in contrast to the previous study. (5) Finally, our results also differ fundamentally from our previous study, which found CA1 neurons that represent the position of another bat when the recorded bat is stationary60, as here we did not find CA1 neurons that encode the position of the other bat (Extended Data Fig. 8). This difference may stem from task requirements—in the previous study60, it was behaviourally important to represent the other bat’s position, whereas here it was important to represent the interbat distance in the context of collision avoidance; we suggest that these major differences in behavioural demands were reflected in the hippocampal neural codes.

Our results showing a non-separable neural code may reflect the non-separable aspect of natural behaviour in the wild. Navigation behaviours typically depend on the location where they happen, for example, commuting in one location versus foraging in another location61. This non-separability of behaviour was demonstrated also for collision-avoidance behaviours, for example, in bats that avoid wind turbines differently based on their location62, or in social-foraging bats, which respond differently to their conspecifics at different locations63. We speculate that the hippocampal system evolved to support (together with other brain areas) the animal’s ability to perform these challenging location-dependent behaviours. As a consequence, we suggest that the non-separable code that we found in the hippocampus of wild-born bats—a code that we showed is more efficient when considering 2D decoding of position by distance—is particularly suitable to guide such non-separable behaviours in the wild. By contrast, a separable neural code might be more suitable in other brain areas, such as inferior temporal cortex, in which an invariant and separable representation of objects is needed (for example, classifying a cat versus a dog irrespective of position). Indeed, a largely separable neuronal code was demonstrated experimentally in the inferior temporal cortex, and was shown to be beneficial for position-invariant object classification64,65.

Reporting summary

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