Main

Animals display an extraordinary diversity of behaviour both within and between species. Although there is increasing insight into how learning and experience modify neural processing to produce variations in individual behaviour, far less is known about how evolution shapes neural circuitry to generate species-specific responses. Cross-species comparative studies have identified genetic loci that explain behavioural diversity1,2,3,4, but only rarely have they examined the neural substrate upon which this genetic variation acts. Consequently, how the nervous system evolves to give rise to species-specific behaviours remains unclear.

As species diverge, their reproductive isolation is often reinforced by the development of behavioural differences that signify species identity and discourage interspecies courtship. The rapid evolution of courtship rituals therefore provides an entry point to examine the neural mechanisms that underlie behavioural divergence between closely related species. For example, D. melanogaster and D. simulans diverged 2–3 million years ago5 (Fig. 1a) and, although these cosmopolitan species frequently encounter each other in the environment, they remain reproductively isolated and rarely mate. When copulation does occur, it results in inviable or sterile offspring. The avoidance of interspecies mating therefore benefits both species. Indeed, both D. melanogaster and D. simulans males are choosy in selecting mates and, when offered a choice, preferentially court conspecific females (Fig. 1b).

Fig. 1: Pheromone regulation of D. simulans courtship.
figure 1

a, Predominant cuticular hydrocarbons of related species. b, Courtship preferences of D. melanogaster (mel) and D. simulans (sim) males with foreleg tarsi intact (+) or removed (−). c, d, Courtship indices (c) and preference indices (d) of wild-type (WT), Gr32a−/− and ppk23−/− D. simulans males offered D. simulans and/or D. melanogaster females. e, Preference indices of wild-type or ppk23−/− D. simulans males offered D. simulans females perfumed with ethanol (EtOH) or 7,11-HD. Statistical tests used were a one-sample t-test (b, d, e) and a Kruskal–Wallis test (c). **P < 0.01, ***P < 0.001, NS, not significant (b, d, e); different letters mark significant differences in courtship by Dunn’s multiple comparison test (c). Data are mean and s.d., with individual data points shown. See Supplementary Table 1 for details of statistical analyses.

One mechanism for selective courtship is the use of sex- and species-specific pheromones that either promote the courtship of conspecific females or suppress the pursuit of inappropriate mates6. Pheromone production has rapidly diversified across drosophilids7, such that D. melanogaster females predominantly produce 7,11-heptacosadiene (7,11-HD) on their cuticle whereas D. simulans females produce 7-tricosene (7-T), as do D. simulans and D. melanogaster males6. This pheromonal difference seems to be sufficient for species discrimination: perfuming D. simulans females with 7,11-HD renders them attractive to D. melanogaster males but unattractive to D. simulans males8. 7,11-HD is therefore detected by males of both species, but plays an opposing role in controlling their courtship decisions.

Species-specific pheromone responses could arise from the evolution of peripheral detection mechanisms or the central circuits that process pheromone signals to regulate courtship. To differentiate between these possibilities, we performed a direct comparison of the homologous pheromone pathways in D. simulans and D. melanogaster males. Here we demonstrate that species-specific responses to 7,11-HD emerge from the reweighting of excitatory and inhibitory inputs at a central node in the courtship circuit, highlighting how functional adaptations of central sensory processing pathways can lead to divergent behaviours.

Ppk23 mediates 7,11-HD detection

A critical step in Drosophila mate assessment occurs when a male taps the abdomen of another fly with his foreleg to taste their cuticular pheromones9,10. D. melanogaster and D. simulans males whose foreleg tarsi have been surgically removed still court vigorously (Extended Data Fig. 1a–c), but do so promiscuously (Fig. 1b). Therefore, although the detection of cuticular pheromones is not necessary for robust courtship8, it is essential for species discrimination.

Several classes of gustatory sensory neurons on the D. melanogaster male foreleg detect pheromones to differentially regulate courtship. One heterogeneous sensory population expresses the Ppk23 DEG/ENaC channel: a subset of Ppk23+ neurons detects female pheromones, including 7,11-HD, to promote courtship, and another subset detects male pheromones to inhibit courtship11,12,13. A smaller population of foreleg sensory neurons expresses the Gr32a receptor and detects 7-T to suppress inappropriate pursuit of D. simulans females and D. melanogaster males10,14. Although it is not known whether Gr32a and Ppk23 directly bind cuticular hydrocarbons, they serve as essential components of these pheromone transduction pathways10,11,12,13,14. We therefore investigated how Gr32a and Ppk23 shape mate preferences in D. simulans by using CRISPR–Cas9 genome editing to generate mutant alleles (Extended Data Fig. 1d). Both Gr32a and ppk23 mutant males pursued conspecific females with the same vigour as wild-type D. simulans males (Fig. 1c), suggesting that either these receptors do not contribute to the detection of 7-T in D. simulans, or that 7-T does not play a role in promoting male courtship15, despite being the predominant cuticular pheromone on D. simulans females6. D. simulans Gr32a mutant males also did not court D. melanogaster females or females of more distant species (Fig. 1c, d, Extended Data Fig. 1e, f). Therefore, contrary to its role in mediating courtship suppression in D. melanogaster10,14, Gr32a does not seem to influence mate choices in D. simulans.

By contrast, ppk23 mutants pursued D. melanogaster females and other drosophilids carrying diene pheromones with the same intensity as they courted D. simulans females (Fig. 1c, Extended Data Fig.  1e), and were unable to differentiate between D. melanogaster and D. simulans females in preference assays (Fig. 1d, Extended Data Fig. 1f). Moreover, ppk23 mutants were not deterred from courting D. simulans females that were perfumed with 7,11-HD (Fig. 1e, Extended Data Fig. 1g), suggesting that their promiscuous courtship reflects an inability to detect the D. melanogaster pheromone. As such, males of both species rely on ppk23 to detect 7,11-HD, but detection of this pheromone initiates opposing behaviours in the two species—promoting courtship in D. melanogaster while suppressing courtship in D. simulans. We therefore developed genetic tools in D. simulans to examine the sensory neurons in which Ppk23 is expressed and the downstream circuits that they activate to identify the neural adaptations that contribute to species-specific pheromone responses.

fruitless specifies courtship circuitry

In D. melanogaster, the male-specific isoform of the Fruitless transcription factor (FruM)16,17 marks the majority of Ppk23+ sensory neurons in the male foreleg11,12,13 along with the neural circuitry mediating most of the components of male courtship, from sensory detection to motor implementation. To gain genetic access to the repertoire of Fru+ neurons in D. simulans, including those that detect and process 7,11-HD, we integrated either the GFP or Gal4 coding sequence into the first intron of the fru locus (Extended Data Fig. 2a). We observed that, in both species, fru marks a similar ensemble of neurons distributed throughout the male nervous system, with comparable innervation patterns evident in most brain neuropils (Fig. 2a, Extended Data Fig. 2b–g).

Fig. 2: Fruitless has a conserved role in male courtship.
figure 2

a, Fru+ neurons (green) with neuropil counterstain (magenta) in brains of D. melanogaster and D. simulans males. Scale bar, 30 μm. b, Courtship preference indices of wild-type (WT) and fru−/− D. simulans males. c, Fraction of time that solitary males displayed courtship behaviours with (right) or without (left) optogenetic stimulation of Fru+ neurons. Statistical tests used were a one-sample t-test (b) and a Wilcoxon matched-pairs signed-rank test (c). *P < 0.05, ***P < 0.001. Data are mean and s.d., with individual data points shown. See Supplementary Table 1 for details of statistical analyses.

Given the anatomic similarity of Fru+ neurons, we wanted to confirm the evolutionary conservation of fru as a master regulator of male courtship behaviours16,17,18,19,20. We found that, as in D. melanogaster, mutation of fruM resulted in D. simulans males that exhibited aberrant mate preferences, whereas the optogenetic activation of Fru+ neurons triggered multiple components of the courtship ritual in an isolated male (Fig. 2b, c, Extended Data Fig. 2h, i). Therefore, in both species, fru marks circuits that specify male courtship towards appropriate sexual partners, providing an inroad to trace and compare the neural pathways that underlie mate discrimination, from the sensory periphery to higher brain centres.

Conserved peripheral sensory responses

To investigate the pheromone tuning of the Ppk23+ sensory population in D. melanogaster and D. simulans males, we expressed the Ca2+ indicator GCaMP6s in Fru+ neurons and monitored the aggregate responses of foreleg sensory afferents in the ventral nerve cord of a male as his tarsus contacted the abdomen of a female (Fig. 3a). We found that the Fru+ sensory neurons of both D. melanogaster and D. simulans males exhibited comparable pheromone tuning, responding robustly to the taste of a D. melanogaster female but weakly to that of a D. simulans female (Fig. 3b, c). In males of both species, sensory neuron responses were strongly attenuated in ppk23 mutants (Fig. 3b, c, Extended Data Fig. 3e), verifying that Ppk23 plays a conserved and essential role in pheromone detection.

Fig. 3: Conserved pheromonal tuning of Ppk23+ and Fru+ foreleg sensory neurons.
figure 3

a, Schematic of ventral nerve cord preparation used for imaging (top) and Fru+ foreleg sensory neurons expressing GCaMP (bottom). Scale bar, 10 μm. b, c, Functional responses of Fru+ foreleg afferents in D. melanogaster (b) or D. simulans (c) males evoked by the taste of a D. melanogaster or D. simulans female. Representative activity traces with time of taps indicated by coloured tick marks (left) and average normalized fluorescence (ΔF/F) in wild-type (WT) and ppk23−/− males (right). d, Functional responses (average ΔF/F) of Ppk23+ foreleg afferents evoked by the taste of a D. melanogaster or D. simulans female. e, Courtship indices towards conspecific females during optogenetic stimulation of Ppk23+ neurons in D. melanogaster (top) and D. simulans males (bottom). Statistical tests used were a Wilcoxon matched-pairs signed-rank test (bd) and a Kruskal–Wallis test (e). *P < 0.05, **P < 0.01, ***P < 0.001 (bd); different letters mark significant differences in courtship indices by Dunn’s multiple comparison test (e). Data are mean and s.d., with individual data points shown. See Supplementary Table 1 for details of statistical analyses.

To compare the distribution of 7,11-HD-responsive sensory neurons across species directly, we generated a ppk23-Gal4 construct in D. simulans, taking advantage of the fact that, in D. melanogaster, the ppk23 promoter faithfully reproduces endogenous channel expression12. We found that the ppk23 promoter from either species drove expression in a comparable number of sensory neurons in the male foreleg, whose axons exhibited a similar sexually dimorphic projection pattern within the ventral nerve cord (Extended Data Fig. 3a–d). Imaging the aggregate activity of these Ppk23+ sensory afferents revealed equivalent pheromone tuning across males of both species, with significantly stronger responses to the taste of a D. melanogaster female than to that of a D. simulans female (Fig. 3d, Extended Data Fig. 3e). Moreover, we observed no difference in the distribution or magnitude of functional responses in Ppk23+ soma when we stimulated individual sensory bristles on the foreleg with synthetic 7,11-HD (Extended Data Fig. 3f). As in D. melanogaster12,21, Ppk23+ soma were paired beneath a sensory bristle, and only one soma of each pair responded to 7,11-HD. Somatic responses to synthetic 7-T were negligible in both species (data not shown), mirroring the weak responses evoked at the population level by the taste of a D. simulans female (Fig. 3d).

Together, these experiments demonstrate that a quantitatively and qualitatively similar population of Ppk23+ sensory neurons is tuned to 7,11-HD in both D. melanogaster and D. simulans males. To assess whether the activation of Ppk23+ sensory neurons could replicate the opposing courtship behaviours elicited by 7,11-HD, we expressed CsChrimson in this sensory population in males of both species and examined how optogenetic activation influenced courtship of a conspecific female. Whereas optogenetic stimulation of Ppk23+ sensory neurons in D. melanogaster males drove increased courtship12,13, it inhibited courtship towards an otherwise attractive conspecific female in D. simulans males (Fig. 3e), replicating the courtship suppression that results from perfuming a D. simulans female with 7,11-HD. Therefore, activation of the homologous Ppk23+ sensory neuron population is sufficient to drive opposing behavioural responses in D. melanogaster and D. simulans males, suggesting that differences must exist in the downstream circuits that link pheromone detection to courtship decisions.

Divergent responses in central circuits

In D. melanogaster, male-specific P1 neurons form a central node in the Fru+ circuitry that integrates input from multisensory pathways to represent the suitability of a potential mate and triggers the initiation of courtship21,22,23,24,25,26. Anatomic labelling revealed that, in both species, P1 neurons exhibit rich projections in the lateral protocerebral complex (LPC, Fig. 4a), a sexually dimorphic Fru+ neuropil that receives input from multiple sensory processing pathways and outputs to descending neurons that drive the component behaviours of male courtship21,25,27.

Fig. 4: Divergent pheromone responses in courtship-promoting P1 neurons.
figure 4

a, P1 neurons (grey) innervate the Fru+ (green) LPC. b, c, Optogenetic stimulation of P1 neurons in D. simulans males. b, Courtship towards a rotating magnet (top), D. simulans female (middle), or D. melanogaster female (bottom). Fraction of flies courting (left; grey boxes indicate illumination with bright light) and courtship indices pre-, during, and post-stimulation (right). c, Courtship indices of D. simulans males towards D. simulans (top) and D. melanogaster (bottom) females in dim or bright white light or the indicated illumination intensity at 627 nm. d, Experimental set-up for in vivo functional GCaMP imaging (top) and schematic of Fru+ neurons (bottom; the regions imaged are outlined). e, f, Functional responses of Fru+ neurons in the LPC of D. melanogaster (e) and D. simulans (f) males evoked by tapping D. melanogaster and D. simulans females. Representative GCaMP fluorescence increase upon stimulation (left). Representative activity traces with time of stimulating taps indicated (middle). Average ΔF/F for individual males (right). AU, arbitrary units. g, h, Simultaneously recorded activity of LPC and P1 neurons in D. melanogaster (g) and D. simulans (h) males evoked by the taste of a D. melanogaster female. Magnified P1 neuron anatomy (left; same images as in a). Representative activity traces (middle; grey bars indicate taps) and relationship between responses in LPC and P1 neurons evoked by individual taps (right). Statistical tests used were a Kruskal–Wallis test (b), a paired t-test (e, f) and linear regression (g, h). Different letters mark significant differences in courtship indices by Dunn’s multiple comparison test (b); ****P < 0.0001 (ef); R2 = 0.3575 (g) and R2 = 0.0275 (h). Data are mean and s.d., with individual data points shown. Scale bars for anatomic images, 10 μm. See Supplementary Table 1 for details of statistical analyses.

To test whether P1 neurons play a conserved role in regulating courtship across species, we introduced a transcriptional enhancer (R71G01-Gal4) that labels this neural population in D. melanogaster23 into the D. simulans genome and used it to drive expression of CsChrimson (Extended Data Fig. 4a). Optogenetic activation of P1 neurons in D. simulans males strongly enhanced courtship of conspecific females and drove almost incessant courtship of inappropriate targets, including D. melanogaster females and a small rotating magnet (Fig. 4b, Supplementary Video 1). Pursuit of the magnet was significantly reduced when it was stationary or moving slowly, highlighting the importance of motion for vigorous courtship23,26 (Extended Data Fig. 4c). Courtship towards all targets remained increased after stimulation, indicating that transient activation of P1 neurons is sufficient to trigger an enduring state of sexual arousal across species24,25,26,28 (Fig. 4b, Extended Data Fig. 4b–f).

Notably, titration of the stimulating light revealed that evoked courtship in D. simulans males was significantly weaker towards D. melanogaster females than D. simulans females (Fig. 4c), raising the possibility that 7,11-HD may suppress courtship by countering the excitation of P1 neurons. To compare how pheromone signals are propagated from the periphery to P1 neurons and other central Fru+ populations, we monitored responses either in the LPC or in the P1 neurons in a tethered male as he tapped the abdomen of a target fly with his foreleg (Fig. 4d, Extended Data Fig. 4g). In D. melanogaster males, robust responses were evoked in the LPC by the taste of a D. melanogaster female, but not a D. simulans female, reflecting strong excitation of P1 neurons by the pheromones of an appropriate mate25,29 (Fig. 4e, g, Extended Data Fig. 4h, Supplementary Videos 2, 3). By contrast, in D. simulans males, neither the P1 neurons nor any other Fru+ neural populations in the LPC were activated in response to the taste of a D. simulans female (Fig. 4f, Supplementary Video 4), which is consistent with behavioural evidence that contact pheromones are not necessary to promote D. simulans courtship8,15. Neurons in the LPC of D. simulans males were, however, weakly activated by the taste of a D. melanogaster female, but these signals failed to propagate to the P1 neurons (Fig. 4f, h, Supplementary Video 5). Responses were not apparent in ppk23 mutants, verifying that pheromone signalling to the LPC relies on Ppk23+ sensory pathways (Extended Data Fig. 4i, j). Opposing behavioural responses to 7,11-HD in the two species therefore appear to be mirrored by divergent P1 neuron excitation.

Species-specific central circuit changes

In D. melanogaster and D. simulans males, equivalent pheromone responses at the sensory periphery are translated into differential excitation of P1 neurons, suggesting that the ascending pathways that convey pheromone signals from the forelegs to the LPC have diverged. In D. melanogaster, 7,11-HD signals are transmitted from Ppk23+ sensory neurons to vAB3 neurons, whose dendrites reside in the ventral nerve cord and whose axons project to the LPC, providing a direct excitatory route to the P1 neurons25 (Fig. 5a). vAB3 neurons also extend collaterals into the suboesophageal zone (SEZ), where they synapse onto GABAergic (γ-aminobutyric acid-releasing) mAL interneurons25. mAL axons arborize extensively in the LPC and provide inhibitory input onto P1 neurons, forming a feedforward inhibitory circuit motif that tempers P1 neuron excitation and regulates the gain of pheromone responses21,25. In D. melanogaster, P1 neurons thus receive excitatory and inhibitory input even in response to the taste of a conspecific female, with 7,11-HD evoking net excitation to trigger courtship. Anatomic labelling of D. simulans vAB3 and mAL neurons revealed broadly conserved projection patterns within the LPC (Fig. 5b, Extended Data Fig. 5), indicating that they remain anatomically poised to synapse onto P1 neurons.

Fig. 5: Differential propagation of ascending pheromone signals to P1 neurons.
figure 5

a, Schematic of the Fru+ circuit that processes 7,11-HD. b, Anatomy of vAB3 and mAL neurons in D. melanogaster and D. simulans with the LPC and SEZ marked. Scale bars, 10 μm. c, d, Average ΔF/F for individual males evoked by D. melanogaster and D. simulans females in vAB3 (c) and mAL (d) neurons. e, Representative GCaMP fluorescence increase in Fru+ neurons evoked by direct vAB3 stimulation with acetylcholine (ACh). f, P1 neuron responses to vAB3 stimulation before (top) and after (bottom) mAL severing in D. melanogaster and D. simulans males. Left, coloured lines depict individual stimulations and black lines show the average; right, the graph plots the peak ΔF/F per fly. Scale bars are the same for P1 activity traces and graphs. Statistical tests used are a paired t-test (c, d) and an unpaired t-test with Welch correction (f). *P < 0.05; **P < 0.01, ***P < 0.001. Data are mean and s.d., with individual data points shown. See Supplementary Table 1 for details of statistical analyses.

Given the structural conservation of these ascending pathways, we considered whether there might be functional differences in how pheromone signals are transmitted through this circuit to generate divergent P1 neuron responses. Functional imaging revealed that vAB3 neurons were similarly tuned to pheromones across species, with robust responses elicited only by the taste of a D. melanogaster female, and not a D. simulans female (Fig. 5c, Extended Data Fig. 6a–d). Moreover, in both species, vAB3 pheromone responses were lost in ppk23 mutants (Extended Data Fig. 6b–d). Therefore, although Ppk23+ sensory neurons drive opposing courtship behaviours in D. melanogaster and D. simulans males, they nevertheless elicit comparable pheromone responses in the homologous ascending pathways in the brain.

To compare the role of mAL neurons across species directly, we introduced a genetic driver (R25E04-Gal4) that labels mAL neurons25 into D. simulans (Extended Data Fig. 6e). Optogenetic activation of mAL neurons in D. simulans males strongly attenuated courtship (Extended Data Fig. 6f), replicating the robust courtship suppression mediated by mAL neurons in D. melanogaster21 and confirming that this population inhibits neurons in the LPC in both species. Functional imaging revealed that mAL neurons were equivalently excited by the taste of a D. melanogaster female in both D. melanogaster and D. simulans males (Fig. 5d, Extended Data Fig. 6g). Therefore, in both species vAB3 and mAL pathways are similarly activated by D. melanogaster female pheromones, suggesting that alterations in the strength of their signalling to P1 neurons might underlie the emergence of species-specific mate preferences, such that 7,11-HD can evoke excitation of P1 neurons only in D. melanogaster males to initiate courtship of a D. melanogaster female.

To examine this possibility, we directly stimulated vAB3 neurons through iontophoresis of acetylcholine onto their dendrites within the ventral nerve cord and performed multi-plane functional imaging to visualize activated Fru+ neurons in the brain (Fig. 5e, Extended Data Fig. 7a, b). Although this stimulation elicited equivalent responses in the vAB3 and mAL neurons of both species, P1 neurons and other neurons of the LPC were excited only in D. melanogaster and not in D. simulans males (Fig. 5e, f, Extended Data Fig. 7d–g), mirroring the differential propagation of pheromone signals through this pathway in vivo. In both species, the responses of all Fru+ neurons were lost after we severed the vAB3 axons with a two-photon laser, verifying that vAB3 neurons mediate these divergent activity patterns (Extended Data Fig. 7c).

To assess whether mAL-mediated inhibition could counter vAB3 excitation to suppress P1 neurons in D. simulans, we used a two-photon laser to sever the mAL axonal tract and prevent the transmission of their GABAergic signal to the LPC. After the severing of mAL, we found that P1 neurons could be excited by vAB3 stimulation in D. simulans males, although to a lower level than in D. melanogaster males (Fig. 5f, Extended Data Fig. 7g). Pharmacological weakening of inhibition by injection of the GABA-receptor antagonist, picrotoxin, into the LPC similarly enhanced pheromone responses in vivo, unmasking excitation specifically in response to the taste of a D. melanogaster female (Extended Data Fig. 6h). These results suggest that mAL-mediated inhibition antagonizes vAB3 excitation to fully suppress P1 neuron responses in D. simulans males, but not in D. melanogaster males, revealing how alterations in excitatory and inhibitory input to this population may generate divergent responses to the same pheromone cue.

Discussion

The sensory periphery has been proposed to be the most evolutionarily labile element of the nervous system30,31,32, as changes in the expression or tuning of sensory receptors can allow for the emergence of species-specific behaviours without necessitating potentially more complex developmental rewiring of central pathways in the brain. By contrast, our results suggest that species-specific behavioural responses to 7,11-HD arise through functional alterations in how pheromone signals are propagated through a structurally conserved central circuit that consists of parallel excitatory and feedforward inhibitory branches. By reweighting the balance of excitatory vAB3 and inhibitory mAL signalling to P1 neurons, 7,11-HD is transformed from an excitatory signal that promotes courtship in D. melanogaster males into an inhibitory signal that suppresses courtship in D. simulans males. Although our analysis highlights the importance of this pheromone pathway in shaping species-specific mate preferences, we cannot exclude the possibility that additional inputs to P1 neurons or other targets of mAL and vAB3 neurons also contribute to divergent courtship decisions. Nevertheless, our data suggest that the branched architecture of pheromone-processing pathways serves as a substrate for the evolution of mate preferences, pointing to the potential existence of favourable sites within neural circuits to instantiate adaptive behavioural changes, analogous to how specific nodes within developmental regulatory networks contribute to morphological diversity33.

The conserved tuning of Ppk23+ neurons suggests that D. simulans males dedicate this sensory pathway to the detection of D. melanogaster female pheromones, rather than sensing the chemical cues carried by conspecific females. Consistent with this idea, although P1 neurons are sufficient to elicit courtship in D. simulans males, they are not excited by the taste of a D. simulans female. Given that D. simulans cuticular pheromones are sexually monomorphic and offer ambiguous signals for mate recognition, males probably rely on additional sensory inputs for their arousal. Indeed, the fervent courtship exhibited by D. simulans ppk23 mutants towards females of different species demonstrates that D. simulans males can be aroused in the absence of any species-specific excitatory cue. Dienes, such as 7,11-HD, actively suppress this arousal, presumably through recruitment of strong mAL-mediated inhibition via Ppk23+ pathways. Together, these observations reinforce the notion that pheromone communication in Drosophila serves to focus a male’s desire, such that flies lacking cuticular pheromones can be inherently attractive and appropriate mate choices are honed by specific inhibitory chemical cues8,10,14.

Peripheral adaptations are likely to play an important role in the evolution of novel chemical sensitivities2,31,32. In this case, however, preserving the sensory periphery while varying central circuits provides a mechanism to alter the behavioural valence of a single chemical cue. As D. melanogaster and D. simulans diverged, their reproductive isolation was probably strengthened by the ability of both species to detect the same pheromone but assign it a different meaning through these central circuit modifications. Notably, in D. melanogaster, P1 neuron excitability is regulated by the social history of a male24,34. This suggests that both experience-dependent and evolutionary adaptations may act on the same neural substrate to modify sensory integration and mate choices, similar to how phenotypic plasticity may facilitate morphological evolution35. Therefore, functional reweighting of sensory inputs at flexible nodes in the nervous system, shaped by evolutionary selection or individual experience, may allow for alternative behavioural responses to the same sensory signal.

Methods

Data reporting

Preliminary experiments were used to assess variance and determine adequate sample sizes in advance of conducting the experiment. We used random.org/sequences to randomize the order of all behaviour experiments. To control for potential variations in experimental conditions across days, we collected a similar sample size for each variable, every day the experiment was conducted. For functional experiments, we interleaved genotypes and female stimuli when applicable. All behaviour experiments were conducted with the experimenter blinded to the genotype or condition of any male or female fly that was a variable in a given experiment. The experimenter was unblinded only after analysis of the assay. The experimenter was not blinded to the genotype of males used in functional imaging assays.

Fly stocks and husbandry

Flies were housed under standard conditions at 25 °C under a 12 h light:12 h dark cycle. Fly stocks and sources were as follows: Drosophila melanogaster Canton-S, 20xUAS-IVS-GCaMP6s (Bloomington; 42746, 42749), UAS-mCD8::GFP (5130, 5137), LexAop-GCaMP6s (53747), 10xUAS-IVS-myr::tdTomato (32222), R71G01-Gal4 (39599), AbdB-Gal4 (55848) R25E04-Gal4 (49125), and 20xUAS-IVS-CsChrimson.mVenus (55134) were obtained from the Bloomington Stock Center. D. sechellia (14021-0248.25) and D. erecta (14021-0224.01) were obtained from the UCSD Stock Center. The following were obtained as indicated: D. ananassae and D. simulans (Ruta laboratory), D. simulans attP203936 (Y. Ding and D. Stern, Janelia Research Campus); SplitP1-Gal424 (D. Anderson, Caltech); fruLexA37 and fruGal416 (B. Dickson, HHMI/Janelia Farm Research Campus); D. melanogaster ppk23-Gal411 (K. Scott, UC Berkeley); LexAop-myr::tdTomato (C. Mendes, Columbia University); UAS-SPA-t2a-SPA-GFP25 (Ruta laboratory). Supplementary Table 1 provides detailed descriptions of genotypes used in each experiment.

Courtship behaviour assays and analysis

To standardize fly size and life history across trials, all flies used for behavioural assays were reared in food vials at a low density (3 females and 3 males seeded into vial). All experimental flies were male and all stimulus flies were virgin females unless otherwise noted. Males for all assays were collected as virgins, placed in individual food vials (d = 3 cm, h = 9.5 cm) and housed in isolation for 3–6 days. Males were added to behavioural assays by direct aspiration from the food vial without ice or CO2 anaesthetization, except for the tarsi ablation experiments in which males were ice-anaesthetized. Virgin females were group-housed in food vials and aged 3–6 days. All behavioural assays were conducted at Zeitgeber 0 to 3 h except for assays using flies reared in the dark. All behavioural assays were conducted in a heated, humidified room (25 °C, 46% relative humidity) on a back-lit surface (Logan Electric Slim Edge-Light Pad A-5A, 5400K, 6 klx). For all preference assays, only males who spent more than 5% of the time courting (>30 s of total courtship) were included in the analysis. Courtship behaviours included in the analysis were singing, tapping, licking, orienting, abdomen bending and chasing. QuickTime7 software was used when analysing courtship videos.

For all preference assays (Figs. 1b, 1d, 1e, 2b), a male and two female flies were placed into a 38-mm diameter, 3-mm height circular chamber with sloping walls (courtship arena)38. The experimenter, who was blinded to the genotype of the flies, kept track of the females during the assay either by noting which female was introduced first to the courtship arena or by painting a small white dot on the thorax of the female 16–20 h before the start of the experiment under ice anaesthesia. Results were not affected by the method used to differentiate between females and the experimenter was unblinded only after analysis. The preference index is the amount of time the male spent courting one female subtracted from the amount of time spent courting the other female divided by the total time spent courting within a 10-min assay. The wide spread of the data reflects the fact that individual males will sometimes continue to pursue a single female throughout the assay even if both females are equivalent. In Extended Data Fig. 1 we plot the courtship indices (time spent courting/total time of assay) underlying the preference indices of Fig. 1.

For the tarsi ablation assays (Fig. 1b, Extended Data Fig. 1a–c), males were ice-anaesthetized 16–20 h before the start of the experiment and had either the distal three tarsal segments on both forelegs removed or a sham treatment that left their appendages intact. For single-choice assays (Extended Data Fig. 1b, c), the rear leg tarsi were ablated as a control. Males were then returned to a food vial to recover in isolation. Males without foreleg or rear leg tarsi still vigorously court females.

In D. simulans single-pair courtship assays (Figs. 1c, 3e, 4b, 4c; Extended Data Figs. 1b, 1c, 1e, 4e, 4f, 6f), a single virgin female and a D. simulans male were loaded into a courtship arena. Courtship index (time spent courting/total time together) was measured for the 10 min after the male was introduced into the chamber.

For the chaining assay (Extended Data Fig. 2i), eight males were loaded into a courtship arena and the chaining index (time in which at least three of the males were simultaneously courting each other divided by the total time of the assay) was measured for 10 min after the males were introduced into the chamber.

For the preference assays with perfumed females (Fig. 1e), we provided a male the choice between a D. simulans virgin female perfumed with 7,11-HD (7(Z),11(Z)-heptacosadiene, 10 mg ml−1, Cayman Chemicals, 100462-58-6) or ethanol using a previously published protocol8. In brief, 7,11-HD or ethanol was added to 1 ml of ethanol in a 2-ml glass vial (Thermo Scientific, 03-377D), placed on ice and dried using a stream of nitrogen gas. Seven ice-anaesthetized female flies were placed in each vial, and the vials were then gently vortexed three times for 30 s before placing the females on food for an hour to recover. After perfuming, separate aspirators were used to handle the flies to avoid pheromone contamination. Courtship indices underlying courtship preference in Fig. 1e were plotted in Extended Data Fig. 1g.

For fruGal4 optogenetic stimulation experiments (Fig. 2c), fruGal4>UAS-CsChrimson.tdTomato or fruGal4 parental controls were reared in the dark for 3–7 days after eclosion. Male flies were transferred to food containing 400 µM all-trans-retinal (Sigma, R2500-10MG) 16–20 h before the assays24. Single male flies were loaded into a courtship arena and allowed to acclimate for 1 min. Flies were subsequently recorded for 7 min, alternating between 1 min of dim white light followed by 1 min with constant LED stimulation (530 nm Precision LED Spotlight with Uniform Illumination–PLS-0530-030-S, Mightex Systems at an intensity of 0.02 mW mm−2). Genotypes were established using PCR screening of the UAS transgene. We quantified a courtship behaviour index, which represented the fraction of time a male spent performing courtship behaviours.

For ppk23-Gal4 (Fig. 3e) and R25E04-Gal4 (Extended Data Fig. 6f) optogenetic stimulation experiments, we used D. simulans w+ R25E04-Gal4, ppk23-Gal4 and UAS-CsChrimson.tdTomato parental stocks and D. melanogaster w ppk23-Gal4 and UAS-CsChrimson parental stocks lacking balancer chromosomes. The original D. simulans R25E04-Gal4, ppk23-Gal4 and UAS-CsChrimson.tdTomato parental stocks were in a background mutant for white (w), which exhibited extremely low courtship indices (around 5% on average), presumably owing to their low visual acuity. By contrast, D. melanogaster transgenic lines maintained robust courtship even in a white mutant background (data not shown). Therefore, we backcrossed D. simulans stocks to wild-type flies to generate w+ strains and confirmed their genotype by PCR. All crosses were reared in the dark. Virgin male progeny were reared in isolation in the dark for 3–7 days after eclosion and then transferred to food containing 400 µM all-trans-retinal 16–20 h before the assays24. We found that D. simulans courtship was less robust under single-wavelength LED illumination or dim white-light illumination, so we conducted our assays using the same lighting conditions used for the non-optogenetic courtship assays (Logan Electric Slim Edge-Light Pad A-5A, 5400K, 6 klx). Single male flies were loaded into a courtship arena that contained a conspecific virgin female and the courtship index was calculated over a 10-min period after the male was introduced. Owing to the lack of balancers and visual markers in D. simulans, stable, homozygous stocks of most transgenes were difficult to generate. Therefore, progeny of crosses were a mix of wild-type, parental controls and experimental flies. The experimenter was blinded to the genotype of the flies until after the experiment. Genotypes were established using PCR amplification of the Gal4 and UAS transgenes. Males of all genotypes exhibited similar levels of locomotion when they were not courting (data not shown).

For optogenetic stimulation of P1 neurons in D. simulans (Fig. 4b, c, Extended Data Fig. 4c–f), we used R71G01-Gal4>UAS-CsChrimson.mVenus males that carried a wild-type (w+) X chromosome. As in other behavioural experiments, P1 neuron-elicited courtship pursuit was far weaker in males mutant for white (data not shown). For optogenetic stimulation of P1 neurons in D. melanogaster, w; R71G01-Gal4>UAS-CsChrimson.mVenus males lacking balancer chromosomes were used. We observed a high degree of lethality in both the D. melanogaster and D. simulans R71G01-Gal4>UAS-CsChrimson crosses grown on standard fly food containing cornmeal (presumably owing to the low levels of retinal metabolized from vitamin A). Therefore, we grew these crosses on sugar-yeast food in the dark (per 1 l of water: 100 g Brewer’s yeast, 50 g sucrose, 15 g agar, 3 ml propionic acid, 3 g p-hydroxy-benzoic acid methyl ester). Progeny of parental crosses were group-housed in the dark for 3–7 days after eclosion, before males were transferred to food containing 400 µM all-trans-retinal 48 h before the assays24. Single male flies were loaded into a courtship arena that contained either a virgin D. simulans female, virgin D. melanogaster female or a magnet (radius, 1 mm; height, 1 mm) rotating in a circle at 9 mm s−1 (ref. 25). Upon loading the male fly into the chamber with the target, we alternated between 2 min of dim light (10 lx) and 2 min of bright light (6 klx) in a 14-min assay. Dim light was used because it was sufficient to enable males to visually track a target object but insufficient to optogentically activate the P1 neurons, as evidenced by the lack of courtship towards a magnet or D. melanogaster female before bright illumination. Assays were filmed (Sony Alpha 6) and later scored for courtship behaviour, binned in 1-s intervals. We calculated ‘fraction courting’ as a function of time by dividing the number of males courting during a one-second interval (aligned from the start of the assay) by the total males tested. Courtship indices were also calculated for each individual at different times relative to the optogenetic stimulation: ‘pre’ represents the courtship index of the 2 min before the first bright-light stimulus, ‘stimulus’ represents an average of the courtship indices during bright-light illumination period and ‘post’ represents an average of the courtship index after the bright-light illumination. For the parental controls (Extended Data Fig. 4d–f), we used w+; UAS-CsChrimson.mVenus males grown in an identical manner to the experimental flies and similarly placed on retinal for 48 h. For the non-retinal controls (Extended Data Fig. 4d–f), w+; R71G01-Gal4>UAS-CsChrimson.mVenus males were placed in a new vial of sugar-yeast food for 48 h before the experiment. To characterize evoked courtship as a function of light intensity (Fig. 4c), each experiment was initiated by illuminating for 2 min with dim light (10 lx) to establish a baseline, then at increasing intensities of 627-nm LED illumination with 2 min at each intensity, finally ending with 2 min of bright white-light illumination. A power meter (Coherent PowerMax-USD light sensor and Coherent PowerMax PC Software) was used to measure the intensity of 627-nm illumination in the behavioural chamber during the assay. To examine how elicited courtship depends on the speed of the magnet (Extended Data Fig. 4c), each male was given the opportunity to court a magnet moving at 0, 3, 6, 10 and 20 mm s−1 during bright white-light illumination. Magnet speed order was randomized and there were 1-min periods in between stimulus trials in which the light was off and the magnet was stationary.

Targeted mutagenesis and transformation in D. simulans

The protocols described below combine methods for CRISPR mutagenesis39,40,41. Supplementary Table 2 provides details of single-guide RNA (sgRNA) sequences, sgRNA primers and sequencing primers.

CRISPR guide RNAs had an 18–20 nucleotide target sequence and were flanked by a 3′ PAM sequence (‘NGG’) and a 5′ T7 RNA polymerase recognition sequence (‘GG’). Before designing sgRNAs, Sanger sequencing was carried out across target genomic sites to identify single-nucleotide polymorphisms. Guide RNA template was amplified using KOD HotStart (Millipore, 71086-3) and 0.5 µM forward and reverse primers. Reactions were cycled on an Eppendorf MasterCycler (98 °C 30 s, 35 cycles of (98 °C 10 s, 60 °C 30 s, 72 °C 15 s), 72 °C 10 min, 4 °C hold) and then purified (PCR purification kit, Qiagen). In vitro transcription of 300 ng of sgRNA template DNA using T7 MEGAscript kit (Ambion) was carried out at 37 °C for 16–20 h. Turbo DNase was added for an additional 15 min at 37 °C before adding a 10% ammonium acetate stop solution. The RNA was phenol/chloroform extracted and precipitated with isopropanol at −20 °C for 16–20 h. Precipitated RNA was washed with 70% ethanol, resuspended with RNase-free water, and frozen in small aliquots at −80 °C for long-term storage. Before injection, the sgRNA was thawed on ice and purified using sodium acetate and ethanol before being resuspended in RNase free water.

CRISPR injection mixtures contained 300 ng µl−1 recombinant Cas9 protein (CP01, PNA Bio), 40 ng µl−1 sgRNA (per guide) and 125 ng µl−1 single-stranded DNA oligonucleotide. The CRISPR injection mixture was combined on ice and placed at −80 to −20 °C until the injection. φC-31 mediated recombination injection mixtures contained donor plasmid (1 µg µl−1) and helper plasmid (1 µg µl−1), both of which were purified using endotoxin-free plasmid prep kits (Qiagen). Rainbow Transgenic Flies, Inc. performed all injections.

To generate mutant alleles of ppk23 and Gr32a (Extended Data Fig. 1d), we designed sgRNAs targeting three regions spanning 200 bp of the first exon for each gene. These sgRNAs were combined into a single cocktail and injected into approximately 200 wild-type D. simulans embryos. Only CRISPR guide sequences that generated the mutations are listed in Supplementary Table 2. The adult G0 flies were individually crossed to wild-type male or virgin female flies. For each G0 cross, we PCR screened 8–16 progeny (F1s) for the presence of an insertion or deletion. Genomic DNA was extracted from the F1 flies by removing a midleg, hindleg or wing and placing it into a well of a 96-well plate containing 20 µl of lysis buffer (10 mM Tris pH 8.2, 1 mM EDTA pH 8.0, 25 mM NaCl, 400 µg ml−1 Proteinase K). The fly was then placed in the corresponding well of a 96-well deep-well plate (Brandtech VWR, 80087-070) filled halfway with fly food and capped with cotton. The 96-well plate containing lysis buffer and fly legs or wings was then heated at 37 °C for 1 h followed by a 2-min heat inactivation at 95 °C. Genomic DNA (3.2 µl) from the reaction was used as the PCR template for a 25-µl reaction of Apex Taq Red Master Mix (Genesee Scientific, 42-138) for 35 cycles. The PCR screening primers spanned an approximately 400-bp region encompassing the three sgRNA target sites. To maximize the resolution of heterozygous indels, we ran the entire PCR reaction on a 2% agarose gel at 70 V. Using these specifications, the smallest indel we detected was around 20 bp. We backcrossed any flies that had a heterozygous mutation to wild-type flies and then homozygosed their progeny. Flies were Sanger-sequenced to determine if an in-frame stop codon was introduced. Homozygous stocks were genotyped and Sanger-sequenced for three generations to ensure that the population was pure.

For recombination into the fru locus, we prescreened sgRNAs to identify those that mediate efficient cutting. Nine sgRNAs were designed, six of which targeted the region upstream of the first coding exon and three of which targeted the first exon. Pools of three sgRNAs were injected into 100 embryos and genomic DNA was extracted from surviving flies. We first used the T7 endonuclease1 (T7E1) assay for preliminary qualitative analysis of cutting propensity (http://www.crisprflydesign.org/t7-endo-i-assay/). Two positive hits from the T7E1 assays were analysed using MiSeq analysis39, which revealed that over 95% of the reads in the PCR product were mutated. We used only these two sgRNAs (listed in Supplementary Table 2), one targeted to the first exon and one targeted upstream of the start codon of the first intron, for generating mutant flies.

To generate fruattP flies, we integrated in a 200-bp single-stranded oligonucleotide designed to have the minimal 51 bp attP sequence42, including a diagnostic restriction enzyme site and around 70 bp homology arms that flanked the CRISPR targeted site into the fru locus (Extended Data Fig. 2a). To generate fru−/− flies, we integrated a similar attP-containing oligonucleotide into the first exon of the FruM coding sequence, replacing the ATGATG start site with TTGTTG (Extended Data Fig. 2h), as has been reported previously in D. melanogaster17. The sgRNA, attP-oligo and Cas9 protein were injected into around 200 embryos. G0s were singly crossed to wild-type virgin flies. F1s with successful integration of the attP site were identified by PCR genotyping, isolated and sequenced using methods described above. fruattP and fru−/− F1s were backcrossed to wild-type flies and then homozygosed. Homozygous stocks were genotyped for three generations to ensure that the population was pure.

We used φC31-mediated recombination to integrate attB plasmids containing transgenes into the fruattP locus (Extended Data Fig. 2a). We chose not to use eye colour as a visual marker to avoid complications of the white mutation on behaviour. To determine whether the transgene was homozygous, we screened F1s using the protocol described above for the binary presence of a PCR product using one primer pair that spanned the transgene and the genomic locus. To create a stable stock of flies, we crossed homozygous virgin females to D. simulans males with a balancer allele on their 3rd chromosome (In(3R)Ubx, Flybase ID FBab0023784, UCSD Stock Center, 14021-0251.098). Progeny with the Ubx visible mutation were crossed together and subsequent progeny were genotyped.

attB-SAS-GFP (Extended Data Fig. 2a) was made by amplifying enhanced green fluorescent protein (eGFP) from pUAST-mCD8GFP using primers that attached a splice acceptor site43 and Kozak sequence onto the 5′ end of the GFP and an SV40 termination sequence onto the 3′ end. Nested-PCR was performed to attach Gibson-assembly adaptors onto the GFP PCR product, which was then combined with PCR-linearized pHD-DsRed-attP using Gibson assembly (NEB). The plasmid was then digested with EcoRI and NotI to insert a 51-bp attB oligonucleotide with flanking EcoRI and NotI sites. The double-stranded oligonucleotide was made by annealing two single-stranded oligonucleotides together.

attB-SAS-Gal4 (Extended Data Fig. 2a) was made by cloning attB-SAS and Gal4 DNA fragments into pHD-DsRed cut with EcoRI and SpeI using Gibson Assembly (NEB). The digestion removed 3xP3-DsRed. The attB-SAS fragment was amplified from attB-SAS-GFP and the Gal4 fragment was amplified from pBPGUw.

We generated an attP landing site with an inactivated EYFP gene using CRISPR–Cas9 mutagenesis. We co-injected embryos of D. simulans strains carrying an attP landing site marked with 3XP3::EYFP with p{CFD4-EYFP-3xP3::DsRed}36 and Cas9 mRNA and sibling-mated surviving adults. We screened for progeny with reduced or no EYFP expression in the eyes. Flies with EYFP were bred to homozygosity and the 3XP3::EYFP transgene in each line was re-sequenced to confirm the presence of the mutation and to confirm that the mutation did not disrupt the attP landing site.

To generate flies expressing GCaMP6s under UAS control, we co-injected p{GP-JFRC7-20XUAS-IVS-GCaMP6s}44 and pBS130 (containing φC-31 integrase under control of a heat-shock promoter) into a D. simulans attP, EYFP- strain 2178 (ref. 36) and screened for w+ integrants. We generated one D. simulans UAS-CsChrimson transgenetic line by co-injecting p{20XUAS-IVS-CsChrimson.tdTomato}45 and pBS130 into attP, EYFP strain 2178 and screening for w+ integrants. We generated a second D. simulans UAS-CsChrimson transgenetic line by co-injecting a piggyBac vector pBac(20xUAS-CsChrimson.mVenus, 3xp3::dsRed) and a piggyBac transposase helper plasmid into the Lethal Hybrid Rescue strain of D. simulans46 and then screened for dsRed expression in the eyes. The CsChrimson.mVenus piggyBac insertion was mapped with TagMap47 to base pair 23,569,712 on chromosome 3R.

The D. simulans ppk23-Gal4 plasmids were generated by amplifying the 2.695-kb fragment upstream of the D. simulans ppk23 promoter, analogous to previously published methods12. Using a BP-clonase Gateway reaction, the sim-ppk23 promoter was recombined into pBPGUw (Addgene, 17575). φC31-mediated recombination was used to integrate sim into D. simulans attp217636 (Fig. 3d and Extended Data Fig. 3a–d), R25E04-Gal4, 3xp3::DsRed in D. simulans attP217636 (Extended Data Fig. 6e) and pBPGuW R71G01-Gal4 in D. simulans attP217636 (Extended Data Fig. 4a).

Immunohistochemistry

To visualize D. simulans fruGFP (Fig. 2a, Extended Data Fig. 2b–g), D. melanogaster fruGal4>UAS-GCaMP (Fig. 2a, Extended Data Fig. 2b–g), D. simulans ppk23Gal4>UAS-GCaMP (Extended Data Fig. 3b) and R25E04-Gal4>UAS-GCaMP (Extended Data Fig. 6e), brains from 1–3-day-old adults were dissected in Schneider’s medium for 1 h then immediately transferred to cold 1% paraformaldehyde (Electron Microscopy Sciences) and fixed for 16–20 h at 4 °C. Samples were then washed in PAT3 buffer (0.5% BSA, 0.5% Triton X-100, 1X PBS pH 7.4) three times, with the last two washes incubated for 1 h on a nutator at room temperature. Brains were blocked in 3% normal goat serum for 90 min at room temperature. Primary antibodies in 3% normal goat serum were incubated for 3 h at room temperature then left at 4 °C for 16–20 h. Primary antibodies used were 1:20 mouse anti-Brp (nc82, Developmental Studies Hybridoma Bank), 1:1,000 sheep anti-GFP (sim fruGFP, mel fruGal4>UAS-GCaMP, ppk23-Gal4>UAS-GCaMP and R25E04-Gal4>UAS-GCaMP, Bio-Rad, 4745-1051) and 1:100 rabbit anti-GABA antibody (D. simulans fruGFP, Sigma, A2052). Brains were then washed in PAT3 buffer. Samples were incubated in secondary antibody for 3 h at room temperature then for 5–7 days at 4 °C. Secondary antibodies used were 1:500 anti-sheep Alexa Fluor 488, anti-rabbit Alexa Fluor 546, anti-mouse Alexa Fluor 647 and anti-mouse Alexa Fluor 555 (ThermoFisher Scientific). Brains were washed in PAT3 buffer three times then once in 1X PBS, rotating at room temperature for 5 min. Samples were mounted in Vectashield (Vector Laboratories) in 5/8th inch hole reinforcements placed on glass slides. Images were captured on a Zeiss LSM 880 using a 40× objective.

Two-photon functional imaging

All imaging experiments were performed on an Ultima two-photon laser scanning microscope (Bruker Nanosystems) equipped with galvanometers driving a Chameleon Ultra II Ti:Sapphire laser. Emitted fluorescence was detected with either photomultiplier-tube or GaAsP photodiode (Hamamatsu) detectors. Images for ex vivo experiments were acquired with an Olympus 60×, 1.0 numerical aperture objective and in vivo experiments were acquired with an Olympus 40×, 0.8 numerical aperture objective (LUMPLFLN). All images were collected using PrairieView Software (Version 5.4) at 512 pixel × 512 pixel resolution with a frame rate from 0.2–0.4 Hz when imaging a region of interest (ROI) and 0.7–0.8 Hz when imaging the entire field of view. Saline (108 mM NaCl, 5 mM KCl, 2 mM CaCl2, 8.2 mM MgCl2, 4 mM NaHCO3, 1 mM NaH2PO4, 5 mM trehalose, 10 mM sucrose, 5 mM HEPES pH 7.5, osmolarity adjusted to 275 mOsm) was used to bathe the brain for all imaging experiments unless otherwise noted.

To prepare flies for in vivo imaging of Fru+ and Ppk23+ sensory afferents in the ventral nerve cord (VNC; Fig. 3a–d, Extended Data Fig. 3e), the wings and all legs except one foreleg were removed from a CO2-anaesthetized male. The single-legged male was tethered to a piece of clear packing tape covering a hole in the bottom of the modified 35-mm Petri dish using a hair placed across his cervical connectives. The body was oriented such that the ventral side faced the inside of the dish. A rectangular hole, the length and width of the body of the male fly, was cut from the tape and the fly was positioned such that the ventral half of the body was placed above the plane of the tape. Great care was taken to ensure that the foreleg was extended so that the tibia and femur did not contact the thorax. Small dots of UV-curable glue were used to secure the eyes, part of the thorax and the tip of the abdomen to the tape. The dish was then filled with saline and the cuticle covering the first thoracic ganglion was gently removed, taking care to not damage the foreleg nerve. The preparation was positioned on the two-photon microscope and an ROI was centred on the most ventral portion of the first thoracic ganglion of the VNC corresponding to the intact foreleg (Fig. 3a). To prepare a stimulating female abdomen, a pin was attached to the dorsal thorax of virgin female D. melanogaster or D. simulans fly with her head, wings and legs removed so that the abdomen could make contact with the distal tarsal segments of the foreleg of the male fly. To guide stimulation with the fly abdomen, an 850 nm IR light was used to illuminate the chamber. The fly was imaged from the side using a Point Grey Firefly camera mounted with a 1×-at-94 mm Infinistix lens fitted with a shortpass IR filter (850 nm, optical density 4, Edmund Optics) to block 925 nm two-photon laser illumination and viewed using FlyCapture2 Software (2.12.3.2). After recording a 10-s baseline, the experimenter gently tapped the female abdomen onto the tarsi of the experimental fly once every 10 s for 6–8 bouts. Three replicates per preparation (total 18–24 tapping bouts) were conducted with D. simulans and D. melanogaster stimuli interleaved.

Images and quantification of Ppk23+ soma in the foreleg of the male were completed using a Zeiss Axioplan 2 scope under Nomarski optics and widefield fluorescence at 40× or 63×. Images were acquired through a Zeiss AxioCam and the Axiovision software (Extended Data Fig. 3a). Somata were counted only in the first three tarsal segments of the foreleg.

We modified published methods12,21 for in vivo imaging of Ppk23+ soma in the foreleg (Extended Data Fig. 3f). Male ppk23-Gal4>UAS-GCaMP flies were isolated as virgins, aged 3–6 days, CO2-anaesthetized, decapitated and immobilized by folding a piece of Parafilm over the body such that the first five tarsal segments extended out of the Parafilm. The immobilized fly was placed on a glass coverslip for imaging using a monochromatic camera (Point Grey Research, Flir Chameleon 3). Pheromone was presented as follows: 1 µl of 7,11-HD or ethanol was pipetted onto a paper wick (Hampton Research) that had been trimmed such that one constituent fibre was exposed at the tip. Using a micromanipulator, the wick was brought into contact with one chemosensory sensillum on the 3rd tarsal segment of the foreleg. GCaMP responses were visualized using a 50× air objective using 488-nm LED illumination on a bright-field microscope (Scientifica). ΔF/F values were calculated using ImageJ as the maximum signal in the 30 s after pheromone presentation in accordance with published methods12,21. Without more precise genetic tools in D. simulans, we defined soma A as the soma that responded more strongly to 7,11-HD presentation, in accordance with previous work12. To demonstrate that the response of soma A was specific to the pheromone, we also presented the ethanol vehicle in which ethanol alone was adsorbed to a wick. The range of our maximum ΔF/F values for 7,11-HD stimulation were consistent with previously published results in D. melanogaster12,21,48.

To prepare flies for in vivo imaging of the LPC, P1 neurons and mAL neurons in the central brain using both fruGal4 and R25E04-Gal4 neural drivers (Figs. 4d–h, 5d, Extended Data Figs. 4g–j, 6g–h), CO2-anaesthetized 4–7-day-old males were affixed to a customized, milled tethering plate49 using UV-curable glue around their head and thorax. Glue was cured in short bursts to minimize exothermic damage to the preparation and flies whose legs touched the glue were discarded. The proboscis was glued to the head, carefully avoiding the antennae, to minimize movement of the brain during imaging. Flies were given an hour to recover and were used only if they displayed vigorous activity post-tethering. A small hole in the head was opened under external saline using sharp forceps. Muscle 16, obstructing trachea, and fat were removed. The imaging plate had magnets inside to enable facile positioning under the 40× objective in the two-photon microscope. Using a micromanipulator, a styrofoam ball50 floating on an air stream was positioned under the fly to permit standing and walking. A D. melanogaster or D. simulans virgin female tethered to a pin (see above for tethering details) was positioned in front of the tethered male using a micromanipulator. To stimulate tapping events, the female was moved in front of the male fly, who then freely tapped on her abdomen with his foreleg tarsi. The male fly was imaged from the side (see above) to facilitate positioning the ball and the abdomen stimulus during the experiment. After 4 to 5 s of baseline recording, the stimulus fly was presented to the tethered male for 2–5 s, allowing for several taps before being withdrawn. This was repeated nine times for each fly stimulus with D. melanogaster and D. simulans stimuli interleaved. An ROI was centred on the LPC or on the fasciculated projections from P1 neuron cell bodies to the LPC. We vetted our ability to reproducibly identify the characteristic processes of P1 neurons by first imaging them using R71G01-Gal4>UAS-GCaMP in D. melanogaster males (Extended Data Fig. 4g), which showed robust and specific responses in all parts of the P1 neurons to the taste of a D. melanogaster female. When imaging the fasciculated projections of P1 neurons, our field of view contained both the LPC and the P1 projections, enabling us to simultaneously record responses in the LPC and P1 neurons when the male tapped a female (Fig. 4g, h). We attempted to use the R71G01-Gal4 driver for functional imaging of the P1 neurons in D. simulans, but observed no response to the taste of either a D. melanogaster or D. simulans female. Although this is consistent with the lack of pheromone-mediated excitation that we observed when imaging all Fru+ neurons in the LPC or Fru+ P1 neurons in D. simulans, we could not rule out that the lack of responses was due to weak expression of GCaMP. Notably, we observed pheromone responses using driver lines with similar levels of expression, such as R25E04-Gal4, in both D. melanogaster and D. simulans.

For experiments in which picrotoxin was used to block inhibition (Extended Data Fig. 6h), in vivo responses were recorded in the LPC before and after iontophoresis of picrotoxin unilaterally into the LPC (1 mM in saline, 3–5 pulses, 100 ms at 20 V). Local injection of picrotoxin had no noticeable effect on the behaviour of the male fly or on baseline fluorescence of the LPC, in contrast to bath application of picrotoxin (10 µM and 100 µM), which caused seizures in the fly and a marked, fluctuating increase in baseline fluorescence of the LPC (data not shown). Iontophoresis of saline had no effect on pheromone-evoked responses in either species (data not shown). Picrotoxin iontophoresis was based on previously published methods51,52. We did not attempt picrotoxin iontophoresis with D. simulans R71G01-Gal4 because we could not confidently identify the LPC owing to weak expression of GCaMP.

To prepare flies for in vivo imaging of vAB3 (Fig. 5c, Extended Data Fig. 6a–d), 2–5-day-old male flies were briefly anaesthetized using CO2 and then tethered used a previously described preparation53 in which the male was affixed to a piece of tape covering a hole in the bottom of a modified 35-mm Petri dish using human hair placed across the cervical connectives. A small strip of tape was placed over the proboscis of the fly and two pieces of putty were placed next to the thorax to prevent the legs from becoming stuck onto the tape. A small hole above the head was precisely cut into the tape and the head was secured using two small dots of UV-curable glue that bridged the eyes and the tape. The dish was filled with saline and the head capsule was opened by carefully tearing off the flap of cuticle covering the dorsal portion of the head and removing any obstructing trachea and fat. The dish was placed under the microscope and the axonal tract of vAB3 projecting from the SEZ to the LPC was identified. We vetted our ability to reproducibly identify the characteristic morphology of vAB3 by first imaging the vAB3 axonal tract using AbdB-Gal4>UAS-GCaMP in D. melanogaster males (Extended Data Fig. 6a, b). Baseline fluorescence was recorded for 4 s before a female abdomen was presented to the male for him to tap. Trials were repeated three times for each female species and then ΔF/F responses were averaged.

Ex vivo stimulation of vAB3 (Fig. 5e, f, Extended Data Fig. 7) was performed as previously described25. A Grass stimulator was used to iontophorese acetylcholine (10 V, 200 ms) through a fine glass electrode positioned on the axons of the Ppk23+ sensory neurons in the VNC (Fig. 5e, f, Extended Data Fig. 7). The stimulating electrode was filled with 10 mM acetylcholine, 10 mM glutamate or saline and Texas-Red Dextran BSA to facilitate positioning the electrode in the Fru+ neuropil. The local nature of the stimulation combined with the anatomically segregated sensory innervation of the Ppk23+ sensory neurons in the VNC facilitated restricted and reproducible stimulation. To functionally visualize responsive neurons in the brain, we imaged a z-plane every 5 µm and combined these to build a volume of the anterior around 100 µm of the brain. For quantitative comparisons of vAB3-evoked activity in specific neural populations across individuals (Fig. 5f, Extended Data Fig. 7), single z-planes were recorded using a 40× objective at 2× zoom with an ROI of 300 × 300 pixels. Given that P1 soma and fasciculated processes reside on the posterior side of the brain, when imaging P1 and vAB3 neurons in response to vAB3 stimulation, we rotated the brain 180° around the cervical connectives.

For two-photon severing of mAL (Fig. 5f, Extended Data Fig. 7), the brain was pinned ventral side up and we focused 925-nm light on a small ROI encompassing only the mAL axon tract at 8× optical zoom. The mAL axon tract could be readily identified by its characteristic morphology. For two-photon severing of vAB3 or a mock Fru+ neuron (Extended Data Fig. 7c), the VNC and brain were pinned ventral side up. We validated that vAB3 axons could be reproducibly identified within the VNC by performing initial experiments in AbdB-Gal4>UAS-Tomato/fruLexA>LexAOP-GCaMP D. melanogaster males in which vAB3 neurons are anatomically marked by Tomato expression. We found that vAB3 axons were always robustly activated by acetylcholine iontophoresis and have a characteristic position within the ventral cord that enabled their identification even in the absence of an anatomic marker. We focused 925-nm light on a small ROI encompassing either the vAB3 axon tract or the tract of a Fru+ neuron more lateral than vAB3. We then switched the laser to 850 nm and imaged using short (<1 s) pulses until a cavitation bubble was observed. After switching back to 925 nm and zooming out, if the axon tract was successfully severed, we observed a marked increase in baseline fluorescence due to Ca2+ influx into the neurons and activating GCaMP. Because vAB3 neurons project bilaterally, we also severed the corresponding axon tract on the contralateral side of the brain. To image P1 neurons after severing mAL, we re-pinned the brain such that the dorsal side of the brain and the ventral side of the VNC were facing up, rotating around the cervical connectives, inserted the stimulating electrode in the VNC and recorded activity in P1 neurons and vAB3 neurons. vAB3 activation was not affected by mAL severing (data not shown).

Dye-filling of neural tracts using Texas-Red Dextran (100 mg ml−1, Invitrogen) was performed as previously described54. For dye-filling specific neural populations, we targeted the fasciculated bundle of P1 neurons projecting from the somata (Fig. 4a, h, Extended Data Fig. 5a), the segregated vAB3 terminals in the VNC (Fig. 5b, Extended Data Fig. 5b) and the characteristic mAL axonal bundle projecting between the SEZ and LPC (Fig. 5b, Extended Data Fig. 5c) with a dye-filled electrode. To photolabel neurons, we expressed sPA-GFP in Fru+ neurons, located the neural structure of interest using 925-nm laser illumination, a wavelength that does not cause substantial photoconversion, defined an ROI in PrairieView software in a single z-plane, and exposed the target area to 710-nm light (around 10–30 mW at the back aperture of the objective) 100–300 times over the course of several rounds of photoactivation. We allowed diffusion of the photoconverted fluorophores throughout the targeted neurons for 30–60 min and then imaged at 925 nm. All anatomical images are maximum projections of z-stacks with 1-μm steps. Autofluorescence from the glial sheath and basal fluorescence from non-dye-filled structures were masked for clarity.

Unless stated, anatomical images were acquired on the 2P microscope using standard techniques.

Imaging analysis

To analyse functional responses, we calculated ΔF/F for each frame of calcium-imaging time-courses, using the second to sixth frames as the baseline. The peak ΔF/F value was defined as the maximum value within the time during which the stimulus was presented, which could vary due to inconsistent tapping rate of a male fly. Heat maps (∆F) were generated using the maximum projection of two frames of baseline subtracted from the maximum projection of the two frames encompassing the peak fluorescence in response to a stimulus. Arbitrary units (AU) correspond to 1/100th of the minimum displayed value and maximum displayed value in the display range set in FIJI.

Statistics and reproducibility

For courtship indices, each data point represents a biological replicate of an individual male’s courtship behaviour. For in vivo and ex vivo functional assays (Figs. 3b–d, 4e, f, 5c, d, f; Extended Data Figs. 3f, 6b, c, h, 7c, e), each pair of dots represents the average response for a given preparation (biological replicate). In Fig. 4g, h and Extended Data Figs. 3e, 4h–j, 6d, g, 7c–g, individual stimulations were plotted. Each representative example was replicated more than five times in independent experiments (Figs. 2a, 3a–c, 4a, e–h, 5b, e; Extended Data Figs. 2b–g, 3a–d, 4a, g, 5, 6a, e, 7a–c and Supplementary Videos 15). Sample sizes were based on pilot experiments. For all behavioural experiments n > 15, and for all in vivo imaging experiments n > 5. We used the PRISM software package to graph and statistically analyse data. Before statistical analysis, we tested whether the values were normally distributed using D’Agostion–Pearson omnibus and Shapiro–Wilk normality tests. When data were normally distributed, we used parametric tests; when data were not normally distributed, we used non-parametric tests. We adjusted P values accordingly when multiple comparisons were conducted. See Supplementary Table 1 for more details on statistical tests and P values.

Reporting summary

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

Data availability

Datasets generated during the current study are available from the corresponding author on reasonable request.