Introduction

The ability to generate and manipulate internal representations of the sensory world is fundamental to cognitive functions of the brain. Representations in higher order cortical structures are likely to result from interactions between sensory responses and the intrinsic dynamics of neural circuits. This is exemplified by the grid cell system, in which neurons in the medial entorhinal cortex (MEC) are organised into modules that have population activity suggesting they form a network with continuous attractor dynamics (Obenhaus et al., 2021; Rowland et al., 2016; Sreenivasan and Fiete, 2011). In the grid system, individual neurons represent external location through grid firing fields (Hafting et al., 2005), while coordination within the network ensures that grid neurons maintain stable phase relationships to one another, even across different environments (Fyhn et al., 2007; Gardner et al., 2021; Waaga et al., 2021; Yoon et al., 2013). This provides a stable and potentially high capacity mechanism for encoding location across spatial scales (Fiete et al., 2008; Mathis et al., 2012; Sreenivasan and Fiete, 2011), with the underlying coordinated network dynamics appearing to be maintained even during sleep states (Gardner et al., 2019; Trettel et al., 2019). While these network dynamics are increasingly well described, it is unclear whether and when representations generated by grid cells contribute to spatial behaviours (Ginosar et al., 2023).

Experiments that have manipulated circuits containing grid cells support the idea that they contribute to spatial behaviours and suggest that this role may be selective for behaviours that rely on path integration. Lesions of the MEC disrupt place representations in the hippocampus and impair performance in spatial memory tasks (Brun et al., 2008; Hales et al., 2021, 2018, 2014; Miao et al., 2015; Schlesiger et al., 2015; Steffenach et al., 2005). These impairments are often not complete in that hippocampal place representations remain, although are less stable, and spatial tasks can still be solved, although path integration-dependent behaviours in particular appear to be sensitive to MEC lesions. More selective genetic manipulations support similar conclusions. Deletion during postnatal development of NMDA receptors from neurons in the MEC and nearby structures reduces the number of detected grid cells in these areas while appearing to have less effect on other spatial cell types (Gil et al., 2017). This manipulation impairs path integration without affecting other spatial behaviours. Targeted inactivation of stellate cells in layer 2 of the MEC, which are thought to be a major grid cell population (Gu et al., 2018; Rowland et al., 2018), also impairs learning of path integration-dependent behaviours and cue-based navigation more generally (Qin et al., 2018; Tennant et al., 2018). However, for each of these manipulations it is difficult to establish whether impairments result from deficits in grid firing per se, or from other alterations in the circuit and its potential for plasticity.

If grid cells contribute to spatial behaviour, then a straightforward possibility is that they provide representations of location that are always available and well registered to the external environment (Figure 1A). However, this notion is challenged by recent observations. For example, in circular track environments, repeated grid firing patterns are maintained but are no longer anchored to the track (Jacob et al., 2019). Under these conditions, the grid network performs path integration and its representations are informative about distance travelled but not about absolute position (Figure 1B). Moreover, spatial representations within populations of MEC neurons that include grid cells can be unstable even in fixed task and environmental conditions (Low et al., 2021). In these experiments, the instability results from remapping, such that the network switches between different representations of location. These results suggest that grid representations are not necessarily stably anchored to the external world, but it is unclear whether this instability impacts performance of spatial tasks. This is crucial for understanding how grid firing contributes to cognition and behaviour. For example, if grid firing does not contribute to a particular behaviour, then stable anchoring of grid firing to the environment should be unrelated to performance. By contrast, under conditions where grid firing is required for behaviour, stability should predict behavioural performance.

Models for grid representation and experiment design

(A) Positional grid code model with firing fields anchored to the environment.

(B) Grid firing encoding distance rather than position.

(C) Neurons were recorded in an open arena and then in a location memory task. Trials were configured with a reward for stopping in a visually cued zone (beaconed), or a reward for stopping in the same zone but with the cue absent (non-beaconed), or without the visual cue or the reward (probe).

(D) In a positional coding scheme, a grid cell fires with field spacing λ and resets its firing every trial by anchoring its fields to the same track location, with a realignment lag R observed in the spatial autocorrelogram. Fields locations remain constant on each trial and thus peaks in the spatial periodogram occur at integer spatial frequencies relative to the track repetition (see Figure 1, Figure Supplement 3)

(E) In a distance coding scheme, a grid cell fires with field spacing λ and continues to fire at regular intervals without anchoring to the track. Unless field spacing and the track length are integer divisible, the location of fields varies across trials, and thus the peak of the spatial periodogram is not constrained to an integer spatial frequency (see Figure 1, Figure Supplement 3).

Here, we approach the question of whether and when grid representations contribute to behaviour by taking advantage of a virtual reality based location memory task that can be solved either using local cues that indicate a reward location or by path integration to the reward location from a well defined starting point (Figure 1C)(see also (Tennant et al., 2022, 2018)). The task differs from cue rich virtual environments typically used to study grid cells (e.g. (Campbell et al., 2018; Domnisoru et al., 2013)) in that in the standard configuration of the task the only spatially fixed cue available after initiation of a trial is the visual marker of the reward zone. On trials in which this marker is removed, efficient localisation of the reward zone demands the use of a path integration-based strategy (Tennant et al., 2018). In the experiments we describe here, we identify grid cells through their firing patterns in open arenas and then evaluate their activity in the location memory task. We find that grid cells can either represent location on the virtual track or can encode a path integrated measure of distance that is independent from track location. The use of each representational strategy differs both between sessions and within a recording session. On trials when the reward zone cue is present, adoption of the positional representation does not predict task performance. When the reward zone cue is absent, mice can maintain spatial behaviour when grid cells encode distance, but on average their performance is impaired compared to when grid cells encode position. Thus, our results suggest that positional anchoring of the grid cell network may selectively promote successful localisation by path integration.

Results

We recorded grid fields from neurons in the MEC of 9 wild-type mice exploring an open arena and then performing a location memory task in a virtual linear track environment. By comparing the hexagonal symmetry of spatial autocorrelograms of neural activity in the open arena with corresponding shuffled data we identified 103/1974 neurons as grid cells (8.6 ± 15.7 grid cells / mouse, range 0.4 % to 9.3 %) (see Methods for classification procedures). These grid cells had field sizes of 7.5 ± 3.3 cm and grid spacing of 72.5 ± 13.7 cm and were found in dorsomedial parts of the MEC. Until indicated otherwise, we report analyses of neurons across all trials of the location memory task regardless of whether the reward zone is indicated by the cue or whether mice stop at the rewarded location.

Grid cells encode either position or distance

Positional and distance coding schemes both predict spatially periodic activity of grid cells but they differ in the relationship between firing periodicity and the track length (Figure 1A-B). To distinguish these scenarios we estimated the spatial periodicity of each neuron’s activity on the virtual track using the Lomb-Scargle method (Lomb, 1976; Scargle, 1982; VanderPlas, 2018) (Figure 1, Supplements 13). This approach yields estimates of power as a function of the period of underlying oscillations and an associated estimate of the false alarm probability. We validated these estimates for detection of periodicity associated with grid firing using synthetic and shuffled data (Figure 1, Supplements 45).

According to positional coding schemes, the grid representations should be anchored to the environment, providing a positional code that could be used to solve the task (Figure 1A). In this case, because the track used for the virtual memory task repeats every 2 m, significant peaks in the periodogram should occur at integer multiples of the spatial frequency of the repeating track (Figure 1D, Figure 1, Figure Supplement 3). By contrast, in distance coding schemes the activity of grid cells encodes output from a neural path integrator but without anchoring to the environment (Figure 1B). In this case, periodic grid representations should encode distance moved but not track position and therefore would not be useful for solving the task. Significant peaks in the spatial periodogram would then be independent of the track length, but would reflect the intrinsically generated spatial period of the neural path integration (Figure 1E, Figure 1, Figure Supplement 3). A further possibility is that grid firing decouples from movement signals that drive path integration and therefore fails to encode either position or distance. In this case, peaks in the periodogram above the false alarm threshold should be absent.

We initially tested these predictions for neural activity across a complete behavioural session (n = 103 grid cells, N = 61 sessions, 233 ± 135 trials / session)(Figure 2). We found that 68 of 103 grid cells had peaks in their periodograms within 5 % of an integer multiple of the spatial frequency of the track repetition, consistent with their encoding position (Figure 2A, D-E). We refer to these neurons as positional grid (PG) cells. By contrast, 32 of 103 grid cells had periodograms consistent with their encoding distance (Figure 2B, D-E). We refer to these neurons as distance grid (DG) cells. Periodograms lacking peaks, which we will refer to as aperiodic grid (AG) cells, were rare (3/103)(Figure 2C-E). As expected, given their activity did not anchor to the environment, DG cells had much lower spatial information scores than PG cells while having similar average firing rates (Figure 2F). Other features of the periodogram also differed, with peak power larger and peak width narrower for PG cells compared with DG cells (Figure 2F). The AG cells had much lower mean firing rates than the PG or DG cells suggesting that their apparent lack of periodicity may reflect inactivity (Figure 2F).

Grid cells use position or distance coding schemes

(A-C) Examples of grid cells with activity during the location memory task that follows predictions of positional (A) or distance coding schemes (B), and example of a cell that does not follow either scheme (C). Examples are ordered in their respective groups by their spatial information content on the track. From top to bottom plots show: heap map of firing rate as a function of track position, spatial autocorrelation of the track firing rate, spatial periodogram of the track firing, open field firing rate map and open field spatial autocorrelogram. The red line indicates the false alarm threshold estimated from shuffled data and significant peaks are labelled with a triangle. X-axis scales are adjusted on the virtual reality spatial autocorrelation for several examples to better illustrate the long-range periodic signal.

(D) Peak power as a function of the spatial frequency at which the peak occurs for all recorded cells. The red dashed line indicates the false alarm threshold generated from shuffled data.

(E) Percentage of grid (G) and non-grid (NG) cells classified to position, distance and aperiodic groups.

(F) Comparison of mean firing rate (position vs distance, DF = 98, P = 0.63, T = 1257.0; position vs aperiodic, DF = 69, P = 0.03, T = 185.0; distance vs aperiodic, DF = 33, P = 0.06, T = 10.0, Mann-Whitney U tests, adjusted for multiple comparison using a Bonferroni correction), spatial information scores (position vs distance, DF = 98, P = 0.003, T = 1535.0; position vs aperiodic, DF = 69, P = 0.78, T = 61.0; distance vs aperiodic, DF = 33, P = 0.09, T = 83.0, Mann-Whitney U tests, adjusted for multiple comparison using a Bonferroni correction), peak power (DF = 98, P = 0.0007, T = 1549.0, Mann-Whitney U test), and peak width (DF = 98, P = 0.0001, KS = 0.46, Kolmogorov-Smirnov test) between position, distance and aperiodic encoding grid cells.

These data suggest that during the location memory task we consider here, grid firing can encode either position or distance. The finding of a majority of position encoding grid cells is consistent with previous reports of grid cell activity on virtual and real world linear tracks (Domnisoru et al., 2013), while the finding of a substantial proportion of distance encoding grid cells is consistent with previous reports of distance encoding grid cells in real world circular tracks (Jacob et al., 2019).

Grid cells switch between position and distance coding

While grid firing is often considered as providing a stable readout of position (Figure 3A), population activity of neurons in the MEC has been found to switch reference points within a behavioural session (Low et al., 2021) (Figure 3B). Given that we find that grid firing can be either positional or distance related it is conceivable that grid cells could switch between these anchoring modes (Figure 3C). Visual inspection of firing rate heat maps indicated that while for some grid cells their firing pattern appeared stable across trials (Figures 3B-C), for many grid cells there were groups of consecutive trials where the typical spatial firing pattern was altered (Figure 3D-E). We reasoned that this could result from disruption to the grid coding mechanisms during these epochs, or it could result from switching between place and distance coding schemes (cf. Figure 3A). To distinguish these possibilities we evaluated rolling periodograms across each recording session (see Methods). We classified each window as position encoding, if the periodogram peaks occurred at integer multiples of the spatial frequency at which the track repeats, as distance encoding if there were periodogram peaks at other spatial frequencies, or as aperiodic if peaks were absent from the periodogram. For 26.2% of neurons (27/103) the classification was consistently (> 85% of trials) position or distance encoding (Figure 3F). We refer to these neurons as stable PG or DG cells. However, for 73.8% of neurons (76/103), no single coding scheme accounted for more than 85% of trials (Figure 3F). Consistent with our classification scheme correctly separating each window, spatial information scores were greater for positional compared to distance windows, while mean firing rates were similar (Figure 3G). PG cells identified in our initial analysis (Figure 2) covered a continuum, from neurons with stable positional encoding to neurons with fewer than 25% of positional trials (Figure 3C, F). Likewise, for many DG cells there were periods when they showed positional firing (Figure 3D-F). Across all grid cells, periods of position or distance coding extended in blocks across multiple trials, with the distribution of block lengths substantially different to that generated by shuffled data (Figure 3, Figure Supplement 3)(DF = 1765, 2359; Ks = 0.066; P = 0.0003; Kolmogorov-Smirnov test). Consistent with grid cells forming coherent networks, when we recorded multiple grid cells simultaneously we found that they typically switched at the same time between position and distance coding (Figure 3, Figure Supplement 4).

Coding schemes switch within behavioural sessions

(A) Under a ‘stable coding’ scenario grid cells represent either position or distance throughout the recording session (left), whereas with ‘unstable coding’ the grid activity switches between representation of position and distance (right).

(B-E) Example trial by trial firing rate heat maps (upper left), corresponding rolling periodogram heat maps (upper right), mean rate maps (lower left) and mean periodograms (lower right) for neurons exhibiting stable positional coding (B), stable distance coding (C) and unstable coding in which representations switch between position and distance (D-E).

(F) Distribution across all recorded grid cells of position encoding trials (left), distance encoding trials (centre) and aperiodic trials (right).

(G) Spatial information is higher for trials on which grid cells encode position compared to distance (left)(P = 0.006, T = 1018.0, DF = 78, Wilcoxon signed-rank test), whereas the average firing rate is similar between position and distance-encoding epochs (right)(P = 0.2, T = 1541.0, DF = 84, Wilcoxon signed-rank test).

Position and distance coding by grid cells differentially predicts path integration-dependent but not cue-dependent reward localisation

Our analyses indicate that grid cells represent either position or distance, and that these representations can switch within a recording session. Since only position representations should reliably predict the reward location, and as grid networks have highly coherent low dimensional dynamics such that activity of individuals neuron is informative about the network state as a whole (Gardner et al., 2021; Waaga et al., 2021), we reasoned that the presence of positional coding could be used to assess whether grid firing contributes to the ongoing behaviour. Thus, if anchoring of grid representations to the environment is critical for localisation of the reward, then position rather than distance representations should predict successful trials. On the other hand, if behavioural performance is similar when the grid representation is of distance rather than position, then it is unlikely that grid representations are necessary for reward localisation.

To distinguish these possibilities we compared stopping behaviour when grid cells showed positional firing to when they showed distance firing (Figure 4). The behaviour of the mice varied such that they either stopped correctly in the reward zone (‘hit’ trials), slowed down on approach to the reward zone but did not stop (‘try’ trials) or maintained a high running speed across the reward zone (‘run’ trials)(Figure 4A and Figure 4, Figure Supplement 1). On cued trials the spatial organisation of stopping behaviour (Figure 4B-F), and the proportion of hit trials (Figure 5), was similar irrespective of whether grid cells encoded position or distance. This was the case when grid cells stably encoded either position or distance (Figure 4C-D, Figure 5A), or when they switched states (Figure 4E-F and Figure 5B). Thus, anchoring of grid firing to the track position does not appear to be necessary to solve the location memory task when the reward zone cue is visible, or to confer any advantage compared with when grid firing encodes distance.

Spatial behaviour during position and distance encoding by grid cells

(A-B) Running speed as a function of track position for trial outcomes classified as a hit, try, or run (A), and for beaconed and non-beaconed trials in which a recorded grid cell encodes position (upper) or distance (lower)(B).

(C-F) Example of variation in the behaviour-related activity of grid cells recorded on the location memory task. (C) and (D) show examples of stable position and distance coding respectively, whereas (E) and (F) show unstable position-distance coding. Speed profiles in (A) and (B) are taken from the session and grid cell shown in (E).

Positional grid coding is not required for cued spatial localisation but promotes path integration-dependent localisation

(A, C) Stopping probability relative to baseline as a function of position for grid cells with stable grid cell codes (A) and for all grid cells (C). Shaded regions in A and B represent standard error of the mean measured across sessions and cells respectively.

(B) Percentage of hits on beaconed, non-beaconed and probe trials when grid cells encode position (turquoise) or distance (purple) for sessions with stable grid code. (Beaconed, P = 0.33, Χ2 = 0.95, DF = 19; Non-beaconed, P = 0.024, Χ2 = 5.11, DF = 1; Probe, P = 0.075, Χ2 = 3.17, DF = 1, ANOVA, see Methods).

(D) Percentage of hits on beaconed, non-beaconed and probe trials when grid cells encode position or distance trial epochs. (Beaconed, P = 0.26, Χ2 = 1.25, DF = 1; Non-beaconed, P = 3.16e-5, Χ2 = 17.3, DF = 1; Probe, P = 0.32, Χ2 = 0.98, DF = 1, ANOVA, see Methods)

(E) Percentage of trials with hit, try and run outcomes in which grid cells encode position or distance. (Beaconed-position, P = 0.3, Χ2 = 2.38, DF = 1; Non-beaconed-position, P = 0.02, Χ2 = 7.87, DF = 1; Probe-position, P = 0.13, Χ2 = 4.05, DF = 1, Beaconed-distance, P = 0.28, Χ2 = 2.53, DF = 1; Non-beaconed-distance, P = 0.26, Χ2 = 2.70, DF = 1; Probe-distance, P = 0.08, Χ2 = 5.04, DF = 1, ANOVA, see Methods). Error bars denote standard error of the mean measured across the mean values for each animal. Faded lines show percentage values for individual mice that contained hit, try and run trials for a given trial type.

(F) Odds ratio between receipt of reward for trials on which grid cells encode position relative to trials on which they encode distance (Beaconed, P = 0.23, non-beaconed, P = 0.002, probe, P = 0.27).

On trials in which the reward zone cue was hidden but rewards were available, the relationship between grid firing and behavioural outcome was more complex. In some sessions, localisation of the reward occurred almost exclusively when grid cells were anchored to position and not when they encoded distance (Figure 4C). This is consistent with predicted path integrator roles for grid cells. In other sessions, animals localised the reward when grid firing was anchored to position or distance, but overall performance was improved on positional trials (Figure 4D-E). In a few sessions, we observed spatial stopping behaviour comparable to cued trials, even when grid firing almost exclusively encoded distance rather than position (Figure 4F). On average, we found that localisation behaviour was reduced but not abolished when grid cells stably encoded distance rather than position (Figure 5A). Considering unstable as well as stable grid cells, the spatial organisation of stopping behaviour was also clearer and the overall proportion of hit trials was substantially higher for positional compared with distance coding (Figure 5B). We obtained similar results on probe trials in which the reward zone was again hidden, and in addition rewards were not available (Figure 5).

Together, these analyses demonstrate that anchoring of grid codes to track position is not necessary to successfully obtain rewards when visible cues are present. By contrast, when visual cues that indicate the reward zone are absent, positional coding appears to promote successful localisation although may not be strictly necessary.

Discussion

Despite extensive investigation of mechanisms and potential functions for grid representations, it has been unclear whether and when grid firing contributes to behaviour. We find that grid representations can either be anchored to position in the environment, or can provide an environment-independent distance metric (Figure 2), and that grid cells can switch between these operating modes within a behavioural session (Figure 3). By taking advantage of this variability, along with the fact that representations by individual grid cells are strongly coordinated with the activity of the grid network as a whole, we demonstrate that anchoring of grid firing fields to location is not required for cued reward localisation, but appears to promote path integration-dependent reward localisation (Figures 45).

Positional anchoring of grid cells varies within and between behavioural sessions

A standard view of grid firing is that it provides an ‘always on’ representation of current location. In contrast, our results demonstrate that grid representations are not necessarily anchored to the behaviourally relevant environmental reference frame. This extends previous observations that on circular tracks grid cells read out path integrated distance rather than absolute position (Jacob et al., 2019). Our results show that both modes of grid representation can be observed during the same behavioural task, and that the grid network can switch between positional and distance coding within a session. This is consistent with MEC networks as a whole switching states within a behavioural session (Low et al., 2021). However, previously reported switching was between network states rather than grid representations, was independent of any task contingencies and involved remapping of positional representations. By contrast, we show here switching between anchored position representations that may be directly useful for solving the task at hand, and non-anchored distance representations that appear unlikely to contribute to solving the task.

The extent and causes of switching between positional and distance representations may be an important focus for future investigation. The reported continuous attractor dynamics of grid networks implies all grid cells are similarly informative of the network state, in which case the state switching we observe should reflect changes in the grid network as a whole. Nevertheless, without recording from all grid cells simultaneously we can not rule out the possibility that switching reflects a subset of grid cells that become disconnected from the wider network, although experiments in which we recorded simultaneously from multiple grid cells argue against this (Figure 3, Figure Supplement 1). In either scenario, it appears unlikely that distance coding by grid cells result from failure of upstream circuits to generate appropriate visual representations, for example through a shift in visual attention, as mice performed well on the visually cued version of the location memory task when grid cells were encoding distance. A perhaps more promising hypothesis for future investigation is that switching reflects modulatory pathways reducing the impact of visual inputs to the grid system, possibly reflecting top down control mechanisms, shifts in brain state, or uncertainty about whether visual or motor signals indicate the correct environment.

Spatial roles of grid cells may be specific to path integration-dependent behaviours

Our finding that cued identification of a reward location is similar when grid cells encode position or distance, suggests that grid representations are not required for cued recall. Thus, when both visual and grid inputs are both available to downstream decision making circuits, the grid input appears not to be used as otherwise the inconsistent positional signals from the distance encoding grid cells would impair performance. Several observations suggest the MEC could nevertheless be required for recall of cued locations. First, inactivation of stellate cells in layer 2 of the MEC causes deficits in the task we use here (Tennant et al., 2018). Second, other spatial tasks that involve selections between cued locations appear to require the MEC (e.g. (Gaskin and White, 2013, 2010)). In this case, spatial representations used for the task could be encoded by other functional cell types, for example neurons that encode location through border (Solstad et al., 2008) or ramping firing fields (Tennant et al., 2022), or through cue-responsive cells (Casali et al., 2018; Keene et al., 2016; Kinkhabwala et al., 2020).

On trials in which the reward zone cue is absent, efficient reward localisation relies on path integration from the start of the track (Tennant et al., 2018). We found that on these trials, positional grid firing was associated with a spatially localised stopping strategy and a higher proportion of successful trials compared with when grid firing encoded distance. This is consistent with previous evidence for specific roles of grid firing in path integration based on genetic manipulations that abolish grid firing without affecting other functional cell types (Gil et al., 2017). Nevertheless, our finding of residual localisation performance on distance trials, suggests that additional neural mechanisms may also support path integration-dependent behaviour. This residual spatial behaviour was variable between sessions, with some sessions having almost no spatial stopping behaviour when grid cells encoded distance, whereas other sessions showing similar spatial stopping behaviour when grid cells encoded position or distance. This could reflect use of alternative continuous coding schemes for path integration (cf.(Tennant et al., 2022)). If multiple mechanisms support path integration then it will be important to establish when each contributes. For example, because grid representations are available on the first entry to an environment they may be important for behaviour in newly learned locations, whereas for familiar locations complementary representational strategies that emerge with learning may be sufficient.

Ideas and speculation

Our results point to a specific role for grid firing in path integration-dependent behaviour, and demonstrate the importance of anchoring of grid representations to the environment. One implication of our results is that rather than being an ‘always on’ tracking system, grid cell networks vary in their engagement with the environment. This may reflect control of the grid network by attentional or other top down mechanisms. Alternatively, as the CA1 region of the hippocampus provides a major input to the MEC, instability of grid anchoring could be an indirect consequence of mechanisms that control the structure and stability of place cell maps (Krishnan et al., 2022; Pettit et al., 2022). Our results also offer a new perspective on interindividual differences in path integration by humans (e.g. (Chrastil et al., 2017; Lakshminarasimhan et al., 2018; Petzschner and Glasauer, 2011)). Thus, rather than resulting from variation in path integration per se, differences between individuals could instead result from variation in the anchoring of grid representations underlying path integration. Such deficits could be important as potential mechanisms for deficits in spatial localisation associated with neurological and neurodevelopmental disorders (Kunz et al., 2015; Newton et al., 2023; Noel et al., 2020).

Materials and Methods

All experiments were carried out under a UK Home Office project licence, were approved by the Animal Welfare and Ethical Review Board of the University of Edinburgh College of Medicine and Veterinary Medicine, and conformed with the UK Animals (Scientific Procedures) Act 1986 and the European Directive 86/609/EEC.

Microdrive fabrication and surgical procedures

Microdrive fabrication and surgical procedures were similar to our previous work (Gerlei et al., 2020; Tennant et al., 2022). Microdrives containing 4 tetrodes were built by threading 90% platinum, 10% iridium tetrode wires (18 µm HML-coated, Neuralynx) to an EIB-16 board (Neuralynx) via an inner cannula (21 gauge 9 mm long). The board was covered in epoxy and a poor lady frame (Axona) cemented to the side. An outer cannula (17 gauge 7 mm), placed around the inner cannula, was secured temporarily using vaseline, allowing it to be lowered during the surgery. Tetrodes were trimmed to ∼3 mm using ceramic scissors (Science Tools, Germany) and gold plated (Non-cyanide gold plating solution, Neuralynx)63 to give an impedance between 150 and 200 kΩ.

Before surgery, tips of the tetrodes were washed with ethanol and then sterile saline. Anaesthesia was induced using 5 % isoflurane / 95 % oxygen, and sustained at 1 – 2 % isoflurane / 98-99 % oxygen. After exposing the surface of the skull a RIVETS head-post (Osborne and Dudman, 2014) was attached to the skull with UV curing resin cement (RelyX™ Unicem, 3M). For electrical grounding, two M1 x 4 mm screws (AccuGroup SFE-M1-4-A2) were implanted through small craniotomies drilled on the left hemisphere ∼3.4 mm lateral, and ∼1 mm rostral relative to Bregma and the centre of the intraparietal plate respectively. The microdrive was attached to a stereotaxic frame via an Omnetics to Mill-Max adaptor (Axona, HSADPT-NN1) and the tetrodes lowered 1.2 - 1.4 mm into the brain, beginning at 3.4 mm lateral from Bregma (right hemisphere) and along the lambdoid suture, and at an angle of −15° in the posterior direction. The outer cannula was lowered and sealed with sterile Vaseline, and the implant fixed to the skull with UV curing resin. After the resin hardened, the grounding wires were wrapped around the grounding screws and fixed with silver paint (RS components 101-5621). The grounding screws were covered with resin and any holes filled with dental cement (Simplex Rapid). After the surgery, mice recovered for ∼20 minutes on a heat mat, had unlimited access to Vetergesic jelly (0.5 mg / kg of body weight buprenorphine in raspberry jelly) for 12 hours, and before proceeding were given a minimum of 2 days postoperative recovery.

Behavioural and electrophysiological recording

The behavioural set up, training procedures and recording approaches were similar to those described previously (Tennant et al., 2022, 2018). Mice were handled twice a day for 7 days following surgery. They were then habituated to the virtual reality setup for 10 - 20 minutes per day over two consecutive days. After each habituation session the mice were given access to soy milk to familiarise them with the reward and were given access to a larger arena for 5 - 10 minutes of free exploration. From 4-5 days before starting training their access to food was restricted so that their body weight was ∼85% of its baseline value, calculated from its weight prior to restriction and normalised to the expected daily growth for the animal’s age.

Experimental days involved recording from mice in an open arena and then in the virtual location memory task. On a few days this order was reversed without apparent effects on the results obtained. Mice were collected from the holding room 30 - 60 minutes before recording, were handled for 5 - 10 minutes, weighed and placed for 10-20 minutes in a cage containing objects and a running wheel. Between recording sessions mice were placed back in the object-filled arena for 30 minutes. Tetrodes were typically lowered by 50 - 100 µm after each session. The open arena consisted of a metal box with a square floor area, removable metal walls, and a metal frame (Frame parts from Kanya UK, C01-1, C20-10, A33-12, B49-75, B48-75, A39-31, ALU3). For the location memory task mice were trained to obtain rewards at a marked location on the virtual linear track. Mice were head-fixed using a Rivets clamp (Ronal Tool Company, Inc)64 and ran on a cylindrical treadmill fitted with a rotary encoder (Pewatron). A feeding tube placed in front of the animal dispensed soy milk rewards (5 - 10 µl per reward). Virtual tracks, generated using Blender3D (blender.com), had length 2 m, with a 60 cm track zone, a 20 cm reward zone, a second 60 cm track zone and a 60 cm black box to separate successive trials. The reward zone was marked by distinct vertical green and black bars. The distance visible ahead of the mouse was 40 cm.

Electrophysiological signals were acquired using an Intan headstage connected via an SPI cable (Intan Technologies, RHD2000 6-ft (1.8 m) standard SPI interface cable) attached to an Open Ephys acquisition board. Signals were filtered (2.5 Hz −7603.8 Hz). For the location memory task, behavioural variables including position, trial number and trial type were calculated in Blender3D at 60 Hz and sent via a data acquisition (DAQ) microcontroller (Arduino Due) to the OpenEphys acquisition board. In the open arena, motion and head-direction tracking used a camera (Logitech B525, 1280 x 720 pixels Webcam, RS components 795-0876) attached to the frame. Red and green polystyrene balls were attached to the sides of the headstage and were tracked using a custom script written in Bonsai (Lopes and Monteiro, 2021). Synchronisation of position and electrophysiology data used an LED attached to the side of the open arena in the field of view of the camera, with randomly timed trigger pulses sent to the LED via an Arduino board (Arduino Uno) and to the Open Ephys acquisition board via the I/O board.

Following experiments, tetrodes were localised using a microCT scanner (Data S1). Mice were anaesthetised with isoflurane and then a lethal dose of sodium pentobarbital (Euthatal, Meridal Animal Health, UK), were perfused with a mixture of PFA and glutaraldehyde, and the head with the microdrive still intact on the skull left in the same solution for 2 nights. All tissue and bone except that attached to the microdrive was removed before washing the brains in ddH20 before and incubating at 4° for two weeks in 2 % osmium tetroxide (2% OsO4). Brains were then washed in ddH20, dehydrated in ethanol and then embedded in resin. After the resin had cured the brains were imaged in a micro-CT scanner (Skyscan 1172, Bruker, Kontich, Belgium). Scanning parameters were: source voltage 54 kV, current 185 μA, exposure 885 ms with a 0.5 mm aluminium filter between the X-ray source and the sample. The scan dataset was reconstructed (CTan software, v1.13.5.1) and viewed with DataViewer (Bruker). Tetrodes were localised relative to landmarks in version 2 of the Allen Reference Atlas for the mouse brain (https://mouse.brain-map.org/static/atlas).

Spike sorting

Spikes were isolated from electrophysiological data using an automated pipeline based on MountainSort (v 0.11.5 and dependencies)(Chung et al., 2017; Gerlei et al., 2020). Recordings from the open field and virtual reality tasks were concatenated for spike sorting. Pre-processing steps converted Open Ephys files to mda format, filtered signals between 600 Hz - 6000 Hz and performed spatial whitening over all channels. Events were detected from peaks > 3 standard deviations above baseline and separated by at least 0.33 ms from other events on the same channel. The first 10 principal components of the detected waveforms were used as inputs to the ISOSPLIT algorithm. Cluster quality was evaluated using isolation, noise-overlap, and peak signal to noise ratio metrics (Chung et al., 2017). Units with firing rate > 0.5 Hz, isolation > 0.9, noise overlap < 0.05, and peak signal to noise ratio > 1 were used for further analysis. Downstream analyses were carried out using Python (version 3.8.1) and R versions: 4.2.3.

Analysis of neural activity in the open arena

For analysis of neural activity in the open arena, firing rate maps were calculated by binning spikes into 2.5 cm bins, dividing by the total time occupied in each bin and then smoothed with a Gaussian kernel. Autocorrelograms were calculated by sliding the rate map over all x and y bins and calculating a correlation score. Grid scores were defined as the difference between the minimum correlation coefficient for rate map autocorrelogram rotations of 60 and 120 degrees and the maximum correlation coefficient for autocorrelogram rotations of 30, 90 and 150 degrees (see (Sargolini et al., 2006)). Fields were detected in the autocorrelogram by converting it into a binary array using 20% of the maximal correlations as a threshold. If the binary array had more than 7 local maxima, a grid score was calculated. Correlations between the rotated autocorrelograms were then calculated using a ring containing the 6 local maxima closest to the centre of the binary array and excluding the maximum at the centre. The ring was detected based on the average distance of the 6 fields near the centre of the autocorrelogram (middle border = 1.25* average distance, outer border = 0.25 * average distance). For assessing spatial stability, firing rate maps were generated for the first and second half of the session. Bins that were not visited in both halves were excluded from the calculation. Spatial stability was calculated as the Pearson correlation coefficient between these two rate maps. To calculate spatial information, scores were generated as

where i indexes a position bin in the firing rate map, N is the number of bins, Pi is the occupancy probability, Ri is the firing rate in the bin, R is the mean firing rate. Shuffled spike data was generated by drawing a single value from a uniform distribution between 20-580 seconds and adding this to the timestamp of each spike. Spike times that exceeded the recording duration were wrapped to the start of the session. Spike locations were recomputed from the shuffled spike times and spatial scores recalculated. Neurons were classified as grid cells when their grid score was in the 99th percentile of the same scores from 1000 shuffled datasets, and the correlation between the first and second half of the recording session exceeded the 99th percentile from the shuffled datasets.

Spatial information scores were calculated as in the open field, but with bin sizes of 1 cm and occupancy maps calculated across trials. When spatial information scores were generated for epochs within a session, we took the same number of trials for each epoch (e.g. when comparing position and distance-encoding epochs). This was done by randomly subsetting the epoch with the greater number of trials to match the number of trials of the epoch with the smaller number of trials.

Analysis of neural activity and behaviour during the location memory task

Movement speed as a function of location on the virtual track was calculated by binning speed into 1 cm location bins and then smoothing by convolution with a Gaussian filter (SD = 2 cm, SciPy Python package). Speed for each bin was then averaged over trials within a session. The mean speed across all sessions was calculated for each animal for each trial outcome. The mean and standard error across all animals was calculated from the means for each animal. To compute stop histograms for individual sessions, stops were counted within 1 cm location bins and counts were divided by the number of trials to obtain the number of stops per trial. This was smoothed by convolution with a Gaussian filter (SD = 1 cm). To construct average stop histograms by either aggregating sessions or epochs of trials within a session. The same procedure was applied to create individual stop histograms. These histograms were normalised by subtracting a baseline stop histogram, which was constructed by creating and averaging over 100 shuffled stop histograms whereby stop locations were randomly drawn from a uniform distribution of track locations.

Trials were classified into hits and misses based on whether the mouse stopped (speed < 4.7 cm/s) within the reward zone (Figure 4, Figure Supplement 1). Miss trials were further split by comparing their average speeds in the reward zone to hit trials; the 95th percentile of speeds in the reward zone for hit trials was used to discriminate between try trials (< 95th percentile speed) and run trials (> 95th percentile speed). Trials in which the mouse’s average speed across the full length of the track was < 10 cm/s were left unclassified.

To analyse neural activity during the location memory task, firing rate maps for each trial were generated by binning the track into 1 cm bins, summing the number of spikes in each bin and dividing by the time the animal spent there. Firing rates were smoothed with a Gaussian filter (SD = 2 cm, SciPy Python package). To quantify the spatial periodicity of neural firing, the Lomb-Scargle method of least-squares spectral analysis (LSSA) as implemented by the Astropy Python module (The Astropy Collaboration et al., 2022) was used to generate a frequency spectrum in the spatial domain (Lomb, 1976; Scargle, 1982). A periodogram was computed every 10 cm with a sample length equal to 3 track lengths (600 cm). Track locations were normalised between 0 and 1 such that spatial frequencies correspond to the number of oscillations per trial. Spatial frequencies > 5 were discarded from further analysis as no grid cells were found with grid spacings < 40 cm. Periodograms were concatenated to create an average spatial periodogram across the session (Figure 1, Figure Supplement 1 for an illustrative example).

To distinguish spatially periodic firing from aperiodic firing, we compared the spectral peaks between a cell’s observed data and a false alarm threshold signifying the likelihood of the peak power being greater than chance level periodicity. The threshold was calculated with a bootstrapping method that used 1000 shuffled instances of the cell’s firing, with the aim of disrupting spatial periodicity while preserving any local temporal firing. This was inspired from the field shuffle procedure used for grid cells in 2D (Barry and Burgess, 2017). First, firing fields were identified in a highly smoothed version of the cell’s firing rate map (convolution with a Gaussian filter, SD = 4 cm). The field positions were reallocated in an unsmoothed rate map to random positions, preserving the spatial organisation of the field and subsequently bins not attributed to a firing field filled the remaining gaps. The shuffled unsmoothed rate map was then smoothed by convolution with a Gaussian filter (SD = 2 cm) and the spatial periodogram calculated. This was repeated 1000 times and the 99th percentile calculated from the distribution of shuffled peak powers to create the false alarm threshold. Cells with a measured peak power lower than this threshold were classified as aperiodic (Figure 1, Figure Supplement 2 for an illustrative example).

To distinguish periodic cells, we used the spatial frequency of the largest peak in the periodogram to classify cells as position or distance-encoding. To do so, we calculated the difference between the peak spatial frequency and the nearest positive-integer value. We found position-encoding cells could be distinguished from distance-encoding cells by using a spatial frequency tolerance within 0.05 from a positive-integer spatial frequency to classify a position-encoding cell. Using this metric yielded high prediction accuracies when comparing our classification to true labels when we simulated anchored or non-anchored grid cells on the linear track (Figure 1, Figure Supplement 5).

To classify activity within a recording session, rolling windows of the total spatial periodogram were averaged over 200 periodograms which equated to 10 trials (20 samples per 200 cm track with 10 cm steps). The peak of the average spatial periodogram from a single window was identified, and the peak power and the spatial frequency at which this occurred were extracted. To determine if the peak reflected a periodic signal that occurred above chance level, it was compared with an adjusted false alarm threshold. Figure 3, Figure Supplement 2 shows how the false alarm threshold changes as a function of the number of periodograms used to compute the average periodogram from a representative recording. As the number of samples within the rolling window increases, the false alarm threshold decreases. An adjusted false alarm threshold was therefore calculated, such that for each field shuffle, the first 200 samples were used to compute the average periodogram, thus matching the number of samples used in the rolling window calculation. The 99th percentile of peak powers from 1000 field shuffles is used as the adjusted false alarm threshold. We also found the number of periodograms used to calculate the average spatial periodogram greatly affected the prediction accuracy and bias. We opted for a rolling window size equal to 200 periodograms as this was found to achieve high accuracy with minimal bias within the classification of our simulated dataset (Figure 3, Figure Supplement 1).

Simulation of firing during the location memory task

To evaluate classification of cells as positional or distance coding we simulated cell types including grid cells, place cells, ramp cells and aperiodic cells. For each cell type, we simulated an agent moving with a constant velocity of 10 cm/s across 100 trials of a 200 cm long linear track and recorded the locations visited with a sampling rate of 1000 Hz. For each cell-type, the probability of firing at any given location was defined by a probability density function (PDF) with a range of 0 to 1, with 1 equating to a guaranteed firing event. The average firing rate was loosely set by multiplying this normalised PDF by a scalar variable Pmax(spike) which by default was set to 0.1. Firing events were then assigned to each sampled location based on the scaled PDF. Firing rate maps and subsequent spatial periodograms were created as described previously.

PDFs for grid cells were created by positioning Guassians kernels at equidistant locations along the track, with kernel standard deviation equal to 0.1 multiplied by a given grid spacing between the kernels. To simulate positional grid codes, the Guassian kernels were positioned at the same track location on each trial, whereas to simulate distance grid codes the kernels were positioned independently from the track with distances equal to the grid spacing. To simulate field jitter, a displacement of the kernel position was drawn from another Guassian distribution with mean = 0 cm and SD = 0 cm (for no jitter) or 10 cm (for default jitter). A random variable for jitter was drawn for each field and was used to shift fields accordingly. The PDF for the place cell example was made up of a singular Guassian kernel (mean = 100 cm, SD = 10 cm) positioned at the centre of the track and was repeated every trial. The PDF for the ramp cell example consisted of a linear ramp from the start of the track (0 cm) to the end of the track (200 cm). The PDF for the “random field” cell was created by first generating the PDF for the place cell example and then passing this through the field shuffle as described (see Figure 1, Figure Supplement 2). The PDF for the Gaussian noise example was a uniform distribution.

To generate PDFs of grid cells alternating between positional and distance codes, representations of each type were generated and merged based on the type of alternation. For the simulations that alternated in blocks of trials, the initial trial was randomly assigned to either the anchored PDF or the non-anchored PDF with equal probability, for all subsequent trials there was a 10% chance of alternating to the other PDF (e.g. anchored to non-anchored or non-anchored to anchored). For simulations that alternated at the level of single trials, every trial was randomly assigned to either the anchored PDF or the non-anchored PDF, with equal probability.

To evaluate our classification of periodic firing at the level of individual cells, we simulated 500 anchored grid cells and 500 non-anchored grid cells with grid spacings uniformly distributed between 40 - 400 cm and compared the true labels of these simulated cells with the predicted classifications. To determine what spatial frequency tolerance to use in our classification, we classified the simulated dataset across the full range of spatial frequency thresholds to graph at which spatial frequency we could maximise prediction accuracy and minimise bias between position and distance encoding classifications. This was repeated using a range of Pmax(Spike) and jitter SD values. To simplify the analysis, no field shuffle was computed on simulated data within this particular analysis and therefore no false alarm threshold was used. This effectively forced our classifier to label cells position or distance without the possibility of an aperiodic label. The prediction accuracy of our classification was calculated as the percentage of true position and distance-encoding grid cells with a correct prediction label. The prediction bias was calculated as the difference between the number of cells predicted as position-encoding and the number of cells predicted as distance-encoding.

To evaluate our classification of periodic firing at the level of individual trials, we simulated 100 grid cells with grid spacings uniformly distributed between 40 - 400 cm that could alternate between position and distance coding either in blocks of trials or every trial (see above) and compared the true labels of these simulated cells and trials with the predicted classifications. To determine how many spatial periodograms to average over (or if any), we classified the simulated dataset across a range of rolling window sizes to graph at which rolling window size we could maximise prediction accuracy and minimise bias between position and distance encoding classifications. Again this was repeated using a range of Pmax(Spike) and jitter SD values and no field shuffles were computed. The prediction accuracy of our classification was calculated as the average percentage of true position and distance-encoding trials with a correct prediction label. The prediction bias was calculated as the difference between the true difference between the number of position and distance encoding trials and the predicted difference between the number of position and distance encoding trials.

Statistical analyses for the location memory task

To calculate the spatial information of cells on the linear track, the same formula was used as in the open field calculation however in cases where the number of position and distance encoding trials differed, the group with the greater number of trials was randomly subsampled to equal the number of trials as the group with the lower number of trials. This was done to avoid bias in the spatial information scores that can occur when comparing differently sampled groups of spatial firing.

To evaluate the relationship between periodic coding of grid cells and task performance, we constructed a GLMM (generalised linear mixed-effect model) using the lme4 package within R (Bates et al., 2015). Firstly, we constructed data tables in a longform format, whereby each row of the data table represents a single trial or in a wideform format, whereby each row of the data table represents a single grid cell. To test the influence of the periodic classification on task success, we then constructed the formula:

formula_full <- formula(cbind(n_hits, n_trials-n_hits) ∼ periodic_classification + (1 | mouse_id) + (0 + Lomb_classifier | mouse_id))

And a second formula to represent the null hypothesis:

formula_null <- formula(cbind(n_hits, n_trials-n_hits) ∼ (1 | mouse_id) + (0 + periodic_classification | mouse_id))

Where n_hits is the number of hits for a given trial type, n_trials is the number of trials attempted for a given trial type, classification is a categorical variable to symbolise the class of periodic firing for a given grid cell and mouse_id is a unique identifier for individual mice. As no session contained a stable position and also a stable distance-encoding grid cell, we did not need to exclude any sessions that contained stable encoding grid cells. Duplicates were removed where multiple grid cells were recorded in the same session. A binomial model with a logit linker function was then fitted with the wideform data table. To establish whether the classification of periodic firing of grid cells in the location memory task improved the model, we compared the full model with the null model with an ANOVA.

Similarly we asked whether the classification of periodic firing of grid cells on individual trials could improve prediction of task success. We constructed the formula:

formula_full <- formula(hit ∼ classification + (1 | mouse_id / session_id / cluster_id) + (0 + classification | mouse_id / session_id / cluster_id))

And a second formula to represent the null hypothesis:

formula_null <- formula(hit ∼ (1 | mouse_id / session_id / cluster_id) + (0 + classification | mouse_id / session_id / cluster_id))

Where hit is a binary variable representing whether on a given trial the mouse achieved a hit trial, classification is a categorical variable used to symbolise the classification of periodic firing for a given grid cell on an individual trial, session id is a unique identifier for a single session and cluster_id is a unique identifier for a single grid cell. We fit a binomial model with a logit linker function with the longform data table and compared the full model with the null model with an ANOVA to test whether classification at the level of trial improves the prediction of task success.

Finally, we asked whether the behavioural outcome of a trial could improve prediction of the occurrence of a specific periodic grid code (position or distance). We constructed the formulas:

position_formula_full <- formula(position_coding ∼ behavioural_outcome + (1 | mouse_id / session_id / cluster_id) + (0 + behavioural_outcome | mouse_id / session_id / cluster_id)) and:

distance_formula_full <- formula(distance_coding ∼ behavioural_outcome + (1 | mouse_id / session_id / cluster_id) + (0 + behavioural_outcome | mouse_id / session_id / cluster_id))

And a second set of formulas to represent the null hypothesis:

position_formula_null <- formula(position_coding ∼ (1 | mouse_id / session_id / cluster_id) + (0 + behavioural_outcome | mouse_id / session_id / cluster_id))

and:

distance_formula_null <- formula(distance_coding ∼ (1 | mouse_id / session_id / cluster_id) + (0 + behavioural_outcome | mouse_id / session_id / cluster_id))

Where position_coding and distance coding are binary variables representing whether on a given trial the grid cell was classified as position or distance encoding respectively. We fit a binomial model with a logit linker function with the longform data table and compared the full model with the null model with an ANOVA to test whether trial outcome at the level of trial improves the prediction of position or distance-encoding.

Acknowledgements

We thank Caswell Barry for helpful discussions. This work was supported by the Wellcome Trust (200855/Z/16/Z to MFN), MRC Precision Medicine PhD programme (HC) and the Simons Initiative for the Developing Brain (to MFN). This work made use of resources provided by the Edinburgh Compute and Data Facility. For the purpose of open access, the author has applied a CC BY public copyright license to any Author Accepted Manuscript version arising from this submission.

Supplemental Figures

Procedure for extracting a spatial periodogram from a set of spike timestamps

A single cell’s spikes are binned in space (1 cm bin size) and smoothed using a Guassian kernel (SD = 2 cm). Least squares spectral analysis (LSSA) was computed on a signal equivalent to 3 track lengths long using the Lomb-Scargle implementation in the Astropy python module (Δx = distance elapsed in trials, Δy = firing rate)(The Astropy Collaboration et al., 2022). The signal was advanced 10 cm and repeated for the whole session. All spatial periodograms were concatenated and averaged across trials to generate the average spatial periodogram.

Procedure for estimating a false alarm threshold for a given cell

A cell’s spikes were binned in space (1 cm bin size) and smoothed using a Guassian kernel (SD = 4 cm). Firing fields were detected and the original field bins reallocated to a new unsmoothed rate map. Bins not attributed to a field were allocated to the remaining gaps in the new map. To identify fields, the peaks and troughs of the highly smoothed firing rate map were first identified, with a minimum peak distance of 20 cm, smaller peaks were removed until the condition was satisfied (see Scipy.signal.find_peaks). Fields were defined as the detected trough to trough. The unsmoothed rate map was then smoothed with a Guassian kernel (SD = 2 cm). An average spatial periodogram was calculated and peak power detected. This is repeated 1000 times and a false alarm threshold assigned from the 99th percentile of the shuffled cell’s peak power distribution.

Identification of position-anchored periodic signals

Examples of least squares spectral analysis (LSSA) used to estimate the sinusoidal components that best describe the firing rate profile of a positional grid code (upper) and a distance grid code (lower). In each plot the schematised firing fields (solid colours) are shown as a function of track position. Each row shows examples of different sinusoidal components (f = frequency, p = period) at different phases. LSSA minimises the chi-squared error by searching over all phases (three example phases are shown in red, green and blue per row) and amplitudes (amplitude is ignored in this example for simplicity) for each spatial frequency. For positional grid representations, the chi-squared error is minimal at positive-integer spatial frequencies that correspond to sinusoidal waves with periods that are integer divisible by the track length. For distance encoding grid representations the chi-squared error is minimal at a spatial frequency that corresponds to the underlying periodic firing rate profile.

Expected spatial periodicity for different functional cell types

Plots show simulations of track firing for (i) a positional grid (PG) cell, (ii) a distance grid (DG) cell, (iii) a positional grid cell with field jitter, (iv) a distance grid cell with field jitter, (v) a place cell, (vi) a ramp-like cell, (vii) a cell with randomly positioned fields and (viii) a cell with Guassian noise-like activity. Each group of panels shows firing rate heat map by trial (upper left) and corresponding average firing rate (lower left), rolling spatial periodogram (upper centre) and corresponding average (lower centre), the true and predicted trial classification (upper right). The predicted trial classification is established using analyses described in Figure 1, Figure Supplements 13.

Validation of accuracy and bias for classification of positional and distance encoding by grid cells

To validate classification of grid encoding we simulated 500 anchored grid cells and 500 non-anchored grid cells with grid spacings between 40-400 cm (randomly assigned individually). Each grid cell was simulated as a periodic set of firing fields on a linear track of length 200 cm and with 100 trials. Cells were simulated as position encoding by anchoring field locations to track locations on each trial, or as distance encoding by continuing the periodic field locations without explicit track anchoring. Simulations were repeated using different spike rate probabilities and different field jitters (as defined by the standard deviation of the field locations from their preassigned locations) parameter values. Roughly, Pmax(spike) values of 0.01, 0.1 and 1 covered average firing rates on the order of magnitudes of 10-1, 100, 101 Hz respectively whereas jitter SD values of 0, 10, 20 and 30 cm covered a range of deviations from perfect periodic firing. To compute the maximal prediction accuracy from our classification based on a spatial frequency threshold, we calculated the accuracy and bias across the full range of spatial frequencies from a positive integer (0 - 0.5). Classifications were made on each set of simulations in the same way as for analysis of experimental data (see Figure 1, Figure Supplements 14). Prediction accuracy (left) and bias (right) are shown as a function of the spatial frequency from a positive-integer used for the spatial frequency threshold. Chance level accuracy is denoted with a red dashed line.

Classification accuracy and bias as a function of the number of periodograms used for rolling classification

To assess classification of grid firing on individual trials 100 grid cells were simulated with grid spacings between 40-400 cm (randomly assigned individually). Each grid cell was simulated as a periodic set of firing fields following on a linear track of length 200 cm and with 100 trials. Cells were simulated as position encoding by anchoring field locations to track locations on each trial, or as distance by maintaining the field periodicity across trials irrespective of track position. Simulations were repeated using different spike rate probabilities and different field jitters (as defined by the standard deviation of the field locations from their preassigned locations) parameter values. Roughly, Pmax(spike) values of 0.01, 0.1 and 1 covered average firing rates on the order of magnitudes of 10-1, 100, 101 Hz respectively whereas jitter SD values of 0, 10, 20 and 30 cm covered a range of deviations from perfect periodic firing. Two separate methods were used to alternate between position coding and distance coding within the simulated session. The first allowed for alternation in blocks of trials (by trial block) whereas the second allowed for alternation independent of the previous trial (by trial), see methods. For each trial the rolling classifier was used to assess whether firing could be identified as position or distance encoding.

(A) Examples of the activity of simulated grid cells that switch between positional and distance encoding modes of operation. Each example shows the firing rate heatmap by trials (upper left), the average firing rate map (lower left), the rolling spatial periodogram (upper right), the average spatial periodogram (lower right) and the classification labels (true and predicted; far right).

(B) To assess classification accuracy under different rolling windows, we calculated the prediction accuracy and bias. Chance level is denoted with a red dashed line. Classifications were made on each set of simulations by comparing the spatial frequency at which a peak occurred within the average spatial periodogram. Prediction accuracy and bias were calculated for a range of window sizes of the rolling periodogram to generate the average spatial periodogram in which to extract the peak spatial frequency. On the left, shows the prediction accuracy (top) and the prediction bias (bottom) when grid cells alternate between anchored and non-anchored firing fields in blocks of trials, whereas the right shows the accuracy and bias when the probability of track anchoring is independent of whether track anchoring occurred on the previous trial.

Classification accuracy and bias on the level of trial as a function of rolling window size

The false alarm threshold is defined by the 99th percentile of the distribution of the peak power of the average spatial periodogram for 1000 shuffled instances of a cell’s firing rate profile across the full experimental session. The increased number of periodograms over which to average decreases this false alarm threshold asymptotically. Each red line represents a single cell within a representative session. The blue line represents the maximum number of periodograms in this session.

Assessment of the length of periodic coding blocks

(A) We compared the length of coding blocks - sequences of trials in which grid cells operate in the same mode - in the observed data with the length in datasets shuffled at the level of trials. To generate shuffled data spike locations were reallocated to a new position in the firing profile by randomly shuffling the trials. The rolling classification was then recomputed and length of coding blocks measured.

(B) Cumulative histogram of block lengths for the observed grid cell population (red) and the same grid cell population with the trial order shuffled and blocks recalculated (grey). P value for the Kolmogorov-Smirnov test is given above.

Grid cells switch between coding schemes coherently

(A) Joint activity of 6 simultaneously recorded grid cells. From top to bottom, plots show the firing rate map across trials, rolling spatial periodogram with predicted classifications to the right, and the average spatial periodogram. Cluster IDs (CIDs) are labelled at the top left on each panel.

(B) (i) Encoding blocks of the rolling classification are shuffled by positioning whole encoding blocks at random positions and (ii) an agreement score calculated based on the proportion of the session where coding blocks overlap between two cells.

(C) Agreement matrix for the coding scheme across a session for the example cells in A for the true comparison and between the average of shuffled blocks. Cluster IDs are ordered by their grid spacing (lowest to highest).

(D) Agreements between the true grid pairs and the block shuffled pairs test whether coding blocks agree within a session between pairs of grid cells above chance level (n = 110 grid pairs, N = 18 sessions). Only cells without a stable coding scheme were compared (<85 % of a stable coding scheme; Wilcoxon sign-rank test).

Classification of trial outcomes

Trials were classified into hits, tries and runs, based on stopping locations and the speed profile on a given trial. First, trials were classified into hits and misses based on whether a stop was registered in the reward zone or not. Next, a distribution of the average speeds in the reward zone is drawn for hit and miss trials, the 95th percentile of the hit average speeds in the reward zone was used to split the miss trials into near hits (tries) and run-throughs (runs). Finally, slow trials were removed to better discriminate trial outcomes based on the mouse’s engagement.

Supplemental Data

Tetrode localisation.

Micro-CT images used for assessment of tetrode locations in eight mice. For each animal, sagittal slices are presented lateral to medial from left to right and the classification of the tetrodes target is shown at the top left. This classification is based on the terminal location of the tetrode and the distance travelled during the experiment (see Methods). M10 sustained significant damage during preparation for microCT imaging and was not imaged. In all images red triangles point to the tetrode tracks. Scale bar denotes 1 mm.