Main

Motor cortex and its descending projections have expanded in certain mammalian lineages, seemingly because of the fitness conferred by the motor performance that they support1,2,3. Without normal motor cortical output, certain types of movement cannot be executed4,5,6. Many other types are slower, less agile and less effective, especially when dexterity is challenged or movements must adapt during execution7,8,9,10,11,12. Yet, when and how motor cortical output directly influences muscle activity through its descending projections to mediate this influence remains poorly resolved. The consequent ambiguity of direct motor cortical influence on muscles has stymied the development of more mechanistic models of descending motor control13.

Deficits from lesions and other inactivation of the motor cortex have not clearly resolved its involvement in movement execution. As the motor cortex is involved in motor learning14,15 and movement preparation or initiation16,17, deficits could reflect disturbance to these processes on which execution depends, rather than on the execution itself. Moreover, recent results indicate that motor cortical influence on muscle activity at the shortest latencies (10–20 ms in mice) differs from its influence on even slightly longer timescales (~50 ms)18.

During tasks requiring the motor cortex, existing results leave open several basic possibilities for the form that direct motor cortical influence on muscles could take. First, the motor cortex could drive the entirety of limb muscle activity patterns, with substantial compensation provided by other motor system regions after motor cortical disturbance. For example, when motor cortex needs to generate some muscle activity patterns that cannot be achieved by other regions19, it may assume all of the pattern-generating burden20. Second, the motor cortex could participate together with the rest of the motor system in generating motor output, without playing a role necessary to determining its pattern. Here loss of direct motor cortical influence on muscles would cause, at most, a nonspecific, fractional attenuation of motor output. Third, the motor cortex could selectively influence particular components of muscle activity, such that it informs (‘instructs’) ongoing muscle activity patterns and acts in a distinctly different way from the rest of the motor system. The loss of direct motor cortical influence would then cause changes in muscle activity that themselves vary as the state of muscle activity changes.

This ambiguity about the form of direct motor cortical influence on muscles has prevented resolution of other key issues related to the mechanisms of this influence. It remains unclear whether, on balance, motor cortical output only activates individual limb muscles or at times also suppresses their activity. The motor cortex is thought to drive online movement corrections and the adaptation of movements based on context9,21,22,23,24; such a role could involve the activation and deactivation of individual muscles at different times to steer movement as the context requires.

It also remains unclear what components of motor cortical output drive muscle activity. Previous descriptions of motor cortical activity have focused on components that covary with limb muscle activity25,26 or movement parameters like joint angles or reach direction (kinematics)27,28. However, if motor cortical output does not contribute to all muscle activity patterns, but instead selectively alters them, we might expect that the components of motor cortical output driving muscle activity may not reflect muscle activity in total, but only some fraction of it. Moreover, motor cortical activity that covaries with muscle activity or kinematics in total may be a consequence of monitoring or predicting the body state29, perhaps to subserve aspects of motor control apart from directly driving muscle activation30. In line with this, muscle activity can be decoded from motor cortical activity during movements where this activity does not directly drive muscles18. Thus, the components of motor cortical activity responsible for its direct influence may differ from those to which functional roles have previously been attributed31,32,33,34,35.

Below we address these basic questions about direct motor cortical influence on limb muscles36 using mice. The three possible forms that direct motor cortical influence on muscles could take make different predictions about how the influence will vary across different muscle activity states during a given motor behavior. Thus, we measured this influence across muscle activity states during a behavior expected to depend on motor cortical output. Our characterization of this influence includes identification of states where motor cortical output activates and deactivates muscles. Finally, we describe components of motor cortical output that could be responsible for its influence on muscle activity.

A naturalistic climbing paradigm

As previous studies have implicated the motor cortex in adaptive limb movements in response to unpredictable sensory information10,13,37, we developed a behavioral paradigm that emphasizes such movements. Inspired by the natural movement repertoire of mice, we developed a paradigm in which head-fixed mice climbed across a series of handholds that extend radially from a wheel, thereby rotating the wheel (Fig. 1a–d, Extended Data Fig. 1 and Supplementary Video 1). After each handhold accessible to the right limbs has rotated 180° past the mouse, a linear actuator embedded within the wheel moves the handhold to a new, randomly chosen, mediolateral position; the left handholds remain fixed (Fig. 1e and Extended Data Fig. 1b–d). This ensures that the sequence of right handholds across which the mouse climbs is unpredictable (Fig. 1f), so sensory information must be used in real time to steer right limb movement. In this paradigm, water-restricted mice earn water rewards by climbing intermittently in bouts throughout hour-long daily sessions. The variation in the mediolateral position of the right handholds leads to a variation in the direction in which the right forelimb reaches (Supplementary Video 1). A broad range of body postures is expressed (Extended Data Fig. 1e).

Fig. 1: Head-fixed climbing paradigm.
figure 1

a, Bird’s eye view of wheel apparatus for climbing. A shaft encoder measures the wheel’s angular position. Actuators randomize the position of each right handhold when they reach a point 180° away from the mouse. A ratchet ensures that the wheel rotates in only one direction. A slip ring commutes voltage signals to and from the actuators. b, A head-fixed mouse climbing in the paradigm. c, Frame of side-view video of a mouse climbing, with line plots connecting points tracked on the right forelimb and hindlimb from 50 sequential images (100 Hz) that have been overlaid. Line plot color reflects the time in the sequence. The points tracked were on the shoulder, elbow, wrist, last digit of the hand, hip, knee, ankle and edge of the foot. d, Same as c, but showing only the last frame in the sequence. e, Example sequence of right handhold positions over time, illustrating randomization. f, Autocorrelation of right handhold positions. gi, Median (black dots, n = 9 mice) and first and third quartiles (whiskers) for the fraction of time spent climbing (g), median climbing velocity (h) and median climbing bout distance (i) across sessions. Gray lines in gm are for individual mice. Session 1 indicates the first session after the mice had learned the pairing between climbing and reward, when reward dispensation switched from experimenter to computer control. j,k, Median (black dots, n = 9 mice) and first and third quartiles (whiskers) for the first (j) and second (k) principal angles between electromyographic time series collected during the twentieth climbing session and each of the first 20 climbing sessions. l,m, Median (black dots, n = 9 mice) and first and third quartiles (whiskers) for the sample entropy of muscle activity (l) and limb kinematics (m) time series across sessions. For each session, we took the mean across-sample entropy values for each muscle or for the xand y positions of each tracked limb point. The sample entropy measures the regularity in the time series40.

As it may be relevant to motor cortical involvement38, we assessed how the performance of climbing mice varied across daily sessions. To look for progressive improvement in a performance, we examined the measures of bout length and climbing speed, because the reward scheme depends on them. We found that, after mice are acclimated to head fixation (two sessions) and taught the pairing between climbing and reward (one to three sessions), there was little change, on average, in the time spent climbing (Fig. 1g), the velocity of climbing (Fig. 1h) and the distance of climbing bouts (Fig. 1i). To assess whether forelimb muscle activity patterns change progressively across sessions, we computed the principal angles between the first two principal components (PCs) for the activity of four muscles in the right forelimb39 during each session (two PCs by T time points; Extended Data Fig. 1f–h). Comparing each of the first 20 daily sessions to the twentieth session, we found that the first principal angle was generally low, averaging <2° (Fig. 1j,k). Although adjacent sessions appeared more similar (see the lower angles for session 19), there was little indication that increasingly distant sessions were increasingly more dissimilar, which would be expected for a progressive change in muscle activity. We also found that the stereotypy in both muscle activity and limb kinematics did not show clear signs of increasing across sessions40 (Fig. 1l,m and Extended Data Fig. 1i). Thus, after beginning to climb for rewards, mice do not appear to progressively develop climbing skills specific to our paradigm nor does muscle activity appear to change progressively across sessions. These results indicate that our climbing paradigm differs from those in which participants learn new tasks and become increasingly skillful and stereotyped with repeated training14,41.

Quantifying direct motor cortical influence during climbing

We next sought to quantify direct motor cortical influence on contralateral forelimb muscles across the range of muscle activity states expressed during climbing. Such an influence is not seen during treadmill walking18 and mice can still learn new stereotyped locomotor behaviors during split-belt treadmill adaptation after a bilateral motor cortical lesion42. However, lesion and pharmacological inactivation of the motor cortex does affect the execution of new locomotor adaptations in mice10,42,43. Given the different form and predictability of the movements elicited in our climbing paradigm, motor cortical influence was unclear a priori.

While mice (n = 8) were actively climbing, we sporadically and briefly inactivated the left caudal forelimb area (CFA, forelimb primary motor cortex + primary somatosensory cortex (M1 + S1)) at random. We used transgenic mice that express Channelrhodopsin-2 in all cortical inhibitory interneurons, applying occasional 25-ms blue light pulses that covered the surface of CFA (10 mW mm2; Fig. 2a). This yields an ~50% activity reduction across cortical layers within 7 ms, which reaches 90–95% in <20 ms (refs. 18,44). Light pulses were always >4 s apart to allow recovery of neural activity between events; on average, ~100–200 trials were collected during each daily session (11–37 sessions per animal). Equivalent events without blue light were notated in recordings to serve as control trials. Random trial timing ensured broad coverage of the muscle activity states that each mouse expressed during climbing. We found that inactivation and control trial averages diverged ~10 ms after light onset, which reflects the shortest latency at which CFA output influences muscles18 (Fig. 2a–c and Extended Data Fig. 2a–d). We also found that inactivation effects were similar in form across mice (Fig. 2a and Extended Data Fig. 2b) and strikingly consistent both within and across sessions (Extended Data Fig. 2e–g). Thus, CFA directly influences muscle activity during climbing, as we previously observed in mice performing a trained forelimb reaching task18.

Fig. 2: Comprehensive assessment of CFA influence across muscle activity states.
figure 2

a, Control (n = 1,671 trials) and inactivation (795 trials) trial averages (mean ± s.e.m.) for 4 muscles in 1 mouse. The inset showing the brain schematic is adapted from ref. 18. Vertical cyan bars in ad, g and k indicate the 25-ms epoch of blue light applied to the CFA and gray dotted lines are 10 ms after light onset. As we z-scored muscle activity measurements using the mean and s.d. from each given session, here and throughout we express measurements in s.d. values of the recorded signal. b, Control (18,397 trials) and inactivation (9,029 trials) trial averages for all 8 mice. c, Mean absolute difference between inactivation and control trial averages across all four muscles. Light-gray lines are individual animals and the solid black line is the mean across animals. For baseline subtraction, control trials were resampled to estimate the baseline difference expected by chance. d, Example of muscle activities and their corresponding first derivatives surrounding trials that were used for creating muscle activity state maps. The weight epoch immediately precedes the start of effects. e, Example of muscle activity state map from one animal. Larger, connected dots show examples of states for sequential overlapping epochs from individual trials. Pairs were chosen based on their similarity during the weight epoch. f, Grid overlaying a map, including only points from the weight epochs used for weighting trials in grid point trial averages. g, Schematic of the calculation of the inactivation effect at each grid point from the control (black) and inactivation (cyan) trial-averaged muscle activity. ΔC and ΔL reflect the slopes of lines connecting the average activity just before to just after the inactivation effect begins, for control trials and light trials, respectively. h, Schematic illustration of the effect size on a plot of ΔL versus ΔC. Their difference is proportional to the distance from the identity line. i, Map in which each grid point colored by the mean distance, in the full 80 dimensional space, between all pairs of embedded state vectors, with each individual distance weighted by a Gaussian function of the pair’s mean distance from the grid point on the 2D map. The Gaussian function is the same as that used for inactivation maps. j, Inactivation effect maps for the four recorded muscles. The color scale maximum and minimum reflect the maximum and minimum effect sizes across all four muscles collectively. jm, Representative results from one mouse. k, Grid point-averaged muscle activity from control (gray, mean ± s.e.m.) and inactivation (cyan, mean) trials, for three example grid points from the maps in j. l, Maps of P values computed for inactivation effects at each grid point. The q values (gray overlay) reflect the expected false discovery rate below the corresponding P value46. m, Maps showing the average activity for the four recorded muscles at each grid point. The color scale maximum and minimum reflect the maximum and minimum activity level for each muscle separately. The darker blue regions reflect states where the given muscle is inactive. The darker red regions reflect states where the given muscle is highly active, up to between 2.7 s.d. and 5.5 s.d. values above the mean. dist., distance; max., maximum; min., minimum.

To initially gauge whether direct motor cortical influence varies throughout climbing, we examined the effects of CFA inactivation during three stereotypical features of climbing: pulling a handhold down with the right forelimb, reaching the right forelimb up and palpation of the right handhold while grasping it (Extended Data Fig. 3). We assembled trial averages for muscle activity and limb kinematic time series aligned on trial onsets that occurred during each feature. The effect magnitude appeared to be vary across features. The effects were also more prominent in trial-averaged muscle activity than limb kinematics across all three features, which we explore further below.

We thus proceeded to more comprehensively assess CFA influence at different muscle activity states during climbing. We first sought a means for collecting together inactivation and control trials that began at similar muscle activity states, so that we could average across them. Plotting trials according to linear functions of muscle activity at trial onset led to an uneven distribution of trials across plots (Extended Data Fig. 3d,e). This was suboptimal for efficiently utilizing the statistical power afforded by our trials to differentiate CFA influence across states (Methods). We also suspected that this statistical power would be improved if trials were grouped together based on the time-varying pattern of muscle activity right before trial onset, because CFA influence could depend on this pattern.

We thus defined states using the activity of all four muscles over 50-ms epochs, rather than individual time points, and used Uniform Manifold Approximation and Projection (UMAP)45 to generate a two-dimensional (2D) map of the states expressed by each mouse, where similar states are close together. To ensure proximity on maps among states visited that are close in time, we defined epochs that overlapped in time. The muscle activity traces surrounding each trial, together with their corresponding first derivatives, were subsampled in 5-ms increments and divided into overlapping 50-ms epochs that began every 10 ms (Fig. 2d). For each 50-ms epoch, the muscle activity and first derivative trace segments were concatenated into a single vector (8 segments × 10 time bins = 80 elements). UMAP was then applied to map vectors onto two dimensions (Fig. 2e). On the resulting maps, embedded state vectors (points) from successive epochs form trajectories that reflect the sequence of states surrounding control and inactivation trials.

To measure direct CFA influence at different muscle activity states, we quantified the immediate inactivation effects for trials starting from states within local neighborhoods on the maps. We first defined a grid over each map (Fig. 2f). For each muscle, we computed its trial-averaged activity at each grid point, separately, for inactivation and control trials. For these averages, we used all trials, but we weighted each by a Gaussian function of the Euclidean distance between the given grid point and the point for the epoch just before an inactivation effect could begin on the given trial (−40 ms to +10 ms from trial onset: ‘weight epoch’; Fig. 2d). Trial weights are hence not influenced by inactivation effects. As a consequence, weight epoch states from control and inactivation trials are similarly distributed across maps (Fig. 2f). We set the Gaussian s.d. as roughly 10% of the map width, so trial averages are heavily weighted toward trials beginning at states close to the given grid point. Only grid points close to a substantial number of weight epoch states were subsequently considered (‘valid grid points’; Methods). For each muscle, we measured separately the size of the inactivation effect at each valid grid point as the difference between the rate of change in inactivation and the control trial averages from 0 ms to 20 ms after trial onset (Fig. 2g,h). We then plotted the resulting effect sizes at each valid grid point across the map, producing an ‘inactivation effect map’ (Fig. 2j and Extended Data Fig. 4a–d). Maps for different muscles in a given mouse show wide variation in the magnitude and sign of inactivation effects across grid points (Fig. 2j,k). We resampled from control trials to compute a P value for each grid point’s effect size (Fig. 2l and Extended Data Fig. 4a–c). The map structure was not strongly dependent on the choice of key parameters (Extended Data Fig. 4f–i).

As UMAP is nonlinear, it is not clear how the distance across maps will correspond to differences in muscle activity state. To address this and clarify muscle activity levels at different map locations, we plotted the average activity of each individual muscle at each grid point using the same Gaussian weighting method as above (Fig. 2m). These plots showed smooth and gradual variation across grid points. We also plotted the average similarity between nearby state vectors across maps (Fig. 2i and Extended Data Fig. 4e). The only prominent variation that we observed was a gradual increase in pairwise distance from the map center to the edges; there was no indication of abrupt changes in pairwise distance. Thus muscle activity state varies smoothly across state maps at the resolution of our inactivation effect maps.

The CFA acts primarily by selectively exciting physiological flexors

To distinguish among the three possible forms that direct motor cortical influence on muscles could take, we then analyzed the inactivation effect maps. We first generated histograms of the P values computed for effects on each muscle at all valid grid points. These histograms consistently showed a skew toward zero, reflecting a substantial fraction of grid points where the null hypothesis of no effect was false (Fig. 3a,b). From these distributions, we estimated the fraction of grid points showing effects46 (Fig. 3c). The mean estimated fractions were 0.62, 0.22, 0.73 and 0.37 for elbow flexor, elbow extensor, wrist extensor and wrist flexor muscles, respectively. These estimates were significantly above zero for all four muscles. Control maps generated from comparisons between separate sets of control trials yielded uniform distributions, as expected under the null hypothesis (Extended Data Fig. 5a). These results show that the direct influence of CFA on muscles is specific to a subset of muscle activity states. This is not consistent with either the CFA driving the entirety of limb muscle activity or the CFA having a nonspecific effect on muscles. Rather, CFA appears to selectively influence particular components of muscle activity.

Fig. 3: The CFA selectively excites physiological flexors.
figure 3

a,b, Distributions of P values for inactivation effects on each muscle for all grid points in one mouse (a) and across all eight mice (b). Left: elbow flexor (first), elbow extensor (second). Right: wrist extensor (second) and wrist flexor (first). The error bars in b indicate the s.e.m. c, Estimated fraction of grid points at which the null hypothesis of no effect is false, calculated from distributions of P values for eight individual mice (black circles) and the mean across mice (red bars). Values were significantly above 0 for all muscles (P = 0.008 or P = 0.016, two-sided Wilcoxon’s signed-rank test). The estimated fraction of grid points yielding false null hypotheses was significantly greater for the elbow flexor (P = 0.007, two-sided Wilcoxon’s rank-sum test) and wrist extensor (P = 0.015), compared with their respective antagonists. d, For one mouse, the 2D autocorrelation (autocorr.) for inactivation effect maps and control maps generated with only control trials (top) and scatterplots of correlation values versus their spatial offset (lag from zero offset). pts., points. e, Difference between inactivation effect maps and control maps in their mean autocorrelation over spatial offsets from 0 grid points to 20 grid points for 8 individual mice (black circles) and the mean across mice (red bars). Differences were significantly >0 for all four muscles (P = 0.008, two-sided Wilcoxon’s signed-rank test). The magnitude of CFA influence across states differed significantly between muscles in six of eight mice (P < 0.004, P = 0.19 and P = 0.83 in two other mice, Kruskal–Wallis test). f, For one animal, scatterplots of inactivation effect size versus muscle activity at trial onset (averaged from −40 ms to +10 ms relative to onset). Each point reflects a different grid point. The R2 is for a linear fit (red). g, R2 for linear fits to scatterplots of inactivation effect size versus muscle activity at trial onset for eight individual mice (black circles) and the mean across mice (red bars). The residuals were significantly nonuniform (P < 10−10 for all mice, two-sided Kolmogorov–Smirnov test). h, Effect size distributions for all grid points across all eight mice, separately for inactivation effect maps and control maps. i,j, Effect size distributions for all significant grid points from all eight mice (i) and one mouse (j). Left: elbow; right: wrist. k, Same as i, but zoomed in to clarify rarer effects. l, Grid point-averaged muscle activity (mean ± s.e.m.) from control and inactivation trials, for four example grid points where inactivation significantly increased muscle activity in four different mice. The three on the left are for the elbow extensor and the one on the right is for the wrist flexor. m, The 2D correlation between inactivation effect maps for different muscles for one mouse (top) and the means across all eight mice (bottom).

To better characterize this selective influence, we next assessed whether CFA influence varies in magnitude across muscle activity states. If this were true, then the 2D autocorrelation of inactivation effect maps should be significantly above what is expected by chance. We computed the 2D autocorrelation of both inactivation effect maps and control maps, observing substantially heightened autocorrelation in the former (Fig. 3d). To assess whether these differences were significant, we computed the mean difference between inactivation effect map autocorrelation and that of control maps, averaged over spatial lags up to 20 grid points (Fig. 3e). These differences were significantly >0 for all four muscles. We also found that the magnitude of CFA influence across muscle activity states differed significantly between muscles in six out of eight mice. The magnitude of CFA influence was not simply proportional to the magnitude of the muscle activity; the coefficient of determination (R2) for linear fits to effect size versus muscle activity magnitude was low (Fig. 3f,g and Extended Data Fig. 5b–e) and the residuals were significantly nonuniform.

A number of previous observations indirectly suggest that primary motor cortex may preferentially control certain muscle groups more so than their antagonists47,48,49. We thus compared the distributions of effect sizes across grid points for each muscle. We found larger deviations from control effect sizes for the elbow flexor and wrist extensor (Fig. 3h). The estimated fraction of grid points showing effects (false null hypotheses, Fig. 3c) was significantly greater for the elbow flexor (61% higher) and wrist extensor (43% higher), compared with their respective antagonists. This indicates that CFA output preferentially influences elbow flexors and wrist extensors, which can be grouped together as physiological flexors because of their coactivation during both locomotion and the flexion reflex50.

We also assessed whether these differences in effects on muscles might extend to the direction of effects. Reduction or elevation of muscle activity after inactivation indicates that CFA output activates or suppresses muscle activity, respectively. We examined the effect sizes that were significantly different from zero, finding that, for the physiological flexors, effects were always a reduction in muscle activity (Fig. 3i–k). However, the elbow extensor exhibited both reduction and elevation and the wrist flexor showed elevation in a small fraction of states as well (Fig. 3k). This can be seen in the trial-averaged muscle activity for individual grid points from inactivation effect maps (Fig. 3l). We also observed that inactivation effect maps for the physiological flexors were more highly correlated compared to those for all other pairs of muscles (Fig. 3m), suggesting a greater degree of coordinated control of these muscles. Collectively, these results indicate that the CFA influences muscles to varying degrees and only at some muscle activity states (that is, the influence is selective). CFA’s influence is therefore primarily an activation of physiological flexors; only the elbow extensor, where influence was relatively infrequent, shows a balance of activation and suppression.

Weak covariation between CFA influence and gross kinematic state of the forelimb

A number of previous observations suggest that the motor cortex may, to some extent, control the limb via commands that dictate its kinematics rather than muscle activation51,52, although this remains controversial32,53. If the CFA were dictating contralateral forelimb kinematics, we reasoned that direct CFA influence on muscles should correlate with the orientation of the contralateral forelimb. We therefore probed for this correlation.

Here we mimicked the approach that we took to assess how CFA influence covaries with muscle activity state. We computed new state maps with UMAP using vectors composed of the horizontal and vertical positions of sites on the right forelimb tracked from a video (Fig. 4a,b and Extended Data Fig. 6a–c). Nearby points on these maps thus reflect 50-ms epochs of limb kinematics that are similar. The resulting 2D maps separated states that correspond to different limb orientations into different map regions (Fig. 4c), with the cyclic changes in limb orientation during iterative climbing ordered around the map. Using these maps, we quantified the effects of CFA inactivation on each forelimb muscle at grid points covering the maps as above. Histograms of the inactivation effect sizes across all grid points showed deviations from the controls (Fig. 4d). However, the P-value distributions for effects on each muscle showed very limited skew toward zero, indicating discernible effects on only a small fraction of grid points (Fig. 4e). Thus, CFA influence on muscles does not covary with forelimb orientation nearly as well as it does with muscle activity state.

Fig. 4: Gross forelimb kinematics capture CFA influence worse than muscle activity.
figure 4

a, Time series of tracked forelimb sites and their corresponding first derivatives surrounding inactivation and control trials windowed into overlapping segments. The segments are used to create 2D embedding via UMAP. b, Image showing the locations of the eight sites tracked on the forelimb, according to the color code in a. c, Example map of forelimb orientation states from one mouse, along with the trial-averaged positions of the forelimb sites at selected grid points within the map (red circles). As the video was captured at 100 Hz, time series segments used here had 10-ms spacing between points instead of 5 ms, as in Fig. 2. dg, Distributions of the sizes of inactivation effects on muscles (d), P-value distributions for inactivation effects on muscles (e), distributions of the sizes of inactivation effects on four main forelimb sites (f) and P-value distributions for inactivation effects on four main forelimb sites (g), calculated using forelimb orientation maps, across all grid points and all eight mice. The error bars in e and g indicate the s.e.m. h, Histograms of Pearson’s correlation between muscle activity and four forelimb site positions (shoulder, elbow, wrist and finger), aggregated over all eight mice and all four sites. i,j, Maps of muscle activity states (left: orange) and limb orientation states (right: green) from one animal. Black circles in each panel mark corresponding sets of embedded vectors on the two maps (that is, those coming from the same set of epochs). The marked sets are clustered based on muscle activity state (i) or limb orientation state (j). Both map types used the same time point spacing (10 ms) and equivalent amounts of data. k, For the embedded vectors from 200 randomly selected epochs, the Euclidean distance between all possible pairs of those vectors on the muscle activity map in i and j plotted against the distance between their corresponding vectors on the limb orientation map. corr., correlation; ES1 and ES2, first and second sites between elbow and shoulder joints; WE1 and WE2, first and second sites between wrist and elbow joints.

If CFA output dictates forelimb kinematics, we might expect CFA inactivation to perturb the limb kinematics themselves. We therefore quantified the effect of inactivation on the position of the sites tracked at the shoulder, elbow, wrist and finger. Inactivation effects were computed as above, but using trial-averaged site position in place of trial-averaged muscle activity. Again, histograms of inactivation effect sizes did show deviation from controls (Fig. 4f), but P-value distributions showed very limited skew toward zero. This indicates that there are discernible effects on only a small fraction of grid points (Fig. 4g). Collectively, these results suggest that CFA output directly specifies muscle activity and not limb orientation.

Given an expectation that muscle activity and limb kinematics should covary, these results may seem surprising. However, we note that, during adaptive, nonstereotyped motor behaviors like climbing in our paradigm, linear covariation between muscle activity and limb orientation will not necessarily be consistent, due to the complex causal interrelationship of these variables. To illustrate this, we measured their correlation over 150-ms epochs (Fig. 4h). Correlation values were broadly distributed from −1 to 1 in all cases. We verified that this was not because changes in muscle activity were somehow not associated with the changes in joint angles that they are expected to cause (Extended Data Fig. 6d–g). Next, we made state maps using muscle activity or limb orientation from the same set of recording epochs. We found that the proximity of muscle activity states on maps only weakly predicted the proximity of the corresponding limb orientation states and vice versa (Fig. 4i–k). Subsets of states close together on one map type corresponded to states that were widely distributed on the other map type. This decoupling between muscle activity and limb kinematics may have helped reveal that CFA influence is not well organized by limb orientation.

CFA firing patterns during climbing

To assess what components of CFA output might drive the direct influence that we have identified, we next sought to determine how CFA firing patterns covary with CFA influence on muscles. We used Neuropixels to measure the firing of CFA neurons across cortical layers in three mice for which inactivation effect maps were computed (Fig. 5a–c). After completing the collection of inactivation trials for mapping influence, we recorded neural activity in the CFA with acutely implanted Neuropixels during the next three to four daily behavioral sessions. The majority of both wide-waveform and narrow-waveform units had higher firing rates during forelimb muscle activity compared with periods when all recorded muscles were quiescent (Fig. 5d). Over 80% of recorded units had firing rate time series that were significantly correlated with the activity of at least one muscle (Fig. 5e). Fitting muscle activity time series with neuronal firing rates using ridge regression and Weiner’s cascade models yielded similar accuracy across muscles (Extended Data Fig. 7a).

Fig. 5: CFA firing patterns vary in their sparsity across muscle activity states.
figure 5

a, Histogram of the depth below pia of recorded neurons across all 3 mice (366–684 single units met selection criteria). Inset: a schematic coronal section showing placement of the Neuropixels in the CFA. b, Fractions of neurons assigned to narrow-waveform (87–189 per mouse) and wide-waveform (279–495 per mouse) subsets in each of 3 mice (black circles) and the mean across mice (red bars). c, Normalized absolute activity change from baseline summed across the top three PCs for recorded CFA neurons and the top PC for muscle activity, for individual mice (thin gray) and the mean across mice (black). d, Scatterplot of the mean firing rate for neurons during periods of no muscle activity (rest) and periods of muscle activity, across all three mice. e, Fraction of neurons in different layers with firing rate time series significantly correlated (corr.) with the activity time series for at least one forelimb muscle. The results are shown for three mice (black circles), except one mouse that had very few neurons assigned to layer 6, preventing a reliable calculation in that case. The red bars indicate the mean across mice. f, Schematic of the calculation of an activity map for each recorded neuron across 180 Neuropixels channels (ch) that is registered to inactivation effect maps. g, Example neural activity maps exhibiting somewhat sparse firing (black values) for 11 neurons from 1 mouse, along with their maximum firing rates (red). h, Neural maps with sparsity values reflecting the quartiles of the sparsity distribution for the given mouse. i, Cumulative histograms of sparsity values for all neurons in each of three mice. j, Scatterplot of sparsity versus mean firing rate during climbing for neurons in all three mice. The R2 is for a linear fit (red). k, Mean 2D correlation of activity maps for neurons assigned to different layers (red), compared to a null distribution computed by repeating the calculation 100× after randomly permuting neuronal layer labels (gray) and the means thereof (black bars).

To enable alignment with CFA influence, we measured the variation in the firing of neurons across the muscle activity state maps used for quantifying inactivation effects (Fig. 5f). Muscle activity state vectors for 50-ms epochs during Neuropixels recordings were embedded on the same state maps used for quantifying inactivation effects in the given animal. For each neuron, its average firing rate was estimated at each grid point, producing a ‘neural activity map’. This aligns neural activity during muscle activity states with inactivation effects which immediately follow similar muscle activity states.

Neural activity maps showed a wide array of muscle state-dependent firing patterns. In particular, we found many neurons with firing that was somewhat sparse across maps; firing was heavily concentrated in subregions of the maps and mostly or completely absent in others (Fig. 5g). To quantify this sparsity, we used an index that was originally developed to measure the place-dependent firing of hippocampal neurons54. Ordering neurons by this sparsity index revealed that even the neurons with a median level of sparsity had firing that was heavily concentrated in subregions of the maps (Fig. 5h,i and Extended Data Fig. 7b). Sparsity was only weakly dependent on the mean firing rate during climbing (Fig. 5j). Neural activity maps did not vary substantially across cortical layers, because the average 2D correlation between maps for neurons assigned to different layers was similar to that expected, assuming no variation across layers (Fig. 5k). Thus, a substantial fraction of CFA neurons across cortical layers each fire primarily at a limited range of muscle activity states during climbing. These results indicate that CFA neuron firing carries information about muscle activity states organized by their similarity.

CFA activity components that align with inactivation effects

We then used neural activity maps to identify components of CFA firing that align with CFA influence on muscles. We did so by combining singular value decomposition (SVD) and canonical correlation analysis (CCA) to align neural activity maps with the inactivation effect maps computed for the same animals55. The neural activity map for each wide-waveform neuron with overall mean firing rate >0.1 Hz was converted to a vector by concatenating its columns. For each mouse, these vectors were combined into grid points by neurons matrix, which was then replaced with a dimensionally reduced grid points by 20 neural singular vectors matrix computed with SVD (Fig. 6a,b). These dimensionally reduced matrices were then aligned through CCA with grid points by muscles matrices formed similarly by concatenating the columns of inactivation effect maps for the four recorded muscles (Fig. 6a–d).

Fig. 6: A CFA activity subspace that aligns with CFA influence.
figure 6

a, Schematic for computing the influence subspace. b, Cumulative neural activity variance captured for singular vectors ordered by their singular values, for each of three mice. Each connected set of dots in b and eg is from a separate mouse. c,d, Canonical variables for the inactivation effects (c) and neural activity (d) for one mouse. Max., maximum; min., minimum. e, Correlation coefficients of canonical variables for each mouse. Correlations were significantly higher than null distributions generated by randomly permuting the map locations of muscle activity states from neural recordings (for canonical variables 1–4, mean null correlation = 0.74, 0.72, 0.69 and 0.65; P = 0.001 in all cases). f, Fractional inactivation effect variance captured by canonical variables for each mouse. g, Cumulative fraction of inactivation effect variance captured by canonical variables after orthogonalizing their corresponding vectors, for each mouse.

The resulting canonical variables reflect the components of CFA firing patterns that maximally correlate with components of inactivation effects but are mutually uncorrelated with each other. For all three animals, neural and inactivation effect canonical variables were highly correlated and the inactivation effect variables captured substantial fractions of inactivation effect variance (Fig. 6e,f; mean correlation = 0.99, 0.97, 0.92 and 0.86 for canonical variables 1–4; mean effect variance capture = 0.29, 0.26, 0.18 and 0.11). Plots of the cumulative variance captured across orthonormalized canonical vectors indicated that each inactivation effect variable captured a substantial amount of additional inactivation effect variance (Fig. 6g). Although CCA attempts to maximize correlation between canonical variables, it is not fated that each inactivation effect variable will account for a great deal of the variance in effect maps, as they do here. Repeating CCA using the inactivation effect map of each individual muscle found a CFA activity component that highly correlated with the inactivation effects for the given muscle in all cases (median correlation = 0.97, range = 0.89–0.99, total of 12 muscles in 3 animals). This indicates that CFA activity aligns well with the effects on each individual muscle.

To validate our results, we repeated the CCA calculations after randomly permuting the map locations of muscle activity states from neural recordings. The resulting correlation between canonical variables was significantly lower than for the original data (Fig. 6e). We also repeated CCA calculations 300× using separate, randomly chosen halves of trials for computing the inactivation effect maps. The canonical variables identified with each half of the trials were highly similar (Extended Data Fig. 8a), as were the 4D neural activity subspaces spanned by the neural canonical vectors (Extended Data Fig. 8b). In addition, we found that CCA results were not highly dependent on the number of singular vectors used for neural dimensionality reduction (Extended Data Fig. 8c–f), nor did they depend on the choice of key inactivation map parameters (Extended Data Fig. 8g). Thus, neural canonical vectors span a neural activity subspace where activity aligns closely and nontrivially with inactivation effects. Below we refer to this as the ‘influence subspace’.

We also assessed whether subsets of neurons contributed disproportionately to these influence subspaces. To compute the relative contribution of each neuron to each canonical vector, we used the weight of each neuron in the singular vectors and the weights of these singular vectors in the neural canonical vectors. However, we found no evidence that neurons cluster in terms of their contribution sizes (Extended Data Fig. 9a–d). Contributions to canonical vectors were substantially overlapping for neurons localized to different layers, although they were significantly higher for neurons localized to layers 5 and 6 compared to those localized to superficial layers (Extended Data Fig. 9e,f).

Influence subspace differs from muscle activity and limb kinematic equivalents

Finally, we sought to test the hypothesis that CFA’s direct influence on muscles is mediated via the CFA activity components that correlate with muscle activity or limb kinematics in total. If this were true, we would expect that the influence subspace would be similar to subspaces aligned with muscle activity or limb kinematics (Fig. 7a). To find a subspace in which CFA activity aligns with muscle activity, average muscle activity maps (Fig. 2m) for each mouse were converted to vectors, assembled into a grid points by muscles matrix and aligned via CCA with the matrix of dimensionally reduced neural activity (Fig. 7b,c and Extended Data Fig. 10a,b). To find a subspace in which CFA activity aligns with limb kinematics, we used the limb kinematic state maps generated for inactivation sessions (Fig. 4). We embedded vectors, composed of limb site positions and their corresponding first derivatives from neural recording sessions, into these existing limb kinematic state maps. We then made maps of the average horizontal and vertical positions of each site at grid points defined on the limb kinematic state maps (Extended Data Fig. 10c). We assembled neural activity maps for each neuron using segments of their firing rate time series that correspond to embedded limb kinematic state vectors (Extended Data Fig. 10d). These site position and neural maps were aligned via SVD and CCA (Fig. 7d,e and Extended Data Fig. 10e). Substantial fractions of both muscle activity and kinematics variance were captured by canonical variables that were highly correlated with their corresponding neural canonical variables (Fig. 7f–i). Thus, the resulting neural canonical vectors span neural activity subspaces where activity aligns with either muscle activity or limb kinematics.

Fig. 7: Divergence between neural activity subspaces aligned with inactivation effects, muscle activity and limb kinematics.
figure 7

a, Schematic of different scenarios for the overlap between neural activity subspaces. Dim, dimension. b,c, Canonical variables for muscle activity (b) and neural activity (c) for one mouse. Max., maximum; min., minimum. d,e, Canonical variables for limb kinematics (d) and neural activity (e) for the mouse used in b and c. f, Correlation coefficient (black) and fractional muscle activity variance captured (red) for canonical variables. Each set of connected dots in fn is from one mouse. g, Cumulative fraction of muscle activity variance captured by canonical variables after orthogonalizing their corresponding vectors. h, Correlation coefficient (black) and fractional limb kinematics variance captured (red) for canonical variables. i, Cumulative fraction of limb kinematics variance captured by canonical variables after orthogonalizing their corresponding vectors. j, Overlap of different activity subspaces (black circles) compared to 100 estimates of the overlap expected by chance for each animal (gray dots). km, Principal angles for different activity subspaces (black circles) compared to 100 estimates of the principal angles expected by chance for each animal (gray dots). k, Effect versus muscle. l, Effect versus limb. m, Muscle versus limb. n, Mean overlap (black circles) between subspaces defined from two maps made with separate halves of time series segments, for 300 different segment parcellations (gray dots).

To evaluate the similarity among the influence, muscle activity and limb kinematics subspaces, we compared them in two ways. First, we asked whether they were more similar than would be expected by chance for different subspaces. We measured the overlap between pairs of subspaces and compared this to the overlap when one was replaced by a random subspace that captured the same amount of neural activity variance (Methods). On a scale from 0 (no) to 1 (complete) overlap, the overlap of the influence subspace with the muscle activity subspace ranged from 0.423 to 0.740 across the 3 mice, substantially above chance (Fig. 7j). However, the overlap between influence and limb kinematics subspaces ranged only from 0.018 to 0.030 and the overlap between muscle activity and limb kinematics subspaces ranged only from 0.025 to 0.060; these overlaps were on a par with those expected by chance. The same relationships between subspaces were reflected in their principal angles as well (Fig. 7k–m). Overlap values were not strongly sensitive to the precise choice of key map parameters (Extended Data Fig. 10f).

Second, we asked whether these three subspaces were less similar than would be expected by chance for two subspaces of the same type. We measured the overlaps between subspaces of the same type or different types, each computed from separate sets of time series segments (Fig. 7n). In all cases, the overlap for subspaces of different types was much lower than that for the same type. Thus, the influence subspace overlaps partially, but not completely, with the muscle activity subspace, yet the influence subspace has no appreciable overlap with the limb kinematics subspace.

Discussion

Here we have assessed the direct influence of motor cortical output on muscle activity during naturalistic climbing in mice. By quantifying this influence across the full range of muscle activity states that occur during climbing, we have shown that the CFA acts selectively, instructing motor output patterns. CFA activates physiological flexor muscles to varying degrees and only at a subset of muscle activity states, while activating or suppressing their antagonists less frequently. We have also shown that many CFA neurons are primarily active at subsets of similar muscle activity states. Finally, our approach enabled us to distinguish a neural activity subspace aligned with CFA influence from those aligned with muscle activity or limb kinematics. These results suggest that, during an ethologically relevant motor behavior, mouse motor cortex appears to selectively direct muscle activity through a neural activity subspace distinct from those previously thought to contribute directly to motor output31,32,33,34,35.

The motor cortex has activity components that predict muscle activity and movement kinematics25,26,27,28. This could reflect a cortical role in generating all limb muscle commands during motor cortically dependent behaviors. At the same time, disturbance to motor cortical output often causes hypometric limb movements9,24,43,56,57, suggesting that the motor cortex contributes to driving muscle activity, but does not play a necessary role in determining its pattern in many cases. In either of these scenarios, we would have observed inactivation effects that were pervasive across all muscle activity states. Instead, we have found that, during a cortically dependent task in mice, the influence of the primary motor cortex on forelimb muscle activity is selective and instructive. This is supported by our observations that inactivation effects on individual muscles are present only at a subset of muscle activity states, these effects vary in magnitude across that subset, and the pattern of effect magnitudes across states itself varies across muscles. To focus on the CFA’s direct influence on muscles, we measured inactivation effects at the shortest latency CFA output that can affect forelimb muscles in mice18. Effects at this latency are not seen during all motor behaviors.

The motor cortex may confer an added level of muscle control that improves movement efficacy by generating muscle activity patterns that cannot be achieved by other motor system regions19. Our results suggest that this role may be mediated by a selective modulation of ongoing motor output, one that differs categorically between muscles of different functional types. We were surprised to observe that direct motor cortical influence on physiological flexors was always activating. Although influence on their respective antagonists did involve a mix of activation and suppression, the prevalence of activation and suppression was similar only for the elbow extensor where its influence was relatively infrequent overall. Thus, the CFA acts primarily by selectively exciting physiological flexors. Given the nonstereotyped and adaptive nature of the movements that mice perform in our paradigm, during an otherwise rhythmic locomotion, we had expected the CFA output to both activate and suppress each muscle at different states. For example, if the motor cortex served only to introduce corrections to reduce the deviation from a target movement, as predicted by the current theory58,59, we would expect both activation and suppression if errors were symmetrical around the target.

It remains unclear how well our basic results here generalize to other mammals, including primates. Despite substantial homology between rodent and primate motor circuits2,60, functionally salient differences exist, especially in the circuits that govern finger movements13,61. That said, at least for nonhuman primates, broad swaths of the motor behavioral repertoire recover after motor cortical lesions, including walking, climbing, jumping and even goal-oriented manual tasks, although performance efficacy is reduced in all cases8,62,63. These results could reflect that, aside from individuated finger movements, the motor cortex does not generate the entirety of limb muscle activity patterns, but instead selectively modulates muscle activity patterns to improve movement efficacy.

We found that some CFA neurons fire preferentially for different subsets of similar muscle activity states. This does not align with the view that M1 activity is well described as a low-dimensional, linear, dynamic system34,53. In this view, the activity of each M1 neuron reflects a linear combination of a small number of latent variables. Neurons active during distinct subsets of muscle activity states would require distinct latent variables to capture their activity, increasing the dimensionality of the population activity as a whole. A small number of linear latent variables might still capture much of the variance in our activity measurements, but they would not explain the highly state-specific firing patterns of some neurons. As these firing patterns carry information about motor output, they may play an important role in motor control. The high state specificity of many neurons is also not predicted by previous characterizations of M1 neurons as broadly tuned for muscle activity or movement kinematics27,28,64. Here again, however, this aspect of our results may not generalize to other species or to the ballistic reaching tasks used in many previous studies. That said, it does align with recent demonstrations of reproducible, high-dimensional activity in the monkey M165.

Our observations also have important implications for the functional interpretation of kinematics-related neural activity. By focusing on a context in which muscle activity and gross limb kinematics are substantially uncoupled, we found that the neural activity subspace where activity aligns with these kinematics is essentially orthogonal to the one that aligns with direct CFA influence. However, we cannot rule out that there are other, perhaps finer, kinematic features that more substantially covary with direct CFA influence. Despite this, our observations remain a substantial revelation given the contemporary prevalence of video-based kinematic tracking for measuring nervous system output. Prominent kinematic features can correlate substantially with activity in a neuronal population, but correlate negligibly with the functional influence of that activity.

Methods

All experiments and procedures were performed according to the US National Institutes of Health (NIH) guidelines and approved by the Institutional Animal Care and Use Committee of Northwestern University (protocol no. IS00009077). No statistical methods were used to predetermine sample sizes but our sample sizes were similar to those reported in previous publications10,14,18. No parametric statistical tests were used for data analysis, so we did not test whether data were normally distributed.

Experimental animals

A total of 50 adult male mice were used, including those in early experimental stages to establish methodology. Strain details and number of animals in each group are as follows: 44 VGAT-ChR2-EYFP line 8 mice (B6.Cg-Tg(Slc32a1-COP4*H134R/EYFP) 8Gfng/J; Jackson Laboratories, stock no. 014548) and 6 C57BL/6J mice (Jackson Laboratories, stock no. 000664). All experiments were performed using VGAT-ChR2-EYFP line 8 mice.

All mice used in experiments were individually housed under a 12-h light:dark cycle in a temperature-controlled and humidity-controlled room with free access to food and water, except during experiments. At the time of the measurements reported, animals were 12–18 weeks old and weighed 24–30 g. All animals were being used in scientific experiments for the first time, including no previous exposure to pharmacological substances or altered diets.

Climbing apparatus

The climbing apparatus (Extended Data Fig. 1) was housed inside a sound-attenuating chamber (Coulbourn, cat. no. H10-24A). Experimental control was performed using the MATLAB Data Acquisition Toolbox, the NI PCI-e-6323 DAQ and two Arduino Duos. The climbing apparatus itself consisted of a 3D printed cylindrical wheel with alternating handholds positioned 12° apart from each other. The right handholds were affixed to linear actuators (Actuonix, cat. no. L-12-30-50-12-I), whereas the left handholds were statically positioned. A ratchet mechanism was used to ensure that the climbing wheel could rotate only downward from the mouse. One end of the wheel was supported by a shaft angular encoder (US Digital, cat. no. A2-A-B-D-M-D). Angular position signals were sent to the Arduinos to track the location of each handhold. When each right handhold reached a position 180° away from the mouse, the linear actuator moved the handhold to a new, randomly chosen, mediolateral position. The other end of the wheel was supported by a slip ring (Michigan Scientific, cat. no. SR20M-LT) that commuted voltage signals to and from the actuators embedded in the wheel. Water rewards were dispensed with a solenoid valve (NResearch, cat. no. 161T012) attached to a lick tube (Thermo Fisher Scientific, cat. no. 01-290-12) and this dispensation was controlled by MATLAB through the NI PCI-e-6323 DAQ. A speaker was used to play a 5-kHz tone for 200 ms whenever rewards were dispensed.

Training

Under anesthesia induced with isoflurane (1–3%), mice were fitted out with titanium or plastic head plates affixed to the skull using dental cement (Metabond, Parkell). Headplates had an open center that enabled subsequent access to the skull, which was covered with dental cement. During headplate implantation, the position of bregma relative to the marks on either side of the headplate was measured to facilitate the positioning of craniotomies during later surgeries. After recovery from headplate implantation surgery, mice were placed on a water schedule in which they received 1 ml of water per day.

At least 4 d after the start of the water schedule, the mice were acclimated to handling by the experimenter following established procedures66. After acclimation to handling, the mice were acclimated to head fixation over two daily sessions during which they were placed in a 3D printed hutch positioned directly in front of the climbing wheel apparatus and provided water rewards (3 μl per reward) at regular intervals.

After acclimation, the mice underwent daily hour-long training sessions on the wheel apparatus. Training involved an initial stage (one to three sessions) aimed at training mice to grab for and pull at the handholds to rotate the wheel downward and receive a water reward. The mice were head fixed in an upright position, facing the front of the wheel so that all four limbs could easily grab on to the handholds, and the right handholds remained fixed. Rewards were triggered by an experimenter’s key press whenever a mouse performed any slight rotation of the wheel downward toward its body and longer or faster bouts were rewarded with additional rewards. Over the course of these sessions, the mice generally learned to associate rotating the wheel with a water reward and began iteratively rotating the wheel.

During the next stage of training (four to ten sessions, median five), right handholds were kept fixed and the mice were encouraged to rotate the wheel for increasingly long bouts. Here rewards were dispensed for continuous climbing bouts above a threshold distance after the bout ended, using an automated experimental control script written in MATLAB. The first ten times during a training session that the threshold distance was met, the mice automatically received a water reward. Subsequently, the total distance traveled was compared to those from the previous ten bouts. If the time was above the 25th percentile value for those ten bouts, the mouse received one water reward, if it was above the 60th percentile value, the mouse received two water rewards and, if it was above the 90th percentile value, the mouse received four water rewards. Otherwise, the mouse received no water reward. The threshold distance was adaptively adjusted to maintain the reward rate such that the mouse received approximately 1 ml of water during each hour-long training session. Thus, if the recent reward rate was too low, the threshold distance was lowered and, if the recent reward rate was too high, the threshold distance was raised. During all subsequent training sessions, the right handhold positions were randomly repositioned along the horizontal axis after rotating past the mouse, although the same reward scheme was used.

In this paradigm, the mice performed a sophisticated locomotion that deviated from a rhythmic pattern to negotiate unpredictable variation in the ‘terrain’ presented by the handholds. The consistency of climbing form and performance across sessions (Fig. 1), together with the natural climbing ability that mice possess, obviated the need for extensive training. In fact, some mice exhibited long, continuous bouts of climbing over the first session during which they were taught the climbing–reward pairing.

EMG recording

Electromyographic (EMG) electrode sets were fabricated for forelimb muscle recording using established procedures18,39. Briefly, each set consisted of four pairs of electrodes. Each pair comprised two 0.001″ braided steel wires (A-M Systems, cat. no. 793200) knotted together. On one wire of each pair, insulation was removed from 1 mm to 1.5 mm away from the knot; on the other wire, insulation was removed from 2 mm to 2.5 mm away from the knot. The ends of the wires on the opposite side of the knot were soldered to an eight-pin miniature connector (Newark, cat. no. 11P3828). Different lengths of wire were left between the knot and the connector, depending on the muscle within which a given pair of electrodes would be implanted: 3.5 cm for biceps and triceps, 4.5 cm for extensor carpi radialis and palmaris longus. The ends of the wires with bared regions had their tips stripped of insulation and then were twisted together and crimped inside a 27G needle that facilitated insertion into the muscle.

Mice were implanted with EMG electrodes during the surgery in which headplates were attached. The neck and right forelimb of the mouse were shaved and incisions were made above the muscle to be implanted. Electrode pairs were led under the skin from the incision on the scalp to the incision at the site of implantation. Using the needle, electrodes were inserted through the muscle and the distal portion of the electrodes was knotted to secure both 0.5-mm bared-wire regions within the muscle. The needle and excess wire were then cut away. Incisions were sutured and the connector was affixed with dental cement to the posterior edge of the headplate.

EMG recordings were amplified and digitized using a 16-channel bipolar amplifying headstage (Intan Technologies, cat. no. C3313). Data were acquired at 4 kHz using the USB interface board (Intan Technologies, cat. no. RHD2000).

Optogenetic inactivation

After a VGAT-ChR2-EYFP mouse completed a few climbing sessions with randomly positioned handholds, dental cement above the skull was removed and a 2-mm-diameter craniotomy was made above the left caudal forelimb area centered at 1.5 mm lateral and 0.25 mm rostral of bregma. A thin layer of Kwik-Sil (World Precision Instruments) was applied over the dura and a 3-mm-diameter no. 1 thickness cover glass (Warner Instruments) was placed on the Kwik-Sil before it cured. The gap between the skull and the cover glass was then sealed with dental cement around the circumference of the glass. A customized stainless steel ferrule guide (Ziggy’s Tubes and Wires) was then cemented to the headplate a certain distance above the surface of the brain. This distance was set to ensure that the cone of light emanating from a 400-μm core, 0.50 numerical aperture optical patch cable, terminating in a 2.5-mm ceramic ferrule (Thorlabs, cat. no. M128L01), would project a spot of light 2 mm in diameter on to the surface of the brain (Fig. 2a). The ferrule guide enabled quick and reliable positioning of the ferrule above the brain surface, so that a large expanse of cortex could be illuminated. In previous experiments using this method for inactivation, control experiments in wild-type mice showed no discernible muscle activity perturbation in response to light18. Moreover, the short latency at which we measured effects here would preclude visually driven responses.

To attenuate firing throughout motor cortical layers, we used a 450-nm laser (Opto Engine, cat. no. MDL-III-450) to sporadically apply 25-ms light pulses at an intensity of 10 mW mm2 to the brain surface. During each session that involved inactivation of the motor cortex, trials were initiated after the distance climbed on the current bout exceeded a random threshold between 0° and 20° and a mouse was actively climbing. Light was applied on a random third of trials. This ensured that inactivation and control (no light) trials were broadly distributed across the muscle activity states that occurred during climbing. Inactivation trials were never triggered <5 s apart. A total of 2,292–5,115 trials (median = 2,715) was collected in each mouse (roughly one-third inactivation and two-thirds control), spanning 11–37 (median = 18.5) climbing sessions. Inclusion of twice as many control trials as inactivation trials enabled comparisons between separate sets of control trials to aid statistical testing.

Neural recording

For some mice, optogenetic inactivation sessions were followed by three to four daily neural recording sessions that typically lasted an hour each. One day before the first neural recording session, the cover glass and Kwik-Sil were removed, a small durotomy was made in the craniotomy center and a Pt or Ir reference wire was implanted to a depth of 1.5 mm in the left posterior parietal cortex. Opaque silicone elastomer (Kwik-Cast, World Precision Instruments) was used to cover the craniotomy after the surgery and between recording sessions. At the time of recording, the exposed brain surface was covered with agarose and silicone oil or liquid paraffin oil. A Neuropixels 1.0 (IMEC) was subsequently inserted to a depth of 1.5 mm into the brain (Fig. 5a) at a rate of 3–5 μm s−1 using a motorized micromanipulator (Sutter Instrument, cat. no. MP-225A). Electrode voltages were acquired at 30 kHz and bandpass filtered at 0.3–10 kHz using SpikeGLX (Bill Karsh, https://github.com/billkarsh/SpikeGLX) and then sorted with Kilosort 2.067 (https://github.com/MouseLand/Kilosort2). Sorted units were assigned to separate cortical layers based on the depth below the pia assigned to the waveform centroid in Kilosort and the laminar depths reported in ref. 68. To be conservative, units near laminar boundaries were ignored when analyzing neural responses by layer. To classify units as either wide-waveform, putative pyramidal neurons or narrow-waveform, putative interneurons, we pooled the spike widths of all sorted single units, obtaining a bimodal distribution18,69. Neurons with spike widths >450 µs were classified as putative pyramidal neurons and the remainder were classified as putative interneurons. The proportion of units classified as wide waveform and narrow waveform was in line with previously observed proportions13,44.

EMG preprocessing

For both optogenetic inactivation and Neuropixels recording sessions, EMG measurements were downsampled to 1 kHz, high-pass filtered at 250 Hz, rectified and convolved with a modified Gaussian filter kernel. We used causal filtering to enable precise assessment of perturbation latencies and, hence, used a Gaussian filter kernel that was initially defined with a 10-ms s.d., but then had amplitudes for times <0 (its ‘backwards-in-time’ side) set uniformly to zero. EMG traces were then z-scored across all time points during the given session.

Video recording and analysis

A high-speed, high-resolution monochrome camera (Blackfly S USB 3.0, 1.6 MP, 226 FPS, Sony IMX273 Mono; Teledyne FLIR) with a 12-mm fixed focal length lens (C-Mount, Edmund Optics) was positioned to the right of the head-fixed mouse during inactivation and neural recording sessions and videos were acquired under a near-infrared light source at 100 frames s−1 with a resolution of 400 × 400 pixels2. During optogenetic inactivation sessions, the camera was triggered to start recording using StreamPix software (NorPix, Inc.) 20 ms before each inactivation or control trial. Each recording lasted 500 ms beyond the 25-ms light or control command pulse that marked the trial. Annotation of behavior was accomplished using DeepLabCut70. To enable better markerless tracking, the right forelimbs of mice were shaved and tattooed (Black tattoo paste, Ketchum Manufacturing) at eight different sites along the right arm. All videos were also adjusted with ffmpeg (ffmpeg.org) to improve brightness and contrast. DeepLabCut using the ResNet-50 neural network with an Adam optimizer was trained on the annotated images for 1,030,000 iterations; on ~4,000 randomly sampled video frames across mice and sessions, we provided manually labeled locations of the 8 forelimb sites for training: shoulder, two sites between the shoulder and elbow, elbow, two sites between the elbow and wrist and wrist and tip of the last digit (Fig. 4b). The training set comprised 80% of the labeled frames.

All DeepLabCut-tracked forelimb site trajectories were then exported to MATLAB for further postprocessing to remove outliers (Extended Data Fig. 6a–c). First, sites in each video time series that were assigned, by DeepLabCut, a likelihood (that is, its confidence that a site was correctly labeled) <0.75 were replaced with an interpolated value using the median of the ten previous and ten following values (MATLAB function fillmissing). Next, outliers in site position time series were identified using the median absolute deviation (m.a.d.): shoulder coordinates were constrained to lie within 1.5 m.a.d. from their median, digit coordinates to be within 3 m.a.d. from their median and all other joints to be within 2 m.a.d. from their respective medians. Outliers were replaced with an interpolated value using a moving median of window length 10. Last, limits were imposed on the pairwise distances and angles between neighboring joints (the shoulder–elbow, elbow–wrist and wrist–digit tip) such that the angle between shoulder–elbow and elbow–wrist could not exceed 180° and the distances between each of these joints were within 2 m.a.d. of their medians. Site positions not meeting these criteria were also replaced with an interpolated value using a moving median of window length 10.

To verify that extracted forelimb orientation had the expected relationship with muscle activity, we compared changes in muscle activity to the corresponding changes in joint angle. For each control trial, we extracted muscle activity and forelimb site time series from 750-ms epochs that began 250 ms before each trial onset. The elbow angle was calculated as the inverse tangent of the position vectors connecting the shoulder site to the elbow site and the elbow site to the wrist site. The wrist angle was similarly calculated using vectors connecting the elbow and wrist sites and the wrist and finger sites. We also computed the difference in activity between elbow flexors and extensors and between wrist flexors and extensors. Time series were segmented into overlapping epochs beginning every 10 ms. For elbow angle and elbow flexor or extensor activity, we used 100-ms epochs. For wrist angle and wrist flexor or extensor activity, we used 50-ms epochs. Within each epoch, we computed the slope of a linear fit to the difference in flexor or extensor activity. Slopes were aggregated for each session, and epochs corresponding to the bottom and top 5% of the slope distribution were identified and combined across sessions. Epochs in the bottom 5% reflected increasing flexor bias, whereas those in the top 5% reflected increasing extensor bias (Extended Data Fig. 6d–g).

For the extracted muscle activity and forelimb site time series, Pearson’s correlation was computed over nonoverlapping 150-ms epochs. For each epoch, we calculated the mean correlation across shoulder, elbow, wrist and finger sites for each muscle. Correlation values were aggregated across all epochs and sessions (Fig. 4h).

We note that our findings here applied only to the kinematic features that our measurements captured, primarily the right forelimb joint angles in the sagittal plane. Our measurements did not account for forelimb orientation in the mediolateral dimension. However, the elbow and wrist muscles from which we have recorded primarily govern the angles of the elbow and wrist, which our measurements did capture. Mediolateral forelimb orientation was primarily determined by shoulder muscles. Moreover, as illustrated in Supplementary Video 1, the range of limb motion in the two dimensions that we did examine was much larger than the range in the mediolateral dimension. Thus, inclusion of the mediolateral dimension in measurements was not likely to have changed our results substantially.

Behavioral analysis

For each animal, we computed the principal angles between muscle activity time series for each of the first 20 climbing sessions that used the automated control script, compared to the twentieth session. Principal component analysis was first performed on the muscle activity time series for the four recorded muscles. The top two PCs were used for the subsequent calculations, because they captured >90% of activity variance. The principal angles were then computed using a standard approach: the cross-covariance matrix was computed for the two PC time series from the given session and those from the twentieth session and SVD was applied to the result. The principal angles were then computed as the real part of the inverse cosine of the resulting singular values.

Sample entropy41 was computed for the muscle activity time series for the four recorded muscles using the ‘sampen’ function downloaded from the MATLAB file exchange, with the embedding dimension set to 10. Sample entropy has previously been used to measure regularity in electrocardiography, electroencephalography and functional magnetic resonance imaging blood oxygenation level dependent signal imaging.

Inactivation effects during stereotypical climbing features

We identified three recurring kinematic features that are stereotypical in our observations of climbing behavior: pulling a handhold down with the right forelimb, reaching the right forelimb up for a handhold and palpation with the right hand when grasping for a handhold. Limb movement during each of these features was best reflected along the y axis of video frames. Pulling down was accompanied by an increase in averaged y coordinates as measured in pixels (values increase as you move downward in the video frame), which corresponds to a positive slope. The opposite was true for reaching up. Handhold palpations were associated with an oscillatory increase, decrease and increase, or vice versa, of y coordinates. Both of these patterns correspond to a minimum of two sign changes in slopes over a brief time window. To identify instances of each feature during climbing, we thus looked at changes in the y coordinates of the four tracked forelimb joints (shoulder, elbow, wrist and finger) across video recordings spanning 100 ms before and after the trial onset. We first fit a line of best fit to the y coordinates averaged over the 4 tracked joints across the entire 200-ms window to obtain a slope.

Then, we calculated slopes from overlapping 50-ms sliding windows that began every 10 ms, starting from 100 ms before trial onset. From these slope measurements, we detected changes in the slope across time. A trial was assigned as pulling down if the overall slope was positive with a magnitude of ≥2 and no sign changes in slope were detected. Conversely, a segment was assigned as reaching up if the overall slope was negative with a magnitude of ≤−2 and no sign changes were detected. Segments with ≥3 slope sign changes were assigned as handhold palpation. After this, for verification purposes, we randomly selected a quarter of trials assigned to each of the three features. Using visual inspection of video data, we confirmed that the kinematics associated with each trial matched the assigned feature in all cases. This validated the criteria that we imposed for assignment. Trial averages of the muscle activity and limb kinematic time series aligned by trial onset were then assembled for each behavioral feature.

Muscle activity state maps

We explored organizing inactivation and control trials based on the forelimb muscle activity immediately preceding trial onset. For example, we plotted trials along axes defined by the relative activity of antagonist muscles at each joint (Extended Data Fig. 3d) or along the top two PCs for the activity of all four muscles (Extended Data Fig. 3e). However, the density of trials across these plots varied greatly, with subsets of trials clustered closely together. Thus, these plots were not conducive to collecting together trials in similarly sized groups that would afford a similar degree of statistical power in distinguishing effects between groups; dividing trials based on these plots would concentrate trials, and statistical power, around certain states. To more effectively distribute the statistical power afforded by our trials, we explored the use of dimensionality reduction methods that organize states according to their n nearest neighbors. Recognizing that CFA inactivation effects may also depend on the time-varying pattern of muscle activity immediately before trial onset, we reasoned that capturing this history in our definition of muscle activity state could further increase our statistical power.

We ultimately used UMAP to obtain 2D muscle activity state maps on which nearby states are highly similar. We applied UMAP to segments extracted from the EMG time series collected during the optogenetic inactivation sessions and their corresponding first derivatives. For each control or inactivation trial, we defined 13 overlapping 50-ms epochs centered every 10 ms from −55 ms to +75 ms from command pulse onset (Fig. 2c). Then, for each 50-ms epoch, we averaged the EMG traces for each muscle over 5-ms bins and concatenated the resulting values for the four muscles and their corresponding first derivatives, yielding one 80 × 1 vector. Thus, in these vectors, the first 40 values reflected the EMG signals from 4 muscles and the last 40 values reflected their first derivatives (Fig. 2c). UMAP (MATLAB function run_umap, from the MATLAB File Exchange, with the following parameters: n_neighbors = 30, n_components = 2, min_dist = 0.3, metric = Euclidean) was applied to embed all resulting vectors from both inactivation and control trials, generating the 2D muscle activity state maps (Fig. 2d). Using two dimensions here simplified subsequent quantification of inactivation effects across muscle activity states. Using overlapping epochs ensured that embedded state vectors from individual trials formed continuous trajectories across the resulting maps (Fig. 2d).

Inactivation effect maps

To quantify the influence of CFA inactivation on muscles across the muscle activity state maps, we first excluded outlying embedded state vectors. For each embedded vector on a given map, we computed its mean Euclidean distance on the map from all other vectors. A vector was deemed an outlier if its mean distance was >3 s.d. values above the mean for all other vectors. Some mice had no embedded vectors classified as outliers and the percentage classified as such was, overall, <1%.

We then defined uniformly spaced grid points across each map at which we would calculate the effects of CFA inactivation. As the number of grid points of a fixed spacing across a map would depend on the scale of the map, which could vary between maps, we rescaled the coordinates of each 2D map rd to \(r{d}_{\mathrm{rescaled}}=\frac{rd-\min \left(rd\right)}{\mathrm{s.d.}(\mathrm{PD})}\times 10+\mathrm{weightPara}\times 2\), where PD is the set of all Euclidean distances between embedded vectors and weightPara is the s.d. of the Gaussian function used to weight trials in computing the inactivation effect size at each grid point (see below and ‘spatial filter width’ in Extended Data Figs. 4, 8 and 10). For all maps, we used weightPara = 5.

We then sought to compute the inactivation effect at each grid point, based on trials that began from muscle activity states close to each given grid point. Our approach was to compute effects for each grid point from inactivation and control trial averages made from all trials of a given type, but where trials were weighted by the distance on the 2D map from the given grid point to the weight epoch state vector for the given trial. The weight epoch state vector was defined as the embedded vector from the epoch spanning −40 ms to +10 ms from command pulse onset on the given trial (that is, the epoch just before any direct effect could begin; Fig. 2c,e). However, the density of these vectors varied across maps, meaning that the summed weight of trials contributing to trial averages would vary across grid points as well. Given this, to ignore grid points around which the weight epoch state vectors were too sparse for reliable trial averaging, a grid point was designated as ‘valid’ only if \({\sum }_{i}{W}_{g,i}\) > a threshold.Wg,i was in essence a Gaussian function, defined as \({W}_{g,i}=\exp \,(-\frac{{\left({\mathrm{Loc}}_{g}-{\mathrm{Loc}}_{i}\right)}^{2}}{2\times {\mathrm{weightPara}}^{2}})\), where i is the weight epoch state index (one per trial), \(g\) is the grid point index and \({\mathrm{Loc}}_{g}-{\mathrm{Loc}}_{i}\) is the Euclidean distance between the weight epoch state and the grid point on the 2D map. We used a threshold of 10, which led to nearly all grid points falling within a convex hull surrounding embedded vectors being classified as valid, whereas nearly all grid points falling outside this hull were not. Grid points not designated as valid were ignored in subsequent calculations. All embedded muscle activity state vectors (those not deemed outliers) were close to valid grid points and so this criterion did not prevent an appreciable contribution from any vectors. Together with the very small fraction of embedded vectors ignored as outliers, this implies that our analysis involved practically all the muscle activity states that occur during climbing.

Next, we calculated the trial-averaged activity for each muscle at each valid grid point, separately for the inactivation and control trials. For each muscle and trial type, we extracted segments of their activity time series from −10 ms to +30 ms relative to command pulse onset. We then took a weighted average of these segments across each trial type, where each segment was weighted by Wg,i. At each grid point, this produced control and inactivation trial averages for each muscle, where each trial is weighted by the distance from the grid point to the muscle activity state just before any direct inactivation effect during the trial. Use of weightPara = 5 here (roughly 10% of the width of the map) reflected a trade-off between differentiating effects across distinct map regions and the statistical power gained from combining trials.

Finally, we quantified the size of the CFA inactivation effect at each valid grid point by comparing the rates of change (slopes) in inactivation and control trial averages 0 ms to +20 ms from command pulse onset (Fig. 2f). Muscle activity at time 0 ms was defined as the mean from −10 ms to +10 ms and, likewise, activity at +20 ms was defined as the mean from +10 ms to +30 ms. Quantifying the inactivation effect by taking the ratio or difference between the control and inactivation slopes returned qualitatively similar results. We used the difference because it was more easily interpretable (Fig. 2h).

We also sought to assess the similarity between nearby state vectors embedded in local neighborhoods across maps and thus the similarity of states from which trials contributing strongly to given grid point trial averages began. To do this, we computed the average Euclidean distance in the full 80D space between state vectors embedded near each grid point on the 2D maps. We first calculated the Euclidean distances between all possible pairs of embedded vectors in the full 80D space. For each grid point, we then computed a locally weighted average of these distances. In these averages, each distance d was weighted by a Gaussian function of the distance on the 2D map between the grid point and the midpoint between the corresponding two embedded vectors (that is, those separated by d), using the same Gaussian function as above (weightPara = 5).

There are a number of important caveats in evaluating inactivation effect maps. Collapsing 80D muscle activity state vectors on to a 2D map eliminates substantial information about those states. The smoothing that we have applied in computing trial averages will also mask fine structure. UMAP organizes states according to similarity and so ignores other features potentially relevant to cortical influence. As a consequence, these maps do not reflect all the structure that may exist in the relationship between muscle activity state and CFA influence.

Analysis of inactivation effect maps

To determine which muscle activity states were significantly influenced by CFA inactivation, we performed a two-tailed nonparametric permutation test at each grid point by computing the probability of obtaining the observed inactivation effect size by chance. For each animal, and each grid point, 300 permutations were performed by first randomly splitting control trials into two groups, each with a number of trials equal to the number of inactivation trials. The number of trials in both the control (Ncontrol) and inactivation (Ninactivation) trial groups was such that, if \({N}_{\mathrm{total\_control}}/2 > {N}_{\mathrm{total\_inactivations}}\), we would set \({N}_{\mathrm{control}}={N}_{\mathrm{total\_inactivations}}\); otherwise, \({N}_{\mathrm{inactivation}}={N}_{\mathrm{total\_control}}/2\). As our experiments were designed to collect twice as many control trials as inactivation trials, control trials could be sampled without replacement during the splitting process. For each grid point, and for each permutation, we calculated the inactivation effect size using the control trial average, computed as above, for one randomly selected group of control trials and the inactivation trial average, also computed as above. For each permutation, and at each grid point, we also calculated the effect size expected by chance (‘null’) using trial averages for the two control trial groups. Then, at each valid grid point, we randomly picked 1 inactivation effect size from the 300 permutations and compared that with all 300 null effect sizes. To calculate the P value, we compared the 300 null effects with the randomly chosen inactivation effect, calculated the fractions of the null effects where the null effects were smaller than or greater than the inactivation effect and multiplied the smaller fraction by 2. To correct for multiple comparisons, the Benjamini–Hochberg method was used to control the false discovery rate (FDR; MATLAB function fdr_bh). The effect size at each grid point was considered to be statistically significant if the FDR-corrected P value was 0.05 (that is, the likelihood of false discovery was ≤5%). We also used P values across all grid points to estimate the fraction of null hypotheses that were false for each mouse (MATLAB function mafdr) and used this as the fraction of grid points exhibiting inactivation effects.

The 2D autocorrelation for inactivation effect maps was computed using the MATLAB function xcorr2 and normalized by the maximum value for the given map. For controls, maps were generated using null effect sizes at each grid point from 1 of the 300 comparisons of effect sizes computed with 2 separate sets of control trials described above. To test that inactivation effect maps differ across muscles for each animal using the Kruskal–Wallis test, we first removed inactivation effect sizes from the maps until the minimum distance between the grid points for remaining effect sizes was >3× s.d. of the Gaussian function used for computing grid point trial averages. This ensured that the remaining effect sizes were effectively computed from separate trials. Roughly ~15–20 inactivation effect sizes remained after this removal. Linear models were fit to scatter plots using the MATLAB function fitlm. The 2D correlation between inactivation effect maps was computed using the MATLAB function corr.

Maps of average muscle activity

For each muscle, we first calculated its mean activity during the 50-ms epoch reflected in each state vector. Then, for each grid point, we calculated a weighted average of these values, where the mean for each epoch was weighted by a Gaussian function of the Euclidean distance on the 2D map between the epoch’s embedded muscle activity state vector and the given grid point. Here we set the s.d. of the Gaussian function to be the same as that used for the inactivation effect maps. The resulting plots clarify the activity of muscles at each grid point and how this activity varies across grid points.

Neural activity maps

To compare firing patterns in the CFA to inactivation effects, we generated maps of average firing rate across grid points for each recorded CFA neuron. As neural recordings and optogenetic inactivations were carried out in separate sessions, the first step was to align muscle activity states from the neural recording sessions with those from the optogenetic inactivation sessions by embedding the former set of states on the same 2D map used to make inactivation effect maps. To do this, we identified a large number of 50-ms epochs during active climbing from the neural recording sessions. To identify these epochs, peaks in the activity summed across all four muscles were first detected using the MATLAB function findpeaks, where a peak was identified if a sample in the time series surpassed a threshold equal to the mean + ½ × s.d. Based on visual inspection, this identified many peaks that always fell during active climbing. Next, two time points (‘onset points’) were randomly selected on either side of the peak, such that the expected interval from the peak to each point was 50 ms. Then, any onset point was eliminated if it was <50 ms from either the previous or the subsequent onset point. This ensured that 50-ms epochs defined around onset points would not overlap. For each remaining onset point, EMG time series segments from the epoch spanning −45 ms to +5 ms relative to the onset point were extracted. Each recording session typically yielded upward of 30,000 epochs. Of these, 10,000 were randomly selected for each session to limit compute time for subsequent calculations. State vectors (80 × 1) were assembled for each epoch as above.

We then embedded the resulting 10,000 state vectors from each neural recording session on to the muscle activity state maps previously defined via UMAP to make inactivation effect maps for the given mouse. We next extracted the segments of each neuron’s firing rate time series corresponding to each state vector. For each neuron and at each valid grid point, the firing rate segments were averaged as above, weighting each segment by a Gaussian function of the distance on the map from their corresponding state vector to the grid point (weightPara = 5). The resulting segment-averaged firing rates were then averaged across time, yielding a single scalar firing rate value for each neuron at each grid point (Fig. 5f,g).

For the analysis described below, only putative pyramidal neurons were included. To estimate the number of neurons that showed behaviorally dependent firing across muscle activity states, we first generated an empirical null distribution for the degree of variation across neural activity maps separately for each neuron. To do this, we reassigned each state vector from neural recording sessions to the location of a different, randomly selected vector on the map and recomputed the neural activity maps. We repeated this 500× to yield 500 permuted maps for each neuron. To assess behaviorally dependent variation, the skewness of the original neural activity map values and those on the 500 permuted neural activity maps was calculated (MATLAB function kurtosis) as \(k=\frac{E{\left(x-\mu \right)}^{4}}{{\sigma }^{4}}\), where x is the set of firing rates at all grid points, μ is the mean of \(x\), \(\sigma\) is the s.d. of \(x\) and \(E(\cdot )\) represents the expected value. Significance was assessed using a P value, defined as the fraction of null distribution skewness values greater than the original. From the P values for all neurons in a given mouse, we estimated the fraction of false null hypotheses (MATLAB function mafdr) and used this as the fraction of cells with behaviorally dependent firing.

The sparsity for neural activity maps was computed using the formula given in ref. 54. Here the sparsity is the mean of the firing rates at each grid point on the map, squared and divided by the mean of the squares of the firing rates at each grid point. Note that, as in the original reference, this minimizes the dependence of sparsity values on the frequency at which each state on the map is visited. The 2D correlation between neural maps was computed using the MATLAB function corr.

Neural subspace for inactivation effects

Separately for each animal (n = 3 mice), neural subspaces were identified using singular vector CCA (SVCCA55) applied to the inactivation effect and neural activity maps. An SVD-based approach was taken here because the number of recorded neurons was much larger than the number of recorded muscles. Neurons with mean firing rates <0.1 Hz over the 10,000 epochs were excluded. Two matrices were generated for alignment with SVCCA. One matrix had a column for each neuron generated by vertically concatenating the successive columns of that neuron’s neural activity map. The resulting matrix had dimensions of Ngrid × Nneuron, where Nneuron is the number of neurons recorded in a given mouse across recording sessions (putative pyramidal, mean firing rate >0.1 Hz), whereas Ngridis the number of valid grid points. The second matrix was made in a similar fashion by vertically concatenating the successive columns of the inactivation effect map for each muscle. This matrix had dimensions of Ngrid × 4 because four muscles were recorded.

SVCCA was conducted in two steps: neural activities were first soft normalized71 using a soft normalization constant of 5 Hz. SVD was performed using numpy.linalg.svd in Python to decompose the neural data into left singular vectors, a diagonal matrix containing singular values and right singular vectors. Next, the diagonal matrix, truncated to just the top 20 singular values, was multiplied with the corresponding top 20 right singular vectors, resulting in 20 neural activity components. CCA was applied to the Ngrid × 20 matrix of these components and the Ngrid × 4 matrix of inactivation effects. Then 20 dimensions were retained here because the amount of variance captured and CCA alignment quality saturated at around 20 dimensions. CCA was also repeated with individual columns of the matrix of inactivation effect sizes in place of the full 4D matrix, to show that there were CFA activity components that correlated with the inactivation effects for each individual muscle.

To compute the additional variance captured by each successive canonical vector, canonical vectors were orthogonalized using the Gram–Schmidt process. In addition, we randomly shuffled the neuronal firing rate segments relative to the embedded vectors on the maps to generate shuffled neural activity maps and performed SVCCA again as a negative control. The highest correlations between the canonical neural and effect vectors for all animals were <0.75. To further verify the effectiveness of SVCCA, for each mouse separately we split the inactivation and control trials from inactivation experiments randomly into two groups, calculated separate inactivation effect maps for each group, used SVCCA to find subspaces where CFA activity aligns with each of them and calculated the principal angles between the two resulting neural activity subspaces. This procedure was repeated 300× (Extended Data Fig. 8b).

Using the CCA results for individual columns of the matrix of inactivation effect sizes (that is, results for effects on individual muscles), we computed the effective weight of each neuron’s activity in each canonical variable by matrix, multiplying the neuron to singular vector coefficients and the singular vector to canonical vector coefficients. The four individual muscle effect size vectors yielded four effective weights for each neuron. To compare across animals in which we had recorded different numbers of neurons, we normalized these weights to have a median of 1 for each animal (Extended Data Fig. 9). To measure the relative contribution of neurons across all four muscles, we computed the norm of the four-element vector composed of the weights for each muscle for a given neuron and again normalized these so that the median for each animal was 1.

Overlap between subspaces

To find a neural activity subspace that aligned with muscle activity itself, we again performed SVCCA using the Ngrid × Nneuron matrix of mean firing rates. However, in place of the matrix of inactivation effect sizes, an Ngrid × 4 matrix was used where each column reflected the average activity at each grid point for one of the four muscles, computed just as was done for the neural activity maps, except muscle activity from inactivation sessions was used. Similar methods were used to find a neural activity subspace that aligned with limb kinematics. Here, instead of 4 columns, we began with 16—the horizontal and vertical coordinates for the 8 positions tracked along the right forelimb. As the 16 kinematic variables were highly correlated, SVD was also used on this matrix to reduce its dimensionality to 7 before performing CCA.

To compute principal angles between two neural activity subspaces, we orthonormalized the neural canonical vectors defining each subspace, computed the cross-covariance matrix for the two sets of vectors, computed the SVD of the matrix and calculated the inverse cosine of the singular values in degrees. We also measured the degree of overlap between neural activity subspaces using the metric \({\rm{O}}{\rm{L}}=\frac{\sum {\rm{v}}{\rm{a}}{\rm{r}}({{C}_{{\rm{s}}2}\times M}_{{\rm{r}}{\rm{e}}{\rm{p}}{\rm{r}}{\rm{o}}{\rm{j}}})}{\sum {\rm{v}}{\rm{a}}{\rm{r}}({M}_{{\rm{p}}{\rm{r}}{\rm{o}}{\rm{j}}})}\), where \(M\) is the original matrix of neural activity and \({C}_{{\rm{s}}1}\) and \({C}_{{\rm{s}}2}\) are matrices comprising coefficient vectors that define the two subspaces, \({M}_{{\rm{p}}{\rm{r}}{\rm{o}}{\rm{j}}}={C}_{{\rm{s}}1}\times M\) and \({M}_{{\rm{r}}{\rm{e}}{\rm{p}}{\rm{r}}{\rm{o}}{\rm{j}}}={C}_{{\rm{s}}1}^{T}\times {M}_{{\rm{p}}{\rm{r}}{\rm{o}}{\rm{j}}}\).

To verify the significance of the overlap, we permuted the order of coefficients in the columns of \({C}_{{\rm{s}}2}\) to get \(\underline{{C}_{{\rm{s}}2}}\). We used \(\underline{{C}_{{\rm{s}}2}}\) only when the total variance of \(\underline{{C}_{{\rm{s}}2}}\times M\) was in between 0.8 and 1.2× the total variance of \({C}_{{\rm{s}}2}\times M\). We then repeated subspace overlap calculations for 100 different \(\underline{{C}_{{\rm{s}}2}}\) values meeting this criterion. This ensured that the resulting null distribution of overlap values did not differ from the actual value simply because the \(\underline{{C}_{{\rm{s}}2}}\) value captured much less variance than \({C}_{{\rm{s}}2}\). We also calculated subspace overlap for subspaces that were each computed using just one half of the total epochs from the neural recording, repeating this for 300 different random parcellations of the epochs.

Reporting summary

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