Magnesium efflux from Drosophila Kenyon cells is critical for normal and diet-enhanced long-term memory

Dietary magnesium (Mg2+) supplementation can enhance memory in young and aged rats. Memory-enhancing capacity was largely ascribed to increases in hippocampal synaptic density and elevated expression of the NR2B subunit of the NMDA-type glutamate receptor. Here we show that Mg2+ feeding also enhances long-term memory in Drosophila. Normal and Mg2+-enhanced fly memory appears independent of NMDA receptors in the mushroom body and instead requires expression of a conserved CNNM-type Mg2+-efflux transporter encoded by the unextended (uex) gene. UEX contains a putative cyclic nucleotide-binding homology domain and its mutation separates a vital role for uex from a function in memory. Moreover, UEX localization in mushroom body Kenyon cells (KCs) is altered in memory-defective flies harboring mutations in cAMP-related genes. Functional imaging suggests that UEX-dependent efflux is required for slow rhythmic maintenance of KC Mg2+. We propose that regulated neuronal Mg2+ efflux is critical for normal and Mg2+-enhanced memory.

Perhaps surprisingly, increasing brain Mg 2+ through diet can enhance neuronal plasticity and memory performance of young and aged rodents, measured in a variety of behavioral tasks (Slutsky et al., 2010;Landfield and Morgan, 1984;Mickley et al., 2013;Abumaria et al., 2013). In addition, elevated Mg 2+ reduced cognitive deficits in a mouse model of Alzheimer's disease (Li et al., 2013) and enhanced the extinction of fear memories (Abumaria et al., 2011). These apparently beneficial effects have led to the proposal that dietary Mg 2+ may have therapeutic value for patients with a variety of memory-related problems (Billard, 2011).
Despite the large number of potential sites of Mg 2+ action in the brain, the memory-enhancing property in rodents has largely been attributed to increases in hippocampal synaptic density and the activity of N-methyl-D-aspartate glutamate receptors (NMDARs). Extracellular Mg 2+ blocks the channel pore of the NMDAR and thereby inhibits the passage of other ions (Mayer et al., 1984;Bekkers and Stevens, 1993;Jahr and Stevens, 1990;Nowak et al., 1984). Importantly, prior neuronal depolarization, driven by other transmitter receptors, is required to release the Mg 2+ block on the NMDAR and permit glutamate-gated Ca 2+ influx. The NMDAR therefore plays an important role in neuronal plasticity as a potential Hebbian coincidence detector. Acute elevation of extracellular Mg 2+ concentration ([Mg 2+ ] e ) within the physiological range (0.8-1.2 mM) can antagonize induction of NMDAR-dependent long-term potentiation (Dunwiddie and Lynch, 1979;Malenka et al., 1992;Malenka and Nicoll, 1993;Slutsky et al., 2004). In contrast, increasing [Mg 2+ ] e for several hours in neuronal cultures leads to enhancement of NMDAR mediated currents and facilitation of the expression of LTP (Slutsky et al., 2004). The enhancing effects of increased [Mg 2+ ] e were also observed in vivo in the brain of rats fed with Mg 2+ -L-threonate (Slutsky et al., 2010). Hippocampal neuronal circuits undergo homeostatic plasticity (Turrigiano, 2008) to accommodate the increased [Mg 2+ ] e by upregulating expression of NR2B subunit containing NMDARs (Slutsky et al., 2004;Slutsky et al., 2010). The higher density of hippocampal synapses with NR2B containing NMDARs are believed to compensate for the chronic increase in [Mg 2+ ] e by enhancing NMDAR currents during burst firing. In support of this model, mice that are genetically engineered to overexpress NR2B exhibit enhanced hippocampal LTP and behavioral memory (Tang et al., 1999).
Olfactory memory in Drosophila involves a heterosynaptic mechanism driven by reinforcing dopaminergic neurons, which results in presynaptic depression of cholinergic connections between odoractivated mushroom body (MB) Kenyon cells (KCs) and downstream mushroom body output neurons (MBONs) (Schwaerzel et al., 2003;Aso et al., 2010;Aso et al., 2012;Claridge-Chang et al., 2009;Burke et al., 2012;Liu et al., 2012;Plaç ais et al., 2013;Hige et al., 2015;Barnstedt et al., 2016;Perisse et al., 2016;Aso et al., 2014;. In addition, olfactory information is conveyed to KCs by cholinergic transmission from olfactory eLife digest The proverbial saying 'you are what you eat' perfectly summarizes the concept that our diet can influence both our mental and physical health. We know that foods that are good for the heart, such as nuts, oily fish and berries, are also good for the brain. We know too that vitamins and minerals are essential for overall good health. But is there any evidence that increasing your intake of specific vitamins or minerals could help boost your brain power?
While it might sound almost too good to be true, there is some evidence that this is the case for at least one mineral, magnesium. Studies in rodents have shown that adding magnesium supplements to food improves how well the animals perform on memory tasks. Both young and old animals benefit from additional magnesium. Even elderly rodents with a condition similar to Alzheimer's disease show less memory loss when given magnesium supplements. But what about other species? Wu et al. now show that magnesium supplements also boost memory performance in fruit flies. One group of flies was fed with standard cornmeal for several days, while the other group received cornmeal supplemented with magnesium. Both groups were then trained to associate an odor with a food reward. Flies that had received the extra magnesium showed better memory for the odor when tested 24 hours after training. Wu et al. show that magnesium improves memory in the flies via a different mechanism to that reported previously for rodents. In rodents, magnesium increased levels of a receptor protein for a brain chemical called glutamate. In fruit flies, by contrast, the memory boost depended on a protein that transports magnesium out of neurons. Mutant flies that lacked this transporter showed memory impairments. Unlike normal flies, those without the transporter showed no memory improvement after eating magnesium-enriched food. The results suggest that the transporter may help adjust magnesium levels inside brain cells in response to neural activity.
Humans produce four variants of this magnesium transporter, each encoded by a different gene. One of these transporters has already been implicated in brain development. The findings of Wu et al. suggest that the transporters may also act in the adult brain to influence cognition. Further studies are needed to test whether targeting the magnesium transporter could ultimately hold promise for treating memory impairments. projection neurons (Yasuyama et al., 2002;Leiss et al., 2009). Although it is conceivable that glutamate is delivered to the MB network via an as yet to be identified route, there is currently no obvious location for NMDAR-dependent plasticity in the known architecture of the cholinergic input or output layers . The fly therefore provides a potential model to investigate other mechanisms through which dietary Mg 2+ might enhance memory.
The reinforcing effects of dopamine depend on the Dop1R D1-type dopamine receptor (Kim et al., 2007;Qin et al., 2012;Handler et al., 2019), which is positively coupled with cAMP production (Tomchik and Davis, 2009;Boto et al., 2014). Moreover, early studies in Drosophila identified the dunce and rutabaga encoded cAMP phosphodiesterase and type I Ca 2+stimulated adenylate cyclase, respectively, to be essential for olfactory memory (Dudai et al., 1976;Byers et al., 1981;Dudai and Zvi, 1984;Chen et al., 1986;Livingstone et al., 1984;Levin et al., 1992). Studies in mammalian cells have shown that hormones or agents that increase cellular cAMP level often elicit a significant Na + -dependent extrusion of Mg 2+ into the extracellular space (Romani and Scarpa, 1990b;Romani and Scarpa, 1990a;Romani and Scarpa, 2000;Vink and Nechifor, 2011;Vormann and Günther, 1987). However, it is unclear whether Mg 2+ extrusion plays any role in memory processing.
Here we demonstrate that Drosophila long-term memory (LTM) can be enhanced with dietary Mg 2+ supplementation. We find that the unextended (uex) (Maeda, 1984;Coulthard et al., 2010) gene, which encodes a functional fly ortholog of the mammalian Cyclin M2 Mg 2+ -efflux transporter (CNNM) proteins, is critical for the memory enhancing property of Mg 2+ . UEX function in MB KCs is required for LTM and functional restoration of uex reveals the MB to be the key site of Mg 2+ -dependent memory enhancement. Chronically changing cAMP metabolism by introducing mutations in the dnc or rut genes alters the cellular localization of UEX. Moreover, mutating the conserved cyclic nucleotide-binding homology (CNBH) domain in UEX uncouples an essential role for uex from its function in memory. UEX-driven Mg 2+ efflux is required for slow rhythmic maintenance of KC Mg 2+ levels suggesting a potential role for Mg 2+ flux in memory processing.

Mg 2+ feeding enhances LTM of wild-type flies
Prior studies reported that feeding rats with food containing a high concentration of Mg 2+ -enhanced their learning and memory capability (Slutsky et al., 2010;Landfield and Morgan, 1984;Abumaria et al., 2011;Mickley et al., 2013;Abumaria et al., 2013). We therefore tested whether similar effects exist in flies by feeding them with food containing a high concentration of Mg 2+ before training. Surprisingly, wild-type flies fed for 4 days before training with food supplemented with additional magnesium chloride (MgCl 2 ) exhibited significantly enhanced 24 hr memory performance. Memory enhancement depends on concentration and was maximal when food was supplemented with 80 mM MgCl 2 ( Figure 1A). Immediate memory performance was not obviously enhanced ( Figure 1B). The enhancing effect of MgCl 2 was also observed in flies fed with magnesium sulfate (MgSO 4 ) but not calcium chloride (CaCl 2 ) ( Figure 1C). In addition, feeding flies for 4 days with food containing between 5 and 80 mM strontium chloride (SrCl 2 ) resulted in high levels of mortality and flies that survived 5 mM SrCl 2 feeding did not show enhanced immediate or 24 hr memory performance (data not shown). The memory enhancing effects can therefore be specifically attributed to dietary supplementation of divalent Mg 2+ .

Mg 2+ -enhanced memory is independent of NMDAR in the mushroom bodies
Since magnesium-L-threonate enhanced memory in rats was correlated with an upregulation of hippocampal NR2B subunit-containing NMDARs (Slutsky et al., 2010), we tested for changes in glutamate receptor expression in flies fed with MgCl 2 . RT-qPCR analyses did not reveal a significant difference in the abundance of mRNAs for the putative NMDA (Nmdar1, Nmdar2), AMPA (GluRIA), or kainate-type (GluRIIA) receptors in heads taken from flies fed for 4 days with 80 mM MgCl 2 versus those fed with 1 mM MgCl 2 ( Figure 1D).
We next directly tested whether Mg 2+ -enhanced memory required NMDAR function, by knocking down expression of the Nmdar1 or Nmdar2 genes using transgenic UAS-driven RNA interference (RNAi) constructs (Dietzl et al., 2007;Perkins et al., 2015). Of the two independent UAS-Nmdar1 R-NAi and four UAS-Nmdar2 RNAi lines we tested, only one Nmdar1 RNAi (BDSC 25941) line, when driven in all neurons by neuronal Synaptobrevin (nSyb)-GAL4, exhibited significantly decreased 24 hr memory performance, as compared to that of heterozygous control flies (Figure 1-figure supplement  1A). In contrast, more selective expression of this UAS-Nmdar1 RNAi in LTM-relevant ab KCs using c739-GAL4 did not significantly impair 24 hr memory performance ( Wild-type flies were trained and tested for 24 hr appetitive memory after 1-5 days of ad libitum feeding on food supplemented with Mg 2+ . Memory was significantly enhanced in flies fed for 4 days with 80 mM MgCl 2 , as compared to those fed with 1 mM. 80 mM MgCl 2 produced marginally higher performance than 50 mM or 100 mM and so was considered optimal (asterisks denote p<0.05, t-test between 1 mM and 80 mM groups for each time point, n = 6-8). (B) 4 days of 80 mM MgCl 2 food did not enhance immediate memory. (C) Appetitive 24 hr memory was enhanced by feeding wild-type flies for 4 days with MgCl 2 and MgSO 4 , but not CaCl 2 . Asterisks denote significant differences (p<0.05, ANOVA, n = 6) between Mg 2+ fed and plain groups. (D) RT-qPCR showed no significant differences in glutamate receptor mRNA expression between 1 mM and 80 mM fed flies (t-test, n = 5). (E) c739-GAL4; UAS-MagFRET-1 flies were fed for 4 days on food supplemented with Mg 2+ . Brains were dissected and fixed and a fluorescence emission ratio measurement (Citrine/Cerulean) was taken as an indicator of [Mg 2+ ] i . The MagFRET signal was significantly greater in the ab lobes of flies fed with 80 mM MgCl 2 than those fed with 1 mM MgCl 2 (p<0.05, t-test, n = 52-60). Unless otherwise noted, all data are mean ± standard error of mean (SEM). Asterisks denote significant differences (p<0.05), individual data points displayed as open circles. The online version of this article includes the following figure supplement(s) for figure 1: Mg 2+ concentration in ab neurons is elevated in flies fed high Mg 2+ We used MagFRET, the first genetically encoded fluorescent Mg 2+ sensor (Lindenburg et al., 2013), to test whether Mg 2+ feeding altered the intracellular Mg 2+ concentration ([Mg 2+ ] i ). We constructed flies harboring a UAS-MagFRET-1 transgene and combined it with c739-GAL4 to express MagFRET-1 in ab KCs. We compared the FRET signals in fixed brains from c739; UAS-MagFRET-1 flies fed with either 1 mM or 80 mM MgCl 2 food for 4 days. The MagFRET signal was significantly higher in both the a and b collaterals of ab KCs of flies fed with 80 mM, than in those fed with 1 mM ( Figure 1E). This result indicates that Mg feeding elevates neuronal [Mg 2+ ] i . Given the affinity of MagFRET-1 (Kd = 148 mM) and the~50% increase in FRET signal upon Mg 2+ binding (Lindenburg et al., 2013), we estimate that the~8% enhancement of the MagFRET signal measured in flies fed 80 mM MgCl 2 corresponds approximately to a 50 mM increase of ab KC [Mg 2+ ] i on average.
The unextended encoded CNNM-type Mg 2+ transporter has a role in memory We identified unextended (uex;Maeda, 1984;Coulthard et al., 2010) as a gene altering appetitive olfactory LTM, reinforced with sucrose reward. Flies with the uex MI01943 MiMIC insertion (Venken et al., 2011) showed a strong defect in 24 hr memory, but their performance immediately after training was indistinguishable from that of wild-type controls. More detailed analysis of uex MI01943 flies revealed a steady decay of memory that first became significantly different to that of wild-type flies 12 hr after training ( Figure 2A). No memory defect was evident in heterozygous uex MI01943 /+ flies, demonstrating that this putative uex allele is recessive.
uex piqued our attention because it is the single fly ortholog of the four human CNNM genes that encode Mg 2+ transporters (Ishii et al., 2016), and it also contains a putative CNBH domain that is structurally related to those in cyclic nucleotide-gated channels (Zagotta et al., 2003;Flynn et al., 2007;Kesters et al., 2015). Alignment of the 834 amino acid UEX sequence with CNNM1-4 reveals particularly high sequence conservation with CNNM2 and CNNM4 in the DUF21, CBS pair, and CNBH domains (Figure 2-figure supplement 1A-C). We therefore hypothesized that UEX had potential to link the memory-enhancing effects of dietary Mg 2+ with cAMP-dependent neuronal plasticity.
Although uex MI01943 is assigned to the uex gene, the MiMIC element is annotated to lie 17 kb downstream of the uex coding region (Venken et al., 2011;Figure 2B). RYa (Yoon et al., 2016) is the next nearest gene to uex MI01943 but is >230 kb further away. We first confirmed the MiMIC location by inverse PCR (Attrill et al., 2016). Importantly, no additional MiMIC insertion was detected in these flies. We next tested whether uex MI01943 was responsible for the memory defect by precisely removing the MiMIC element by Minos transposase-mediated excision (Arcà et al., 1997;Figure 2figure supplement 2A and B). MiMIC removal in uex MI01943.ex1 and uex MI01943.ex2 flies restored normal 24 hr memory performance, demonstrating that the MiMIC insertion is required for the uex MI01943 memory defect ( Figure 2C).
Both qRT-PCR of mRNA and western blot analysis of protein extracts from fly heads failed to reveal a significant difference in uex/UEX expression in uex MI01943 flies. We therefore used CRISPR to introduce a stop codon into the fifth coding exon of the uex locus ( Figure 2B and Flies homozygous for the resulting uexD mutation were not viable as adults, dying at the larval stage. In contrast, heterozygous uex MI01943 /uexD flies were viable, but their 24 hr appetitive memory was significantly impaired ( Figure 2D). These data demonstrate that uex is an essential gene and that uex MI01943 is a viable hypomorphic allele of uex.
We also tested the aversive memory performance of uex MI01943 mutant flies. Homozygous uex MI01943 flies exhibited immediate memory that was indistinguishable from that of heterozygous and wild-type controls ( Figure 2E). However, their 24 hr memory, formed following either five trials of aversive spaced training (Tully et al., 1994;Jacob and Waddell, 2020), or one trial of fasting facilitated training (Hirano et al., 2013), was significantly impaired ( Figure 2E). These experiments suggest that uex MI01943 flies are more generally compromised in their ability to form LTM. Unless otherwise specified, all subsequent analyses of memory in this study use appetitive sugar-rewarded conditioning.  To localize uex in the brain we first took advantage of VT23256-GAL4 transgenic flies, in which GAL4 is driven by an 853 bp sequence from the first intron of uex (Kvon et al., 2014). VT23256-driven UAS-EGFP revealed restricted expression in ab KCs with particularly strong label in ab core (ab c ) neurons ( Figure 3A). We also used CRISPR to insert a C-terminal HA-epitope tag into the uex open reading frame (Figure 3-figure supplement 1A). These flies were viable as homozygotes indicating that the resulting UEX::HA fusion protein retains function. Immunostaining flies harboring this uex:: HA locus with an anti-HA antibody revealed prominent labeling of all the major KC classes in the MB, in addition to lower expression throughout the brain ( Figure 3B). This uex expression profile is also supported by single-cell sequencing analyses (Figure 3-figure supplement 1B; Croset et al., 2018;Davie et al., 2018). Given the established role for ab KCs in olfactory LTM (Pascual and Préat, 2001;Yu et al., 2006;Krashes et al., 2007;Krashes and Waddell, 2008), we reasoned that a mnemonic role for UEX may involve expression in KCs. We next used GAL4-directed expression of RNAi to test whether 24 hr memory performance required uex in the MB. Flies expressing uex RNAi (Perkins et al., 2015) in all ab KCs (c739-GAL4; Yang et al., 1995;Perisse et al., 2013) or only in ab c KCs (NP7175-GAL4; Tanaka et al., 2008) showed normal immediate memory but significantly impaired 24 hr memory ( Figure 3C). In contrast, uex RNAi expression in ab surface (ab s , 0770-GAL4; Perisse et al., 2013) or a 0 b 0 KCs (c305a-GAL4; Krashes et al., 2007) did not significantly alter immediate or LTM performance. Normal 24 hr appetitive memory performance is therefore particularly sensitive to uex expression in ab c neurons. To reduce the likelihood that the uex RNAi associated memory defect results from a developmental consequence, we also restricted UAS-uex RNAi expression to adulthood using GAL80 ts -mediated temporal control (McGuire et al., 2003). At permissive 18˚C, GAL80 ts binds to GAL4 and suppresses its transcriptional activator function. At restrictive 30˚C, GAL80 ts can no longer bind to GAL4, which frees GAL4 to direct expression of the UAS-uex RNAi transgene. Flies were raised through development at 18˚C and moved to 30˚C after eclosion. Restricting UAS-uex RNAi expression to ab KCs in adult flies using c739-GAL4 with GAL80 ts produced a similar 24 hr specific memory defect to that observed when UAS-uex RNAi was expressed without temporal control ( Figure 3D-F). We assessed the efficacy of the UAS-uex RNAi knockdown using our tagged uex::HA locus. Brains from heterozygous uex::HA flies expressing uex RNAi in the ab and g KCs with MB247-GAL4 (Zars et al., 2000) were immunostained using anti-HA antibody. Comparing the intensity of immunolabeling in brains from uex::HA; MB247-GAL4/uex RNAi flies with that from uex::HA; MB247-GAL4/+ flies showed that uex RNAi expression significantly reduced anti-HA signal in the ab and g KCs ( Figure 3G and H). This result demonstrates the efficiency of the uex RNAi transgene and the utility of the CRISPR/Cas9 edited uex::HA locus.
We next tested whether expression in specific KCs of an UAS-uex transgene could restore 24 hr memory capacity to uex MI01943 flies. Memory performance of uex MI01943 flies expressing UAS-uex in ab and g KCs (MB247-GAL4; Zars et al., 2000) or only the ab KCs (c739-GAL4) was significantly improved over that of uex MI01943 flies, and was statistically indistinguishable from that of controls with an intact uex locus ( Figure 4A). In contrast, UAS-uex expression in a 0 b 0 , ab c , or ab s KCs did not restore memory performance to uex MI01943 flies and overexpressing uex in ab KCs of wild-type flies did not augment 24 hr memory ( Figure 4A and B). Normal 24 hr memory performance could also be restored to uex MI01943 flies if UAS-uex expression was confined to c739-GAL4 neurons (all ab KCs) in adulthood using GAL80 ts -mediated temporal control ( Figure 4C and D). Together, these loss-of-function RNAi and restoration experiments establish that UEX plays an important role in adult compared to the performance of heterozygous uex MI01943 /+ and wild-type control flies (p<0.05, ANOVA, n = 8-12). An LTM defect was also observed following five cycles of aversive spaced training and a 16 hr fasting facilitated one-cycle training protocol. Immediate aversive memory was unaffected in uex MI01943 homozygous mutant flies. The online version of this article includes the following source data and figure supplement(s) for figure 2: Source data 1.  24 hr memory (re-suppressed) ab KCs. Finding that ab c RNAi knockdown of uex produces a memory defect ( Figure 3C) but UASuex expression in ab c does not rescue the uex MI01943 mutant defect ( Figure 4A) suggests that UEX function in ab c KCs is essential for appetitive LTM, whereas both the ab c and ab s KCs need to have functional UEX to support LTM. In addition, the ability of UAS-uex to restore performance to uex MI0194 flies provides further support that uex is responsible for the memory impairment in uex MI01943 flies.
uex expression in the MB supports Mg 2+ -enhanced memory We next investigated whether Mg 2+ feeding (4 days with 80 mM MgCl 2 ) could improve memory performance in flies with compromised uex function. Flies carrying the uex MI01943 allele ( Figure 4F) or those expressing UAS-uex RNAi in the ab KCs with c739-GAL4 ( Figure 4E) did not show enhanced memory when fed with 80 mM MgCl 2 , as compared to flies fed with 1 mM MgCl 2 . Moreover, the Mg 2+ -enhanced memory was recovered in uex MI01943 mutant flies when uex expression was restored to the ab KCs ( Figure 4F). All control flies (c739-GAL4, UAS-uex RNAi , and UAS-uex) with unperturbed uex expression exhibited significantly enhanced memory when fed with 80 mM as compared to 1 mM MgCl 2 . Overexpressing UAS-uex in ab KCs with c739-GAL4 in flies with a wild-type genetic background neither enhanced regular 24 hr memory ( Figure 4B), or that in flies fed for 4 days with 40 or 80 mM MgCl 2 ( Figure 4G). We also tested whether 4 days of 80 mM MgCl 2 supplementation enhanced 24 hr memory performance following aversive spaced training. Again, memory of wildtype, but not uex MI01943 mutant flies showed enhancement (Figure 4-figure supplement 1). Together these results indicate that optimal memory enhancement with Mg 2+ feeding requires, and can be fully supported by, UEX function in ab KCs.

UEX is a functionally conserved magnesium transporter
Given the strong sequence conservation of UEX with mammalian CNNM2/4 we tested whether CNNM2 could functionally substitute for UEX and restore the LTM defect of uex MI01943 flies. Several point mutations in CNNM2 have been identified in human patients with hypomagnesemia, which is associated with brain malformation and intellectual disability (Arjona et al., 2014). Introduction of the equivalent mutations into mouse CNNM2 (CNNM2 E357K , CNNM2 T568I , CNNM2 S269W , and CNNM2 E122K ) showed that these patient-derived lesions impair magnesium transport (Arjona et al., 2014). We constructed flies carrying wild-type and these mutant variant UAS-CNNM2 transgenes ( Figure 5A). Staining for an associated C-terminal HA-tag revealed clear expression of all UAS-CNNM2::HA variants in ab neurons when driven with c739-GAL4 (Figure 5-figure supplement 1). However, only expression of wild-type CNNM2, and not point-mutant forms, in ab KCs of uex MI01943 mutant flies restored 24 hr memory performance ( Figure 5B).
We also tested whether UEX can mediate Mg 2+ extrusion. UEX expressed in HEK293 cells localized to the plasma membrane and cells loaded with Mg 2+ and the Mg 2+ indicator Magnesium Green showed rapid Mg 2+ efflux (Figure 5-figure supplement 2 and Video 1), as compared to cells transfected with empty vector. Mg 2+ extrusion driven by UEX was noticeably less efficient than in cells expressing Human CNNM4 (Figure 5-figure supplement 2), which is known to have similar efficiency to CNNM2 (Hirata et al., 2014). However, we do not know if UEX and CNNM4 expression is equivalent. Nevertheless, demonstration of cross-species complementation and Mg 2+ efflux activity defines UEX as a functional homolog of mammalian CNNM2/4. Figure 3 continued ANOVA, n = 6-10 for immediate and n = 8-14 for 24 hr memory). (D) Defective LTM was observed if uex RNAi expression was confined to ab KCs of adult flies using GAL80 tsmediated temporal control. (E) LTM performance was unaffected if the uex RNAi was kept suppressed throughout and (F) LTM performance was restored to normal levels if expression of uex RNAi was re-suppressed for 3 days (p<0.05, ANOVA, n = 6 for immediate and n = 8 for 24 hr memory). (G) Immunostaining shows the effectiveness of uex RNAi . Fluorescence intensity in the ab and g lobes of uex::HA flies decreased significantly when UAS-uex RNAi was expressed with MB247-GAL4. Scale bars 20 mm. (H) Quantification of fluorescence intensity in G (p<0.05, t-test, n = 6-8). The online version of this article includes the following figure supplement(s) for figure 3: An intact CNBH domain is required for memory Given the established role for cAMP signaling in memory-relevant plasticity in invertebrates and mammals (Kandel, 2012), we tested the importance of the CNBH domain in UEX. We constructed flies carrying a point-mutated CNBH UAS-uex R622K transgene ( Figure 6A). The equivalent R622K amino acid substitution abolishes cAMP binding in the regulatory subunit of cAMP-dependent protein kinase, PKA (Bubis et al., 1988). Expressing UAS-uex R622K in ab neurons with c739-GAL4 did not restore 24 hr memory performance, or alter the immediate memory performance, of uex MI01943 mutant flies ( Figure 6B).
We also used CRISPR to attempt to introduce the R622K mutation into the CNBH of the native uex locus (Bassett et al., 2013;Gratz et al., 2013;Yu et al., 2013). Unexpectedly, this approach did not introduce the R622K substitution but instead replaced T626 in the CNBH with NRR. Fortuitously, flies homozygous for this uex T626NRR allele were viable as adults, unlike those homozygous for uexD, suggesting that the uex T626NRR encoded UEX retains function. However, flies homozygous for uex T626NRR or heterozygous uex T626NRR / uex MI01943 flies exhibited a strong 24 hr memory defect ( Figure 6C). Immediate memory was also impaired in homozygous uex T626NRR flies, unlike flies carrying all other combinations of uex alleles. In addition, memory of uex T626NRR flies could not be enhanced with Mg 2+ feeding ( Figure 6D). The uex T626NRR mutation therefore uncouples the essential Figure 4 continued for 24 hr memory) but (D) remained defective if UAS-uex expression was not released. (E) Memory enhancement with dietary Mg 2+ is supported by UEX in ab KCs. Memory of flies expressing UAS-uex RNAi in the ab KCs cannot be enhanced with Mg 2+ feeding (t-test, n = 8). (F) Memory of uex MI01943 mutant flies cannot be enhanced with Mg 2+ feeding, but enhancement was restored by expressing UAS-uex in ab KCs (p<0.05, t-test, n = 8-12). (G) Memory of wild-type flies was not sensitized to Mg 2+ enhancement by overexpressing UAS-uex in ab KCs. Memory was enhanced if the flies were fed with 80 mM MgCl 2 , but not with suboptimal 40 mM MgCl 2 (p<0.05, ANOVA, n = 8). The online version of this article includes the following figure supplement(s) for figure 4: role for uex from a function in memory and suggests that cyclic nucleotide regulated activity is critical for UEX to support normal and Mg 2+enhanced memory. Although we confirmed using western blotting that a full-length protein is expressed in uex T622NRR flies ( Figure 6E), our antibody did not permit us to verify that the UEX T626NRR protein localizes appropriately in the brain. Further work is therefore required to characterize the cellular localization, cAMP binding, and Mg 2+ transport function of the protein encoded by this serendipitous uex T626NRR allele.

Chronic cAMP manipulation alters UEX localization in KCs
We tested whether cAMP could acutely alter UEX activity by applying forskolin to UEXexpressing HEK293 cells. However, no obvious change in the UEX-dependent Mg 2+ efflux dynamic was observed (data not shown). We therefore tested whether KC expression of UEX:: HA was altered in flies with chronic alterations of cAMP metabolism, by introducing learning-relevant mutations in the rutabaga-encoded Ca 2+stimulated adenylate cyclase, or the dunceencoded cAMP-specific phosphodiesterase. Anti-HA immunostaining of brains from rut 2080 ; uex::HA and dnc 1 ; uex::HA flies revealed a striking change in UEX localization ( Figure 7A and B and Videos 2-4). Whereas UEX::HA is usually detected in the lobes of all KCs at a roughly equivalent level in wild-type flies, labeling was lower in the MB g lobe and more pronounced in the ab c KCs in rut 2080 and dnc 1 mutant backgrounds ( Figure 7C), although the overall MB expression of UEX::HA is similar between wild-type and mutant flies ( Figure 7D). In addition, western blot analyses of protein extracted from heads of these flies did not reveal a significant difference in overall UEX::HA expression levels (data not shown). These data are therefore consistent with cAMP regulating UEX function and perhaps its cellular localization in KCs.

UEX is required to maintain a fluctuating [Mg 2+ ] i in ab KCs
Although MagFRET can report [Mg 2+ ] it does not respond quickly enough to record stimulus-evoked signals. We therefore constructed flies harboring UAS-transgenes for two newer genetically encoded Mg 2+ sensors, MagIC (non-FRET based; Koldenkova et al., 2015) and MARIO (FRET based; Maeshima et al., 2018). We were unable to detect UAS-MARIO expression in the fly brain and therefore could only use UAS-MagIC. MagIC was reported to respond most strongly to Mg 2+ but also to a lesser extent to Ca 2+ (Koldenkova et al., 2015). We therefore first verified the specificity of MagIC responses in a cell-permeabilized ex vivo fly brain preparation. Brains were removed from flies expressing UAS-MagIC in ab KCs with c739-GAL4 ( Figure 8A), incubated in a dish with saline  and changes in fluorescence were monitored before and after bath application of chemicals. Whereas application of MgCl 2 evoked a dose-dependent increase in the MagIC response, chelation of Mg 2+ with EDTA produced a dose-dependent decrease ( Figure 8B and Videos 5 and 6). In comparison, CaCl 2 only registered a slight increase at the highest concentrations whereas the more Ca 2+ -selective chelator EGTA had little effect ( Figure 8B). These results demonstrate that UAS-MagIC can monitor [Mg 2+ ] i in the ab KCs in the fly brain.
Increasing intracellular cAMP has been shown to elicit Mg 2+ flux from mammalian cells (Romani and Scarpa, 2000;Vormann and Günther, 1987;Jakob et al., 1989;Romani and Scarpa, 1990b;Romani and Scarpa, 1990a;Vormann and Günther, 1987;Günther et al., 1990;Howarth et al., 1994). Since our experiments also indicated that cAMP might regulate UEX, we next tested whether stimulating cAMP synthesis with forskolin (FSK) might alter MagIC signals in ab Video 1. UEX promotes Mg 2+ -efflux from HEK293 cells. Representative movies showing Mg 2+ -efflux from HEK293 cells transfected with different expression vectors. Imaging protocol is described in Yamazaki et al., 2013. The cells indicated with asterisks in the first frame of each movie are the cells expressing the anti-FLAG immunostained CNNM4 or UEX, which were identified after each live-imaging experiment. Empty vector control is shown in the upper left. The fluorescence signal of CNNM4-FLAG and UEX-FLAG expressing cells decreases rapidly when extracellular Mg 2+ is depleted, which was performed between the third and fourth frames in each movie.  KCs. For these experiments we again used an ex vivo brain preparation but this time the cells were not permeabilized. 30 mM FSK has been shown to evoke a peak increase in cAMP in KCs that approximates that observed following appetitive conditioning (Louis et al., 2018). Applying 30 mM FSK to c739-GAL4; UAS-MagIC brains evoked a consistent dynamic in MagIC fluorescence. After a sharp initial rise, responses slowly decayed back toward baseline before again rising slowly to a point at which the signal started to fluctuate. ( Figure 8C and D and Video 7). The key signatures of this response were only recorded in the Mg 2+ -sensitive Venus signal ( Figure 8D). In contrast mCherry fluorescence did not fluctuate but steadily decreased across the time course of the recording (likely a result of photo-bleaching), demonstrating that the fluctuation in the Venus signal is not a movement artifact ( Figure 8E). Importantly, FSK induced MagIC responses were greater than those following application of saline ( Figure 8-figure supplement 1A). However, a fluctuating response also developed after saline applications (Figure 8-figure supplement 1B) suggesting that the rhythmic MagIC signal may be a general response to an increase in [Mg 2+ ] i that follows cellular perturbation.
The Drosophila MB has previously been reported to exhibit a slow (0.004 Hz) Ca 2+ oscillation in ex vivo brains whereas a much faster 20 Hz oscillation is evoked by odors in the locust MB (Laurent and Naraghi, 1994;Rosay et al., 2001). Although our initial characterization of MagIC in the fly brain indicated a preferential response to Mg 2+ ( Figure 8B), we nevertheless explicitly tested whether FSK induced fluctuation of the [Ca 2+ ] i of ab KCs, using expression of UAS-GCaMP6f . FSK induced a delayed increase in the GCaMP response but no clear oscillatory activity was observed (Figure 8 Lastly, we tested whether the observed MagIC responses were sensitive to the status of the uex gene. We generated uex MI01943 flies that also harbored c379-GAL4 and UAS-MagIC and compared their FSK-and saline-induced MagIC responses to those of flies with a wild-type uex locus. The uex MI01943 mutant flies showed an increased FSK response to that of wild-type flies, whereas salineevoked responses were indistinguishable ( Figure 8F and G). Responses evoked by the inactive FSK analogue, ddFSK, were also insensitive to the status of uex (Figure 8-figure supplement 1F). Mutation of uex therefore selectively increases mean FSK-evoked MagIC responses.
We also noticed that MagIC traces from uex mutant flies did not exhibit a fluctuating signal ( Figure 8H and Figure 8-figure supplement 1G). To quantify this difference we calculated the mean power spectral density (PSD) of traces from uex MI01943 and wild-type flies treated with FSK or saline. In both conditions the mean PSD was significantly left-shifted toward lower frequencies in the uex MI01943 mutants compared to the wild-type controls ( Figure 8I). Wild-type fly brains had significantly more oscillatory activity centered around 0.015 Hz than those from uex MI01943 mutants. These data therefore suggest that UEX is required for slow rhythmic maintenance of KC [Mg 2+ ] i . Importantly, finding that MagIC signals are elevated and altered in uex mutants confirms that the observed MagIC responses are Mg 2+ -dependent. Moreover, they suggest that the KC expressed UEX limits Mg 2+ accumulation, consistent with a role in extrusion.

Discussion
We observed an enhancement of olfactory LTM performance when flies were fed for 4 days before training with food supplemented with 80 mM [Mg 2+ ]. This result resembles that reported in rats, although longer periods of feeding were required to raise brain [Mg 2+ ] to memory-enhancing levels (Slutsky et al., 2010). A difference in optimal feeding time may reflect the size of the animal and perhaps the greater bioavailability of dietary Mg 2+ in Drosophila. Whereas Mg 2+ -L-threonate (MgT) was a more effective means of delivering Mg 2+ than magnesium chloride in rats (Slutsky et al., 2010), we observed a similar enhancement of memory performance when flies were fed with magnesium chloride, magnesium sulfate, or MgT (data not shown). Elevating [Mg 2+ ] e in the rat brain leads to a compensatory upregulation of expression of the NR2B subunit of the NMDAR and therefore an increase in the proportion of postsynaptic NR2B-containing NMDARs. This class of NMDARs have a longer opening time Erreger et al., 2005) suggesting that this switch in subunit composition represents a homeostatic plasticity mechanism (Turrigiano, 2008) to accommodate for the increased NMDAR block imposed by increasing [Mg 2+ ] e . Moreover, overexpression of NR2B in the mouse forebrain can enhance synaptic facilitation and learning and memory performance (Tang et al., 1999), supporting an increase in NR2B being an important factor in Mg 2+ -enhanced memory. However, even in the original in vitro study of Mg 2+ -enhanced synaptic plasticity (Slutsky et al., 2004), it was noted that NMDAR currents were insufficient to fully explain the observed changes.
Our NMDAR subunit loss-of-function studies in the Drosophila KCs did not impair regular or Mg 2+ -enhanced memory. Furthermore, we did not detect an obvious change in the levels of brainwide expression of glutamate receptor subunits in Mg 2+ -fed flies. Although NMDAR activity has previously been implicated in Drosophila olfactory memory, the effects were mostly ascribed to function outside the MB (Xia et al., 2005;Wu et al., 2007). In addition, overexpressing Nmdar1 in all neurons, or specifically in all KCs, did not alter STM or LTM. Ectopic overexpression in the MB of an NMDAR N631Q version, which cannot be blocked by Mg 2+ , impaired LTM (Miyashita et al., 2012). However, this mutation permits ligand-gated Ca 2+ entry, without the need for correlated neuronal depolarization, which may perturb KC function in unexpected ways. It is perhaps most noteworthy that learning-relevant synaptic depression in the MB can be driven by dopaminergic teaching signals delivered to cholinergic output synapses from odor-responsive KCs to specific MBONs (Claridge-Chang et al., 2009;Aso et al., 2012;Burke et al., 2012;Liu et al., 2012;Hige et al., 2015;Barnstedt et al., 2016;Perisse et al., 2016;Aso et al., 2014;Handler et al., 2019). It is conceivable that KCs receive glutamate, from a source yet to be identified, but there is currently no obvious place in the MB network for NMDAR-dependent plasticity. Evidence therefore suggests that normal and Mg 2+ -enhanced Drosophila LTM is independent of NMDAR signaling in KCs. In addition, our MagFRET measurements indicate that Mg 2+ feeding also increases the [Mg 2+ ] i of ab KCs by approximately 50 mM.
We identified a role for uex, the single fly ortholog of the evolutionarily conserved family of CNNM-type Mg 2+ efflux transporters (Ishii et al., 2016). There are four distinct CNNM genes in mice and humans, five in C. elegans, and two in zebrafish (Ishii et al., 2016;Arjona et al., 2013). The uex locus produces four alternatively spliced mRNA transcripts, but all encode the same 834 aa protein. The precise role of CNNM proteins in Mg 2+ transport is somewhat contentious (Funato et al., 2018a;Arjona and de Baaij, 2018;Funato et al., 2018b;Giménez-Mascarell et al., 2019). Some propose that CNNM proteins are direct Mg 2+ transporters, whereas others favor that they function as sensors of intracellular Mg 2+ concentration [Mg 2+ ] i and/or regulators of other Mg 2+ transporters. We found that ectopic expression of Drosophila UEX enhances Mg 2+ efflux in HEK293 cells and that endogenous UEX limits [Mg 2+ ] i in ab KCs in the fly brain. Therefore, if UEX is not itself a Mg 2+ transporter, it must be Total intensity over all six ROIs on the MBs was not significantly different between the rut 2080 , dnc 1 and wild-type brains (p>0.13; ANOVA, n = 6-10).
Video 2. Expression of UEX in a wild-type Drosophila brain. Confocal Z-stack of a uex::HA fly brain stained with anti-HA antibody.
https://elifesciences.org/articles/61339#video2 able to interact effectively with human Mg 2+ efflux transporters and to influence Mg 2+ extrusion in Drosophila. Since UEX is the only CNNM protein in the fly, it may serve all the roles of the four individual mammalian CNNMs. However, the ability of mouse CNNM2 to restore memory capacity to uex mutant flies suggests that the memory-relevant UEX function can be substituted by that of CNNM2.
Interestingly, none of the disease-relevant variants of CNNM2 were able to complement the memory defect of uex mutant flies. The CNNM2 T568I variant substitutes a single amino acid in the second CBS domain (Arjona et al., 2014). The oncogenic protein tyrosine phosphatases of the PRL (phosphatase of regenerating liver) family bind to the CBS domains of CNNM2 and CNNM3 and can inhibit their Mg 2+ transport function (Hardy et al., 2015;Giménez-Mascarell et al., 2017;Zhang et al., 2017). It will therefore be of interest to test the role of the UEX CBS domains and whether fly PRL-1 regulates UEX activity.
RNA-seq analysis reveals that uex is strongly expressed in the larval and adult fly digestive tract and nervous systems, as well as the ovaries (Gelbart and Emmert, 2010;Croset et al., 2018;Davie et al., 2018) suggesting that many uex mutations will be pleiotropic. Our uexD allele, which deletes 272 amino acids (including part of the second CBS and the entire CNBH domain) from the UEX C-terminus, results in developmental lethality when homozygous, demonstrating that uex is an essential gene. Mammalian CNNM4 is localized to the basolateral membrane of intestinal epithelial cells (Yamazaki et al., 2013). There it is believed to function in transcellular Mg 2+ transport by exchanging intracellular Mg 2+ for extracellular Na + following apical entry through TRPM7 channels. Lethality in Drosophila could therefore arise from an inability to absorb sufficient Mg 2+ through the larval gut. However, neuronally restricted expression of uex RNAi with elav-GAL4 also results in larval lethality (data not shown), suggesting UEX has an additional role in early development of the nervous system, like CNNM2 in humans and zebrafish (Arjona et al., 2014;Accogli et al., 2019). Perhaps surprisingly, flies carrying homozygous or trans-heterozygous combinations of several hypomorphic uex alleles have defective appetitive and aversive memory performance, yet they seem otherwise unaffected.
Genetically engineering the uex locus to add a C-terminal HA tag to the UEX protein allowed us to localize its expression in the brain. Labeling is particularly prominent in all major classes of KCs. Restricting knockdown of uex expression to all ab KCs of adult flies, or even just the ab c subset reproduced the LTM defect. The LTM impairment was evident if uex RNAi expression in ab neurons Video 3. Expression of UEX in a rut 2080 Drosophila brain. Confocal Z-stack of a brain from a rut 2080 ; uex:: HA fly stained with anti-HA antibody. The ab c Kenyon cells label more prominently than in the wild-type uex:: HA brain in Video 2.

https://elifesciences.org/articles/61339#video3
Video 4. Expression of UEX in a dnc 1 Drosophila brain. Confocal Z-stack of a brain from a dnc 1 ; uex::HA fly stained with anti-HA antibody. The ab c Kenyon cells label more prominently than in the wild-type uex::HA brain in Video 2. was restricted to adult flies, suggesting UEX has a more sustained role in neuronal physiology. In contrast, knocking down uex expression in either the ab s or a 0 b 0 neurons did not impair LTM. Activity of a 0 b 0 neurons is required after training to consolidate appetitive LTM (Krashes and Waddell, 2008), whereas ab c and ab s KC output, together and separately, is required for its expression (Krashes and Waddell, 2008;Perisse et al., 2013). Therefore, observing normal LTM performance in flies with uex loss-of-function in ab s and a 0 b 0 neurons argues against a general deficiency of ab neuronal function when manipulating uex.

https://elifesciences.org/articles/61339#video4
Dietary Mg 2+ could not enhance the defective LTM performance of flies that were constitutively uex mutant, or harbored ab KC-restricted uex loss-of-function. However, expressing uex in the ab KCs of uex mutant flies restored the ability of Mg 2+ to enhance performance. Therefore, the ab KCs are the cellular locus for Mg 2+enhanced memory in the fly.
It perhaps seems counterintuitive that UEX-directed magnesium efflux is required in KCs to support the memory-enhancing effects of Mg 2+ feeding, when dietary Mg 2+ elevates KC [Mg 2+ ] i . At this stage, we can only speculate as to why this is the case. We assume that the brain and ab KCs, in particular, have to adapt in a balanced way to the higher levels of intracellular and extracellular Mg 2+ that result from dietary supplementation. Our live-imaging of KC [Mg 2+ ] i in wild-type and uex mutant brains suggests that UEX-directed efflux is likely to be an essential factor in the active, and perhaps stimulus-evoked, homeostatic maintenance of these elevated levels.
A number of mammalian cell-types extrude Mg 2+ in a cAMP-dependent manner, a few minutes after being exposed to b-adrenergic stimulation (Romani and Scarpa, 2000;Vormann and Günther, 1987;Jakob et al., 1989;Romani and Scarpa, 1990b;Romani and Scarpa, 1990a;Vormann and Günther, 1987;Günther et al., 1990;Howarth et al., 1994). The presence of a CNBH domain suggests that UEX and CNNMs could be directly regulated by cAMP. We tested the importance of the CNBH by introducing an R622K amino acid substitution that should block cAMP binding in the UEX CNBH. This subtle mutation abolished the ability of the uex R622K transgene to restore LTM performance to uex mutant flies. We also used CRISPR to mutate the CNBH in the native uex locus. Although deleting the CNBH from CNNM4 abolished Mg 2+ efflux activity (Chen et al., 2018), flies homozygous for the uex T626NRR lesion were viable, demonstrating that they retain a sufficient level of UEX function. However, these flies exhibited impaired immediate and long-term memory. In addition, the performance of uex T626NRR flies could not be enhanced by Mg 2+ feeding. These data demonstrate that an intact CNBH is a critical element of memory-relevant UEX function. Binding of clathrin adaptor proteins to the CNNM4 CNBH has been implicated in basolateral targeting (Hirata et al., 2014), suggesting that UEX T626NRR might be inappropriately localized in KCs. Furthermore, KC expression of the CNNM2 E122K mutant variant, which retains residual function Video 5. KC-expressed MagIC responds to Mg 2+ application. Confocal time-series recording from a c739/+; UAS-MagIC/+ fly brain shows an increase in Venus, but not mCherry, fluorescence signal in response to 20 mM MgCl 2 application. https://elifesciences.org/articles/61339#video5 but has a trafficking defect (Arjona et al., 2014), did not restore the uex LTM defect.
Although it has been questioned whether the CNNM2/3 CNBH domains bind cyclic nucleotides (Chen et al., 2018), we found that FSK evoked an increase in ab KC [Mg 2+ ] i that was sensitive to uex mutation, and that UEX::HA was mislocalized in rut 2080 adenylate cyclase  and dnc 1 phosphodiesterase (Dudai et al., 1976) learning defective mutant flies. Whereas UEX::HA label was evenly distributed in g, ab c , and ab s KCs in wild-type flies, UEX::HA label was diminished in the g and ab s KCs and was stronger in ab c neurons in rut 2080 and dnc 1 mutants. The chronic manipulations of cAMP in the mutants are therefore consistent with cAMP impacting UEX localization, perhaps by interacting with the CNBH. In addition, altered UEX localization may contribute to the memory defects of rut 2080 and dnc 1 flies.
Our physiological data using Magnesium Green in mammalian cell culture and the genetically encoded MagIC reporter in ab KCs demonstrate that fly UEX facilitates Mg 2+ efflux. Stimulating the fly brain with FSK evoked a greater increase in ab KC [Mg 2+ ] i in uex mutant brains than in wild-type controls which provides the first evidence that UEX limits a rise in [Mg 2+ ] i in Drosophila KCs. Our MagIC recordings also revealed a slow oscillation (centered around 0.015 Hz, approximately once a minute) of ab KC [Mg 2+ ] i that was dependent on UEX. We do not yet understand the physiological function of this [Mg 2+ ] i fluctuation although it likely reflects a homeostatic systems-level property of the cells. Biochemical oscillatory activity plays a crucial role in many aspects of cellular physiology (Novák and Tyson, 2008). Most notably, circadian timed fluctuation of [Mg 2+ ] i links dynamic cellular energy metabolism to clock-controlled translation through the Mg 2+ sensitive mTOR (mechanistic target of rapamycin) pathway (Feeney et al., 2016). It is therefore possible that slow Mg 2+ oscillations could unite roles for cAMP, UEX, energy flux (Plaç ais et al., 2017), and mTOR-dependent translation underlying LTM-relevant synaptic plasticity (Casadio et al., 1999;Huber et al., 2000;Beaumont et al., 2001;Hou and Klann, 2004;Hoeffer et al., 2008).

Contact for reagent and resource sharing
A full list of reagents can be viewed in the Key Resources Table. Further information and requests for resources and reagents should be directed to and will be fulfilled by the Lead Contact, Scott Waddell (scott.waddell@cncb.ox.ac.uk).

Experimental model and subject details Fly strains
Unless stated otherwise, flies were raised on standard cornmeal food under a 12 hr light-dark cycle at 60% humidity and 25˚C. Test and control flies for GAL80 ts experiments were raised at 18˚C. Mixed sex flies 1-7-days-old were used in experiments.
UAS-uex R622K transgenic flies were generated similar to UAS-uex flies. A missense mutation was introduced at codon 622 of UEX within the CNBH domain, mimicking that previously engineered in the cAMP-binding domain of the regulatory subunit of protein kinase A (Bubis et al., 1988). The mutation changes the CGT codon encoding Arg into AAA encoding Lys. The mutation was introduced into the wild-type uex CDS using Gibson Assembly Master Mix (New England Biolabs, E2621S) as described in 'Improved methods for site-directed mutagenesis using Gibson Assembly Master Mix' (NEB Application Note). The primer sets used are detailed in the Resource Table. The product of Gibson assembly was further amplified by PCR and the resulting product was cloned into the pUAST vector and sequenced. Transgene insertions were mapped as for UAS-uex and one of two insertions mapped to the third chromosome was used in behavior experiments.
UAS-CNNM2, UAS-CNNM2 E122K , UAS-CNNM2 E357K , UAS-CNNM2 S269W , and UAS-CNNM2 T568I transgenic fly lines were generated by transformation with pUAST constructs containing wild-type or point mutated versions of a mouse CNNM2 cDNA tagged with HA (mCNNM2::HA), described in Arjona et al., 2014. Wild-type or mutated versions of CNNM2 were amplified from original mCNNM2::HA clones in pCiNEO_IRES_GFP plasmids (Arjona et al., 2014). Primers are detailed in the Resource Table. PCR products were digested with XhoI and XbaI and ligated into the complementary sites in pUAST. Insertions of each construct on the third chromosome were identified by mapping as described above and were used in the behavior experiments. Note that all CNNM2 encoding constructs used in the study are HA tagged, although the notation is often omitted for brevity.
UAS-MagFRET-1 transgenic fly lines were generated by transformation with pJFRC-MUH constructs containing MagFRET-1 CDS, which was sub-cloned from the pCMVMagFRET-1 plasmid, described in Lindenburg et al., 2013. Primers are detailed in the Resource Table. PCR products were digested with XhoI and XbaI and ligated into the complementary sites in pJFRC-MUH. Insertion of the construct was mediated by the site-specific transgenesis system and the landing site is attP2 (on the third chromosome).
UAS-MagIC and UAS-MARIO transgenic fly lines were generated by transformation with pTW constructs containing the MagIC/MARIO CDS, which were sub-cloned from the plasmids MagIC/ pcDNA3 and MARIO/pcDNA3, kindly provided by T. Nagai: (Maeshima et al., 2018 andKoldenkova et al., 2015). MagIC/MARIO CDS were first PCR amplified from MARIO/pcDNA3 and MagIC/pcDNA3 respectively and were cloned into the pENTR/D-TOPO vector. Primers are detailed in the Resource Table. Note that the MARIO sense primer was designed to overlap with the sequence of pcDNA3 at the insertion site of MARIO. MagIC/MARIO CDS were further cloned into the Gateway destination vector pTW (Drosophila Gateway Vector Collection).
The CRISPR/Cas9 edited uexD locus was generated commercially by GenetiVision. The editing scheme is shown in Figure 2-figure supplement 2C. The uex locus sits in reverse orientation on chromosome 2R, spanning a 49,141 bp region between position 3,900,285 and 3,949,425 (FlyBase, Release 6). The following description relates to these coordinates within the uex locus. To generate uexD, two gRNA plasmids and one double strand DNA donor (dsDNA) plasmid were constructed and injected into nos-Cas9 embryos (BDSC, 54591). As indicated in Figure 2-figure supplement 2C and detailed in the Resource Table, the upstream gRNA1 lies in Exon 6 and targets sequence 30,930.30,952. The corresponding downstream gRNA2 lies between Exon 7 and Exon 8 between 33,988 and 34,010. Both gRNAs were individually cloned into pCFD3-dU63gRNA (Addgene, 49410). The cut site of gRNA1 should be between 30,946 and 30,947 while gRNA2 should lead to a cut between 33,993 and 33,994. A 795 bp upstream homology arm (30,152.30,946) and 977 bp downstream homology arm (33,994.34,970) were cloned into the donor DNA plasmid. A termination codon (STOP, in all three reading frames) was inserted between the two homology arms and followed by a GFP cassette driven by a 3xP3 promoter. The donor DNA backbone was engineered by GenetiVision and the complete donor sequence for the uexD line is available upon request. Successful editing was identified by expression of GFP in the fly eyes and confirmed by genomic PCR and sequencing. In the uexD flies, a 3047 bp fragment from 30,947 to 33,993 was replaced by the sequence between the two homology arms in the donor plasmid, mainly the STOP signal and GFP cassette. The uexD allele truncates the uex ORF. Primers used for genomic PCR verification are detailed in the Resources Table. The nos-Cas9 transgene (on X chromosome) was removed by crossing.
CRISPR/Cas9-edited uex::HA flies were generated by WellGenetics using the ScarlessDsRed system developed by Kate O'Connor-Giles' lab (unpublished, original plasmid donated to Addgene, #80822). A 6XHA tag was fused in frame to the carboxy-terminus of UEX by inserting the 6XHA-coding sequence immediately prior to the native STOP codon in the uex locus (Figure 3-figure supplement 1A). The process involved two main steps. In step 1, a 6XHA tag together with a pBAC transposon containing a DsRed cassette were inserted in frame with the STOP codon of uex using CRISPR/Cas9-mediated genome editing by homology-directed repair (HDR) using 1 gRNA and one dsDNA plasmid donor. The gRNA lies À50 bp from the uex STOP codon and should direct a cut between 48,587 and 48,588. The gRNA was cloned into a pCFD3-dU63gRNA plasmid. A 1,200 bp upstream arm (47,438.48,637) and 1,033 bp downstream arm (48,641.49,673) were cloned into the donor DNA plasmid with the pUC57-Kan (2579 bp) backbone. See Resource Table for gRNA and primer sequences. A Protospacer Adjacent Motif (PAM) mutation (TCC to TCG,48,581.48,583) was introduced in the donor to promote HDR. A 6XHA tag, followed by a pBAC transposon containing a 3XP3 promoter-driven DsRed cassette, was inserted between the two homology arms. A pBAC recognition motif TTAA is embedded in the STOP codon of 6XHA. The complete donor sequence is available upon request. Donor and gRNA plasmids were injected into nos-Cas9 embryos (NIG-FLY, CAS0002). Successful editing was identified by expression of DsRed in the fly eyes and confirmed by genomic PCR and sequencing. Six independent positive lines were identified and four passed PCR validation. Of these four lines, one further passed sequencing validation and is the intermediate line represented in Figure 3-figure supplement 1A. Four isogenized and balanced stocks were established from this line. In step 2, the DsRed selection marker was excised by PiggyBac (PBac) transposition with the helper line Tub-PBac (BDSC,8285). Five homozygous viable lines with successful excision were validated by genomic PCR and sequencing. One designated uex::HA was used in experiments in the manuscript.
To construct the CRISPR/Cas9-edited uex T626NRR flies, we designed and cloned a gRNA and designed and ordered (Sigma) a single-stranded oligo-deoxynucleotide (ssODN). gRNA and ssODN sequences are detailed in the Resource Table. As we planned to make a single amino acid substitution R622K in the UEX CNBH domain, the 120 bp ssODN donor was centered on codon R622 and carries the codon change CGT to AAA (at 31,179.31,181) corresponding to R622K. The expected cut site of the gRNA (between 31,192 and 31,193) is only 11 bp away from the expected mutation point. To enhance the likelihood of HDR, which is reportedly low using ssODN as donor, we commercially (GenetiVision) injected editing material into 250 lig4 KO vasa-Cas embryos (Zimmer et al., 2016). We obtained 37 viable G0 flies from the injected embryos. A total of 224 G1 flies were subjected to single fly genomic PCR and sequencing to screen for the expected mutation. Primers detailed in Resource Table. We identified 59 putative edited lines from first-round screening, and of these 12 were confirmed. Despite using lig4 KO vasa-Cas9, we detected only non-homologous end joining (NHEJ) events instead of HDR-mediated point mutations. Of the 12 edited lines, six were homozygous lethal and the other six were viable. In four of the homozygous viable lines, we found a replacement of G with T at position 31,192 together with a 6 bp in frame insertion of ATCTTC between 31,192 and 31,193. This NHEJ editing corresponds to the T626 ! NRR change in the protein sequence of UEX ( Figure 5A). The X chromosome vasa-Cas9 was removed from these lines by crossing and one line referred to as uex T626NRR was used in the behavior experiments in the manuscript.
Appetitive immediate and later memory experiments were performed essentially as described (Krashes and Waddell, 2008;Perisse et al., 2013). Batches of 100-120 flies were starved for 21-23 hr before training in 35 ml starvation vials containing~2 ml 1% agar (as a water source) and a 2 cm Â 4 cm filter paper. Sugar papers (5 cm Â 7.5 cm) for training were prepared by soaking with 4 ml of 2 M sucrose and drying overnight. Water papers of same size were soaked with water and left overnight. For appetitive training, flies were transferred from a starvation tube to a training tube with a dry 'water' paper, and immediately attached to the training arm of the T-maze and exposed to the CSÀ odor for 2 min, followed by 30 s of clean air. Flies were then transferred to another training tube with dry sugar paper, attached to the T-maze and exposed to the CS+ odor for 2 min. Immediate memory was tested by transporting flies to the T-choice point and allowing them 2 min to choose between the two odor streams. To assay 24 hr memory, flies were removed from the training tube and transferred to standard cornmeal food vials for 1 hr, then transferred back into starvation vials for 23 hr until testing. Performance Index was calculated as the number of flies in the CS+ arm minus the number in the CSÀ arm, divided by the total number of flies. MCH and OCT were alternately used as CS+ or CSÀ and a single sample, or n, represents the average Performance Index from two reciprocally trained groups.
For behavior tests after Mg 2+ feeding, 1-2-day-old flies were housed in vials with Mg 2+ supplemented food for 1-5 days before being starved for appetitive training and testing, as described above. To make 80 mM [Mg 2+ ] food, 40 ml of 1 M MgCl 2 solution was added to 460 ml of normal liquid fly food; 1 mM [Mg 2+ ] food was made by diluting 0.5 ml 1 M MgCl 2 in 39.5 ml MilliQ water and adding it to 460 ml liquid food. Food was aliquoted and cooled to solidify. MgSO 4 and CaCl 2 supplemented food was prepared the same way.
Aversive immediate and 24 hr memory experiments were conducted as previously described (Hirano et al., 2013;Perisse et al., 2016;Tully and Quinn, 1985). Groups of 100-120 flies were trained with either one cycle of aversive training, or five cycles spaced by 15 min inter-trial intervals (spaced training). For aversive immediate memory, flies were tested after one-cycle training. Aversive 24 hr memory was tested using two different protocols. In the fasting-facilitated protocol, flies were starved for 16 hr before one-cycle training (Hirano et al., 2013). For spaced training, flies were not starved before training. Flies were fed on normal fly food for 24 hr after fasting-facilitated and spaced training, before being tested for memory performance. During each aversive training cycle, flies were exposed for 1 min to a first odor (CS+) paired with twelve 90 V electric shocks at 5 s intervals. Following 45 s of clean air, a second odor (CSÀ) was presented for 1 min without shock. Performance Index was calculated as the number of flies in the CSÀ arm minus the number in the CS+ arm, divided by the total number of flies. MCH and OCT were alternately used as CS+ or CSÀ and a single sample, or n, represents the average Performance Index from two reciprocally trained groups.
Sensory acuity tests (Figure 2-source data 1) were performed as described (Keene et al., 2004;Keene et al., 2006;Schwaerzel et al., 2003) with modifications. To test olfactory acuity, untrained flies were given 2 min to choose between a diluted odor as used in conditioning and air bubbled through mineral oil in the T maze. An Avoidance Index was calculated as the number of flies in the air arm minus the number in the odor arm, divided by the total number of flies. Electric shock avoidance was performed and calculated similarly. Untrained flies chose for 1 min between two tubes containing electric grids, but only one was connected to the power source. An avoidance index was calculated as the number of flies in the non-electrified arm minus the number in the electrified arm, divided by the total number of flies. To assess sugar acuity, starved flies were given 2 min to choose between an arm of the T-maze containing a dried sugar paper and the other containing a dried 'water' filter paper. Both papers were prepared as in the appetitive memory assays. A Preference Index was calculated as the number of flies in the sugar arm minus that in the other arm, divided by the total number of flies. We found that keeping the light on in the behavioral room and having air flow running through the testing tubes greatly enhanced the Preference Index in wild-type flies and therefore applied those conditions for all sugar preference testing.

Anti-UEX antibody and western blot
A polyclonal UEX antibody was developed commercially by Eurogentec. Two peptides were synthesized as antigens: Peptide 1 H-CLPKLDDKFESKQSKP-OH (16aa) and Peptide 2 H-CVDNRTK TRRNRYKKA-NH2 (16aa) and injected into rabbits. Only Peptide 2 induced a robust immune response and was processed further. The final serum was purified against Peptide 2 and used for western blot analysis as a 1:2000 dilution.
For each sample in western blot, proteins were extracted from 20 fly heads by homogenizing thoroughly in 120 ml of protein sample buffer containing a mixture of 30 ml 2-mercaptoethanol (Bio-Rad), 270 ml 4Â Laemmli sample buffer (BioRad), and 900 ml Nuclease Free Water (Invitrogen). Samples were then boiled on a 100˚C heat block for 3 min and centrifuged for 10 min before loading. A sample volume equivalent to four heads was loaded into each SDS-PAGE gel lane. Proteins were transferred to PVDF membrane and blocked in 5% skim milk for 1 hr at 25˚C with 35 rpm agitation. Membrane was then incubated in anti-UEX solution (1:2000 rabbit anti-UEX in 5% skim milk) overnight at 4˚C with 35 rpm agitation. Membrane was washed quickly three times followed by 3 Â 10 min washes in TBST solution (100 ml of TBS 10Â solution, BioRad, diluted in 900 ml of MilliQ water, with 0.1% Tween 20) and then incubated with HRP-conjugated secondary antibody solution (1:5000 of goat anti-rabbit in 5% skim milk) for 1-2 hr at 25˚C with 35 rpm agitation. The membrane was again washed quickly for three times followed by 3 Â 10 min washes in TBST. Protein bands were visualized using Pierce ECL western blotting substrate (Life technologies, 32134). Membrane was then stripped using Millipore ReBlot Plus Mild solution (Merck, 2502), blocked again in 5% skim milk, and probed with mouse anti-Tubulin primary antibody (1:2000, Sigma, T6199) and corresponding HRP conjugated goat anti-mouse secondary antibody (1:5000) following the protocol detailed above.

Immunostaining
Immunostaining was performed as described (Wu and Luo, 2006). Brains from 1-to 5-day-old adult flies were dissected in PBS and fixed for 20 min in PBS with 4% paraformaldehyde at room temperature. They were then washed twice briefly in 0.5% PBT (2.5 ml Triton-X100 in 497.5 ml PBS) and three 20 min washes. Brains were then blocked for 30 min at room temperature in PBT containing 5% normal goat serum and then incubated with primary and secondary antibodies with mild rotation (35 rpm) at 4˚C for 1 or 2 days. Primary antibodies were rabbit anti-GFP (1:250; Invitrogen A11122) and rabbit anti-HA (1:250, NEB 3724T). Alexa 488-conjugated goat anti-rabbit (1:250; Invitrogen, A11034) was the secondary antibody. Before and after the secondary antibody incubation, brains were subjected to two quick washes followed by three 20 min washes in 0.5% PBT. Stained brains were mounted on glass slides in Vectashield (Vector Labs H1000) and imaged using a Leica TCS SP5 confocal microscope at 40Â magnification (HCX PL APO 40Â, 1.3 CS oil immersion objective, Leica). Image stacks were collected at 1024 Â 1024 resolution with 1 mm steps and processed using Fiji (Schindelin et al., 2012). For quantification in Figure 3G and H, rectangular ROIs of approximately 40 Â 25 mm for the for g lobe, or round ROIs with diameter of 15 mm for ab, a'b', and EB were manually drawn on a single section of a z-stack scan of the fly brain. Corresponding ROIs were also drawn on the superior medial protocerebrum (SMP) as a background control region, and the mean fluorescence was calculated using ImageJ. ROI intensity of the MB lobes and the EB was normalized to that of the respective SMP intensity. An average between left and right brains was used for a single data point. For quantification in Figure 7C and D, ROIs are indicated in the figures and ROI intensity was calculated similar to results in Figure 3H. In Figure 7C, a line was drawn through the widest part of the tip of the a lobe. The intensity profile of this line was obtained through ImageJ. Thirty data points in the middle of such a profile spanning about a 15 mm line were extracted for each line profile. The profile was further normalized to the mean value of the first five data points (F 0 ) and calculated as (FÀF 0 )/F 0 . Mean values of these normalized profiles from different brains were plotted ( Figure 7C, middle panel). Left and right profiles of brains were calculated and are separately displayed. In Figure 7D, the relative intensities from different ROIs representing different regions are added together to generate a total intensity measure for the MB.
The human CNNM4 cDNA expression construct used to investigate Mg 2+ efflux in cell culture is that described previously (Yamazaki et al., 2013). A construct expressing Drosophila uex was generated by inserting a FLAG tag in front of the STOP codon of the uex CDS. FLAG-tagged CNNM4 and uex cDNAs were subsequently inserted into pCMV tag-4A (Agilent) for expression in HEK293 cells. HEK293 cells were cultured in Dulbecco's modified Eagle medium (Nissui) supplemented with 10% Fetal Bovine Serum (FBS) and antibiotics. Expression plasmids were transfected with Lipofectamine 2000 (Invitrogen).
For immunostaining, cells were fixed with 3.7% formaldehyde in PBS for 20 min and then permeabilized with 0.2% Triton X-100 in PBS for 5 min, both at room temperature. They were next blocked with PBS containing 3% FBS and 10% bovine serum albumin (blocking buffer) for 1 hr at room temperature. Cells were then incubated overnight at 4˚C with rabbit anti-FLAG antibody (F7425, Sigma-Aldrich) diluted in blocking buffer, washed 3Â with PBS, and incubated for 1 hr at room temperature with Alexa 488-conjugated anti-rabbit IgG (Invitrogen) and rhodamine-phalloidin (for F-actin visualization, Invitrogen) diluted in blocking buffer. After three washes with PBS, coverslips were mounted on slides and imaged with a confocal microscope (FluoView FV1000; Olympus).
Mg 2+ -imaging with Magnesium Green was performed as described (Yamazaki et al., 2013), with slight modifications. To avoid potentially decreasing [Mg 2+ ] i with the expressed proteins, transfected HEK293 cells were cultured in growth media supplemented with 40 mM MgCl 2 until imaging. Cells were then incubated with Mg 2+ -loading buffer (78.1 mM NaCl, 5.4 mM KCl, 1.8 mM CaCl 2 , 40 mM MgCl 2 , 5.5 mM glucose, and 5.5 mM HEPES-KOH [pH 7.4]), including 2 mM Magnesium Green-AM (Invitrogen), for 30 min at 37˚C. Cells were then rinsed once with loading buffer and viewed with an Olympus IX81 microscope equipped with an ORCA-Flash 4.0 CMOS camera (Hamamatsu) and a SHI-1300L mercury lamp (Olympus). Fluorescence was measured every 20 s (excitation at 470-490 nm and emission at 505-545 nm) under the control of Metamorph software (Molecular Devices). Buffer was then changed to Mg 2+ free buffer (MgCl 2 in the loading buffer was replaced with 60 mM NaCl). Data are presented as line plots (mean of 10 cells). After imaging, cells were fixed with PBS containing 3.7% formaldehyde and subjected to immunofluorescence microscopy to confirm protein expression.

FRET-based Mg 2+ concentration measurements in fixed fly brains
One-to two-day-old flies with genotype c739; UAS-MagFRET-1 were housed in vials with 1 mM or 80 mM [Mg 2+ ] food for 4 days before being collected. Fly brains were dissected in PBS and fixed for 20 min in PBS with 4% paraformaldehyde at room temperature. They were then washed twice briefly in 0.5% PBT (2.5 ml Triton-X100 in 497.5 ml PBS) and three 10 min washes. Brains were then mounted on glass slides in Vectashield (Vector Labs H1000) and imaged using a wide-field Scientifica Slicescope with a 40Â, 0.8 NA water-immersion objective and an Andor Zyla sCMOS camera with Andor Solis software (v4.27). In order to get the FRET ratio that indicates the Mg 2+ concentration of the ab neuron, time series were acquired alternatively between the cerulean channel and the citrine channel at 3 Hz with 512 Â 512 pixels and 16 bit. The excitation wavelength for both channels is 436 nm, while the emission filter for cerulean is 460-500 nm and that for citrine is 520-550 nm. Series acquisition starts from the cerulean channel and lasts for 5 s, then switches to the citrine channel and last for another 5 s, and this cycle is repeated for two more times. A total of 30 s (90 frames) image stack was therefore acquired for each brain. Image stacks were subsequently analyzed using ImageJ and custom-written Matlab scripts. In brief, rectangle ROIs ( Figure 1E, left panel) were manually drawn on the ab lobes (one on a lobe and one on b lobe for each hemisphere), and outside the ab lobes (one for each hemisphere) as background control. Fluorescence intensity from the cerulean channel was calculated by dividing each vertical or horizontal lobe ROI by the background ROI, and averaged between the two hemispheres for each lobe, and averaged over the 15 frames for each cycle. That from the citrine channel was obtained similarly. A FRET ratio was obtained from the above intensities, further averaged among the three cycles of acquisition, depicted as one data point in Figure 1E (right panel).

Confocal Mg 2+ imaging in explant fly brain
Explant brains expressing c739-GAL4 driven UAS-MagIC were placed at the bottom of a 35 mm glass bottom microwell dish (Part No. P35G-1.5-14 C, MatTek Corporation), beneath extracellular saline buffer solution (103 mM NaCl, 3 mM KCl, 5 mM N-Tris, 10 mM trehalose, 10 mM glucose, 7 mM sucrose, 26 mM NaHCO 3 , 1 mM NaH 2 PO 4 , 1.5 mM CaCl 2 , 4 mM MgCl 2 , osmolarity 275 mOsm [pH 7.3]) following dissection in calcium-free buffer . To determine the Mg 2+ sensitivity of UAS-MagIC as well as the response of UAS-MagIC to other chemicals such as EDTA, EGTA, and CaCl 2 ( Figure 8B), brains were incubated in the saline buffer solution with 20 mg/ml digitonin for 6 min before imaging (Koldenkova et al., 2015). To investigate the Mg 2+ fluctuation in response to Forskolin (FSK) application ( Figure 8C-I), brains were put in the saline buffer solution without digitonin or incubation. In both situations, saline refers to the buffer (either with or without digitonin) in which the brain is submerged.
Imaging was carried out in a LSM780 confocal microscope (Zeiss) with a 20Â air objective using the ZEN 2011 software. The Venus part of MagIC was excited with a 488 nm laser and its emission was collected in the 520-560 nm range. mCherry was excited with a 561 nm laser and its emission was collected in the 600-640 nm range. Time series were acquired at 0.5 Hz with 512 Â 512 pixels and 16 bit. Following 60 s of baseline Venus/mCherry measurement, 2-20 ml of saline or other relevant chemical solution was added via a micropipette to the dish with constant image capture. The effects of applied agents on Venus/mCherry emission were then recorded for 15-20 min.
Image stacks were subsequently analyzed using ImageJ and custom-written Python scripts. In brief, rectangle ROIs were manually drawn on the ab neurons (one for each hemisphere, Figure 8A), and another ROI of the same size was drawn in the middle but outside the MBs as background control. Fluorescence intensity from the Venus (or mCherry) channel was calculated by subtracting the background ROI from the calyx ROIs, respectively, and averaged between the two hemispheres. This is referred as 'Rel. Intensity (a.u.)' in Figure 8D and E. The ratio between Venus and mCherry intensity was calculated as 'MagIC Ratio' in Figure 8B and C and Figure 8F and G. For Figure 8H, the intensity for the two channels was calculated separately. In this case, 'Rel. Intensity (DF/F 0 )' refers to the relative fluorescence intensity normalized to the mean intensity from the baseline period F 0 , calculated as (FÀF 0 )/F 0 . The relative intensity DF/F 0 of Venus was used to calculate the PSD ( Figure 8I) through python function psd (under matplotlib.pyplot), which adopted a Welch's average periodogram method (Bendat et al., 2000).

Reverse transcription and quantitative real-time PCR
For each sample, 120 flies were frozen in liquid nitrogen and their heads were homogenized completely in TRIzol reagent (Invitrogen). Total RNA was extracted using Direct-zol RNA MiniPrep (R2050) kit following the manufacturer's instructions. cDNA was synthesized using SuperScript III First-Strand synthesis System (Invitrogen). Five independent samples were prepared for each different treatment or genotype. Quantitative PCR was performed in triplicate for each cDNA sample on a LightCycler 480 Instrument (Roche) using SYBR Green I Master Mix (Roche). Melting curves were analyzed after amplification, and amplicons were visualized by agarose gel electrophoresis to confirm primer specificity. Relative transcript levels were calculated by the 2 -DDCt method (Livak and Schmittgen, 2001), and the geometric mean of the C t values of three reference genes (Gapdh, Tbp, and Ef1a100E) was used for normalization. Primers are detailed in the Resource Table. Inverse PCR Inverse PCR was used to map the MiMIC insertion position in uex MI01943 flies. Genomic DNA was prepared from 15 adult flies. DNA equivalent to two flies was then digested in a 25 ml restriction reaction with Mbo I and 10 ml of the product was ligated overnight at 4˚C overnight to circularize the fragments; 5 ml of the ligation product was used for inverse PCR. PCR product was purified using Exo/SAP reaction (Thermo Fisher, 78201) before being sequenced. Sequence was compared to the D. melanogaster genome (FlyBase, Release 6) by BLAST and matched uniformly to the region 3,882,886.3,882,641 on 2R, consistent with the reported uex MI01943 insertion on FlyBase. Primers detailed in the Resource Table. Protein domain prediction and alignment Protein sequence alignment was carried out using Geneious R10.2.2. Protein domain prediction was performed with InterPro (Finn et al., 2017;Jones et al., 2014) and Phyre 2 . Protein domain and structure alignment was performed using TM-align (Zhang and Skolnick, 2005). Protein structure visualization was rendered in Chimera 1.11.2 (Pettersen et al., 2004).

Quantification and statistical analyses
Behavior data were analyzed using Excel and Prism 6. Imaging data were analyzed using ImageJ and custom-written MATLAB or Python scripts. Unpaired two-tailed t-tests were used for comparing two groups, and one-way ANOVA followed by a Tukey's post-hoc test was used for comparing multiple groups. Threshold of statistical significance was set at p<0.05.