Main

Pain is a complex, aversive perception, fundamental to adaptive survival1. Understanding the neural circuits and cell types underlying the affective and motivational features of pain experiences is crucial for advancing precision therapeutics for individuals with chronic pain conditions3,4. Current analgesic drugs, such as opioids, act on widely expressed molecular targets that reduce pain unpleasantness but also promote serious and fatal side effects. By pinpointing specific neural circuits for pain-associated aversion, which intersect with the expression of the μ-opioid receptor (MOR)5, the molecular target of morphine, a new class of effective analgesics can be developed that interfere with the unpleasantness of pain rather than pain sensation, with reduced addiction and respiratory depression side effects6,7.

Coordinated neural activity in the anterior cingulate cortex (ACC) is essential for encoding the emotional and motivational dimensions of pain8,9,10,11,12,13,14, guiding behavioural choices in real time and promoting future avoidance of harmful stimuli15,16. According to the gate control theory17 and central control models15,18, pain perception is not a passive relay of nociceptive input but is actively shaped by spinal and brain circuits that integrate sensory, cognitive and emotional information to amplify or inhibit pain signals. Within this framework, the ACC has a central role in evaluating nociceptive input in relation to valence, context and internal state. This processing supports the selection of adaptive responses, such as escape and recuperative behaviours19, which act as negative feedback to reduce further injury and promote healing. By tracking spontaneous pain-related behaviours and activity recordings in cortical neurons, we can infer the latent dynamic computations underlying pain. This approach provides a window into identifying single neurons and distributed ensembles in the ACC that represent the affective–motivational components of pain, offering candidate cellular targets for therapeutic strategies.

Perceived pain unpleasantness strongly correlates with functional magnetic resonance imaging activity in the human ACC9,19. Patients with intractable chronic pain treated with surgical cingulotomy lesions do not report changes in pain perception, intensity discrimination or reactions to momentary harmful stimuli20,21,22. Rather, their attitude towards pain is modified, dissociating the negative valence from the experience of pain. In these cases, pain becomes a sensation rather than a threat23. Similarly, in preclinical models, lesions24,25, opioids26,27,28,29 and optogenetic manipulation30,31,32,33,34,35,36 of ACC neural circuits attenuate aspects of the affective–motivational component of pain. Thus, ACC neural circuits that drive adaptive behaviour to acute noxious stimuli might also be maladaptive during chronic pain37,38. Acute pain engages MORs in the dorsal anterior cingulate and lateral prefrontal cortex, and the affective perception of pain is correlated with MOR availability in the ACC and other brain regions26,27,39,40,41. This evidence supports the role of MOR signalling within the ACC in altering the perception of pain13. Leveraging personalized deep-brain stimulation42,43,44 or cell-type-specific approaches45,46 to modulate neural activity in MOR-expressing neurons2 may mimic the prefrontal cortical actions of opioid analgesia without the associated risks of off-target pharmacotherapies1.

Mapping nociceptive and µ-opioidergic ACC neurons

Using nociceptive activity-dependent tagging (painTRAP) and immediate early gene (IEG) mapping (painFOS), we identified a ‘nociceptive hotspot’ approximately 700 μm in length located in the anterior ACC dorsal Cg1 and ventral Cg2 (Extended Data Fig. 1, Supplementary Table 1 (rows 48–49) and Supplementary Note 1). In situ hybridization revealed that approximately 30–50% of painFOS neurons and approximately 70% of Slc17a7+ glutamatergic neurons co-express Oprm1, indicating that a substantial fraction of the nociceptive hotspot expresses MORs (Extended Data Fig. 2 and Supplementary Note 1). Single-nucleus RNA sequencing of this ACC nociceptive hotspot, before and after the development of chronic neuropathic pain using the spared nerve injury (SNI) model, resolved 23 cell types. Only three glutamatergic neuronal clusters (L2/3 IT-3, L5 IT-1 and L6 CT-2) showed persistent nociceptive and neuropathic IEG signatures, all of which expressed Oprm1 (Extended Data Fig. 3 and Supplementary Note 2). Oprm1 transcript levels and distribution were unchanged during chronic neuropathic pain (Extended Data Fig. 3 and Supplementary Note 2), implying that morphine can access molecularly distinct ACC neurons that encode nociception throughout chronic pain.

ACC MORs mediate morphine analgesia

To determine the role of cortical MORs in morphine-mediated analgesia, we genetically deleted MORs selectively in ACC neurons (Extended Data Fig. 4, Supplementary Table 1 (row 50) and Supplementary Note 3). In Oprm1fl/fl mice given AAV9–hSyn–Cre in the ACC versus controls, systemic morphine (0.5 mg kg−1) no longer reduced affective–motivational pain responses to noxious stimuli despite intact sensory thresholds (Extended Data Fig. 4f–j and Supplementary Table 1 (rows 51–57)). Conversely, AAV9–hSyn–FLEx–OPRM1 re-expression of MORs exclusively in the ACC of global MOR knockout mice restored morphine analgesia (Extended Data Fig. 4k–r and Supplementary Table 1 (rows 58–65)). Together, these loss-of-function and gain-of-function experiments demonstrate that ACC MORs are both necessary and sufficient for the affective pain relief produced by clinically relevant morphine doses, identifying this cortical ensemble as a key target for μ-opioid-mediated analgesia.

A deep learning system for pain behaviour analysis

The complexity of pain cannot be fully captured by reflexive withdrawal responses (the current standard for preclinical analgesic evaluation), which assess only evoked responses and fail to reflect the continuing affective experience most relevant to patients with chronic pain47,48,49. Although assays such as conditioned place preference or aversion measure memory-based responses to prior pain or relief24,50,51, they do not capture the dynamic, moment-to-moment motivational behaviours driven by spontaneous or continuing pain1,52.

To address these limitations, we developed Light Automated Pain Evaluator (LUPE; Fig. 1), a behavioural analysis platform designed to resolve fine-scale, naturalistic pain-related behaviours across several timescales. LUPE enables a nuanced and translationally relevant assessment of affective–motivational pain states in freely moving mice. Named after the Greek daemon of pain and suffering (Lýpē; λῡ́πη), LUPE provides a standardized, dark environment optimized for the behaviour of nocturnal prey animals. Critically, it eliminates the presence of the human experimenter both as a looming threat and as a subjective observer, allowing for objective quantification of spontaneous nocifensive behaviours.

Fig. 1: Deep learning analysis of natural behaviour reveals how pain and opioids shape internal affective–motivational states.
Fig. 1: Deep learning analysis of natural behaviour reveals how pain and opioids shape internal affective–motivational states.
Full size image

a, Schematic of the standardized LUPE chamber. b, A 20-body point DLC pose-tracking model was built from male and female mouse pain behaviour. c, Behaviour segmentation models trained iteratively on supervised annotations of behaviours with A-SOiD, followed by unsupervised sub-clustering with B-SOiD. d, Motion energy heat maps illustrating spatial trajectories and intensity distributions for the six primary behavioural repertoires. e, Temporal probability plots for the six primary behaviour repertoires in 1-min bins, comparing uninjured mice to mice with left hindpaw injections of 1% formalin, 5% formalin or capsaicin. f, Raster plots of behaviour transitions within a 30-s window. g, Procedure for behavioural state inference from statistical structure of spontaneous behaviour. h, Left, model centroid transition matrices characterizing each of six inferred states. Right, comparing the fraction occupancy of mice in each state between uninjured (grey), formalin (magenta) and capsaicin (cyan) pain models (n = 20 per group; one-way analysis of variance (ANOVA); Tukey correction: Pstate1 = 0.0007, Pstate3 = 0.0078 and Pstate4 < 0.0001). i, Two-dimensional (2D) visualization of PCA of state occupancies across pain models. j, Magnitude of coefficients of each state in each PCA. k, Scores of each animal along PC1 (top) and PC2 (bottom) across pain models (n = 20 per group; one-way ANOVA; Tukey correction: PPC1 = 0.0027 and PPC2 = 0.0082). l, Dose–response of morphine on PC1 (top) and PC2 (bottom) scores in uninjured, formalin-administered and capsaicin-administered mice (n = 20 per group and dose; one-way ANOVA; Tukey correction: PPC1 uninjured < 0.0001, PPC1 formalin < 0.0001, PPC1 capsaicin < 0.0001, PPC2 uninjured < 0.0001, PPC2 formalin < 0.0001 and PPC2 capsaicin < 0.0001). P < 0.05. Bars are mean; dots are individual animals; vertical lines and shaded areas are s.e.m. See Supplementary Table 1 (rows 1–14) for statistics. NS, non-significant. Scale bar, 2.5 s (f).

Source data

In addition to the standardized chamber and high-speed infrared videography recorded from below a glass floor (Fig. 1a and Supplementary Fig. 1), behavioural classification was driven by a multilayered analysis pipeline. Using DeepLabCut (DLC)53 to track 20 body key points, LUPE extracted detailed posture dynamics that were processed through both semi-supervised (A-SOiD54) and unsupervised (B-SOiD55) algorithms to identify six holistic behavioural repertoires: still, walk, rear, groom, lick left hindpaw and lick right hindpaw (Fig. 1b,c and Supplementary Fig. 1). These repertoires were assembled from sub-second behavioural syllables and allowed quantitative analysis of transitions across time. Motion energy plots visualized the displacement of tracked body points, defining each behaviour and distinguishing similar actions such as grooming and paw-directed licking (Fig. 1d).

To evaluate the sensitivity of LUPE to dynamic changes in pain-related behaviour, we applied the formalin and capsaicin models of acute pain56. Male and female C57Bl/6J mice were habituated to the LUPE chamber for two consecutive days and then injected in the left hindpaw with 1% or 5% formalin or 2% capsaicin, or left uninjured as controls (Fig. 1e). LUPE computed the behavioural probabilities for all six repertoires over 30-min sessions for all 60 mice in under 2 h, compared with 50–150 min for manual57 scoring of one behaviour in one mouse (with the upper bound equivalent to 54,000 min for full dataset scoring; Supplementary Fig. 1k). By automating behaviour classification, LUPE increases the speed, rigor and reproducibility of preclinical pain behaviour analysis. It also generates archival-quality datasets that include video logs and computer-scored results, facilitating transparent cross-laboratory comparison, long-term record keeping and future reanalysis.

LUPE identified a low dose of morphine (0.5 mg kg−1) that reduced licking of the injured hindpaw following both formalin-induced and capsaicin-induced injury that did not affect walking (Extended Data Fig. 6a–g and Supplementary Table 1 (rows 75–87)). Therefore, LUPE provides a sensitive measure of ethologically relevant affective–motivational pain behaviour that can identify translationally relevant analgesic doses.

Discovery of morphine-sensitive latent pain states

Inferring internal states, such as pain, from sparse spontaneous behaviour is a central challenge in ethological neuroscience. An injury to the left hindpaw may or may not elicit licking at a given moment, although the animal may still be experiencing pain. We therefore tested whether latent cognitive–affective pain states could be determined from LUPE-scored behaviour. From 58 mice (formalin, n = 19; capsaicin, n = 20; and SNI, n = 19; Fig. 1g and Extended Data Fig. 5), we modelled behavioural transitions as Markov processes using 30-s sliding windows to produce per-animal transition matrices (Fig. 1g and Extended Data Fig. 5a). Matrices were clustered by k-means (k = 6; 100-fold cross-validation; Fig. 1g and Extended Data Fig. 5b). Classification of animals to these six clusters exceeded chance (Euclidean distance between real versus shuffled cluster centroids; Extended Data Fig. 5c–h and Supplementary Table 1 (rows 66–72)). No single behaviour drove the clustering; systematic removal of individual behaviours disrupted classification less than expected by chance (Extended Data Fig. 5c).

Cluster centroids define the mean transition matrices of six distinct behaviour states (Fig. 1h): (1) stillness, walking, rearing and grooming; (2) stillness, walking and rearing; (3) state 1 plus licking the injured paw; (4) all behaviours except licking the uninjured paw; (5) all behaviours except stillness; and (6) stillness, walking, rearing and licking the injured paw. States evolve over seconds to minutes and show conserved dynamics across pain models (Extended Data Fig. 5i–k and Supplementary Table 1 (rows 73–74)). Behaviour states distinguished injured from uninjured animals but did not separate injury types (Fig. 1h and Supplementary Table 1 (rows 1–6)). Uninjured mice predominantly occupied states 1 and 2; capsaicin and formalin increased occupancy of states 3 and 4 and reduced time in state 1. Notably, state 4 was uniquely and dose-dependently suppressed by morphine, indicating a selectively opioid-sensitive spontaneous-pain dimension (Extended Data Fig. 6g and Supplementary Table 1 (rows 97–99)), although morphine modulated all states dose-dependently across conditions (Extended Data Fig. 6g and Supplementary Table 1 (rows 88–105)). Thus, latent affective–motivational states inferred from spontaneous behaviour track pain and analgesia.

Numeric pain index tracks injury and analgesia

To compress the diverse effects of pain and morphine across all six states, we applied principal component analysis (PCA) to the fraction of time each mouse spent in each state across pain conditions (Fig. 1i). This revealed two principal axes of variation in behaviour. Both capsaicin and formalin shifted scores along these axes, reducing the first component and increasing the second, regardless of injury model (Fig. 1k and Supplementary Table 1 (rows 7–8)). The first principal component (PC1), driven primarily by states 1 and 2, reflects a baseline behavioural structure disrupted by both injury and high-dose morphine and is termed the general behaviour scale (Fig. 1j,l (top) and Supplementary Table 1 (rows 9–11)). The second component (PC2) was weighted by states 2 and 4, selectively increased by injury and dose-dependently suppressed by morphine (Fig. 1l (bottom) and Supplementary Table 1 (rows 12–14)), capturing the presence and relief of affective pain. Because PC2 responds bidirectionally to injury and analgesia, we define it as the affective–motivational pain scale (AMPS), a data-driven, continuous index of pain-related behavioural states.

Licking as a structured motivated response to pain

The gate control theory asserts that volitional behaviours, such as rubbing or licking injured tissue, act as antinociceptive responses by recruiting touch afferents that inhibit spinal nociceptive signalling (Extended Data Fig. 7a). Consequently, the unpleasantness of pain drives motivated licking, which then reduces pain, forming a negative feedback loop. Thus, motivated licking is expected to increase with affective pain and decline as analgesia—or recuperation—is achieved.

Our analysis treated latent behavioural states as Markovian processes, in which behavioural probabilities are stable within a state (Extended Data Fig. 7b (top)). We therefore tested whether licking dynamics followed theoretical predictions by measuring the probability of each behaviour as a function of elapsed time within pain state 4, a latent state consistently enhanced by injury and dose-dependently suppressed by morphine (Fig. 1h).

Across injury models, injured-paw licking showed a reproducible temporal profile within pain state 4: near zero at state onset, accumulating in the latter half and declining just before the state transition (Extended Data Fig. 7b,c and Supplementary Table 1 (rows 106–109)). This temporal structure was not seen for other behaviours in pain state 4 or for licking pooled across all states (Extended Data Fig. 7d–f and Supplementary Table 1 (row 110)). These results indicate that paw licking is not merely a reflexive nocifensive action but an innate affective–motivational response engaged to negatively modulate pain, consistent with the gate control theory and its role as a motivated antinociceptive behaviour.

ACC dynamics reflect nociception and behaviour

To link ACC activity to morphine-sensitive pain behaviour, we performed single-cell calcium imaging in freely behaving mice inside LUPE. We expressed AAV9–hSyn–jGCaMP8m and implanted 1.0-mm GRIN lenses at ACC nociceptive hotspot coordinates (n = 5 male mice; Fig. 2a,b and Extended Data Fig. 8a,b). With a head-mounted one-photon miniscope, we recorded neural activity during acute inflammatory pain (left hindpaw intraplantar injection of 2% capsaicin (10 μl)) and after morphine analgesia (0.5 mg kg−1; Fig. 2c,d). A Fisher linear decoder (100-fold cross-validation) reliably decoded spontaneous behaviours from ACC population activity across mice and sessions, independent of injury or opioid treatment (Fig. 2e, Extended Data Fig. 8g,h and Supplementary Table 1 (row 116)).

Fig. 2: Neural dynamics in ACC track acute pain and analgesia.
Fig. 2: Neural dynamics in ACC track acute pain and analgesia.
Full size image

a, Microendoscope calcium imaging synced with LUPE behaviour tracking. b, GRIN lens implant and hSyn–GCaMP8m expression in ACC Cg1. c, From top to bottom, average and single-cell neural activity (z-score) from a representative mouse, LUPE behaviours, states inferred by our behavioural state model and probability of behaviours given states and behaviour history (binomial GLM). d, Capsaicin imaging protocol injury (intraplantar; 2%; left hindpaw) and morphine (intraperitoneal (i.p.); 0.5 mg kg−1; n = 5). e, Fisher decoder accuracies predicting behaviours from neural activity, averaged over mice (permutation test; Extended Data Fig. 8g). f, Area under the receiver operating characteristic curve (auROC) of GLMs predicting Plick from e in each animal (n = 5). g, Calcium events per second of neurons in all sessions (two-way ANOVA; Tukey correction: Pinteraction = 0.0009). h, Mean ± s.e.m. fraction of positive and negative Plick neurons during capsaicin (red outline) and capsaicin + morphine (purple outline) sessions. i,j, Calcium events per second of positive (i) and negative (j) Plick neurons in capsaicin and capsaicin + morphine sessions (two-way ANOVA; Tukey correction: positive Plick neurons, Pinteraction = 0.0004; negative Plick neurons, Pinteraction = 0.026). k, Average lick probability around lick bout onset (two-tailed unpaired t-test: Pnegative, 1–2 s = 0.0003). Light grey, 0–1 s; dark grey, 1–2 s. l,m, Left, average activity in positive (l) and negative (m) Plick neurons around lick bout onset, pooled across animals. Right, area under the curve (AUC) of lick probability from 0 to 1 s and from 1 to 2 s post- initiation (two-tailed unpaired t-test: Pnegative, 0–1 s = 0.0003). Light orange, 0–1 s; dark orange, 1–2 s (l). Light blue, 0–1 s; dark blue, 1–2 s (m). n, Behavioural probability as a function of fraction time in pain state 4 (n = 19–20 per group). o, Cumulative lick probability over fraction of time remaining in pain state 4 (two-sided Kolmogorov–Smirnov test: P = 1.1 × 10−23). p, Summary of results. P < 0.05. Bars, lines or dots are mean; error bars and shaded areas are s.e.m. (see Supplementary Table 1 (rows 15–24) for statistics). Scale bars, 1.0 mm (b (yellow bar)), 1 zS (c).

Source data

We next investigated whether ACC ensembles encode nociceptive signals by modality or valence. In uninjured mice, we delivered mechanical and thermal stimuli to the left hindpaw (0.16-g filament; pin prick; 30 °C water drop; 55 °C hot-water drop; 6 °C acetone) and compared these to orally consumed stimuli of opposing valence (10% sucrose versus quinine) and a 55 °C hot-water drop. ACC neurons showed greater overlap in responses to noxious stimuli across modalities (approximately 11–20% overlap among excited cells and approximately 25% among inhibited cells) than between stimuli of opposite valence. Among excited cells, only 6% responded to both 55 °C heat and sucrose versus 13% for heat and quinine; the overlap among inhibited cells was approximately 11% for both pairings (Extended Data Figs. 9a,c and 10e). Activity patterns and cross-decoding performance further separated heat-activated versus sucrose-activated neurons (Extended Data Fig. 10a–e), consistent with valence-specific encoding in ACC neural populations.

Morphine inhibits pain-tracking ACC neurons

To test whether neurons encoding lick probability are morphine-sensitive, we first estimated lick probability by aligning neural activity to behaviour and latent states and fitting a binomial generalized linear model (GLM; current state and behaviour history using two previous time steps; Fig. 2c). These state-based GLMs outperformed chance and yielded a pseudo-continuous lick-probability trace (Fig. 2c). We then trained GLMs to predict behavioural probability from the PCs capturing 80% of neural variance per animal per session (Extended Data Fig. 8c). These models exceeded performance on shuffled data (Fig. 2f, Extended Data Fig. 8d and Supplementary Table 1 (rows 111–115)). Neurons with the largest absolute weights in the top 3 PCs (P < 0.001; |z-score of coefficient | > 1.5) were labelled Plick neurons (Extended Data Fig. 8e,f).

The ACC population activity was elevated during capsaicin sessions versus baseline and was selectively suppressed by 0.5 mg kg−1 of morphine only with injury (Fig. 2g and Supplementary Table 1 (row 15)). Plick neurons split into positive (activity increased at lick onset; 16.5 ± 3.4% of cells) and negative (activity decreased at lick onset; 16.6 ± 3.4% of cells) subpopulations (Fig. 2h). Morphine inhibited these subpopulations differently; positive Plick cells were suppressed selectively during pain state 4, whereas negative Plick cells showed broader state-independent inhibition (Fig. 2i,j and Supplementary Table 1 (rows 16–17)). Together, this indicates population-dependent and state-dependent modulation of Plick neurons by morphine.

We next examined the dynamics surrounding the onset of a lick bout. Behaviourally, morphine reduced lick probability 1–2 s after lick onset, indicating impaired lick maintenance (Fig. 2k and Supplementary Table 1 (rows 18–19)). Morphine did not alter positive Plick neurons but increased inhibition of negative Plick neurons 0–1 s after lick offset, preceding the behavioural change (Fig. 2l,m and Supplementary Table 1 (rows 20–23)). These effects sharpened Plick selectivity for licking versus other behaviours (Extended Data Fig. 8i–l and Supplementary Table 1 (rows 117–119)).

Over longer pain state 4 bouts, morphine narrowed the lick-probability profile in capsaicin-treated mice by reducing early-state licking and causing greater accumulation near the state end (Fig. 2n,o and Supplementary Table 1 (row 24)). Thus, morphine relieves the affective–motivational drive to lick by suppressing spontaneous activity in positive Plick neurons and enhancing behaviour-locked inhibition of negative Plick neurons, producing delayed initiation and reduced maintenance of licking during pain state 4 (Fig. 2p).

Morphine restores chronic pain-disrupted dynamics

We performed longitudinal miniscope calcium imaging in mice expressing hSyn–GCaMP8m with GRIN lenses in ACC Cg1, recorded in LUPE 1 day before and 1 day, 7 days, 14 days and 21 days after SNI (n = 9) or in uninjured controls (n = 9; Fig. 3a). SNI produced an immediate, sustained increase in spontaneous left-hindpaw lick rate, pain-state occupancy and AMPS scores versus controls (Fig. 3b–e and Supplementary Table 1 (rows 25–27)). As in acute injury, a single 0.5 mg kg−1 of morphine dose at 3 weeks post-SNI reduced AMPS scores in mice with SNI (Fig. 3f and Supplementary Table 1 (row 28)), indicating that opioids remain effective for affective–motivational features of chronic neuropathic pain.

Fig. 3: Morphine targets functionally compromised ACC neurons to relieve chronic pain.
Fig. 3: Morphine targets functionally compromised ACC neurons to relieve chronic pain.
Full size image

a, SNI protocol for chronic neuropathic pain. b, Log-transformed rate of licking at the injured limb in SNI (red; n = 9) or uninjured controls (grey; n = 9; two-way repeated measures ANOVA; Tukey correction: Pinteraction = 0.0036). c, Heat map of average state occupancy. d, Occupancy of pain and non-pain states in SNI and uninjured mice (two-way repeated measures ANOVA; Tukey correction: Pinteraction < 0.0001). e, AMPS score in SNI and uninjured mice (two-way repeated measures ANOVA; Tukey correction: Pinteraction = 0.0089). f, AMPS score in SNI and uninjured mice 3 weeks post-SNI and morphine (0.5 mg kg−1; intraperitoneal; two-way repeated measures ANOVA; Tukey correction: Pinjury = 0.0085; Ptreatment = 0.0041). g,h, Left: lick-evoked activity in positive (g) and negative (h) Plick neurons before (black) and after SNI (warm colour gradient; yellow = 1 day and red = 3 weeks post-SNI). Right: area under the curve of lick-evoked activity (0–1 s post-onset) in SNI and uninjured mice (two-way repeated measures ANOVA; Tukey correction: Ppositive,interaction < 0.0001; Pnegative,interaction = 0.021). i,j, Lick-evoked activity in positive (i) and negative (jPlick neurons. Left, lick-evoked activity at baseline (black), 3 weeks post-SNI (red) and 3 weeks post-SNI + morphine (blue). Right, lick-evoked activity 3 weeks post-SNI versus uninjured mice (two-way repeated measures ANOVA; Tukey correction: Ppositive,interaction = 0.035; Pnegative,treatment < 0.0001; Pnegative,injury < 0.0001). k,l, Calcium event rate in positive (k) and negative (l) Plick neurons before and after morphine treatment (two-way repeated measures ANOVA; Tukey correction: Ppositive,treatment = 0.0023; Pnegative,treatment = 0.0124). m, Linear regression predicting lick rate (purple) and pain state occupancy (grey) from the average magnitude of lick-evoked activity 3 weeks post-SNI (top), after morphine (middle) and change between sessions (bottom; Bonferroni-corrected P values displayed). P < 0.05. Bars, lines or dots are mean; error bars and shaded areas are s.e.m. (see Supplementary Table 1 (rows 25–37) for statistics).

Source data

Using the same Plick identification shown in Fig. 2, SNI impaired decoding accuracy for sensory stimuli, behaviours and latent states relative to baseline and controls (Extended Data Fig. 11a–h and Supplementary Table 1 (rows 121–128)) and persistently blunted lick-evoked responses in both positive and negative Plick neurons (Fig. 3g,h and Supplementary Table 1 (rows 29–30)). Morphine reversed these SNI deficits at lick onset and further enhanced Plick responses in uninjured mice (Fig. 3i,j and Supplementary Table 1 (rows 31–32)). SNI reduced single-cell lick selectivity in both Plick subtypes, which morphine restored (Extended Data Fig. 11i,j and Supplementary Table 1 (rows 129–132)). At 3 weeks, morphine suppressed positive Plick activity in mice with SNI and inhibited negative Plick cells across groups, reproducing the state-dependent and state-independent effects seen in acute pain (Fig. 3k,l and Supplementary Table 1 (rows 33–34)) and shifted the proportions of negative and positive Plick neurons regardless of injury (Extended Data Fig. 11k,l and Supplementary Table 1 (rows 133–136)). The magnitude of lick-evoked responses predicted within-session lick rate and pain-state occupancy, and morphine-induced increases in these responses predicted reductions in both behaviour and time spent in pain states (Fig. 3m and Supplementary Table 1 (rows 35–37)).

Together, these results show that morphine produces analgesia in chronic pain by inhibiting spontaneous activity in positive and negative Plick neurons in an injury-dependent manner, thereby rescuing the behaviour-discriminating and state-discriminating dynamics of ACC pain-tracking ensembles.

Chemogenetic gene therapy targets ACC MOR neurons

Given that morphine relieves chronic pain by modulating defined populations of ACC neurons, including injury-dependent inhibition of positive Plick neurons and widespread suppression of negative Plick neurons, we next sought to mimic these effects through a targeted chemogenetic gene therapy approach. Rather than systemic delivery of opioids, which carries substantialt risk of addiction and off-target effects, we aimed to develop a circuit-specific and cell-type-specific strategy for precision pain management1. Specifically, we designed a chemogenetic gene therapy to silence MOR-expressing neurons in ACC. We engineered an adeno-associated virus (AAV)-packaged synthetic mouse MOR promoter (MORp) to drive the expression of Gi-coupled inhibitory hM4–DREADD, which leverages endogenous transcription factors and molecular machinery to express transgene cargo in MOR+ cell types. The MORp sequence was derived from a 1.5-kb region upstream of the Oprm1 transcription start site on the basis of conserved regulatory elements in both mouse and human promoter regions previously shown to drive selective expression in MOR+ cells2. This allowed us to restrict hM4–DREADD expression to MOR+ neurons within ACC, enabling remote and reversible inhibition through the ligand deschloroclozapine (DCZ)58.

We tested two AAV-delivered strategies for targeting these cells: direct expression of hM4Di or a control fluorescent protein (eYFP) under the control of MORp (constructs: MORp–hM4Di and MORp–eYFP), and an intersectional approach combining painTRAP labelling of noxious stimulus-responsive neurons with MORp-dependent expression using a CreON/FlpON switch to restrict expression to MOR+ pain-activated neurons (Fig. 4a). Following viral incubation, fluorescence in situ hybridization quantification confirmed that more than 97% of ACC neurons expressing endogenous Oprm1 mRNA also expressed MORp-driven eYFP mRNA, indicating high specificity of the synthetic promoter (Fig. 4b). All viral constructs yielded robust expression throughout ACC layers (Fig. 4c and Extended Data Fig. 12), validating this strategy as a viable tool for selective neuromodulation of opioid-sensitive cortical ensembles.

Fig. 4: Precision neuromodulation of chronic pain through an ACC opioid cell-type-specific chemogenetic gene therapy.
Fig. 4: Precision neuromodulation of chronic pain through an ACC opioid cell-type-specific chemogenetic gene therapy.
Full size image

a, MORp-driven viruses deliver actuators to ACC MOR+ neurons. b, Co-expression of MORpeYFP and endogenous Oprm1 mRNA. c, MORp-driven fluorophore or hM4 expression across ACC layers. d, Timeline of SNI and DCZ exposure (0.3 mg kg−1; intraperitoneal) with LUPE and sensory testing. eh, Licking of the injured hindpaw (e; Pinteraction = 0.0012), occupancy of behavioural states (f), fraction of time spent in pain versus non-pain states (g; pain states Pinteraction < 0.0001, non-pain states Pinteraction < 0.0001) and AMPS scores (h; Pinteraction = 0.0003) in MORp–hM4 versus MORp–eYFP mice. Two-way repeated measures ANOVA; Tukey correction for all panels (n = 19 MORp–eYFP mice; n = 30 MORp–hM4 mice). i,j, Brain-wide projections of ACC MOR+ axons expressing hM4 or eYFP (i) to assess neuropathic activity (touchFOS) with or without chemogenetic inhibition (j). Unpaired t-test, two-tailed per region (n = 6, MORp–eYFP; n = 6, MORp–hM4). AIC, anterior insular cortex; BLA, basolateral amygdala; CeA, central nucleus of the amygdala; CL, central lateral nucleus; CLA, claustrum; dPAG, dorsal periaqueductal grey region; DRN, dorsal raphe nucleus; IL, infralimbic cortex; lHab, lateral habenula; mORB, medial orbitofrontal cortex; NAc, nucleus accumbens; NAcC, nucleus accumbens core; PBN, parabrachial nucleus; PIC, posterior insular cortex; PL, prelimbic cortex; PVT, paraventricular thalamus; RSP, retrosplenial cortex; vlPAG, ventrolateral periaqueductal grey; ZI, zona incerta. k, Maximum possible analgesia for morphine (0.5 mg kg−1; intraperitoneal) versus MORp–eYFP, MORp–hM4 or nociceptive MORp–hM4 + DCZ in uninjured mice and mice with SNI (n = 11 uninjured + morphine; n = 10 injured; n = 15 MORp–eYFP uninjured; n = 10 injured; n = 15 MORp–hM4 uninjured; n = 20 injured; n = 15 Noci/MORp–hM4). Maximum possible analgesia of evoked mechanical thresholds (left, Pinteraction = 0.0061), affective–motivational behaviours to acetone (middle, Pinteraction < 0.0001) and 55 °C hot water (right, Pinteraction < 0.0001). One-way ANOVA; Tukey correction for all panels. l, AMPS of uninjured mice or mice with SNI treated with morphine versus acute or chronic MORp–hM4 ACC (neuropathic, left, one-way ANOVA; Tukey correction; Ptreatment = 0.0085. Neuropathic, right, two-way ANOVA; Tukey correction; Pinteraction = 0.0003). m, Using a deep learning behaviour tracking platform to classify behaviour pain states, paired with single-neuron calcium imaging, we uncovered cortical mechanisms of opioid analgesia, which informed the creation of an opioid cell-type chemogenetic gene therapy for chronic pain that mimics morphine analgesia with circuit-targeted precision. P < 0.05. Bars, lines or dots are mean; error bars and shaded areas are s.e.m. (see Supplementary Table 1 (rows 38–47) for statistics). Scale bars, 50 μm (b,c), 200 μm (i).

Source data

Chemogenetic therapy reduces chronic pain

Building on the successful targeting of ACC MOR+ neurons with AAV–MORp, we next investigated whether chemogenetic inhibition of this population could provide sustained relief from chronic neuropathic pain without inducing tolerance. In mice 3 weeks after SNI, we began daily administration of the DREADD agonist DCZ (0.3 mg kg−1; intraperitoneal) for 1 week to assess whether DCZ activation of hM4Di-expressing MOR+ neurons reduced spontaneous and evoked pain behaviours and whether repeated inhibition would produce analgesic tolerance (Fig. 4d). Inhibition of ACC MOR+ neurons significantly reduced several measures of evoked affective–motivational pain behaviour to 6 °C acetone and 55 °C water, with no evidence of tolerance. Spontaneous pain-related licking, occupancy of high-pain latent states and AMPS scores were all reduced following a single dose of DCZ (SNI day 23) and remained suppressed after 1 week of daily dosing (SNI day 29; Fig. 4e–h, Extended Data Fig. 14 and Supplementary Table 1 (rows 38–41 and 146–155)).

Given the anatomical connectivity of ACC with key pain-processing regions, including the prelimbic and orbitofrontal cortices37,59, nucleus accumbens core35,60, insula and calustrum61,62, medial thalamus36,63, basolateral amygdala64,65,66, periaqueductal gray67 and other regions, we suggest that inhibition of ACC MOR+ neurons may influence activity across broader nociceptive circuits. To test this, we collected brain tissue from the same chronic pain cohort after DCZ treatment and exposure to a standardized light touch stimulus (0.16-g filament to the injured hindpaw). Using FOS expression as a proxy for neuropathic neural activation, we quantified the number of light touch-responsive neurons (touchFOS+ cells) across brain-wide projection targets of ACC MOR+ axons (Fig. 4i). We observed reductions in touchFOS+ cell counts in 14 of 19 brain regions downstream of ACC MOR+ projections, indicating that inhibition of this cortical ensemble can suppress widespread nociceptive responses throughout the brain (Fig. 4j and Supplementary Table 1 (row 42)).

Inhibition of ACC MOR neurons is not reinforcing

We tested potential side effects of our MORp chemogenetic approach using a modified real-time place preference (RTPP) assay (Extended Data Fig. 15 and Supplementary Table 1 (rows 156–157)). In painTRAP mice, we injected a Cre-dependent, MORp-driven, light-sensitive inhibitory channel (iC++) bilaterally into ACC and implanted fibre-optic cannulae and then assigned mice to uninjured or SNI groups. At 3 weeks post-SNI, the mice completed a 9-day RTPP: a pretest for baseline preference, seven daily 20-min closed-loop sessions in which entry to one chamber triggered blue-light (5 mW) inhibition and a final free-exploration recall test. Optogenetic inhibition of ACC MOR+ neurons did not change chamber preference in uninjured mice during conditioning or recall. By contrast, mice with SNI developed a preference for the light-emitting diode (LED)-paired chamber and a robust conditioned recall, spending significantly more time in the chamber previously paired with inhibition. Thus, silencing nociceptive ACC MOR+ neurons relieves continuing spontaneous pain and is reinforcing only in the injured state, indicating state-dependent negative reinforcement with minimal addiction-like liability in uninjured animals. Together with our chemogenetic data, these results show that selective, chronic inhibition of ACC MOR+ neurons yields stable, state-dependent analgesia without tolerance or reinforcement in normal conditions.

Chemogenetic therapy mimics morphine analgesia

To assess translational potential, we compared our MORp–hM4Di chemogenetic therapy to systemic morphine across models and stimuli, quantifying per cent maximum analgesia (Fig. 4k, Extended Data Fig. 13 and Supplementary Table 1 (rows 44–45 and 137–145)). Mice expressing MORp–hM4Di, painTRAP/MORp–hM4Di or MORp–YFP controls were tested with or without DCZ (0.3 mg kg−1; intraperitoneal) in uninjured and SNI conditions. These results were compared with mice receiving morphine (0.5 mg kg−1; intraperitoneal) in the same behavioural tests. Consistent with previous reports25,28,29, neither morphine nor our interventions altered mechanical von Frey thresholds (Fig. 4k (left)). However, both morphine and DCZ (in hM4Di or painTRAP/MORp–hM4Di mice) produced significant analgesia to acetone and 55 °C water in uninjured animals versus MORp–YFP controls (Fig. 4k (middle and right)). Critically, in mice with SNI, DCZ in MORp–hM4Di animals significantly reduced responses to noxious heat and cold, whereas morphine failed (Fig. 4k). Acute or 1-week chronic DCZ matched morphine in lowering AMPS scores during chronic neuropathic pain (Fig. 4l and Supplementary Table 1 (rows 46–47)), demonstrating that MORp-based chemogenetic therapy mimics morphine analgesia and, in some cases, may provide superior efficacy against the affective–motivational features of chronic pain.

Discussion

The affective mechanisms of morphine mirror our preclinical results with the genetic tuning of MOR expression in the ACC and our AAV–MORp-driven therapy. We conclude that opioids and our opioid mimicry therapy inhibit cortical nociceptive neural functions to reduce the integration of negative valence information within the ACC, resulting in reduced aversive arousal and attentional processes that bias the selection of nocifensive behaviours (Supplementary Note 5).

Our study demonstrates the therapeutic potential of targeting defined cortical ensembles for precision pain relief. By integrating LUPE’s unbiased tracking of sub-second, spontaneous pain states with single-cell calcium imaging, alongside neural activity-tagging and single-nucleus RNA sequencing ACC cell-type profiling, we pinpointed a μ-opioidergic ACC ensemble with an activity that scales with the affective burden of acute to chronic pain and is uniquely dampened by morphine (Supplementary Note 6). By leveraging the MORp promoter to drive chemogenetic inhibition in opioid-sensitive cortical neurons, we silenced this circuit, successfully reproducing the analgesic effects of morphine while avoiding the sensory, tolerance and reinforcement effects. This cell-type-specific strategy offers a new direction for pain management, one that could bypass the systemic risks of traditional opioids by modulating unique dimensions of pain perception at its cortical origin. For translational neuromodulation, our human opioid receptor promoter-based chemogenetic gene therapy2 (hMORp–hM4) could be adapted for non-invasive delivery using focused ultrasound blood–brain barrier opening68 to access and control multiple pain-encoding opioidergic neurons simultaneously in cortical and subcortical circuits (Supplementary Note 7). Thus, by integrating behavioural state modelling, neural ensemble identification and circuit-targeted intervention, our study provides a framework (Fig. 4m) for biologically informed, precision-based pain therapeutics. Selectively targeting the ACC opioidergic circuits through MORp-based gene therapies holds the promise of offering safer and more effective alternatives to conventional pain treatments, ultimately advancing precision medicine in pain management.

Methods

Sample sizes

The sample sizes were not statistically determined before the experiments. Rather, the group sizes were on the basis of published literature for the type of manipulation (chemogenetics, site-specific genetic knockout and pharmacology) and measured outcome (such as pain behaviours) published in the field and/or by the authors involved2,28,64,66. The sample sizes for all experiments are included in the figure legends.

Data exclusions

For all imaging and behavioural studies, virus-injected animals with either little or no evidence of viral transduction and/or incorrect viral targeting were excluded from any final analyses. No other mice or data points were excluded across analyses.

Replication

For many of the behavioural studies, several cohorts were used owing to the large number of animals in the final group sizes. All behaviour results were consistent and replicated across cohorts. Individual data points or lines were included, indicating consistent trends across many mice in each behavioural study.

Blinding

Mice were randomly assigned into control or experimental groups to the best of the experimenter’s abilities, with counterbalancing for age and sex as needed. In most of the included studies, the experimental and control groups differed only in the type of virus infused intracranially. The surgical protocol for all mice was identical in the amount, wait time and location of the intracranial injection. Each surgery day was randomly assigned as a control or experimental surgery date, and the corresponding mice from the predetermined groups underwent surgery on that day. GRIN lens and fibre placements and viral spread maps were included in the supplement to demonstrate the similarity of the injection protocol and outcome. Once the experimental and control groups were formed to comprise the study cohort of mice, the cohort underwent all behavioural testing concurrently, and experimenters were blinded. After the analyses were completed, the experimenters were unblinded.

Animals

All experimental procedures were approved by the Institutional Animal Care and Use Committee of the University of Pennsylvania and performed in accordance with the US National Institutes of Health guidelines. Male and female mice aged 2–5 months were housed two to five per cage and maintained on a 12-h reverse light–dark cycle in a temperature-controlled and humidity-controlled environment. All experiments were performed during the dark cycle. The mice had ad libitum food and water access throughout the experiments. For behavioural, anatomical and transcriptomic experiments, we used Fos–FOS–2A–iCreERT2 or ‘TRAP2’ mice (Fostm2.1(icre/ERT2)Luo)Luo; The Jackson Laboratory; stock no. 030323)69 bred to homozygosity, C57BL/6J mice (The Jackson Laboratory; stock no. 000664), Oprm1Cre/Cre mice (B6.Cg–Oprm1tm1.1(cre/GFP)Rpa/J; The Jackson Laboratory; stock no. 035574) and Oprm1fl/fl mice (B6;129–Oprm1tm1.1Cgrf/KffJ; The Jackson Laboratory; stock no. 030074). Further anatomical experiments used TRAP2 mice crossed with Ai9 (B6.Cg–Gt(ROSA)26Sortm9(CAG-tdTomato)Hze/J; The Jackson Laboratory; stock no. 007909) reporter mice that express a tdTomato fluorophore in a Cre-dependent manner.

Mouse μ-opioid receptor promoter

MORp2 is a 1.5-kb segment selected and amplified from mouse genomic DNA using cgcacgcgtgagaacatatggttggacaaaattc and ggcaccggtggaagggagggagcatgggctgtgag as the 5′ and 3′ end primers, respectively. All MORp plasmids were constructed on an AAV backbone by inserting either the MORp ahead of the gene of interest (iC++–eYFP) using M1uI and AgeI restriction sites. Every plasmid was sequence verified. Next, all AAVs were produced at the Stanford Neuroscience Gene Vector and Virus Core. Genomic titre was determined by quantitative polymerase chain reaction (qPCR) of the WPRE element. All viruses were tested in cultured neurons for fluorescence expression before use in vivo.

Viral vectors

All viral vectors were either purchased from Addgene or custom designed and packaged by the authors as indicated. All AAVs were aliquoted and stored at −80 °C until use. The following viral vectors were used (titre in viral genomes (vg) per millilitre; volume in nanolitre; total dose in viral genomes; source): AAV9–hSyn–HI–eGFP–Cre–wpre–SV40 (5.44 × 1011 vg ml−1; 400 nl; 2.18 × 108 vg; Addgene 105540-AAV9), AAV9–hSyn–GFP (1.90 × 1011 vg ml−1; 400 nl; 7.60 × 107 vg; Addgene 50465-AAV9), AAVDJ–hSyn1–DIO–mCh–2A–MOR (1.13 × 1012 vg ml−1; 500 nl; 5.65 × 108 vg; custom from Banghart Lab), AAV5–hSyn–DIO–EGFP (1.30 × 1012 vg ml−1; 500 nl; 6.50 × 108 vg; Addgene 50457-AAV5), AAV9–hSyn–jGCaMP8m–WPRE (1.90 × 1012 vg ml−1; 800 nl; 1.52 × 109 vg; Addgene 162375-AAV9), AAV1–mMORp–hM4Di–mCherry (1.17 × 1012 vg ml−1; 500 nl; 5.85 × 108 vg; custom from Deisseroth Lab), AAV1–mMORp–eYFP (1.00 × 1012 vg ml−1; 500 nl; 5.00 × 108 vg; custom from Deisseroth Lab), AAV1–mMORp–Flpo (9.21 × 1011 vg ml−1; 400 nl; 3.68 × 108 vg (co-injected with Con/Fon–hM4D(Gi)); custom from Deisseroth Lab), AAV5–nEF–Con/Fon–hM4D(Gi)–mCherry (7.40 × 1012 vg ml−1; 400 nl; 2.96 × 109 vg (co-injected with mMORp–FlpO); custom from Deisseroth Lab) and AAV1–mMORp–DIO–iC++–eYFP (1.35 × 1012 vg ml−1; 400 nl; 5.40 × 108 vg; custom from Deisseroth Lab).

Stereotaxic surgery

Adult mice (approximately 8 weeks of age) were anaesthetized with isoflurane gas in oxygen (initial dose, 5%; maintenance dose, 1.5%) and fitted into World Precision Instruments or Kopf stereotaxic frames for all surgical procedures. NanoFil Hamilton syringes (10 µl; World Precision Instruments) with 33G beveled needles were used to intracranially infuse AAVs into the ACC. The following coordinates were used on the basis of the Paxinos mouse brain atlas to target these regions of interest (ROI): ACC (bregma: anterior–posterior, +1.50 mm; medial–lateral, ±0.3 mm; dorsal–ventral, −1.5 mm). The mice were given a 3-week to 8-week recovery period to allow ample time for viral diffusion and transduction to occur. For all surgical procedures in mice, meloxicam (5 mg kg−1) was administered subcutaneously at the start of the surgery, and a single 0.25-ml injection of sterile saline was provided upon completion. All mice were monitored and given meloxicam for up to 3 days following surgical procedures.

Chronic neuropathic pain model

As described previously65, to induce a chronic pain state, we used a modified version of the SNI model of neuropathic pain. This model entails surgical section of two of the sciatic nerve branches (common peroneal and tibial branches) while sparing the third (sural branch). Following SNI, the receptive field of the lateral aspect of the hindpaw skin (innervated by the sural nerve) displays hypersensitivity to tactile and cool stimuli, eliciting pathological reflexive and affective–motivational behaviours (allodynia). To perform this peripheral nerve injury procedure, anaesthesia was induced and maintained throughout surgery with isoflurane (4% induction; 1.5% maintenance in oxygen). The left leg and/or hindleg was shaved and wiped clean with alcohol and Betadine. We made a 1-cm incision in the skin of the mid-dorsal thigh, approximately where the sciatic nerve trifurcates. The biceps femoris and semimembranosus muscles were gently separated from one another with blunt scissors, thereby creating a less than 1-cm opening between the muscle groups to expose the common peroneal, tibial and sural branches of the sciatic nerve. Next, approximately 2 mm of both the common peroneal and tibial nerves were transected and removed, without suturing and with care not to distend the sural nerve. The leg muscles were left unsutured, and the skin was closed with tissue adhesive (3M Vetbond), followed by a Betadine application. During recovery from surgery, the mice were placed under a heat lamp until awake and achieved normal balanced movement. The mice were then returned to their home cages and closely monitored for well-being over the following 3 days.

Targeting Recombination in Active Populations protocols

PainTRAP

PainTRAP induction was performed as previously described65. We habituated mice to a testing room for two to three consecutive days. During these habituation days, no nociceptive stimuli were delivered, and no baseline thresholds were measured (the mice were naive to pain experience before the Targeting Recombination in Active Populations (TRAP) procedure). We placed individual mice in red plastic cylinders (approximately 9 cm in diameter), with a red lid, positioned on a raised perforated and flat metal platform (61 cm × 26 cm). The experimenters remained in the testing room for 30 min to allow habituation. This was done to mitigate potential alterations to the animals’ stress and endogenous antinociception levels. To execute the TRAP procedure, we placed the mice in their habituated cylinder for 30 min, after which a 55 °C water droplet was applied to the central–lateral plantar pad of the left hindpaw once every 30 s for 10 min. Following the water stimulations, the mice remained in the cylinder for an extra 60 min before subcutaneous injection of 4-hydroxytamoxifen (40 mg kg−1 in vehicle). After the injection, the mice remained in the cylinder for an extra 4 h to match the temporal profile for c-FOS expression, at which time the mice were returned to their home cages.

Home-cageTRAP

Home-cageTRAP induction was performed without habituation. At least 2 h into the dark cycle, mice were gently removed from their home cages. The mice were then injected with 4-hydroxytamoxifen (40 mg kg−1 in vehicle; subcutaneous) and returned to their home cages.

Immunohistochemistry

Animals were anaesthetized using Fatal-Plus (Vortech) and transcardially perfused with 0.1 M PBS, followed by 10% normal buffered formalin (NBF) solution (Sigma; HT501128). Brains were quickly removed and post-fixed in 10% NBF for 24 h at 4 °C and then cryo-protected in a 30% sucrose solution prepared in 0.1 M PBS until sinking to the bottom of their storage tube (approximately 48 h). The brains were then frozen in Tissue-Tek O.C.T. Compound (Thermo Fisher Scientific), coronally sectioned on a cryostat (CM3050S; Leica Biosystems) at 30 μm or 50 μm, and the sections were stored in 0.1 M PBS. Floating sections were permeabilized in a solution of 0.1 M PBS containing 0.3% Triton X-100 (PBS-T) for 30 min at room temperature and then blocked in a solution of 0.3% PBS-T and 5% normal donkey serum (NDS) for 2 h before being incubated with primary antibodies (chicken anti-GFP (1:1,000; Abcam; ab13970), guinea pig anti-FOS (1:1,000; Synaptic Systems; 226308), rabbit anti-FOS (1:1,000; Synaptic Systems; 226008) and rabbit anti-DsRed (1:1,000; Takara Bio; 632496)), prepared in a 0.3% PBS-T and 5% NDS solution for approximately 16 h at room temperature. Following washing three times for 10 min in PBS-T, secondary antibodies (Alexa Fluor 647 donkey anti-rabbit (1:500; Thermo Fisher Scientific; A31573), Alexa Fluor 488 donkey anti-chicken (1:500; Jackson ImmunoResearch; 703-545-155), Alexa Fluor 555 donkey anti-rabbit (1:500; Thermo Fisher Scientific; A31572) and Alexa Fluor 647 donkey anti-guinea pig (1:500; Jackson ImmunoResearch; 706-605-148), prepared in a solution of 0.3% PBS-T and 5% NDS, were applied for approximately 2 h at room temperature, after which the sections were washed again three times for 5 min in PBS-T and then again three times for 10 min in PBS-T, and then counterstained in a solution of 0.1 M PBS containing DAPI (1:10,000; Sigma; D9542). Fully stained sections were mounted onto Superfrost Plus microscope slides (Fisher Scientific) and allowed to dry and adhere to the slides before being mounted with Fluoromount-G Mounting Medium (Invitrogen; 00-4958-02) and coverslipped.

Fluorescence in situ hybridization

Animals were anaesthetized using isoflurane gas in oxygen, and the brains were quickly removed and fresh frozen in O.C.T. using Super Friendly Freeze-It Spray (Thermo Fisher Scientific). The brains were stored at −80 °C until cut on a cryostat to produce 16-μm coronal sections of the ACC. Sections were adhered to Superfrost Plus microscope slides and immediately refrozen before being stored at −80 °C. Following the manufacturer’s protocol for fresh frozen tissue for the RNAscope v.2 manual assay (Advanced Cell Diagnostics), slides were fixed for 15 min in ice-cold 10% NBF and then dehydrated in a sequence of ethanol serial dilutions (50%, 70% and 100%). The slides were briefly air-dried, and then a hydrophobic barrier was drawn around the tissue sections using a PAP Pen (Vector Labs). The slides were then incubated with hydrogen peroxide solution for 10 min, washed in distilled water and then treated with the Protease IV solution for 30 min at room temperature in a humidified chamber. Following protease treatment, C1 and C2 complementary DNA (cDNA) probe mixtures specific for mouse tissue were prepared at a dilution of 50:1, respectively, using the following probes from Advanced Cell Diagnostics: Oprm1 (C1; 315841), Slc17a7 (C3; 416631) and Fos (C4; 316921). Sections were incubated with cDNA probes (2 h) and then underwent a series of signal amplification steps using FL v.2 Amp 1 (30 min), FL v.2 Amp 2 (30 min) and FL v.2 Amp 3 (15 min). A 2-min wash in 1x RNAscope wash buffer was performed between each step, and all incubation steps with probes and amplification reagents were performed using a HybEZ oven (ACD Bio) at 40 °C. The sections then underwent fluorophore staining through treatment with a series of TSA Plus HRP solutions and Opal 520, 570 and 620 fluorescent dyes (1:5,000; Akoya Biosciences; FP1487001KT and FP1495001KT). All HRP solutions (C1 and C2) were applied for 15 min and Opal dyes for 30 min at 40 °C, with an extra HRP blocker solution added between each iteration of this process (15 min at 40 °C) and rinsing of sections between all steps with the wash buffer. Finally, the sections were stained for DAPI using the reagent provided in the Fluorescent Multiplex Kit. Following DAPI staining, the sections were mounted and coverslipped using Fluoromount-G mounting medium and left to dry overnight in a cool, dark place. The sections from all mice were collected in pairs using one section for incubation with the cDNA probes and another for incubation with a probe for bacterial mRNA (dapB; ACD Bio; 310043) to serve as a negative control.

Imaging and quantification

All tissue was imaged on a KEYENCE BZ-X all-in-one fluorescence microscope at 48-bit resolution using the following objectives: PlanApo-λ ×4, PlanApo-λ ×20 and PlanApo-λ ×40. All image processing before quantification was performed with the KEYENCE BZ-X analyzer software (v.1.4.0.1). Quantification of neurons expressing fluorophores was performed through manual counting of TIFF images in Photoshop (Adobe, 2021) using the Count function or HALO software (Indica Labs), which is a validated tool for automatic quantification of fluorescently labelled neurons in brain tissue70,71,72. Counts were made using ×20 magnified z-stack images of designated ROI. For axon density quantification, immunohistochemistry was performed to amplify the signal and visualize ACC axons throughout the brain in 50-μm tissue free-floating slices as described above. Areas with dense axon innervation were identified using ×4 imaging. Areas implicated in emotion and nociception were selected for further ×20 imaging with z stacks. These ROI were initially visualized at ×20 to determine the region with the highest fluorescence. Exposures for FITC and CY3 were adjusted to avoid overexposed pixels for the brightest area. This exposure was kept consistent for all slices for an individual mouse. For an individual ROI, one slice per mouse was included.

We used HALO software for all quantifications. One representative 16-μm slice containing ACC (selected from 1.1–1.3 mm anterior of bregma) was quantified per mouse using HALO Image Analysis software (Indica Labs). The borders for left and right ACC, Cg1, Cg2, L1, L2/3, L5, L6a and L6b were hand-drawn as individual annotation layers using the Allen Brain Reference Atlas as a guide. Slices were visually inspected for damage, dust or other debris and bound probe, and these areas were manually excluded from their respective annotation layers. Co-localization of nuclei (DAPI) with Oprm1, Fos and Vglut mRNA puncta was automatically quantified using the fluorescence in situ hybridization module (v.3.2.3) and traditional nuclear segmentation. Setting parameters were optimized by comparing performance across six slices, randomly selected across experimental groups, and confirming proper detection by visual inspection. Identical parameters were applied across all slices in the dataset.

Drugs and delivery

For chemogenetic studies, water-soluble DCZ dihydrochloride (Hello Bio; HB9126) was delivered intraperitoneally at a dose of 0.3 mg kg−1 body weight. For Oprm1 knockout, re-expression and miniscope testing, morphine sulfate (Hikma) was delivered acutely through intraperitoneal injection at a dose of 0.5 mg kg−1 body weight.

Human-scored behavioural tests

All experiments were performed during the dark phase of the cycle (0930 hours to 1830 hours). Group-housed and singly housed mice were allowed a 1-week to 2-week acclimation period to housing conditions in the vivarium before starting any behavioural testing. Additionally, 3–5 days before the start of testing, the mice were handled daily to help reduce experimenter-induced stress. On test days, the mice were brought into procedure rooms approximately 1 h before the start of any experiment to allow for acclimatization to the environment. They were provided food and water ad libitum during this period. For multi-day testing conducted in the same procedure rooms, the animals were transferred into individual ‘home away from home’ secondary cages approximately 1 h before the start of testing and were only returned to their home cages at the end of the test day. Testing and acclimatization procedures were conducted under red light conditions (less than 10 lux), with minimal exposure to bright light to avoid disruption of the reverse light cycle schedule. Equipment used during testing was cleaned with 70% ethanol solution before starting and between each behavioural trial to eliminate odors and scents.

Sensory testing for pain affective–motivational and nociceptive reflex behavioural assays

To evaluate responses to acute stimuli, animals were placed in transparent red cylinders placed on top of a metal hexagonal-mesh floored platform. Stimuli were applied to the underside of the left plantar hindpaw. This process was repeated for a total of ten applications, with each droplet applied at a 1-min interval. The animals were continuously recorded using a web camera positioned to face the front of the cylinder in which the animal was housed, and the time spent attending to the affected paw was quantified for up to 30 s after the stimulation.

To evaluate mechanical reflexive sensitivity, we used a logarithmically increasing set of eight von Frey filaments (Stoelting), ranging in gram force from 0.07 g to 6.0 g. These filaments were applied perpendicular to the plantar hindpaw with sufficient force to cause a slight bending of the filament. A positive response was characterized as a rapid withdrawal of the paw away from the stimulus within 4 s. Using the up-and-down statistical method, 50% withdrawal mechanical threshold scores were calculated for each mouse and then averaged across the experimental groups65. To evaluate affective–motivational responses evoked by thermal stimulation65, we applied either a single unilateral 55 °C drop of water or acetone (evaporative cooling) to the left hindpaw, and the duration of attending behaviour was collected for up to 30 s after the stimulation. Response to the noxious stimulus was also tested following acute intraperitoneal administration of morphine (0.5 mg kg−1 body weight) or DCZ (0.3 mg kg−1 body weight). After injection, the animals were returned to their home away from home cages for 30 min to allow complete absorption of the drug. Hot-water hindpaw stimulation testing was conducted in the naive condition as described above.

Additionally, we used an inescapable hotplate set to 50 °C. The computer-controlled hotplate (6.5 in. × 6.5 in. floor; Bioseb) was surrounded by a 15-in.-high clear plastic chamber, and two web cameras were positioned at the front or side of the chamber to continuously record animals to use for post hoc behavioural analysis. For the tests conducted for chemogenetic or pharmacology studies, mice were administered morphine or DCZ 30 min before behavioural testing to allow for complete absorption of the drug and previous sensory testing73. The mice were gently placed in the centre of the hotplate floor and removed after 60 s.

Maximum possible analgesia effect calculation

The maximum possible analgesia (%MPA) metric quantifies how much a pain-related behaviour is reduced following drug administration, relative to both the animal’s baseline response and the maximum behavioural response for that assay. This normalization enables meaningful comparisons across animals with different baseline sensitivity levels. It is calculated as

$$100\,\times \,\frac{\mathrm{post}-\mathrm{drug}\,\mathrm{behaviour}-\mathrm{baseline}\,\mathrm{behaviour}\,}{\mathrm{maximum}\,\mathrm{behaviour}-\mathrm{baseline}\,\mathrm{behaviour}\,}$$

This normalization allows for comparisons across animals with different baseline response levels. For example, in the von Frey up-and-down test, the maximum behaviour for withdrawal threshold is 6.0 g (the highest filament force that would indicate the maximal amount of analgesia post-drug), and the minimum threshold is 0.007 g. For affective–motivational responses to thermal stimuli, behavioural responses such as attending or escape are measured over a 60-s window. Here the minimum behavioural response time is 0.0 s, and the maximum behaviour is capped at 30 s (trial duration). In this case, maximum analgesia corresponds to no response to the noxious stimulus; thus, the maximum behaviour in the %MPA formula is 0.0 s. This approach ensures consistent scaling of behavioural change across experiments and conditions. This formula provides a normalized score ranging from 0% (no analgesia) to 100% (complete analgesia). The definition of ‘maximum behaviour’ depends on the behavioural test and reflects the highest measurable response in the absence of any analgesia, whereas the ‘baseline behaviour’ is typically the pre-drug measurement for that animal. This approach ensures consistent and interpretable scaling of drug-induced behavioural changes across assays and experimental conditions.

LUPE acquisition and analysis software

Video acquisition

Behavioural videos were recorded using a Basler ace UacA2040-120um camera at a fixed resolution of 768 (width) by 770 (height) pixels. Imaging parameters were standardized, with gain set to 10.0 dB and gamma at 2.0. Exposure mode was timed with an exposure duration of 1,550 ms per frame, triggered at the start of each frame. Videos were captured at a consistent frame rate of 60 frames per second at maximum quality, with a recording buffer size of 128 frames. Frames were stored every 16 ms to ensure high temporal resolution of behavioural sequences.

Pose estimation through DeepLabCut

Assigning 2D markerless pose estimation of mice within LUPE was achieved through the DLC program (v.2.3.5-8). DLC was favoured for this purpose because of its ability to track body points at high confidence when animals perform diverse behaviours and to accurately report if a body part is visible in a given frame. Its extensive toolkit, documentation and forums allow flexible user input and manipulation when creating models.

The body points considered for assigning pose in the LUPE–DLC model were based on the clarity and frequency of appearance, involvement in behaviour sequences and prospective analyses performed. As such, 20 body points were included in the LUPE pose estimation network built in DLC: snout, upper mouth, middle forepaw digit and palm of left and right forepaws, all digits and palm of left and right hindpaws, genital region and tail base.

The model was trained iteratively 17 times for up to 350,000 iterations per training when loss and learning rate plateaued. The network architecture and augmentation method chosen were ResNet-50 and imgaug, respectively. The model was trained on 95% of the dataset, with the remaining 5% reserved for testing and evaluation. In the final training iteration, the mean average Euclidean errors between the manual labels and those predicted by the model were 2.2 pixels (0.073 cm) for the training dataset error and 2.33 pixels (0.077 cm) for the test dataset error.

Frames for labelling were manually extracted, targeting specific behavioural sequences and individual frames not accurately or confidently labelled by the model. After each training, frames for data input were added as needed for accuracy and confidence to label videos trained on and new videos analysed through LUPE not trained in the model. The total number of frames labelled was 14,554, with 10,825 (74.38%) and 3,729 (25.62%) frames coming from male and female video data files, respectively. Frames were extracted from 169 unique mouse video files comprising 133 males (78.69%) and 36 females (21.31%). The behavioural assays chosen for recording and model input captured different experimental paradigms and chemically evoked manipulations. From this, the model was able to assign pose data points with high accuracy and confidence for both male and female mouse video data from a variety of behavioural data.

The male video dataset included subcutaneous saline injection response (210; 1.94%), subcutaneous morphine 10 mg kg−1 response (1,105; 10.21%), left hindpaw intraplantar capsaicin response (666; 6.15%), left hindpaw intraplantar 1% formalin (960; 8.87%), left hindpaw intraplantar 5% formalin (1,271; 11.74%), habituation to LUPE chamber (720; 6.65%), formalin left hindpaw intraplantar injection (829; 7.66%), formalin right hindpaw intraplantar injection (719; 6.64%), formalin cheek injection (472; 4.36%), SNI left hindpaw injury day 0 (170; 1.57%), SNI left hindpaw injury day 3 (508; 4.69%), SNI left hindpaw injury day 7 (380; 3.51%), SNI left hindpaw injury day 21 (255; 2.36%), SNI right hindpaw injury day 0 (652; 6.02%), SNI right hindpaw injury day 3 (508; 4.69%), SNI right hindpaw injury day 7 (510; 4.71%), SNI right hindpaw injury day 21 (254; 2.35%) and naloxone precipitated morphine withdrawal (636; 5.88%).

The female video dataset included subcutaneous morphine 10 mg kg−1 response (133; 3.57%), habituation to LUPE chamber (320; 8.59%), formalin left hindpaw intraplantar injection (148; 3.97), formalin right hindpaw intraplantar injection (150; 4.02%), SNI left hindpaw injury day 0 (1,050; 28.17%), SNI left hindpaw injury day 3 (450; 12.07%), SNI left hindpaw injury day 7 (350; 9.39%), SNI right hindpaw injury day 0 (826; 22.16%), SNI right hindpaw injury day 3 (150; 4.02%) and SNI right hindpaw injury day 7 (150; 4.02%).

Behaviour classification through A-SOiD/B-SOiD

We trained a random forest classifier to predict five different behaviours (still, walking, rearing, grooming and licking hindpaw) given the pose estimation of the previously described 20 body parts. This supervised classifier was refined using an active learning approach over 27 iterations, with a total of 51,377 frames: still (11,599), walking (12,809), rearing (7,270), grooming (12,719) and licking hindpaw (6,971). Upon reaching an average f1 score of 93.5% across the five classes, we predicted all existing pose files and segmented licking hindpaw into licking left hindpaw and licking right hindpaw because they were clearly dissociable. After splitting the laterality of licking hindpaw, we retrained the random forest classifier to expand its classification from five classes to six classes. The final average f1 score across the six classes was 94.3%.

LUPE analyses

Once the model was trained, we predicted all the behavioural data in this study using the same random forest classifier model. Owing to the nature of intermittent pose estimation noise, we decided to smooth the output behaviour, considering only continuous bouts of 200 ms or longer.

To analyse behaviour ratio over time (Fig. 1), we calculated per-minute counts for each behaviour and normalized them by the total number of frames. This quantification allowed us to track when a particular behaviour occurred during each session. To explore variability across animals, we plotted the mean ± s.e.m.

To analyse the distance travelled, one body point high in confidence for pose detection and always present in behavioural sequences was chosen as the tail base to calculate the Euclidean distance between consecutive frames of the tail base position. This was calculated by subtracting the x and y coordinates of the tail base between consecutive frames and then calculating the Euclidean norm of the resulting vector. The distance calculated in pixels was then converted to centimetres using a conversion factor of 0.0330828 cm per pixel. This conversion factor is unique to the aspect ratio of our frames and resolution of the video data. To explore the variability across animals, we plotted the mean ± s.e.m.

Heat maps of the distance travelled were generated by constructing a 2D histogram of the tail base x and y coordinates. The code functions by binning the pose data points into a specified number of bins (50 in this case) along each x-coordinate and y-coordinate range. The ‘counts’ collected represent the frequency of occurrences in the 2D histogram that fall in each bin representing a range of x and y coordinates.

Identification of behaviour states and AMPS

Behavioural state identification

LUPE behaviour scores recorded at 60 Hz from all male and female animals across all pain models used in this study (uninjured mice, 2% capsaicin, 1% and 5% formalin and SNI) were downsampled to 20 Hz by taking the mode of every three frames. Transition matrices were generated between behaviours, with values expressed as the percentage of all frames, in which behaviour bx at time t was followed by behaviour by at time t + 1.The transition matrices were taken over 30-s windows sliding by 10-s increments within animals to avoid missing transitions. The window size was chosen in line with empirical findings that showed spontaneous bouts of intense subjective pain under chronic pain conditions lasting 22.5 ± 22.1 s (mean; s.d.)74. The transition matrices were transformed into single rows such that each transition matrix became a single vector of probabilities with 36 possible transitions: P(stillt+1|stillt), P(walkt+1|stillt), P(reart+1|stillt)…P(right lickt+1|right lickt). These probability vectors were then stacked to create a matrix of 215,760 observations (3,596 observations for 60 animals) by 36 transitions. These observations were clustered using 100-fold cross-validated k-means, in which the silhouette and elbow methods robustly converged at six clusters over 100 iterations. Each of six centroids thus defined a single behavioural state that could be expressed as reconstructed transition matrices.

Behavioural state classification

To classify each time point as one of six behavioural states, the same process as described above was repeated to generate smoothed transition matrices over time for each animal. At each time point, the Euclidean distance was calculated between its given transition matrix and each model centroid. The state at that time point was chosen to minimize the distance from the true transition matrix and the model centroid. Model fit for each animal in each session is thus expressed as the mean distance from the nearest centroid to its real transition matrix over the session. As distance approaches 0, the model approaches perfect fit. Transition matrices randomly shuffled over probabilities show that, at chance, model fit converges between 2 arbitrary units (a.u.) and 3 a.u., whereas true model fit ranges between 0 a.u. and 1.5 a.u., indicating genuine discovery of behavioural structure at a timescale of seconds to minutes.

Behaviour state model validation

To ensure that states were not trivially dependent on the occurrence or absence of a single behaviour, states were classified after systematically removing each behaviour from the dataset. Model fit and the percentage of observations matching the original classifications were compared with those of the shuffled dataset.

Pain scale

To distill behavioural states into a single index of pain, PCA was performed on the state distributions of each animal in the uninjured, capsaicin and formalin experiments that received 0 mg kg−1 of morphine. Each animal was described by the fraction time spent in each state, yielding a six-dimensional dataset. The scores of each animal along the first two PCs were considered. To yield scores for animals in every other experiment and condition, state distributions were projected into this PC state by subtracting the mean of the original dataset and matrix multiplying by the coefficients defining the PC space. We predetermined that the PC that scales oppositely with pain condition and analgesia would be designated the AMPS ‘pain scale’. PC2 met this requirement.

Within-state behaviour dynamics

To assess temporal dynamics of behaviours over states, the binarized behaviour classification vectors (behaviour of interest, 1; all others, 0) over the course of a given bout of a state were resampled to be 100 steps long. These vectors were pooled across bouts and animals in a given condition and averaged to yield behavioural probability as a fraction of time completed in state. The fraction of time remaining in state with respect to a behaviour occurrence was calculated by subtracting the absolute time of the behaviour from the absolute end time of that state bout and dividing by the duration.

For simulated behaviour dynamics, 100 Markov simulations of behaviours on the basis of the state 4 centroid transition matrix were produced over the course of a state for each possible initial condition (stillness, walking, rearing, grooming and licking) and allowed to proceed for the empirically determined average number of time steps state 4 lasts (600) before undergoing the same procedure.

In vivo calcium imaging

Miniscope surgery

For miniscope studies, all mice underwent an initial intracranial injection using previously described methods, followed 2 weeks later by a GRIN lens implant surgery. During the intracranial injection surgery, 800 nl of AAV9–hSyn–jGCaMP8m at a titre of 1.9 × 1012 (Addgene virus no. 162375) was infused into the right ACC (anterior–posterior, +1.5; medial–lateral, 0.3; dorsal–ventral, −1.5 mm). Two weeks later, GRIN lens implantation surgeries were performed following the same protocol up to the craniotomy step. A 1-mm craniotomy was made by slowly widening the craniotomy with a drill. The dura was peeled back using microscissors, sharp forceps and curved forceps. The craniotomy was regularly flushed with saline, and gel foam was applied to absorb blood. An Inscopix Pro-View Integrated GRIN lens and baseplate system was attached to the miniscope and stereotax. Using the Inscopix stereotax attachment, the lens was slowly lowered into a position over the injection site. The final dorsal–ventral coordinate was determined by assessing the view through the miniscope stream. If tissue architecture could be observed in full focus with light fluctuations suggesting the presence of GCaMP-expressing cells, the lens was implanted at that coordinate (−0.6 mm to −0.3 mm dorsal–ventral). The GRIN lens/baseplate system was secured to the skull with Metabond, followed by dental cement. After surgery, the mice were singly housed and injected with meloxicam for three consecutive days during recovery.

Miniscope data collection for acute capsaicin

Miniscope neural activity and associated behaviour data were collected over 2 days (baseline/capsaicin (test day 1) and morphine/capsaicin (test day 2)), with 2 weeks between test days. On each day, the Inscopix nVista3.0 miniscope was first affixed on the mouse, and ideal focus was determined on the basis of the field of view. Imaging parameters (power, 0.7 mW mm−2; gain, 2) were held consistent across all mice and test days. The mice were injected with saline (test day 1) or 0.5 mg kg−1 of morphine (test day 2) and placed in LUPE. Five minutes later, miniscope and LUPE recordings were started and continued uninterrupted for 20 min. The recording was then stopped for 5 min to reduce photobleaching risk. Next, the mice were injected with 2-μg capsaicin (Hello Bio; HB1179) in the left hindpaw (both test days) using a Hamilton syringe affixed with a 30G needle and placed in LUPE. Both miniscope and LUPE recordings were immediately restarted after and continued for 30 min.

Miniscope data collection for chronic neuropathic pain

The behaviour and neural activity of mice were recorded eight times before, during and after the onset of SNI. The mice were tested at baseline (1 day before SNI) and then 1 h, 1 day, 3 days, 1 week, 2 weeks and 3 weeks post-SNI. One day after the 3-week testing session, the mice underwent another test day in which they were injected with 0.5 mg kg−1 of morphine 30 min before recording. Each testing day consisted of a 30-min LUPE recording. Ideal imaging parameters were determined on each day, and neural activity was aligned to LUPE behaviour tracking through a transistor–transistor logic pulse at the start of the recording session.

Miniscope data collection for pain and valence panels

Within 1 week after completion of the chronic neuropathic pain LUPE testing, mice underwent exposure to a panel of acute stimuli while neural activity was recorded. The animals were placed in transparent containers placed on top of a metal hexagonal-mesh floored platform. Stimuli were applied to the underside of the left plantar hindpaw. The animals were continuously recorded using two web cameras.

The stimuli were light touch (0.16 g von Frey filament), 30 °C water, pin prick (25G syringe needle), acetone and hot water (55 °C). Water and acetone stimuli were delivered using a needleless syringe, and a droplet of the liquid was applied. Five presentations of each stimulus were administered to the left hindpaw with 90 s between each presentation.

After the pain panel, the mice underwent 3 days of 20-min training for the valence panel, in which they learned to lick a 10% sucrose (Sigma-Aldrich S7903; diluted in water) droplet from a needleless syringe poked through the mesh of the metal rack. On the day of the panel, neural activity was recorded while they licked sucrose (approximately seven presentations), with at least 45 s between each presentation, and then the liquid in the syringe was switched to 0.06 mM quinine (Sigma-Aldrich Q1125; diluted in water). Quinine was presented until the mice licked at least five times. Finally, seven presentations of 55 °C water were applied to the left hindpaw. Both sucrose and quinine concentrations were adapted from ref. 65.

Calcium imaging preprocessing

Videos were downloaded from the Inscopix Data Acquisition Box and uploaded to the Inscopix Data Processing Software. Videos were spatially downsampled by a factor of 4 and spatial bandpass filtered between 0.005 and 0.500. The videos were then motion corrected with respect to their mean frame. Cells were identified and extracted using constrained non-negative matrix factorization for microendoscopic data (default parameters in the Inscopix implementation, except the minimum in-line pixel correlation is 0.7 and the minimum signal-to-noise ratio is 7.0) and deconvolved using second-order constrained spike deconvolution.

Spontaneous activity in neurons

Deconvolved activity in each neuron was z-scored. Peaks were identified using the findpeaks function in MATLAB with the argument ‘MinPeakProminence’ set to 1.

Neural encoding of behavioural probabilities

Categorical frame-by-frame vectors of behavioural values (still, walking, rearing, grooming, licking left hindpaw and licking right hindpaw) were downsampled from 60 Hz to 20 Hz to match sampling rates of neural recordings by taking the floor of the mode for within a sliding window of three frames. The probability of engaging in a behaviour as generated by this k-means–GLM model thus takes into account recent behaviour history and slowly evolving state of the animal. These higher-order measurements of behavioural state have been linked to neural activity previously75,76,77. To identify neurons encoding this higher-order index of behavioural state, a binomial GLM was trained to predict binarized probabilities of a given behaviour (thresholded at Pbehaviour = 0.5) from the PCs of the ACC activity explaining 80% of the variance in individual animals. Neurons with a coefficient greater than 1.5 z-score in the three most highly weighted PCs were classified as Pbehaviour-encoding neurons. Neurons that, on average, increased or decreased their activity within 500 ms following the onset of behaviour were classified as behaviour+ or behaviour− neurons, respectively.

Behaviour-evoked activity

To assess modulation of activity in these neurons by behaviour, peri-behavioural time histograms of neural activity were generated from 2 s before to 2 s after the start of each behaviour bout. To quantify, peri-behavioural time histograms were z-scored to the 1 s before behaviour onset, and areas under the curve were taken for each of the 2 s after the bout start. If a neuron was suppressed after behaviour onset, it was designated a behaviour-off neuron and vice versa for a behaviour-on neuron. Behavioural tuning curves were generated by taking the z-score of the activity of each population of encoding neurons during each scored behaviour. Selectivity of these neurons for a given behaviour was calculated by taking the d′ between their encoded behaviour and each other behaviour:

$${d}^{{\prime} }=\frac{|\mu 1-\mu 2|}{\sqrt{\frac{\sigma 1+\sigma 2}{2}}}$$

Behaviour, sensory and state decoding

For behaviour and sensory decoding, a Fisher linear decoder was trained to predict each behaviour or sensory stimulus in a given session from the activity of all neurons. For state decoding, a support vector machine decoder was trained to predict whether animals were in a pain or non-pain state using the activity of lick-probability-encoding neurons. Each decoder for each animal and session underwent 100-fold cross-validation, training on a random 80% of the data each time and testing on 20%. Data were randomly subsampled to ensure an equal number of samples per class, thereby eliminating training bias. Decoders were also trained on randomly shuffled data as a control. Confusion matrices were generated, averaged over cross-validations and normalized by the true frequency of each behaviour in the test set. Significance was determined using a permutation test.

Identifying stimulus-active neurons

For pain and valence panels, the activity of each neuron from 0 s to 3 s after stimulus was compared with the activity from −3 s to −1 s before stimulus with a permutation test (false discovery rate (FDR) threshold P < 0.01).

Single-nucleus RNA sequencing

Nuclei preparation

A single punch of the right side of the basolateral amygdala measuring 2 mm in width and 1 mm in depth was used to prepare nuclei suspensions. Nuclei isolation was performed using the Minute Single Nucleus Isolation Kit designed for neuronal tissue/cells (BN-020; Invent Biotechnologies). In brief, the tissue was homogenized using a pestle in a 1.5-ml LoBind Eppendorf tube. Subsequently, the cells were resuspended in 700 µl of cold lysis buffer and RNase inhibitor and incubated on ice for 5 min. The homogenate was then transferred to a filter within a collection tube and incubated at −20 °C for 8 min. Following this, the tubes were centrifuged at 13,000g for 30 s, the filter was discarded and the samples were centrifuged at 600g for 5 min. The resulting pellet underwent one wash with 200 µl of PBS + 5% bovine serum albumin and then resuspended in 60 µl of PBS + 1% bovine serum albumin. The concentration of nuclei in the final suspension was assessed by staining with Trypan Blue and counted using a haemocytometer. The suspension was diluted to an optimal concentration of 500–1,000 nuclei per microlitre.

Single-nucleus gene expression assay

Nuclei suspensions were used as input for the 10x Genomics 3′ gene expression assay (v.3.1), following manufacturerʼs protocols. A total of 20,000 nuclei were loaded into the 10x Genomics Chromium Controller, with the aim of recovering approximately 10,000–12,000 nuclei per sample. Subsequently, sequencing libraries were constructed, and unique dual-indexed libraries were pooled together at equimolar concentrations of 1.75 nM and sequenced on the Illumina NovaSeq 6000 using 28 cycles for read 1, 10 cycles for the i7 index, 10 cycles for the i5 index and 90 cycles for read 2.

Data analysis

Preprocessing of single-nucleus RNA sequencing data

Paired end sequencing reads were processed using 10x Genomics Cell Ranger v.5.0.1. Reads were aligned to the mm10 genome optimized for single-cell sequencing through a hybrid intronic read recovery approach78. In short, reads with valid barcodes were trimmed by template switching oligonucleotide sequence and aligned using STAR v.2.7.1 with MAPQ adjustment. Intronic reads were removed, and high-confidence mapped reads were filtered for multimapping and unique molecular identifier correction. Empty gel beads in emulsion were also removed as part of the pipeline. DESeq2 was used to compare expression at the 3-day, 3-week and 3-month time points to control animals for each cluster. Pseudobulked expression differences were assessed by performing Wald test, and a FDR of 0.05 was used to correct for multiple testing.

Clustering and comparison

Count matrices for each individual sample were converted to Seurat objects using Seurat 4.3, and nuclei were filtered with thresholds of greater than 200 minimum features and less than 5% mitochondrial reads. Initial dimensionality reduction and clustering were performed to enable removal of cell-free mRNA using SoupX79. SCTransform was used to normalize and scale expression data, and all samples were combined using the Seurat integration method. Putative doublets identified by DoubletFinder, as well as residual clusters with mixed cell-type markers or high mean unique molecular identifier, were removed. The cleaned dataset was clustered using the first 20 PCs at a resolution of 0.3. Cluster identity was determined by expression of known marker genes.

Modular activity scoring

Modular activity scores were calculated for all clusters using AddModuleScore with the list of the 25 putative IEGs (Arc, Bdnf, Cdkn1a, Dnajb5, Egr1, Egr2, Egr4, Fos, Fosb, Fosl2, Homer1, Junb, Nefm, Npas4, Nr4a1, Nr4a2, Nr4a3, Nrn1, Ntrk2, Rheb, Sgsm1, Syt4 and Vgf) against a control feature score of 5 (ref. 80).

Gene ontology analysis

Gene Ontology analysis was performed on differentially expressed genes (DEGs) identified between uninjured and SNI conditions. To investigate the functional enrichment of genes upregulated in the SNI condition, we used SynGO (https://www.syngoportal.org/), a synapse-specific, evidence-based Gene Ontology annotation platform that provides curated information about synaptic genes and their roles in biological processes, molecular function and cellular localization. Gene symbols corresponding to upregulated DEGs were submitted to the SynGO web-based analysis tool. Enrichment analysis was performed against the background of all protein-coding human genes mapped to orthologous mouse genes using SynGO’s default statistical settings. We focused on enrichment within high-confidence, expert-curated Gene Ontology categories on the basis of experimental evidence. Overrepresentation testing was conducted with FDR correction, and enriched Gene Ontology terms were considered significant at FDR < 0.05. The analysis enabled functional interpretation of synaptic gene expression changes in chronic pain conditions, with particular attention to processes related to synaptic signalling, neurotransmitter transport and pre-synaptic or post-synaptic structural components.

Quantitative PCR

Cellular RNA was extracted with RNAZol (Sigma-Aldrich; R4533) according to the manufacturer’s protocol, and cDNA was synthesized from 1-μg RNA (Applied Biosystems; 4374966). cDNA was diluted 1:10 and assessed for mRNA transcript levels by qPCR with SYBR Green Mix (Applied Biosystems; A25741) on a QuantStudio 7 Flex Real-Time PCR System (Thermo Fisher Scientific). The oligonucleotide primer sequences for target and reference genes are as follows: mouse_GAPDH (forward: AACGACCCCTTCATTGACCT; reverse: TGGAAGATGGTGATGGGCTT), mouse_L30 (forward: ATGGTGGCCGCAAAGAAGACGAA; reverse: CCTCAAAGCTGGACAGTTGTTGGCA) and mouse_OPRM1 (forward: CTGCAAGAGTTGCATGGACAG; reverse: TCAGATGACATTCACCTGCCAA). Fold change in the target mRNA abundance was normalized by the reference gene GAPDH and calculated using the 2−ΔΔCT method81.

Closed-loop, optogenetic real-time place preference and conditioned place preference

First, painTRAP2 mice injected with AAV1–MORp–DIO–iC++ and bilateral fibre-optic implants (200-µm diameter; 0.66 numerical aperture; 700-µm pitch between each fibre centre; Thorlabs), with SNI or no injury, were habituated for 30 min a day for 5 days in a holding cage. For basal place-preference measurements (pretest session), mice with attached patch cables were placed in a two-chamber acrylic box (60 × 25 × 30 cm3), with each side of the chamber measuring 30 × 25 cm2), at room temperature (approximately 23 °C) and under approximately 10 lux red light. Each chamber had different contextual pattern cues on the wall: one side had a black-and-white striped pattern and the other a dotted pattern. Mouse movements were recorded in real time using an overhead Basler top-view camera connected to EthoVision tracking software (Noldus), connected through a mini-I/O box to a 450-nm LED and pulse-wave generator (Prizmatix), for 30 min. Chamber preference times were quantified using EthoVision for the amount of time spent in each chamber. Using a biased design, on the basis of the quantified basal preference, the mice received LED stimulation in the non-preferred chamber because our hypothesis was that activation of iC++ would reduce spontaneous pain and drive increased dwell time in the LED-paired chamber. The following day, to assess optogenetic real-time place preference, the mice were placed in the centre of the apparatus for a 30-min session. During this session, EthoVision body contour tracking of the mouse centre point activated the blue LED when the centre point was detected in the originally non-preferred chamber, which in turn delivered 10-mW continuous light through the bifurcating fibre-optic implants for the entire duration that the mouse centre point was detected in the chamber; the LED would turn off when the mouse centre point was detected in the other chamber (closed-loop protocol). This procedure was repeated daily for seven consecutive sessions to optogenetic real-time place preference-induced learning rates over time. After the pretest and seven closed-loop optogenetic sessions, we performed one post-test session to assess if a conditioned place preference had developed. Here, the mice remained connected to the patch cables, but no light was delivered, and the time spent in each chamber was calculated. Increased time in the formally LED-paired chamber indicates a learned preference for iC++-mediated inhibition of ACC nociceptive MOR+ cell types.

Statistics and reproducibility

The MORp viruses used in Fig. 4 are available from the Gene Vector and Virus Core at Stanford University (https://neuroscience.stanford.edu/shared-resources/gvvc). In our laboratory, MORp–eYFP, MORp–hM4Di and MORp–FlpO have each been used successfully at least three times in independent experiments.

Reporting summary

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