Mice
All animal procedures were approved by the Princeton University Institutional Animal Care and Use Committee and were in accordance with National Institutes of Health standards. For multifibre photometry recording studies, we used Vgat+/− (ref. 52) mice backcrossed with CD1 (Charles River, Crl:CD1(ICR), 022) male mice for a minimum of three generations, wild-type BALB/cJ males (Taconic, 1-99), and wild-type CD1 male mice. Vgat+/− and wild-type CD1 mice that were used as experimental subjects for freely moving or observational assays were sexually naive and aged between 12 and 18 weeks. BALB/cJ mice that were used as social targets for freely moving assays were sexually naive and aged between 8 and 26 weeks. Aggressor animals used during hard fights were single-housed aggression-experienced animals aged between 16 and 25 weeks. Mice (aged between 15 and 16 weeks) used for optogenetic stimulation for simulated fights were Esr1-cre+/− (ref. 53) male mice (Jackson Laboratory, 017911) backcrossed to CD1 (Charles River, Crl:CD1(ICR), 022) male mice for a minimum of three generations. Only male mice were used in this study. Mice were housed under a 12 h–12 h light–dark cycle with experiments taking place exclusively during the dark phase. Food and water were given ad libitum. The ambient temperature was maintained at 21–26 °C with a humidity of 30–70%. Before initiating fibre photometry experiments, Vgat+/− and wild-type CD1 mice used for aggression and/or observation experiments were socially isolated for at least 1 week. All animals were bred within the Princeton University animal facilities or purchased from Taconic Biosciences or Charles River. Animals were assigned to the EXP, OBS and NON groups randomly, constrained by the availability of animals of the appropriate genotype at the time of group assignment. Experimenters were blinded to group identity during behavioural scoring and histological verification.
Behavioural assays
Animals undergoing fibre photometry recordings were subjected to longitudinal resident–intruder experiments under varying conditions. For 8 consecutive days, animals undergoing longitudinal aggression experience (EXP) received unconstrained access to three different male BALB/cJ mice across three separate 9 min sessions, each preceded by a 1 min baseline without social stimuli. These interactions took place in the homecage of the experimental animals (Optimice Auto-Water Cage Bottom with SE Lab Group cage, 34.3 cm length × 29.2 cm width × 15.5 cm height).
For longitudinal observation (OBS), a cage extender made of black acrylic and clear plexiglass was built to match the dimensions of the homecage, along with a compartment in the front of the cage extender designed to hold each observer mouse (10 cm length × 13 cm width × 17 cm height). The observer platformed compartment was separated from the cage floor through a clear plexiglass barrier with multiple horizontal cutouts allowing for visual and olfactory access of the cage bottom. Every OBS mouse was paired with a unique CD1 male mouse, with the latter undergoing 8 consecutive days of three back-to-back resident intruder sessions in its own homecage. For each day, each observer mouse was placed in the observer compartment, and the cage extender housing the compartment was placed on top of the paired animal’s homecage. Before initiating resident–intruder sessions, OBS mice and the partnered CD1 mice were allowed up to 15 min of habituation while separated by the plexiglass barrier. Next, each resident–intruder session consisted of 9 min of social interaction between the paired CD1 mouse and a different male BALB/cJ mouse, each preceded by a 1 min pre-intruder baseline.
The control animals undergoing non-social experience (NON) were longitudinally exposed to an inanimate toy resembling a mouse over the same timespan as the EXP and OBS mice, and across the same number of sessions per day. Note that, while throughout the training period OBS individuals did not engage in social behaviour, photometry recordings were still performed in these individuals to mirror any bleaching-related signal decays present in EXP and OBS individuals after longitudinal imaging. Animals were assigned to the EXP, OBS and NON groups randomly. Blinding during data collection was not possible because group identity was evident from the experimental configuration.
On day 9, each animal from each group was subjected to the hard fight, which consisted of three back-to-back 4–5 min resident–intruder sessions in their homecage, preceded by a 1 min solitary baseline. In each session, each animal received unconstrained social access to a unique undefeated CD1 male screened a priori for aggression against other CD1 males. Two EXP animals, inadvertently exposed to CD1 aggressors outside the scheduled training protocol, were excluded from hard fight behavioural analyses to avoid confounding protocol-driven effects with this uncontrolled exposure (final behavioural, n = 10); neural data from these animals were retained for all neural analyses (final neural, n = 12), as the exclusion was motivated by behavioural interpretability rather than data quality.
For comparison of familiar and novel males during observation, the mice were first defeated in their homecage by a unique CD1 male that had been previously screened for aggression against other CD1 males. This defeat session consisted of a 9 min social interaction preceded by a 1 min pre-intruder baseline. Afterwards, each defeated animal was placed in the observer compartment and was allowed to watch four consecutive resident–intruder sessions. Two of these resident–intruder sessions of the familiar CD1 aggressor while the other two were a novel CD1 male that the observer had not previously interacted with. All four resident–intruder sessions consisted of 9 min of social interaction between the novel or familiar CD1 mouse and a different male BALB/cJ mouse, each preceded by a 1-min pre-intruder baseline. The order of the novel and familiar sessions was randomized for each observer. Subsequent neural analyses were performed only for the first session of each type.
For simulated attack observation, we unilaterally expressed ChR2(H134R)-mCherry in the VMHvl of Esr1+/− CD1 male mice. After viral expression, we screened for optogenetic stimulation evoked attack on an inanimate object (toy mouse)53. To assess whether the observers would respond differently to authentic attacks on a subordinate (like the OBS group) compared with a simulated attack on a toy mouse, the observers were presented with trials for authentic and stimulated aggression. The session structure consisted of a 1 min pre-stimulation baseline followed by 5 min during which optogenetic stimulation was delivered intermittently to evoke attack-like motor sequences toward the toy. Immediately after the toy session, the same observer animal then watched a standard resident–intruder session in which the same Esr1+/− resident received a live male BALB/cJ intruder, preceded by a 1-min pre-intruder baseline. This within-animal design permitted direct comparison of observer neural responses during optogenetically evoked aggression toward an inanimate target versus naturalistic aggression toward a live conspecific, while controlling for the identity of the observed aggressor.
Behaviour acquisition
Social interactions were recorded using customized multi-camera systems, including top and side cameras (40 Hz, FLIR, Spinview). These were controlled with a data acquisition device (DAQ) and associated software (Measurement Computing), which further coordinated the FP3002 CMOS camera in synchrony. The top camera was centred 50 cm above the homecage of experimental mice for each recording session, while the side camera was placed at a height of 30 cm and within 3 cm of the observer compartment. Black paper-chip bedding was used for every recording and miscellaneous items such as food pellets were cleared from homecages before recording. For behavioural analysis, we used a top-down camera, as this is reflective of what the observers viewed from their raised platform.
Behavioural analysis
Behavioural annotation
For supervised classification of attack behaviours during the training period, the ground truth was determined by manual annotations of videos scored with BORIS54 (v.9.3.2). Only attack and fighting behaviours were annotated, defined as rapid forward movements from the resident toward the intruder mouse, such as chases or lunges. The number of annotated frames included 29,805 attack frames out of 759,074 total frames across 49 videos. For hard fight sessions, behavioural annotation of specific behaviours was performed manually and carried out blind to the group identity of the behaving mice. Five behavioural categories were annotated. The first two categories captured aggressive behaviours initiated by the experimental subject: attacks delivered without resistance, defined as forward lunges or chases toward the CD1 aggressor that evoked no retaliatory response (the CD1 fled or remained passive); and attacks delivered with resistance, defined as attacks that evoked active defence from the CD1 aggressor in the form of counter-biting or physical pushback. The next two categories captured the analogous conditions from the perspective of receiving aggression: attacks received without resistance, in which the experimental subject was attacked by the CD1 aggressor and did not retaliate or push back; and attacks received with resistance, in which the experimental subject actively defended itself against the CD1’s attack. The fifth category captured fleeing behaviour by the experimental subject, defined as rapid locomotion away from the CD1 aggressor following an attack, approach or investigation.
Pose tracking
SLEAP software (v.1.2.2) was used to predict resident and intruder positions across social interactions. To do this, 6,305 frames from 141 social interaction videos were labelled for tracking of resident and intruder body positions. These 6,305 frames were divided into training and test sets with an 80:20 split. The following points for both resident and intruder animals were labelled and subsequently tracked for all social interaction videos: nose, head, neck, left ear, right ear, trunk, left hindpaw, right hindpaw, left forepaw, right forepaw, tailbase, bottom segment of tail, middle segment of tail, upper segment of tail and tail tip. Training of the SLEAP model was performed over 93 iterations using a bottom-up approach with custom parameters (initialized with Unet and batch-size of 4).
Feature definition
To define the posture of resident and intruder mice, frame-to-frame pose data were converted to the following behavioural features:
-
(1)
Intruder body length: the Euclidean distance between the head of the intruder and its tailbase.
-
(2)
Resident body length: the same as above but for the resident.
-
(3)
Intruder body orientation: the angle spanning the centroid, head and nose of the intruder.
-
(4)
Resident body orientation: the same as above for the resident.
-
(5)
Intersection over union of resident and intruder: the overlap between the resident and intruder bounding boxes by dividing the area of their intersection by the area of their union.
-
(6)
Intruder head speed: the instantaneous distance in intruder head position (every 4 frames or 100 ms).
-
(7)
Resident head speed: the same as above but for the resident.
-
(8)
Intruder head speed lagged at ±3 s: the sum across lags of intruder head speed, computed within a ±3 s lag window.
-
(9)
Resident head speed lagged at ±3 s: the same as above but for the resident.
-
(10)
Intruder centroid speed: the instantaneous distance in intruder centroid position (every 4 frames or 100 ms).
-
(11)
Resident centroid speed: the same as above but for the resident.
-
(12)
Intruder centroid speed lagged at ±3 s: the sum across lags of intruder centroid speed, computed within a ±3 s lag window.
-
(13)
Resident centroid speed lagged at ±3 s: the same as above but for the resident.
-
(14)
Intruder to resident head-centroid angle: the angle spanning the intruder’s neck, intruder’s head and resident’s centroid.
-
(15)
Resident to intruder head-centroid angle: the angle spanning the resident’s neck, resident’s head and intruder’s centroid.
-
(16)
Intruder to resident head-to-tailbase distance: the Euclidean distance between the head of the intruder and the tailbase of the resident.
-
(17)
Resident to intruder head-to-tailbase distance: the Euclidean distance between the head of the resident and the tailbase of the intruder.
-
(18)
Between centroid distance: the Euclidean distance between the centroids of the resident and intruder.
-
(19)
Between head distance: the Euclidean distance between the heads of the resident and intruder.
Distance-related features were converted from pixels to centimetres using custom software based on our behaviour camera’s stereo parameters and pixel depth information.
Feature preprocessing
To standardize feature processing across all sessions, the mean and s.d. of every feature for every recorded session were pooled and subsequently averaged. Features for each session were processed as follows: (1) removal of outliers 3 s.d. away from the session mean; (2) smoothing through a Gaussian filter of 0.275 s; (3) linear interpolation of missing values; and (4) z-scoring using the mean and s.d. pooled from collating features across sessions. The collated mean and s.d. values for every feature were used for z-scoring in individual sessions to capture a wider variance in feature dynamics as opposed to unit variance, which may reflect data fluctuations that are not scalable across samples.
Supervised behaviour classification
To identify attack behaviours across training period videos, we trained a supervised multilayer perceptron (MLP) on SLEAP-derived feature data using the Keras library (Keras and TensorFlow v.2.11.0). Supervised classification was applied specifically to training period sessions, in which aggressive interactions are initiated exclusively by the resident experimental subject against a subordinate BALB/cJ intruder, yielding unambiguous one-sided attack bouts. Given the large volume of training period recordings across hundreds of videos, automated classification was necessary to make behavioural annotation tractable at scale.
A sequential model was constructed consisting of (1) an input layer shaped after the behaviour feature set; (2) two hidden layers interleaved with batch normalization layers to normalize activations from the preceding layer; and (3) an output layer with a sigmoid activation function for binary classification. The input and hidden layers each consisted of 512 units with ReLU activation functions; the output layer consisted of a single unit. The target matrix was a binary indicator for hand-annotated attack labels pooled from 49 videos, totalling 29,805 attack frames versus 729,269 non-attack frames. The feature matrix included the 19 pose-derived features described above for each video frame, along with 19 additional lagged features capturing the temporal dynamics of the existing feature set, including the instantaneous distance between resident and intruder centroids.
As non-attack frames far outnumbered attack frames, attack frames were oversampled through a synthetic oversampling technique for time series data. This involved generating synthetic samples for both attack labels and accompanying feature matrices by randomly sampling with replacement and combining these synthetic samples with the original data to balance each class distribution while preserving the underlying temporal structure. The resulting distribution totalled 699,464 attack frames versus 729,269 non-attack frames. This distribution was divided into training and validation sets with a 67:33 split, used for model development and internal performance assessment.
To evaluate generalization to entirely new data, model performance was additionally assessed on a held-out test set drawn from videos outside the original annotation pool (totalling 13,747 attack frames versus 433,936 non-attack frames). The performance on this held-out set yielded a balanced accuracy of 0.92; the confusion matrix is reported in Extended Data Fig. 1a. Subsequently, probability distributions for attacks were generated for every training period social interaction video. The probability threshold for classifying a frame as attack versus non-attack was set to 0.25; attack bouts were additionally required to span at least 200 ms of consecutive frames and to be separated from adjacent bouts by at least the same minimum duration.
Supervised classification of behaviour during training period sessions was not performed for NON mice, as individuals in this group were not engaged in social interaction. Instead, behavioural labels for NON animals were generated through a yoked control design in which labels from a randomly assigned EXP or OBS individual were paired to each NON individual for the corresponding recorded day and session.
All behavioural and neural analyses aligned to attacks during the hard fight were derived exclusively from hand-scored annotations rather than supervised model predictions. Hard fight sessions involve bidirectional aggression between the experimental subject and a CD1 aggressor, rendering one-sided supervised classification inappropriate. Hand annotations for hard fight sessions were performed blinded to group identity and segregated into the five behavioural categories described above (attacks delivered not resisted, attacks delivered resisted, attacks received not resisted, attacks received resisted and experimental subject fleeing).
Unsupervised behaviour embedding and clustering
To comprehensively characterize social behaviour in an unbiased manner, we adapted previous unsupervised behaviour classification strategies involving the reduction of high-dimensional behaviour features to a low-dimensional embedding and the definition of behaviours as high-density clusters within this embedding. To achieve dense clusters, we embedded the 19 behaviour features described above into a two-dimensional embedding using UMAP. To generate this embedding, an importance sampling approach was taken. This approach increased the likelihood of generating a final version of the embedding featuring rare or nuanced behaviours. Importance sampling involved a total of two rounds of UMAP reduction. In the first round, 80,000 video frames were uniformly sampled from 504 social interaction videos. As aggression can often happen briefly and therefore be under-represented in the total pool of feature frames used for reduction, an additional 20,000 feature frames aligned to aggression labels according to our supervised attack classifier were randomly added to the frame pool. This total pool of 100,000 feature frames was next embedded into a two-component UMAP manifold (umap from umap-learn, v.0.5.5, n_neighbors=50, min_dist=0.1), which was further binned into a 200 × 200 histogram, smoothed with a 2D gaussian kernel of 3.5 s.d. and parcellated into 21 clusters with watershed (skimage.segmentation.watershed). As UMAP is nonparametric, a separate model was implemented to learn the mapping from the original 19-dimensional feature space to the new 2D UMAP space. An MLP (sklearn.neural_network.MLPRegressor, hidden layer size of 1,000 × 500 × 100 × 50 units) was used for this purpose, allowing the data from every video frame to be represented in UMAP space and therefore fall into any of the 21 clusters previously defined.
To generate the final UMAP embedding, over 20,000 frames were sampled from the 21 clusters generated previously. Specifically, 2 random frames from each cluster and for each recorded session were pooled together for a total of 21,168 frames (2 frames × 21 clusters × 504 videos = 21,168). From these sampled frames, the 19-dimensional feature set was embedded into 2D UMAP space. Next, the full set of video frames were mapped into this final UMAP manifold using another MLP. The resulting embedding was turned into a 2D histogram, smoothed with a Gaussian kernel of 2 s.d. and divided into 13 final clusters with watershed. All behaviour analyses involving behaviour clusters are performed using this final UMAP segmentation. Note that unsupervised classification of NON mouse behaviour during the training period was not performed as individuals in this group were not socially interacting; instead, cluster labels for individuals in this group were generated through a yoked control design whereby labels from a randomly assigned individual in the OBS or EXP groups were paired to each NON group individual for each recorded day and session.
Behaviour transitions and relative similarity of unsupervised behaviour profiles
The expression of UMAP clusters was quantified through the occupancy (fraction of time in cluster relative to whole recording session) or persistence (mean number of consecutive frames comprising a segment of a behaviour cluster) of each cluster, in addition to each cluster’s probability of transitioning to every other cluster on a frame-to-frame basis.
To quantify the transition structure of behaviour clusters (Fig. 1m), pairwise transition probabilities were calculated as the average number of times the first cluster transitions into the second cluster. For each session, a 13 × 13 matrix containing pairwise transition probabilities for all 13 clusters was constructed. A global transition matrix was then generated by averaging the transition matrices of each individual from each group from both training period and hard fight sessions. To evaluate above-chance significance in pairwise transitions, we implemented a surrogate significance test. We first calculated the empirical transition matrix \({T}_{ij}\in {R}^{k\times k}\), where k is the number of states, from UMAP behaviour state cluster labels. Tij denotes the probability of transitioning from cluster i to cluster j. We then constructed a null transition matrix T0 that preserves the diagonal elements of T but replaces all off-diagonal entries with uniform probabilities, such that \({T}_{{ij}}^{0}=\frac{(1-{T}_{{ii}})}{(k-1)}\) for i ≠ j. Using T0 and the empirically fitted state duration distributions, we generated W = 104 surrogate sequences with 105 samples each and re-estimated transition matrix \(\hat{T}\) for each sequence, yielding a null distribution for each off-diagonal element. Let uij be the mean of \(\hat{T}\) across the N surrogates. The two-tailed empirical P value is calculated as \({p}_{{ij}}=\frac{(1+{M}_{{ij}})}{(N+1)}\), where Mij is the number of surrogates with \({| \hat{T}}_{{ij}}-{u}_{{ij}}| \ge | {T}_{{ij}}-{u}_{{ij}}| \). Effect sizes are reported as \({D}_{{ij}}=| {T}_{{ij}}-{u}_{{ij}}| \), the absolute deviation on the include-self transition scale. All 156 off-diagonal cells were tested, and P values were corrected for multiple comparisons at FDR = 0.05. Finally, the resulting global transition matrix was sorted through unsupervised hierarchical clustering (scipy.cluster.hierarchy.linkage) using the complete linkage method and Jensen–Shannon (JS) distance metric, with optimal leaf ordering to enhance the interpretability of the dendrogram. The resulting dendrogram was visualized with a colour threshold of 0.8 to distinguish clusters.
Two complementary representations of this transition structure were used in downstream analyses. First, an aggregate transition weight was computed by pooling pairwise transitions between clusters found to individually differ in occupancy between groups relative to NON (Fig. 1n (clusters 2, 3, 4, 5, 6, 7, 8, 10, 11 and 13)), and summing these pairwise weights within each origin-category-to-target-category pairing according to the behaviour category assignments established in Fig. 1m and Extended Data Fig. 2 (conflict, investigative, asocial), yielding a single aggregate transition weight for each of the nine possible category-to-category transitions (Fig. 1o). Second, the full transition matrix (all 156 off-diagonal pairwise transitions, without category aggregation or cluster filtering) was row-normalized, such that each row summed to 1 and represented a valid probability distribution over target clusters conditional on the origin cluster; this row-normalized matrix was flattened to a single vector per individual per session and used as the transition-probability input to the JS divergence analysis described below.
To assess whether behaviour occupancy, persistence or transition probabilities were predictive of group identity in the hard fight, a leave-one-session-out cross-validated approach (sklearn.model_selection.LeaveOneOut) using support vector machine classifiers (sklearn.svm.SVC) was used. For each session, three kinds of vectors were generated: (1) a 13 × 1 vector in which each element represented the average occupancy each cluster; (2) a 13 × 1 vector in which each element represented the average persistence of each cluster; and (3) an 81 × 1 vector containing the flattened pairwise transition probabilities for 9 UMAP clusters identified as social behaviours. For each vector type above, a separate leave-one-out cross-validation procedure was implemented. Here a new classifier was iteratively constructed in each fold consisting of 68 vectors of occupancy, persistence or transition probabilities as the training set and a single held-out vector for the classifier to predict on. The balanced accuracy score of all held-out predictions was subsequently saved. Finally, to assess statistical significance of this leave-one-out cross-validation strategy, a null distribution was created by shuffling group identity labels 1,000 times and repeating the cross-validation process, recording the accuracy score for each shuffle. The P value for each model’s performance was computed as the proportion of shuffled accuracy scores greater or equal to the test held-out accuracy score.
To assess whether OBS and XPO animals were behaviourally distinguishable from one another during the hard fight, the same leave-one-session-out SVM cross-validation framework described above was applied to decode OBS versus XPO group identity using cluster occupancy, persistence and pairwise transition probability vectors as separate feature sets. Statistical significance of the balanced accuracy score assessed against a permutation null distribution as described above.
Furthermore, to further assess the degree to which OBS and XPO animals individually resembled EXP or NON behavioural profiles, a separate SVM classifier (sklearn.svm.SVC, with probability=True) was trained on EXP and NON animals using cluster occupancy, persistence or pairwise transition probabilities as feature sets. Occupancy, persistence and pairwise transition probability vectors were averaged across all three sessions of the hard fight to yield per-animal input sets. These classifiers were then used to predict on similar behaviour vectors for held-out OBS and XPO test points in which each individual from these groups was assigned a probability of being classified as EXP-like by the trained model. A Brunner–Munzel test (scipy.stats.brunnermunzel) was applied to the continuous EXP-classification probability scores to provide a test that uses the full distribution rather than a binary threshold. This analysis was performed separately for each of the three feature sets (occupancy, persistence and transition probabilities).
To calculate behavioural similarity between individuals in each group during hard fight sessions, the above vectors containing averaged occupancy and row-normalized transition probability variables were used. For every individual at a session level in the OBS group, similarity in occupancy or behaviour transitions to every individual at a session level in the EXP or NON groups was computed through the JS divergence of the occupancy or transition probability vectors of each pair of individuals. JS divergence here is employed as follows:
$${D}_{\mathrm{JS}}(P\mathrm{||}Q)=\frac{1}{2}{D}_{\mathrm{KL}}(P\mathrm{||}M)+\frac{1}{2}{D}_{\mathrm{KL}}(Q\mathrm{||}M)$$
where P represents the probability distribution corresponding to either behaviour occupancies or pairwise transition probabilities of an OBS individual, Q represents the same variable for an individual from either the EXP or NON groups, M is the pointwise arithmetic mean of P and Q (that is, M = 1/2(P + Q)), and DKL is the Kullback–Leibler divergence. The Kullback–Leibler divergence is defined as:
$${D}_{\mathrm{KL}}(P\mathrm{||}Q)=\sum _{i}(i)\log (\frac{P(i)}{Q(i)})$$
JS divergence is disproportionately sensitive to high-probability elements of the distributions being compared, and behavioural cluster occupancy is unevenly distributed across clusters (Fig. 1n), with asocial/avoidance clusters occurring at substantially higher occupancy than conflict and investigative clusters. To prevent this imbalance from disproportionately driving the occupancy-based JS divergence values, occupancy-based JS divergence (Fig. 1q) was computed separately within each of the three behaviour categories established in Fig. 1n (conflict, investigative, asocial/avoidance) and averaged across categories with equal weight. Furthermore, a similar strategy was adopted for transition-based JS divergence (Fig. 1s). Pairwise transition probabilities are likewise unevenly distributed across cluster pairs (Fig. 1m,o), with certain transitions occurring at substantially higher probability than others. To prevent this imbalance from disproportionately driving the transition-based JS divergence values, JS divergence was computed independently for each row of the transition matrix (that is, separately for each of the 13 origin clusters) and averaged across rows with equal weight. Finally, for all JS divergence comparisons (occupancy and transitions), statistical tests were performed at the level of individual animals. For each individual, the (category- or row-averaged) JS divergence values computed against every individual, and across every session, in the comparison group were further averaged to yield a single value representing that individual’s mean divergence from the comparison group. It is these per-individual mean values, rather than the underlying session- or pair-level divergence values, that were used in the paired t-tests or Wilcoxon signed-rank tests described in the corresponding figure legends. Note that JS divergence is 0 when comparing equal distributions and larger values indicate larger divergence. Therefore, as presented in Fig. 1q,s, values closer to 0 reflect greater relative similarity between hard fight sessions.
To visualize cross-cluster differences between groups (Figs. 1l and 5n), raw per-cluster occupancy differences between groups (per-animal, session-averaged) were normalized by that cluster’s grand-mean occupancy across all groups compared, then scaled to a shared [−1, 1] range by the largest such relative difference in the panel. This normalization affects visual presentation only; statistical comparisons between groups are reported separately.
Supervised video-based classification of observer behaviour
Model architecture
We developed a deep neural network to classify observer behavioural states directly from raw video frames, consistent with previous machine learning approaches to behavioural classification55,56. The model processes short video clips (20 frames, 0.5 s at 40 fps) and outputs probability scores across seven behaviour labels: attention, grooming, scratching, still, investigate, rearing and turning. The model architecture consists of two sequential components: a spatiotemporal encoder and a classifier (Extended Data Fig. 5a), which is consistent with common machine learning solutions in animal behaviour55,56. The model is trained with Pytorch library (v.2.5.1).
The encoder is a four-layer 3D convolutional neural network that transforms raw pixel values into high-level feature representation. Each layer applies 3D convolutions with kernel size 3 × 3 × 3, followed by batch normalization, ReLU activation, max pooling (2 × 2 × 2) and a spatiotemporal attention module (described below). Channel dimensions double at each layer (64 → 128 → 256 → 512), while spatial and temporal dimensions are reduced through pooling, progressively capturing higher-order representations of posture and movement. The final feature map is reduced to a 512-dimensional vector using global average pooling. The classifier is a three-layer feedforward network (512 → 256 → 128 → 7) with dropout regularization (p = 0.3) between layers. Output logits are converted to class probabilities through softmax, and each video segment is assigned to the behaviour label with the highest probability.
Spatiotemporal attention mechanism
A key component of the encoder is a spatiotemporal module applied after each convolutional block, which is adapted from CBAM57 for video data. The attention module allows the network to dynamically weight the importance of different spatial regions and specific frames within the data segment through separate stages explicitly. First, a channel attention step computes a global descriptor for each feature channel with adaptive average pooling, passes it through a bottleneck (reduction ratio = 8) with a ReLU nonlinearity, and projects back to the original channel dimension. The resulting sigmoid-activated weights selectively amplify informative feature channels while suppressing less relevant ones. Second, a spatiotemporal attention step applies a 3D convolution across the channel-weighted feature map to produce an attention map, followed by sigmoid activation. This map assigns larger weights to behaviourally relevant regions (for example, hind limbs during scratching, the head during grooming) while suppressing background areas (Extended Data Fig. 5b).
Training procedure
The model was trained end-to-end using the AdamW optimizer with different learning rates per component: the classifier was trained at a fixed rate of 3 × 10−4, while the encoder learning rate was warmed up from 7 × 10−5 to 3 × 10−4 over 20 epochs following an exponential schedule. This strategy allows the feature encoder to adapt gradually while the classifier learns to interpret its evolving representations. Models are trained for 300 epochs with an effective batch size of 256 using cross-entropy loss term with label smoothing (α = 0.1) until validation loss plateaued. Gradient clipping (max norm = 1.0) and mixed-precision training (FP16) were used during training for stability and efficiency. All of the models fully converged, reaching approximately 86% validation accuracy and 92% training accuracy. The model snapshot with the best validation accuracy was used for inference and downstream analysis.
To improve generalization and encourage the model to learn body-orientation-invariant representations, we applied stochastic augmentations in the spatial and temporal domains during training. Each video clip was randomly assigned to one of four augmentation modes: spatial only (30%; random rotation up to ±45°, random erasing of 2–33% of image area and random cropping), temporal only (30%; frame-order reversal), combined spatial and temporal (30%) or no augmentation (10%). Validation and test samples were processed without augmentation.
Dataset and evaluation
We manually annotated observer behaviour across multiple video sessions with BORIS (v.9.3.2)54, labelling each frame with one of seven behavioural labels: rearing (upright posture with front limbs contacting the chamber walls); turning (fast reorientation of body heading within the chamber); investigate (active locomotion or head movements not directed toward the perforated wall); still (stationary idle posture not oriented toward the perforated wall); grooming (rhythmic front-limb movements directed at the head or ears); scratching (rhythmic hind-limb movements directed at the rear of the body); and attention (close proximity to the perforated wall with head oriented toward the barrier slits). The full dataset contains around 18,000 frames in total (rearing, 6%; turning, 5%; investigate, 7%; still, 10%; grooming, 22%; scratching, 8%; attention, 43%).
For model evaluation, we used fivefold cross-validation with 20% frames in validation and 80% frames in training set, stratified by labels. For main figures and downstream analyses, the seven classes are merged into four major categories: exploratory (rearing, turning, investigate), idle (still), self-directed behaviours (grooming, scratching) and attention (attention). Model performance was assessed using the area under the receiver operating characteristic curve (ROC-AUC), with metrics reported as the mean ± s.d. across five validation folds (Extended Data Fig. 5c).
Surgery
Viral strategy
At 12–18 weeks of age, Vgat+/− mice were anaesthetized (isoflurane at 3–5% for induction and 1–3% for maintenance) and placed into a stereotaxic frame before proceeding with injections and optic fibre implanting. A 1:1 300 nl cocktail of Cre-out GCaMP6f58 (Ef1a-Cre out-GCaMP6f) and Cre-activated jRCaMP1b (pAAV.Syn.Flex.NES-jRCaMP1b.WPRE.SV40) was delivered unilaterally into each of the following targeted brain regions: PrL (anteroposterior (AP) −1.40 mm, mediolateral (ML) 0.35 mm, dorsoventral (DV) −1.70 mm), vLS (AP −2.60 mm, ML 0.60 mm, DV −3.25 mm), mPOA (AP −3 mm, ML −0.40 mm, DV −4.75 mm), BNST (AP −3.30 mm, ML 0.85 mm, DV −3.75 mm), AH (AP −3.7 mm, ML −0.50 mm, DV −4.80 mm), VMHvl (AP −4.65 mm, ML 0.72 mm, DV −5.45 mm), LHb (AP −4.70 mm, ML −0.33 mm, DV −2.65 mm), MeA (AP −4.70 mm, ML −2.25 mm, DV −4.90 mm), PA (AP −5.50 mm, ML −2.40 mm, DV −4.95 mm), PMv (AP −5.50 mm, ML −0.58 mm, DV −5.55 mm), lPAG (AP −7.80 mm, ML 0.50 mm, DV −1.65 mm). An additional infusion of 150 nl of GRAB DA1m (hSyn-GRAB_DA1m-WPRE-hGHpA) was delivered to the NAc (AP −1.80 mm, ML 1.15 mm, DV −3.70 mm). Surgery coordinates for each area were calculated relative to the skull surface in the posterior edge of the rostral rhinal vein. All regions included in the final analyses had correct fibre placement based on histology.
For chemogenetic experiments, Vgat+/− or wild-type (Vgat−/−) mice received bilateral infusions of 150 nl of an AAV2 vector encoding a Cre-dependent excitatory DREADD (Ef1a-DIO-hM3Dq-mCherry; Addgene, 50460; PNI Viral Neuroengineering Lab) into the MeA, vLS, PMv and AH. This strategy selectively expressed the Gq-coupled hM3Dq receptor in Vgat+ (inhibitory) neurons in Vgat+/− mice, while serving as a control in wild-type animals lacking Cre recombinase activity.
For optogenetic experiments, Esr1+/− mice received a unilateral infusion of 150 nl of an AAV2/5 vector encoding a Cre-dependent channelrhodopsin (Ef1a-DIO-hChR2(H134R)-mCherry-WPRE-hGHpA; PNI Viral Neuroengineering Lab) into the right VMHvl, enabling selective photoactivation of ESR1+ neurons in this region.
Multi-site fibre strategy
After viral infusions, a custom-built multi-fibre implant59 containing twelve 200-μm-core optic fibres (220 μm cladding, 0.37 NA, THORLabs) was fixed to the skull with Metabond (Parkell). This implant was lowered into the brain to a depth of 5.55 mm relative to the brain surface of the VMHvl using a custom stereotaxic attachment designed to hold multi-fibre implants. Multi-fibre implants are 3D-printed (ABS-Like Micro Resolution, Protolabs) and designed with fibre through-holes in AP and ML locations matching those used for stereotactic viral infusions. Before fixing the fibres in the implant, these are first cleaved with a manual fibre cleaver (THORlabs) and subsequently cut with a ruby scribe to match the specific length of each area’s depth in the brain, with added length accounting for the widths of the implant and each area’s craniotomy. A summary of all coordinates and measurements in mm used for viral deliveries and implant construction is provided in Supplementary Table 2.
Before implantation, bulk light efficiency for every implant was measured, with implants with an average efficiency below 70% getting discarded. After surgery completion, the mice were allowed to recover for at least 3 weeks before the start of recording experiments.
Multi-site fibre photometry
Recording
To record from up to 12 sites simultaneously, we used a custom 12-fibre bundled, branching patchcord (200 μm fibre, 220 μm cladding, 0.37 NA, Doric). One end of the patchcord terminated in an SMA connector in a honeycomb pattern, with the other end affixing all branching fibres in a custom 3D-printed connector at coordinates matching the fibre placements in the multi-fibre implant. The implant fibres were aligned to the patchcord fibres in the connector using four 1 mm steel dowel pins (McMaster), and the two components affixed through 3–4 screws (Open Ephys ShuttleDrive). Recordings were made through a custom written data acquisition program in DAQAmi (Measurement Computing) and using the Neurophotometrics FP3002 system in combination with Bonsai. LEDs delivering three excitation wavelengths (470 nm for optical excitation of GCaMP6f and DA1m GRAB, 560 nm for optical excitation of jRCaMP1b, and 415 nm for a calcium- and dopamine-independent control, light intensity of around 70 μW for each fibre tip of the implant) were interleaved at 40 Hz (for a total 120 Hz sampling rate) throughout recordings. Fluorescence emission was split at 552 nm into green and red channels and focused onto a CMOS sensor for detection. Photometry signals in arbitrary units were collected from 12 sites drawn separately in the green (GCaMP) and red (RCaMP) channels across the imaged honeycomb pattern of fibres.
Signal processing
The mean fluorescence in arbitrary units was collected as raw data for every session. To normalize this signal and correct for potential motion artifacts, we performed processing on individual photometry signals as follows: (1) baseline subtraction using an adaptive iteratively reweighted penalized least squares algorithm60; (2) z-score standardization; and (3) signal subtraction using motion-artifact control signals from 415 nm excitation. For step 3, specifically, we fitted a multilinear regression (sklearn.linear_model.Ridge) for each individual photometry signal using as predictors all calcium-insensitive control signals from 415 nm optical excitation taken from the same recorded session59. The regularization strength (alpha) for each fitted model was determined individually for each session through a grid search. The predicted control signal was then used to subtract the real photometry signal. The resulting corrected signals from this process were finally normalized by their mean value during a 1 min baseline period before any social interaction, yielding the z-scored ΔF/F signal. To remove residual high-frequency artifacts, z-scored ΔF/F traces were subsequently smoothed using a Savitzky–Golay filter (scipy.signal.savgol_filter; window length = 7 samples, polynomial order = 3). As SLEAP-derived behavioural features (see the ‘Pose tracking’ section above) were acquired at a lower temporal resolution than the photometry system, smoothed neural traces were then resampled to match the temporal dimension of the corresponding behavioural feature series for each session: each channel was linearly interpolated onto a new, evenly spaced set of timepoints spanning the same session duration as the original recording, with the number of resampled timepoints set to match the number of frames in the corresponding SLEAP-derived feature series. All analyses were completed on the resulting resampled z-scored ΔF/F data.
Optogenetic stimulation
To optogenetically activate Esr1+/− neurons in the VMHvl, a blue laser (460 nm, 7.0–7.2 mW) was connected to a 200 μm diameter patch cord that was fastened to the mouse’s implanted fibres through ceramic sleeves. For all stimulation, we delivered 20 ms pulses given at 20 Hz (40% duty cycle). Laser activation was controlled through an Arduino microcontroller system that received TTL trigger signals from manual button presses, enabling experimenter-initiated optogenetic stimulation during behavioural sessions. The Arduino was programmed to convert each button press into a train of TTL pulses with the specified temporal parameters (20 ms on, 30 ms off), which directly gated the laser output.
Neural analysis
Time-shifting of attack signals
To identify a population-wide single timepoint for observed attack alignment on a trial-by-trial basis, a shift-only time-warping approach38 was used (Extended Data Fig. 6). This approach addresses temporal uncertainty arising from variability in the timing of neural responses relative to classifier-defined attack onsets. Moreover, moment-to-moment fluctuations in attentional state introduce further latency variability in neural engagement with each observed attack. Traditional PETHs aligned to attack onset therefore average across this temporal jitter, potentially obscuring consistent neural dynamics that are present but variably shifted across trials.
Time-shifting was implemented using the ShiftWarping algorithm from the affinewarp package (v.0.20.0), extended through a custom RobustTimeWarping subclass that adds artifact trial detection, boundary shift correction and template-based alignment of held-out animals. The algorithm learns a single scalar time shift per trial that translates the neural signal forward or backward in time, without stretching or compressing temporal structure. Optimization proceeds iteratively: beginning from the trial-mean as an initial template, the model alternates between (1) finding the optimal per-trial shift that minimizes reconstruction error relative to the current template; and (2) updating the template as the mean of all shift-corrected trials. This loop is repeated for a fixed number of iterations (specified per group below) until convergence. Critically, a single time shift is determined jointly from the activity of all simultaneously recorded neural populations; brain regions are never shifted independently. Before model fitting, trials exhibiting mean z-scored activity exceeding a specified threshold during an early artifact window (frames 0–40, corresponding to the pre-attack baseline period) were excluded. This step removes trials where residual activity from immediately preceding attacks contaminates the baseline, which would bias the learned template toward elevated pre-event activity. For the OBS group, a threshold of 4 z-score units was applied; for the EXP group, this threshold was set permissively high (effectively disabled) given the lower rate of such artifacts in directly experienced aggression.
EXP group: attack-aligned neural signals (−6 s to +6 s, window size = 480 frames at 40 Hz) were extracted for all animals in the EXP group across all training period sessions. Trials containing any NaN values due to missing fibre placements were removed before model fitting. A RobustTimeWarping model was fit to the resulting clean tensor (trials × time × 23 populations) with a maximum allowable shift of ±0.05 × window duration (that is, ±0.5 s; maxlag = 0.05), no smoothness or L2 regularization, and a single optimization iteration. For animals with one or more missing brain regions due to incorrect fibre placement, the learned template from the full-cohort model was used to infer optimal per-trial shifts through a separate align_to_template procedure. In this procedure, missing regions were temporarily filled with data from the nearest available region to enable shift optimization, then restored as NaN in the final time-shifted output.
OBS group: aRobustTimeWarping model was fit to clean OBS trials (NaN-free) from seven of the nine observer animals, with the remaining two animals collected after the primary model was fit. The model was fit with maxlag = 0.18 (±2 s maximum shift), smoothness regularization scale = 0.1, warp regularization scale = 0.1, L2 regularization scale = 0.1, artifact threshold = 4 z-score units over frames 0–40 and 5 optimization iterations. After model fitting, the learned template was used to align the two held-out animals’ clean trials by align_to_template. Animals with one or more missing brain regions due to incorrect fibre placement were handled using the same nearest-available-region substitution procedure described for the EXP group, with missing regions restored as NaN in the final time-shifted output. Time-shifted data from the primary fit and held-out animals were concatenated into a single combined OBS tensor for all downstream analyses. Observer attention state labels (ATTN+/ ATTN−) were propagated through the same trial indexing pipeline to enable subsequent attention-filtered analyses.
NON group: NON animal neural signals, aligned to timepoints derived from OBS attack labels (yoked design), were time-shifted by applying the same fitted OBS model template via fit_transform with identical hyperparameters. This ensures that any temporal structure revealed in OBS signals under the same model reflects genuine signal structure rather than an artifact of the alignment procedure. For neural signals recorded during attacks toward a toy versus a live conspecific, and during familiar versus novel conspecific encounters, the OBS training period model was reset and re-fit to the primary OBS dataset, and the resulting template was used to align these held-out datasets through align_to_template. This ensures that temporal alignment is governed by the same aggression-specific template derived from observer neural dynamics rather than from the held-out behavioural contexts themselves.
Validation controls: to confirm that the learned time shifts reflect aggression-specific neural dynamics rather than generic movement statistics or arbitrary temporal structure in attack bouts, three control conditions were implemented. In the first (synthetic) control, attack labels were replaced with synthetic sequences generated by a Markov chain (order = 10) trained on empirical attack data from 20 randomly selected sessions, preserving the statistical structure of attack timing (transition probabilities and bout durations) while destroying the temporal correspondence between labels and neural activity. The model learned state transition probabilities from the observed attack label sequences and additionally modelled the empirical distribution of attack bout durations, sampling bout lengths from this distribution during sequence generation to preserve realistic bout structure. A target attack rate of 0.1 was applied to match the approximate overall attack frequency observed in real sessions. To ensure a fair comparison between real and synthetic attack-aligned signals, synthetic trial counts were matched to real trial counts on a per-animal, per-day basis by randomly subsampling synthetic trials where the number of synthetic trials exceeded the number of real trials; sessions in which synthetic trials were fewer than real trials retained all available synthetic trials. Neural signals from OBS animals were then time-shifted using these synthetic labels under the same model.
In the second (speed) control, attack labels were replaced with binary indicators of high resident centroid velocity (threshold: >2 z-score units), with any overlap with true attack periods removed. The same OBS model was applied to signals aligned to these speed events. In the third (yoked) control, the OBS model was applied to NON animal neural signals using attack time indices derived from real OBS sessions, testing whether the model produces spurious structure when applied to neural data from animals that never observed aggression. In all three controls, the resulting time-shifted signals and their aligned PETHs were compared against those from real OBS attack trials.
PETH computation: after time-shifting, PETHs were computed for each neural population and experimental group by averaging time-shifted signal tensors across trials, either per-animal (yielding a time × populations × animals array) or across all animals (yielding a time × populations array) pending the type of analysis. Baseline correction was applied by subtracting the per-trial or per-animal median activity during a pre-event window (−5 s to −3 s before attack onset) from each timepoint. For analyses of ATTN+ versus ATTN− trials, time-shifted OBS trials were filtered by requiring a minimum of 5 s of ATTN+ occupancy within the attack window (200 frames out of 480 at 40 Hz) before averaging.
Hard fight: conflict-aligned neural signals during the hard fight were time-shifted using the same RobustTimeWarping procedure described above, with a more conservative parameterization than that used for training-period alignment (center_shift = True, maxlag = 0.05, that is, a maximum allowable shift of ±0.05 × window duration). This approach was adopted for two reasons: first, hard-fight conflict bouts encompass a mixed composition of behaviour types (attacks delivered and received, resisted and not resisted; Fig. 1d), and a tighter, centred shift constraint helps ensure consistent alignment across this heterogeneous trial composition rather than allowing the model to drift toward any one behaviour type; second, the hard fight yields substantially fewer trials per animal than the training period, and a less permissive shift window reduces the risk of overfitting the learned template to a sparse trial set. Missing-region handling, held-out-animal alignment by align_to_template.
Decoding observer behaviour from population neural activity
To test whether population neural activity in OBS animals carries information about the observer’s behaviour, we trained logistic regression classifiers on summary features extracted from windowed neural activity and evaluated their ability to classify behavioural categories. Neural recordings were segmented into 1.5 s windows (60 frames) with a 0.75 s stride (50% overlap), and only windows in which a single behavioural category occupied ≥90% of frames were retained and labelled with that category. Within each window, we extracted 10 summary statistics from the activity of each neural population (maximum, 90th percentile, 10th percentile, median, 10% trimmed mean, s.d., mean squared amplitude, s.d. and mean absolute value of the first-order difference, and s.d. of the second-order difference), yielding a 190-dimensional feature vector per window across the 19 recorded populations.
Decoding was performed separately for each animal and behavioural category as a binary one-versus-rest classification. For each animal and category, a logistic regression classifier with L2 regularization (C = 1) and balanced class weights was fit to features standardized using training-fold statistics. We evaluated model performance with stratified group fivefold cross-validation, in which windows were assigned to folds in blocks of 50 consecutive windows so that temporally adjacent, overlapping windows were not split between training and test sets. Cross-validation was repeated 10 times with different fold assignments, and the positive-class F1 score on held-out windows was averaged across folds and repeats to obtain one score per animal and category. We compared two decoder designs: an all-regions decoder trained on the features of all 19 populations, and a best single-region decoder. For the latter, a separate single-region decoder was trained on the features of each of the 19 populations, and for each animal and category the population whose decoder achieved the highest F1 score averaged across the 10 cross-validation repeats was selected; the F1 score of that decoder was reported. Chance performance was estimated by repeating the all-regions decoding procedure on randomly permuted labels (100 permutations per animal and category) and averaging the resulting F1 scores. Classifiers, feature standardization, cross-validation and F1 scoring were implemented in scikit-learn.
To identify the populations that contributed most to the all-regions decoder, we computed SHAP values61 using the linear explainer from the SHAP package. For each animal and category, the decoder was refitted within the block cross-validation scheme described above, and interventional SHAP values were computed on held-out windows using the training fold as the background distribution. The importance of each population was quantified as the mean absolute SHAP value across held-out windows and that population’s 10 features, averaged across folds and repeats.
Decoding condition and identity from single-population neural activity
To assess whether attack-aligned neural activity in individual SBN populations carries information about the context, social target or identity of the observed aggressor, we trained logistic regression classifiers (LogisticRegression from scikit-learn) on single-region mean z-scored ΔF/F activity and evaluated their ability to decode binary condition labels on a trial-by-trial basis. For each decoding analysis, the feature for each trial consisted of the mean z-scored ΔF/F of a single neural population computed within an active attack window after subtraction of a pre-attack baseline median. Classifiers were trained and evaluated separately for each recorded region, and all analyses were restricted to regions that showed significant attack-aligned activity in OBS animals (identified through the PETH comparison framework described above).
Given the sparsity of trials per animal in certain experimental conditions, decoding was performed across all trials pooled from all animals rather than on a per-animal basis. For each region, a logistic regression classifier with balanced class weights was fit using a pipeline that included standard feature scaling. Regularization strength and penalty type (L1 or L2) were selected by inner grid search using stratified k-fold cross-validation (sklearn.model_selection.StratifiedKFold). The number of folds for the outer cross-validation loop was determined empirically by evaluating classifier performance across a range of fold counts and selecting the value that maximized mean cross-validated accuracy, subject to a minimum of nine samples per fold. The final classifier was re-evaluated using the selected fold structure, and per-fold balanced accuracy scores were stored for subsequent significance testing. To determine whether decoding accuracy was significantly above chance, a one-sample t-test or Wilcoxon signed-rank test was applied to the distribution of per-fold scores against a chance balanced accuracy level of 0.5 (one-sided, testing whether mean accuracy > 0.5).
The following decoding analyses were performed:
Authenticity of aggression (conspecific versus toy target): observer animals watched either naturalistic aggression toward a live BALB/cJ intruder or optogenetically evoked attack-like behaviour directed toward an inanimate toy by an Esr1-cre animal expressing ChR2 in the VMHvl. Neural signals from both conditions were time-shifted using the OBS training period model before feature extraction, applying the same template-based alignment procedure described above.
Familiarity with aggressor (familiar versus novel conspecific): observer animals that had been previously defeated by a CD1 aggressor subsequently watched that familiar aggressor or a novel CD1 aggressor attacking a BALB/cJ intruder. Neural signals were time-shifted using the OBS training period model before feature extraction.
Attack vigour—resident attack speed: observer neural responses were sorted trial-by-trial by the z-scored peak centroid speed of the resident aggressor during the attack window. Trials falling at or below the 10th percentile of resident attack speed were designated as low-vigour trials, and trials at or above the 90th percentile were designated as high-vigour trials.
Attack effectiveness—intruder flight speed: the same trial-sorting and classification procedure was applied using the z-scored peak centroid speed of the intruder following each attack, as an index of attack effectiveness. Trials at or below the 10th percentile of intruder flight speed were designated as low-effectiveness trials, and trials at or above the 90th percentile were designated as high-effectiveness trials.
Response decay
To characterize the temporal dynamics of attack-aligned calcium signals across recorded neural populations, several decay metrics were computed on a per-animal basis from baseline-corrected mean PETHs. For each animal and each recorded population, the mean z-scored ΔF/F signal was computed by averaging across all time-shifted, attack-aligned trials within the training period, yielding a single mean PETH trace per animal per region. All of the subsequent decay metrics were derived from this trial-averaged trace. The peak of each PETH was identified within a search window spanning timepoints −0.5 s to +0.5 s around attack onset. To improve robustness against single-frame transients, a 3-frame (0.075 s) uniform smoothing filter was applied to the trace before identifying the peak location; however, the actual peak value used for all metric calculations was taken from the unsmoothed trace at the identified peak frame. Traces of which the detected peak fell below the noise floor threshold were excluded from all decay metric computations for that region and animal, and the corresponding metric values were set to NaN. For each animal and region with a valid peak, t1/2 was defined as the time elapsed from the peak frame until the signal first crossed 50% of its peak value in the post-peak portion of the trace. To achieve a sub-frame temporal precision, linear interpolation was applied between the last frame above and first frame below the half-target value. If the signal never reached 50% of its peak value within the post-peak analysis window (frames 0 to end of trace from peak), the trial was flagged as non-decaying and the t1/2 value was set to NaN rather than assigned the maximum window duration, to avoid inflating decay time estimates.
Relative similarity of neural activity profiles
To compare the similarity of population-level neural representations across behavioural states between groups, the mean z-scored ΔF/F of each recorded neural population was computed separately for each of the 13 UMAP behavioural clusters, yielding a 13 × 1 activity vector per population per session. Cluster membership at each timepoint was determined by the unsupervised behavioural labels assigned during UMAP segmentation. If no timepoints were assigned to a given cluster within a session, the corresponding vector element was set to zero. Note that activity vectors for OBS mice during the training period were drawn from neural time series filtered for positive attention states (see the ‘Supervised video-based classification of observer behaviour’ section).
Pairwise similarity between sessions from different individuals was quantified using cosine distance, defined as:
$${d}_{\cos }({\bf{A}},{\bf{B}})=1-\frac{{\bf{A}}\cdot {\bf{B}}}{||{\bf{A}}||\,||{\bf{B}}\mathrm{||}}$$
where A and B represent mean activity vectors for two different individuals. Cosine distance measures divergence in the orientation of activity vectors rather than their magnitude, making it well-suited for identifying populations of which the behavioural representations share a similar structure regardless of overall signal scale. A cosine distance of 0 indicates identical vector orientation and therefore maximum similarity, while larger values indicate greater divergence. For training period sessions, activity vectors were mean-centred before computing cosine distance. Specifically, for each session and each neural population, the per-cluster activity vector was centred by subtracting its mean across clusters. Although cosine distance is intended to be invariant to vector magnitude, it is sensitive to differences in the origin of the activity vectors—that is, if two populations share the same representational structure but differ in their absolute baseline level, the vectors will point in different directions in high-dimensional space, inflating the apparent distance between them. Such baseline differences are expected when comparing activity vectors across contexts in animals performing radically distinct behaviours. Furthermore, these differing baseline conditions can shift the absolute level of neural activity, giving the activity vectors different effective origin points. Mean-centring removes this global offset, ensuring that cosine distance reflects differences in the shape of the representation across behavioural states rather than differences in baseline. All 13 UMAP clusters were included in the activity vectors for training period analyses. To further account for the temporal variability in neural responses during the training period—as evidenced by the trial-by-trial time shifts required to align attack-period neural activity (see the ‘Time-shifting of attack signals’ section)—pairwise distances during the training period were computed using a soft cosine distance measure rather than standard cosine distance. Soft cosine distance modifies the standard cosine distance by incorporating a cluster similarity matrix S that encodes the expected functional relationships between behavioural clusters:
$${d}_{{\rm{s}}{\rm{o}}{\rm{f}}{\rm{t}}}(A,B)=1-\frac{{A}^{T}SB}{\sqrt{({A}^{T}SA)({B}^{T}SB)}}$$
The matrix S was constructed by grouping clusters into three functional categories—aggressive (clusters 1–4), investigative (clusters 5 and 7–9) and asocial (clusters 6 and 10–13)—and assigning within-group similarity of 0.5 and between-group similarity of 0.0, with a diagonal of 1.0. This formulation reduces the penalty assigned to activity vector differences that fall within the same functional cluster group, reflecting the expectation that temporal jitter in neural responses may displace activity across closely related behavioural states without representing a true representational difference. As the temporal alignment of neural activity is more reliable during hard fight sessions (where all animals are engaged in equivalent social interactions and the behavioural context is more constrained) standard cosine distance was used for hard fight comparisons and mean-centring was not applied.
Pairwise distance computation
For each session, neural population and pair of animals, cosine distance (or soft cosine distance, for the training period) was computed between the corresponding 13 × 1 activity vectors. Distances were stored in a sessions × populations × OBS animals × other animals array. For statistical comparisons, this matrix was averaged jointly across the sessions and other-animals dimensions to yield a single cosine distance value per population per OBS animal, separately for the OBS-EXP and OBS-NON comparisons. After this reduction, each OBS animal contributed exactly one cosine-distance value per population for its comparison to EXP and one for its comparison to NON, constituting a paired sample (both values are derived from the same animal).
Network-level decoding of group identity from social behaviour-aligned neural activity
To assess whether the multi-region pattern of neural activity during social behaviour distinguishes EXP from NON animals and to determine where OBS animals fall along this axis, a LDA classification approach was applied to population-level activity vectors aligned to social behavioural clusters during the hard fight, implemented using scikit-learn. For each animal and each session, the mean z-scored ΔF/F was computed for each recorded neural population across all frames assigned to social behavioural clusters (conflict clusters 1–4 and investigative clusters 5 and 7–9), yielding a per-session, per-population scalar value. A social engagement index was additionally computed for each session as the difference between mean activity during social clusters (1–5, 7–9) and mean activity during asocial clusters (10–12), providing a single value per population per session that captures the relative modulation of each population by social versus non-social behavioural contexts. These values were averaged across sessions to yield one feature vector per animal, with each element corresponding to a single recorded neural population. Feature matrices were constructed separately for the full population set, excitatory-only and inhibitory-only subsets. An LDA classifier with automatic shrinkage regularization (solver = ‘eigen’, shrinkage = ‘auto’) was fit on EXP (label = 1) and NON (label = 0) animals using each of the three feature subsets. Classifier performance was evaluated using leave-one-out (LOO) cross-validation, with balanced accuracy as the scoring metric. Statistical significance of LOO accuracy was assessed by permutation testing (1,000 permutations of group labels), with the observed LOO accuracy compared against the resulting null distribution. OBS animals were treated as held-out test points and were never included in classifier training; their feature vectors were projected onto the learned discriminant axis using the same imputer and scaler fit on the EXP/NON training data. To provide an interpretable measure of OBS placement relative to the trained groups, a normalized OBS position was computed as:
$${\Delta }_{\mathrm{OBS}}=\frac{{\hat{p}}_{\mathrm{OBS}}-{\hat{p}}_{\mathrm{EXP}}}{{\hat{p}}_{\mathrm{NON}}-{\hat{p}}_{\mathrm{EXP}}}$$
where \(\hat{p}\) denotes the mean projection for each group, such that a value of 0 indicates OBS animals are indistinguishable from EXP mice and a value of 1 indicates that they are indistinguishable from NON mice. Furthermore, to identify which inhibitory populations most strongly drove OBS placement on the EXP–NON axis, a leave-one-population-out procedure was applied to the inhibitory-only subspace. For each iteration, one inhibitory region was dropped from the feature set and the LDA was refit on the remaining regions. The shift in normalized OBS position (ΔOBS position) relative to the full inhibitory model was recorded for each dropped region, with positive values indicating that removing that region shifted OBS animals toward the NON end of the axis.
To provide a complementary dimensionality-reduction view, PCA was applied to the same scaled EXP and NON feature matrices using the full population set. The first two principal components were retained, and OBS mice were projected as held-out test points onto the learned PC space.
Decomposition of shared and unique variance in VMHvl activity across behavioural states
To characterize the unique and shared contributions of each recorded SBN region to VMHvl excitatory population activity, we used an automatic relevance determination (ARD) regression framework with permutation-based variance decomposition41,62,63, applied separately for each behavioural cluster, session and animal. For each animal, neural activity across all sessions was concatenated into a trial × region × epoch array using a standardized formatting pipeline. A fixed set of eight predictor regions was defined a priori (indices corresponding to VMHvl inhibitory, lPAG excitatory, PMv excitatory, PMv inhibitory, AH inhibitory, MeA inhibitory, BNST inhibitory and vLS inhibitory populations), chosen to span the recorded SBN while excluding the target region (VMHvl excitatory). The target variable y was the VMHvl excitatory population activity vector for a given epoch, and the predictor matrix X was the corresponding activity matrix of the nine predictor regions. Epochs or clusters in which any predictor region contained exclusively NaN values, or in which fewer than 80 timepoints were available within a given behavioural cluster, were excluded from analysis. For activity corresponding to OBS mice in the training period, neural activity for each session was filtered for positive attention states a priori.
For each behavioural cluster c within each epoch e, an ARD regression model was fit using threefold cross-validation (KFold, shuffled). ARD regression was selected over standard ridge regression because it places independent Gaussian priors over each regression coefficient, enabling automatic pruning of irrelevant predictors while providing stable coefficient estimates under multicollinearity. Predictions from held-out test folds were concatenated to produce a full out-of-sample predicted time series, and the out-of-sample R2 was computed against the true target. Negative R2 values were clipped to zero. The final cross-validated R2 was stored as the full-model performance score for that cluster and epoch. Regression coefficients were averaged across the three folds to produce a single weight vector per predictor region.
Unique variance (permutation-based knockout): for each predictor region, unique variance was estimated by comparing full-model performance against a knockout model in which the values of that predictor were randomly permuted within the test set at prediction time, leaving the trained model weights intact. This procedure was repeated across 100 permutation iterations per predictor, and the mean knockout R2 was computed across iterations. The unique variance attributable to a given region was defined as the difference between full-model R2 and mean knockout R2, clipped at zero:
$$\Delta {R}_{\mathrm{unique},k}^{2}=\max ({R}_{\mathrm{full}}^{2}-{R}_{\mathrm{knockout},k}^{2},0)$$
Marginal variance and shared variance: to estimate the marginal contribution of each predictor region in isolation, a separate ordinary least squares regression model was fit using only that single predictor, again under threefold cross-validation. Ordinary least squares was used in place of ARD for marginal models given that single-feature models preclude multicollinearity. The marginal R2 was computed from the resulting out-of-sample predictions, clipped at zero. Shared variance for each predictor was then defined as the difference between its marginal R2 and its unique variance:
$$\Delta {R}_{\mathrm{shared},k}^{2}=\max ({R}_{\mathrm{marginal},k}^{2}-\Delta {R}_{\mathrm{unique},k}^{2},0)$$
This quantity captures the portion of variance that a given region shares with the remaining predictors—that is, variance that can be explained by that region alone but is not uniquely attributable to it when the full predictor set is considered.
To test whether the unique variance (ΔR2) attributable to each predictor region changed systematically over the course of training, per-session unique variance values were modelled as a function of training day using a LME model, implemented in statsmodels (mixedlm). For each recorded region and each experimental group (EXP, OBS, NON) separately, a model of the form value ~day + (1|animal) was fit, with the day of training entered as a fixed effect and the animal identity as a random intercept, to account for repeated measurements within animals across the 8-day training period. The day coefficient from each converged model was tested against zero using a Wald test. For excitatory predictors, for which no a priori directional hypothesis was specified, this test was two-sided. For inhibitory predictors, consistent with the a priori hypothesis that inhibitory unique variance declines over the course of training, a one-sided test was used: the two-sided P value was halved when the estimated slope was in the hypothesized (negative) direction, and set to 1 − half the two-sided P value otherwise, preventing an effect in the direction opposite the hypothesis from being reported as spuriously significant.
Behaviour feature encoding
To characterize how the behavioural features were encoded in the neural activities across the network, we fit independently for each feature and each neural signal a linear Gaussian generalized linear model (GLM) with a smoothing regularizer that is chosen based on cross-validation. The input to the model is a one-hot vector representation of the feature value, which was binned in 20 total bins. The fitted GLM weights reflect the tuning curve for that specific region and feature, with positive weights suggesting an increase in activity and negative weights a decrease. To test for group differences in tuning, we used a leave-one-animal-out procedure: for each held-out animal, group-specific tuning curves were fit to the remaining animals, and the cross-validated R2 of the held-out animal’s neural activity was computed using the tuning curve of its own group. For each group, feature and region, a one-sided Wilcoxon signed-rank test was used to determine whether R2 was significantly greater than (P < 0.05). Only feature–region pairs for which at least two of the three groups (EXP, OBS, NON) showed R2 significantly above 0 were analysed further. For these pairs, per-group tuning curves were averaged over the lowest five and highest five bins of the feature, and each pairwise group comparison was performed using a two-sided independent-samples t-test to assess differences in tuning at the extremes of the feature range.
Whole-brain histology for photometry fibre recovery and viral expression assessment
After the completion of our photometry and behavioural studies, animals were deeply anaesthetized by injection of a ketamine and xylazine cocktail, and perfused with 4% paraformaldehyde (PFA) dissolved in 1× PBS. Brains were extracted and post-fixed in 4% PFA for 12–24 h.
For a subset of animals (5 out of 12 EXP mice), after PFA post-fixing, brains were cleared using a previously described iDISCO+ protocol64. Cleared brains were then imaged with light sheet microscopy at ×1.1 or ×1.3 magnification, and these images were registered to a common reference atlas as previously described65. We chose to register to the Paxinos Atlas66 to map fibre tip placement to anatomically defined sub-areas of each SBN location, such as the lateral division of the periaqueductal grey or the NAc core and shell structures. Fibre tip locations were manually identified in registered light-sheet images and plotted together in the common Paxinos coordinate frame. Experimenters were blinded to group identity during histological verification.
For another subset of animals (7 out of 12 EXP, 7 out of 9 OBS and 6 out of 8 NON mice), after PFA post-fixing, the extracted brains were cryoprotected in 30% sucrose and embedded in optimal cutting temperature mounting medium (Fisher Healthcare Tissue-Plus OCT compound, Thermo Fisher Scientific) for freezing over dry ice. Cryosections of the frozen tissue (30 μm slices) were made and stamped directly onto glass microscope slides. The slices were washed with PBS, dried and then coverslipped with a mounting medium (EMS Immuno Mount DAPI and DABSCO, Electron Microscopy Sciences, 17989-98, 180418), and sealed with clear nail polish around the slide edges. After at least 12 h of drying, the slides were imaged with a digital robotic slide scanner (NanoZoomer S60, C13210-01, Hamamatsu).
Fibre placements for all recorded animals are summarized in Extended Data Fig. 4, with coronal reference sections adapted from the Allen Reference Atlas66.
DREADD-Gq perturbation
To assess the causal contribution of inhibitory populations to observation-induced changes in aggressive behaviour, a separate cohort of Vgat+/− (OBS-Gq) or wild-type littermates Vgat−/− (OBS-control) animals expressing hM3Dq-mCherry in MeA, vLS, PMv and AH underwent an observation training regime consisting of five consecutive days of three resident–intruder observation sessions per day, using the same observer compartment setup described above. On the sixth day, the mice were subjected to a hard fight session against a CD1 aggressor screened a priori for aggression against other CD1 males. At 30 min before the hard fight, each animal received an intraperitoneal injection of clozapine-N-oxide (CNO; 1 mg per kg; Hello Bio) and was returned to its homecage to allow for sufficient drug bioavailability before the CD1 aggressor was introduced. Behavioural outcomes, using unsupervised clustering and annotation classification of fight outcome during the hard fight were compared between OBS-Gq and OBS-control cohorts. Note that assignment to OBS-Gq and OBS-control was determined by genotype; both groups received identical viral injections and CNO. Experimenters were not blinded to genotype during CNO administration of the hard fight.
Statistical analysis
All statistical tests were run in Python (v.3.9.23) using numpy (v.1.23.0), pandas (v.2.3.1), matplotlib (v.3.9.4), seaborn (v.0.13.2), scipy (v.1.13.1), scikit-learn (v.1.6.1) and statsmodels (v.0.14.5). Unless otherwise noted in the corresponding figure legend or Methods section, statistical analyses were conducted using biological replicates (individual animals) as the unit of replication. The exception is analysis of trial-level neural-behavioural covariation (for example, decoding of trial-by-trial resident attack speed, subordinate speed; Fig. 3b–d), for which the trial is the appropriate unit of analysis given the trial-level nature of the scientific question being tested.
Before any group comparison, samples were classified as independent or related based on experimental design: distinct animals assigned to different groups were treated as independent, and repeated measurements from the same animals across timepoints or conditions were treated as related.
Sidedness of tests (one-sided versus two-sided) was determined a priori based on directional hypotheses specified before the corresponding analysis was performed, and is stated explicitly in the Methods section and figure legend for each analysis in which a one-sided test was used. In the absence of a specified a priori directional hypothesis, tests were two-sided by default.
For comparisons between two independent groups, normality was assessed per group using the Shapiro–Wilk test (scipy.stats.shapiro). For normally distributed data, equality of variance was assessed using Levene’s test (scipy.stats.levene); group means were compared using Student’s t-test (scipy.stats.ttest_ind) when variances were equal, or Welch’s t-test (scipy.stats.ttest_ind, equal_var=False) when variances were unequal. For non-normally distributed data, the Brunner–Munzel test (scipy.stats.brunnermunzel) was used in place of the Mann–Whitney U-test as the primary nonparametric two-sample test. The Brunner–Munzel test was preferred because, in contrast to the Mann–Whitney U-test, it does not assume equal variances or distributional shape between the two groups being compared and remains valid under heteroscedasticity and unequal sample sizes—both common features of this dataset, where group sizes frequently differ due to histological exclusion criteria. In the rare cases in which the Brunner–Munzel test statistic was undefined (for example, due to zero within-group variance), the Mann–Whitney U-test (scipy.stats.mannwhitneyu) was used as a fallback. Multiple comparisons were corrected using the Bonferroni or FDR (Benjamini-Hochberg; statsmodels.stats.multitest.multipletests) method as specified in the corresponding Methods section and figure legend.
For comparisons between two related samples, the normality of the paired differences was assessed using the Shapiro–Wilk test. A paired t-test (scipy.stats.ttest_rel) was used for normally distributed differences, and a Wilcoxon signed-rank test (scipy.stats.wilcoxon) was used otherwise.
For comparisons across three independent groups (EXP, OBS and NON), normality was assessed per group via the Shapiro–Wilk test and equality of variance via Levene’s test. For normally distributed data with equal variance, a one-way ANOVA (scipy.stats.f_oneway, equal_var=True) was used, followed by post hoc Student’s t-tests. For normally distributed data with unequal variance, Welch’s ANOVA (scipy.stats.f_oneway, equal_var=False) was used, followed by post hoc Welch’s t-tests. For non-normally distributed data, a Kruskal–Wallis test (scipy.stats.kruskal) was used, followed by post hoc Brunner–Munzel tests (with Mann–Whitney U-test as a fallback, as described above). Post hoc pairwise comparisons were corrected using the Bonferroni or FDR method as specified in the corresponding figure legend.
For the single analysis involving three related conditions (day 1, day 8 and the hard fight, within the EXP group; Extended Data Fig. 1d), a Friedman test (scipy.stats.friedmanchisquare) was used in place of a repeated-measures ANOVA, followed by post hoc Wilcoxon signed-rank tests, corrected using the FDR method.
For determining the difference between two flattened distributions (NAc DA/LHb bias), a two-sample Kolmogorov–Smirnov test (scipy.stats.ks_2samp) was conducted.
For assessing whether cross-validated decoding accuracy differed significantly from chance (0.5), one-sample t-tests (scipy.stats.ttest_1samp) or Wilcoxon signed-rank tests (scipy.stats.wilcoxon) were applied to the distribution of per-fold accuracy scores pending normality, tested one-sided for above-chance decoding, with FDR correction across regions where applicable.
Where LME models were fit (for example, to test for a trend in unique variance across the training period; see ‘Decomposition of shared and unique variance in VMHvl activity across behavioural states’ section), convergence was assessed using up to six optimizer/estimation-method combinations in sequence (L-BFGS, Powell and conjugate gradient, each under both restricted and full maximum likelihood), with the first converged fit retained; models for which no combination converged were excluded from the corresponding analysis. Convergence outcomes and the specific method used were logged for every fit as a diagnostic check on model reliability.
Where session-level or pooled data were evaluated by permutation testing (for example, pairwise transition-probability significance across UMAP clusters, decoding accuracy against chance and against group identity; Extended Data Fig. 1g–i), the number of permutations and null-construction procedures are described in the corresponding Methods section.
Where multiple comparisons were corrected within a defined family rather than across all comparisons in a panel, family membership was established a priori and is stated explicitly in the corresponding figure legend. Family structure varied by analysis, reflecting the specific directional hypotheses under test. For behaviour cluster-level comparisons, clusters were divided into two a priori families—social (clusters 1–5 and 7–9) and asocial (clusters 6 and 10–13)—anticipating opposite directions of effect between the two. For Fig. 2, families were defined within each experimental group (EXP, OBS) individually. For Fig. 3, families were defined by valence (NAc-DA, LHb) and excitatory/inhibitory population identity. For Fig. 4, families were defined by behavioural context (training period, hard fight). For Fig. 5, families were defined by cell type (excitatory, inhibitory) for all ARD-based analyses. Where a figure legend does not specify a family structure, correction was applied either within a single planned comparison (no correction required) or across the full set of comparisons presented in that panel.
Our Article follows recommendations for inclusion and ethics in global research.
Reporting summary
Further information on research design is available in the Nature Portfolio Reporting Summary linked to this article.