### Fly husbandry

Flies were raised on a standard cornmeal/agar diet (6.65% cornmeal, 7.15% dextrose, 5% yeast, 0.66% agar supplemented with 2.2% nipagin and 3.4 ml l^{−1} of propionic acid). All experiments were conducted at 25 °C, 65% humidity and on a 12 h light/dark cycle, unless otherwise stated. Flies were virgin and aged to 5 h or 7 days after eclosion for experiments, unless otherwise stated. Experimental and control flies were raised in identical conditions and processed at the same time. For example, for dissections, experimental and control flies, males and females were dissected and processed at the same time on the same slide. For microCT, they were fixed at the same time, mounted in the same tube and scanned at the same time in each batch.

### Temperature-sensitive experiments

For expression of *UAS-Bax* to trigger apoptosis, flies were raised at 18 °C for 7 days after eclosion and then transferred to 29 °C for 3 days for transgene induction.

For expression of *UAS-bnlRNAi* in pupal stages and early adults, larvae were raised at 18 °C and shifted to 29 °C within the first 20 h of pupal formation and until 7 days after pupal eclosion.

For expression of *UAS-btlRNAi* in the gut epithelium or *UAS-traRNAi* in trachea, larvae were raised at 18 °C and shifted to 29 °C within the first 20 h of pupal formation and until 7 days after pupal eclosion.

### Fly stocks

The following fly stocks were used in this study: *Hand-Gal4[MI04106-TG4.0]* (BDSC 66795), *mex1-Gal4* (ref. ^{70}), *esg-Gal4* (ref. ^{71}; NP7397), *btl-Gal4* (ref. ^{72}; DGGR 109128), *trh*–*Gal4* (ref. ^{25}; GMR14D03, BDSC 47463), *vm-Gal4* (ref. ^{25}; GMR13B09, BDSC 48547), *DSRF-Gal4* (ref. ^{73}; BDSC 25753), *bnl-Gal4[MI00874-TG4.1]* (this study, see below for details), *bnl[lexA]* (a gift from S. Roy; ref. ^{31}), *QF6* (a gift from J. Cordero; ref. ^{74}), *UAS-traRNAi.TRiPJF03132* (BDSC 28512), *UAS-traRNAi.GD764* (VDRC 2560), *UAS-SxlRNAi.TRiPGL00634* (BDSC 38195), *UAS-bnlRNAi.GD3070* (VDRC 5730), *UAS-btlRNAi.KK100331* (VDRC 110277), *UAS-Bax* (a gift from J. Cordero; ref. ^{75}), *UAS-myr(src)::GFP M7E* (BDSC 5432), *UAS-StingerGFP* (ref. ^{76}; BDSC 84278), *UAS-Flybow.1.1B* (used as *10xUAS-CD8::GFP;* ref. ^{77}; BDSC 56803), *QUAS-mtdTomato-3xHA* (ref. ^{74}; BDSC 30005), *13xlexAop2-IVS-myr::GFP* (ref. ^{78}; BDSC 32209), *OregonR* (ref. ^{79}), *w*^{1118} (GD control; VDRC 60000), *UAS-mCherryRNAi.Valium10* (TRiP control; BDSC 35787), *ovo*^{D1} (BDSC 1309), *UAS-Dcr-2* (BDSC 24646 and 24650), *UAS-Gal80*^{TS} (ref. ^{80}; BDSC 7108), *UASp-Sxl.alt5-C8* (used as *UAS-Sxl*; ref. ^{81}; BDSC 58484), *Ubi-EGFP.ODD, Ubi-mRFP.nls* (ref. ^{82}; BDSC 86536) and *Ldh::GFP*^{YD0852} (a gift from U. Banerjee; ref. ^{83}).

The *bnl-Gal4* line was generated through integration of a promoterless *T2A-Gal4* transgene into the MiMIC insertion *bnl[MI00874]* through recombination-mediated cassette exchange, as described in the Trojan-MiMIC technique^{84}. Like *bnl[lexA]* (ref. ^{31}), this reporter results in a *bnl* mutation and is homozygous lethal; the *bnl* coding sequence is fused to *T2A-Gal4* after the first *bnl* exon resulting in a truncated protein after translation (schematic in Extended Data Fig. 4a). Unlike *bnl[lexA]*, however, our construct does not eliminate any endogenous genomic regions and the inserted *T2A-Gal4* is under the control of the endogenous *bnl* promoters/enhancers.

### Immunohistochemistry and tissue stainings

Adult guts were dissected in PBS and then transferred to PBS in a well drawn onto a poly-l-lysine-coated slide (Sigma, P1524) using hydrophobic silicone (Intek Adhesives, Flowsil). Guts were fixed at room temperature for 20 min with 4% formaldehyde in PBS. All washes were done with PBS-T (PBS, 0.2% Triton X-100) following standard protocols. Primary antibodies were incubated overnight at 4 °C and secondary antibodies were incubated at 4 °C for 2–3 h. The following primary antibodies were used: mouse anti-DSRF 1:1,000 (Active Motif, 39093), goat anti-GFP 1:1,000 (Abcam, ab5450), rabbit anti-mCherry 1:1,000 (Abcam, ab167453), mouse anti-Prospero 1:1,000 (DSHB, MR1A) and anti-horseradish peroxidase (HRP) rhodamine (TRITC)-conjugated 1:500 (Jackson ImmunoResearch, 123-025-021). The following fluorescent secondary antibodies were used: anti-rabbit FITC-conjugated (Jackson ImmunoResearch, 711-97-003), anti-mouse Cy3-conjugated (Jackson ImmunoResearch, 715-166-150), anti-mouse Cy5-conjugated (Jackson ImmunoResearch, 715-175-151) and anti-goat FITC-conjugated (Jackson ImmunoResearch, 112-095-044) and were diluted 1:500. Guts were mounted in Vectashield with DAPI (Vector laboratories).

### Confocal microscopy

Fluorescent images were taken on a Leica SP5 confocal microscope (1.5152 µm pixel size, 8-bit, 1,024 × 1,024 pixels) or a Leica SP8 DLS confocal microscope (1.4127 µm pixel size, 8-bit, 1,024 × 1,024 pixels) with a ×10 objective and using standard PMT detectors. *Z*-stacks were acquired with *z*-step size of 5 µm.

### MicroCT scans

Adult flies were prepared for microCT using a modified version of a previously described protocol^{12}. Flies were anaesthetized with CO_{2} and transferred to an Eppendorf tube with PBS-T (PBS, 0.5% Triton X-100) for 5 min or until all the flies had sunk to the bottom of the tube. Flies were then fixed in Bouin’s fixative (Sigma, HT10132) for 16–24 h before being washed in PBS for a day with several solution changes. Flies were then stained in 1:1 Lugol’s solution (Sigma, 62650):water for 4 days. Flies were washed once in water and then mounted in p10 pipette tips as follows: two p10 pipette tips were filled with water and the small opening sealed with parafilm. About ten flies were placed end to end inside each tip and the tips were stacked by inserting the tip of one into the open end of the other and then sealing with parafilm. The relative homogeneity and symmetry of *Drosophila* samples allowed us to mount two such tip stacks side by side to double imaging throughput and still retain sufficient contrast to resolve organ structures. This allowed us to mount and scan around 40 flies per scanning session, with each p10 tip containing about 10 flies (Extended Data Fig. 1a). Flies were imaged on the following scanners with the following settings. Zeiss Xradia Versa 510: 40 kV, 75 μA, 3 W, 2.95 pixel size, 0.45 rotation step (801 projection images), LE1 filter, ×4 objective. Bruker Skyscan 1272: 40 kV, 110 μA, 4 W, CMOS camera scanning at a 2.95 μm pixel size, 0.3–0.35 rotation step, 30 μm random movement and four frame averaging. Bruker SkyScan 1172 with a 11 MP CCD detector: 40 kV, 250 μA, 10 W, 2.49 μm pixel size, 0.4 rotation step (479 projection images), 10 μm random movement and four frame averaging. For most experiments, all flies in an experiment were scanned with the same scanner. When several scanners were used, a batch factor was applied in the analysis to control for any potential differences. Images were reconstructed using the Zeiss Reconstructor software v.11 or the Bruker NRecon software, then background was subtracted and images were Gaussian smoothed in FIJI v.2.0.0-rc-69/1.52p.

### RNA-seq data

RNA-seq data were generated as previously described^{17}. RNA was extracted from three samples of 30 pooled dissected guts from each sex from wild-type flies: *w*, *Su(H)GBE-LacZ/w*; *esg-Gal4 NP7397*, *UAS-GFP*, *Tub-Gal80TS/+*. Data visualization was produced with R (v.4.2.1)^{85} using a standard volcano plot script.

### Tracheal ablations

Sets of three to five guts were dissected from *btl>myr::GFP*-expressing virgin female flies and lightly attached onto a poly-l-lysine-coated glass bottom FluoroDish (WPI, FD35-100), containing haemolymph-like HL3 saline^{86}. Guts were mounted unstretched to preserved their naturally coiled shape and avoid manual rupture of trachea spanning across gut loops. Laser ablations were focused on trachea spanning across R2, R3 and R4 regions of the midgut. Imaging and ultraviolet-laser ablation of individual tracheal branches was done with a Nikon CSU-W1 SoRa spinning disk microscope, using the NIS-Elements software. Time-lapse recordings lasted between 30 s and 5 min after tracheal ablation.

### Starvation experiments

For the microCT experiments, 7-day-old adult flies raised on the standard cornmeal/agar diet were placed in vials containing 1% agar jelly and starved for 48 h, before processing for imaging.

To assess resistance to starvation, groups of 30–35 virgin flies were transferred to vials containing 1% agar jelly and death events were recorded three or four times a day from 08:00 to 20:00, until all flies had died. Flies were transferred to fresh vials containing the same medium every 3 days during this process. Survival curves were obtained using the Kaplan–Meir estimate and the difference between curves was assessed using the log-rank Mantel–Cox test, using the GraphPad Prism (v.9.4.1) software.

### Fecundity

To assess fecundity, virgin female flies were placed with males for about 20 h for mating. Groups of three mated female flies were placed in vials containing dark media for contrast during egg counting, consisting of 5% of sucrose, 10% autolysed yeast and 1% agar. Flies were allowed to lay eggs for 24 h. Eggs were counted at days 2, 5 and 8 after mating under microscope.

### Quantifications

#### Tracheal cell numbers

DSRF-positive and StingerGFP-positive nuclei were counted in FIJI on maximum intensity projections of confocal stacks manually with the help of Cell Counter for keeping track of counted nuclei. Malpighian tubules and hindgut regions were excluded from these quantifications.

#### Tracheal filament length and branching

Tracheal filament 3D reconstruction and quantification was performed using Imaris x64 v.9.9.0 (RRID:SCR_007370) using the Filament Tracer and Batch packages (RRID:SCR_007366). Using the surfaces tool, a mask was applied to the tracheal signal channel to reduce signal background before segmentation. The filaments tool was applied using the autopath algorithm to segment all filaments between 2 and 30 µm in diameter. The batch package was used to apply the same settings to a set of images acquired at the same time and from the same microscope slide. The ‘sum of filament lengths’ was taken as the total tracheal length, ‘dendrite mean length’ was taken as the mean tracheal branch length and ‘filament number of Sholl intersections’ was taken as a proxy measurement of tracheal branching. Sholl analysis measures the average number of filament intersections on concentric spheres spaced at 1 μm diameters. Tracheal coverage was measured in FIJI, by segmenting trachea area using autothreshold from the *btl>myr::GFP* signal and representing this as a percentage of gut area. Gut area was measured in FIJI, using manual gut outlines obtained with the magnetic lasso tool in Adobe Photoshop v.25.3.1.

#### Measurement of intensity along gut length

The intensity of myr::GFP or Stinger::GFP driven by *bnl-lexA*, *bnl-Gal4* or *btl-Gal4* or the intensity of *ODD::GFP*, *nls::RFP* and *ldh::GFP*, was measured along the midgut length in FIJI from *z*-stacks projected using maximum intensity. Measurements were taken along a 30 pixel-wide line drawn manually using the freehand line tool through the centre of the gut tube along gut length. A landmark was manually placed in the centre of the R3 region and its *x*,*y* coordinate extracted. Gut length was adjusted relative to the position of the R3 landmark to give percentage position along gut length with R3 aligned between sexes at 50% gut length. In R v.3.6.0, intensity values for several flies were binned into 40 bins along gut length and the mean and standard deviation found for each bin. Code is available on GitHub through Zenodo (https://doi.org/10.5281/zenodo.10905446)^{87}.

#### Food intake

To assay the amount of food ingested, we used the standard cornmeal/agar diet supplemented with 1% FCF Blue (Sigma, 80717). For analysis of feeding ad libitum, flies were transferred from the standard diet to the 1% FCF Blue-supplemented diet and allowed to feed for 4 h. For analysis of feeding after starvation, flies were starved for 16 h in vials containing 1% agar jelly and then transferred to the 1% FCF Blue-supplemented diet and allowed to feed for 15 min. Fed flies were frozen in liquid nitrogen and transferred in groups of three to 2 ml round bottom microtubes with 0.5 ml of water and a 5 mm stainless-steel metal bead (QIAGEN, 69989). Fly tissues were homogenized using a QIAGEN TissueLyser II for 90 s at 30 Hz and the homogenates were cleared by centrifugation at 10,000*g* for 10 min. From each microtube, 0.2 ml of clear supernatant was transferred into a 96-well, flat-bottom, optically clear plate (Thermo Fisher Sterilin, 611F96). A BMG Labtech FLUOstar Omega plate reader was used to measure dye content by reading the absorbance at 629 nm.

FlyPAD assays were performed as previously described^{20,88}. Half the electrode wells of a given flyPAD arena were filled with a pellet disc of cornmeal/agar diet, punched with a 1 ml pipette tip to the exact diameter of the inner electrode circle. The remaining electrode wells were left empty to record non-feeding baseline interactions. Flies were allowed to feed in the flyPAD arenas for 1 h, at 25 °C and 65% humidity. The Bonsai software was used to register capacitance and a MATLAB R2023b custom script was used to extract the total number of sips per fly during 1 h (ref. ^{89}). All flyPAD experiments were performed at the same time of day between 10:00 and 13:00. Data for experimental and control genotypes used for comparison were always acquired in the same flyPAD assay.

#### Intestinal transit

To assess intestinal transit, groups of 30 virgin flies raised on standard cornmeal/agar diet were starved for 16 h in vials containing 1% agar jelly and then allowed to feed for 15 min in vials containing standard cornmeal/agar diet supplemented with 0.5% bromophenol blue (BPB) sodium salt (Sigma, B5525). Fed flies were quickly frozen in liquid nitrogen. Presence of dyed food in the whole gut versus stereotypically demarcated portions of the gut (midgut, hindgut or ampulla) was visually scored from dissected guts and these guts were mounted stretched on sticky poly-l-lysine-coated slides and lined side-to-side from left to right with reference to the order of dissection. Guts were imaged with a Leica MZ16 FA stereomicroscope and a Nikon DS-Fi3 camera. Gut length was measured using the freehand line tool in FIJI, drawn through the centre of each gut. To compare size-matched guts, we excluded guts from the test group that had length smaller than the mean − 1 s.d. of the control group. The effect of sex and genotype on the presence of food in the whole versus portions of the gut was statistically analysed by a logistic regression using the glm function in the VGAM package v.1.1 in R v.4.2.1.

#### Intestinal excretion

To assess intestinal excretion, groups of six virgin flies raised on standard cornmeal/agar diet were transferred to 5 mm clear plastic dishes, each containing a wedge of 0.5% BPB-supplemented food and allowed to feed and excrete for 60 h (refs. ^{90,91}). Deposits left on the lids of the assay dishes were imaged using a transparency scanner (Epson Perfection V700) and quantification of the total amount of deposits was done using the T.U.R.D software^{91}.

#### Gut proliferation

Mitotic indices were quantified by manually counting phospho-histone H3-positive cells using a Nikon50i fluorescent microscope. These were quantified in young virgin flies at 7 days after pupal eclosion or in aged virgin flies at 20 days after pupal eclosion. For damage-induced regeneration assays, virgin flies were transferred to an empty vial containing a piece of 3.75 × 2.5 cm^{2} paper imbibed with 500 ml of 5% sucrose solution (control) or 5% sucrose plus 3% DSS solution. Flies were transferred to a new vial with fresh feeding paper every day for 3 days before gut dissection and quantification of mitotic indices.

#### Segmentations

ITK-snap (v.3.8.0)^{92} was used to manually segment each of the organs. For ovaries and testes, the adaptive paintbrush tool was used. For the crop, the polygon tool was first used to segment the organ perimeter in every 20–30 slices in the axial plane, followed by use of the morphological interpolation tool to fill the spaces in between these presegmented slices^{93}. We expanded this presegmented scaffold using an active contour model. For the gut, centreline traces (see below) were increased to a 5 pixel-wide line in FIJI and were imported into ITK-snap as seeds for the active contour model. For the crop and gut, the active contour model was run using the edge attraction mode with a smoothing factor of 2.5 and expansion (balloon) force, smoothing force (curvature) and edge attraction force (advection) were all set to maximums during the evolution of the model. Further manual corrections were performed using the adaptive paintbrush tool.

For visualization purposes, segmentations were converted into triangular meshes using the marching cubes algorithm run in FIJI with the Wavefront obj package. Using Meshlab (v.2020.07)^{94}, meshes were simplified using quadric edge collapse decimation to reduce the number of faces to 10% and smoothened using HC Laplacian smoothing^{95}.

Organ volumes were measured from segmentations in FIJI. The area of the segmented region was measured on each image slice, summed and multiplied by the slice depth to calculate the volume.

#### Centreline tracing

Centrelines of the gut tube were traced using the simple neurite tracer plugin (v.3.1.6)^{96} in FIJI. Images were first inverted in intensity to make the centre of the gut of highest intensity for the simple neurite tracer algorithm to follow.

#### Landmarks for defining midgut loops

Landmarks were manually marked on the microCT stacks using the FIJI multipoint tool to extract their *x*,*y*,*z* coordinates. Two landmarks were used—the distinction between the apical midgut and the midgut loops was defined as the first main inflection of the midgut, which generally correlated with the point where the midgut transitions from the thorax to the abdomen. The distinction between the midgut loops and the hindgut was defined as the transition between the midgut and the hindgut, easily recognizable morphologically in the microCT image stacks by a reduction in gut diameter and in X-ray absorbance. The *x*,*y*,*z* coordinates of these landmarks were used to subset the centrelines to the midgut loop region before further processing.

#### Geometric morphometrics and PCA analysis

We performed morphometric analysis in R (v.3.6.0) using the geomorph package (v.3.2.1)^{97,98,99}. Centreline data from simple neurite tracer were imported into R (v.3.6.0) using the nat package (v.1.8.18)^{100} and divided into 1,000 (for whole gut centrelines) or 500 (for midgut loop region centrelines) equally spaced pseudolandmarks using the geomorph package. Landmark coordinates were then aligned using a generalized procrustes analysis (GPA) to standardize for size and orientation. For visualization of the average centrelines of a group of flies, corresponding GPA aligned landmark coordinates were averaged and then plotted in 3D.

Variation in gut shape was analysed using a principal component analysis (PCA) of the GPA aligned centreline coordinates. A Procrustes type III analysis of variance (ANOVA) with random residual permutation procedures (RRPP; RRPP package v.0.5.2)^{98,99} was run to test whether variation in gut shape was significantly associated with variation in other factors using the procD.lm function. The 3D Procrustes aligned shape coordinates were set as the response variable and crop volume, genital volume, gut length, imaging batch and sex were set as the predictor variables (shape ~ sex + gonad volume + crop volume + gut length + batch; Supplementary Tables 17–19). Batch was included to control for groups of flies scanned on different scanners or the same scanner at different times. For testing the differences between the male versus female and control versus experimental groups, a model with interaction terms was used: shape ~ genotype * sex + batch * genotype + batch * sex or shape ~ genotype * sex, when only one batch was present (Supplementary Tables 12,13and 20–37). Post hoc pairwise comparisons of Procrustes distances between least squares means and variances of the groups was then conducted using the pairwise function with RRPP^{101} with shape ~ batch or shape ~ 1 as the null model where appropriate. Code is available on GitHub through Zenodo (https://doi.org/10.5281/zenodo.10905446)^{87}.

For all PCA displays, the diagrams at both ends of each principle component (PC) axis represent the extremes of variation along each PC: average shape in grey, theoretical maximum or minimum shape along each PC in black, as previously described^{102}. For all displays in this study, the average coordinates of each Procrustes landmark along the gut were used to generate the average gut centreline in grey. The black lines represent the coordinates of the landmark points from the hypothetical extremes of variation of each PC.

#### Measurements of gut length

Gut length measurements were taken from centreline length measured using the nat package v.1.8.18 in R (v.3.6.0)^{85}. Anterior midgut, midgut loops and hindgut measurements were taken from centrelines subsetted by landmarks as described above.

#### Measurements of radius

Gut segmentations were converted into triangular meshes using the marching cubes algorithm run in FIJI with the Wavefront obj package. Using Meshlab (v.2020.07)^{94}, meshes were simplified using quadric edge collapse decimation to reduce the number of faces to 10%. The radius is then estimated by finding the minimum distance between a given point on the centreline and the unsmoothed gut mesh of the segmentation. Repeating this for all points on the centreline gives the radius as a function of arclength. To smooth the radius as a function of arclength, the function LowpassFilter was implemented in Mathematica (v.13.1)^{103} with a cutoff parameter of 0.3.

#### Extraction of curvature and torsion along gut length

To approximate the curvature and torsion along the centreline obtained from simple neurite tracer, the centrelines were first parameterized using an arclength coordinate, *s*, calculated for each point on the curve by summing the lengths of the line segments leading up to it, starting from the anterior. Value *s* varies between 0 and the length of the centreline (*L*). The centreline in the vicinity of each point was approximated using a third-degree Taylor expansion of the curve position. For this, a neighbourhood of size *δ* = 0.05 × *L* was chosen around a given point on the curve, which consists of points whose distance from the point of interest is less than *δ* and then it was fitted it to a cubic polynomial using the function polyfit implemented in the Python package NUMPY^{104}:

$${\bf{x}}(s)={{\bf{x}}}^{\ast }+{{\bf{x}}}^{{\prime} }({s}^{\ast })(s-{s}^{\ast })+\frac{1}{2}{{\bf{x}}}^{{\prime\prime} }({s}^{\ast }){(s-{s}^{\ast })}^{2}+\frac{1}{6}{{\bf{x}}}^{\prime\prime\prime }({s}^{\ast }){(s-{s}^{\ast })}^{3}$$

Here, \({{\bf{x}}}^{{\prime} }\left({s}^{* }\right)\), \({{\bf{x}}}^{{\prime\prime} }\left({s}^{* }\right)\), \({{\bf{x}}}^{\prime\prime\prime }\left({s}^{* }\right)\) are the first, second and third derivatives of the position with respect to *s*, evaluated at the point whose arclength is *s**. Local curvature \(\kappa ({s}^{* })\) and torsion \(\tau ({s}^{* })\) were computed, using the Frenet–Serret formulae adapted to our parameterization and assuming the curvature is locally uniform:

$$\kappa ({s}^{\ast })=|{{\bf{x}}}^{{\prime\prime} }({s}^{\ast })|,\tau ({s}^{\ast })=\frac{({{\bf{x}}}^{{\prime} }({s}^{\ast })\times {{\bf{x}}}^{{\prime\prime} }({s}^{\ast }))\cdot {{\bf{x}}}^{\prime\prime\prime }({s}^{\ast })}{{\kappa }^{2}({s}^{\ast })}$$

This was repeated for all points on the curve to obtain local approximations of the curvature and torsion. To further smooth the curvature and torsion as a function of arclength, the function LowpassFilter with a cutoff parameter of 0.3 was implemented in Mathematica. Curvature and torsion have units of inverse length and, therefore, are not invariant with respect to scale—for example, if we double the size of the centreline without changing its shape, the curvature and torsion will decrease by a factor of two. To produce scale invariant quantities, that depend on the shape of the centreline but not its size, the normalized curvature and torsion is defined by multiplying them by the total length of the centreline. Code is available on GitHub through Zenodo (https://doi.org/10.5281/zenodo.10905446)^{87}.

#### Comparison of curvature using multidimensional scaling

To compare the curvature of two different centrelines, they were first registered to know which point on the first centreline corresponded to a given point on the second^{105}. For this, elastic distortion was minimized on the basis of the Fisher–Rao metric as described in refs. ^{106,107}, which is implemented in the Python package scikit-fda^{108}.

Once this was known, the two centrelines were compared on a regional basis, by computing the total Euclidean distance between the local morphometric biomarker (such as normalized curvature \((\widetilde{\kappa }\equiv L\times \kappa )\)), at corresponding points and averaged over the entire centrelines. For example, if the normalized curvatures of the first and second centrelines are \(\widetilde{\kappa }\)_{1}(*s*_{1}) and \(\widetilde{\kappa }\)_{2}(*s*_{2}), where *s*_{1} and *s*_{2} are the respective arclength parameters, the registration is given as the function *s*_{2} = *γ*(*s*_{1}) and the distance between two centrelines can be computed using the formula:

$${\rm{d}}{\rm{i}}{\rm{s}}{\rm{t}}({\mathop{\kappa }\limits^{ \sim }}_{1},{\mathop{\kappa }\limits^{ \sim }}_{2})=\sqrt{\frac{1}{L}\int {[{\mathop{\kappa }\limits^{ \sim }}_{1}({s}_{1})-{\mathop{\kappa }\limits^{ \sim }}_{2}(\gamma ({s}_{1}))]}^{2}{\rm{d}}{s}_{1}}.$$

To discretize the curves, with equally spaced points in the coordinate *s*_{1} (denoted as *s*_{n}, where *n* = 1, 2, …., 200), the integral was replaced with a sum,

$${\rm{d}}{\rm{i}}{\rm{s}}{\rm{t}}({\mathop{\kappa }\limits^{ \sim }}_{1},{\mathop{\kappa }\limits^{ \sim }}_{2})=\sqrt{\frac{1}{200}\mathop{\sum }\limits_{n=1}^{200}{[{\mathop{\kappa }\limits^{ \sim }}_{1}({s}_{n})-{\mathop{\kappa }\limits^{ \sim }}_{2}(\gamma ({s}_{n}))]}^{2}}$$

To calculate the relative distances between pairs of centrelines, the distances were divided by the maximum distance (across all pairs of centrelines in each analysis). Once the distance was computed for each pair of centrelines, a multidimensional scaling (MDS) algorithm was used, which converted the distances between the guts into a 3D coordinate for each gut (*μ*_{1}, *μ*_{2}, *μ*_{1}) such that the distance between each pair of points in the MDS space is as close as possible to the original computed matrices. We used the following reference to convert our distances into MDS coordinates^{109}. Once the coordinates were obtained for each group, the region occupied in the MDS space was estimated by fitting a normal distribution to the points and drawing the 95% confidence intervals.

Lastly, to test the location change of the region centrelines with experimental manipulations, the LocationTest function in Mathematica was used to compute the *P* value from several applicable tests (*t*-test, paired sample *t*-test, *Z*-test, paired sample *Z*-test, Mann–Whitney *U*-test, Sign test, Wilcoxon signed-rank test) and returned the *P* value from the most powerful test (one with the highest probability of rejecting the null hypothesis) that applies to the data. Code is available on GitHub through Zenodo (https://doi.org/10.5281/zenodo.10905446)^{87}.

#### Correlation of curvature and tracheal intensity

Average tracheal intensity along gut length was measured as described above, for the midgut not including the hindgut of *btl>myrGFP* male and female flies and correlated with the average curvature along length for *OregonR* male and female flies of the equivalent gut region. Pearson’s product moment was calculated.

#### Correlation of curvature and *bnl* intensity

Males and females were analysed separately. Curvature and *bnl* intensity were normalized so that their range is [−1, 1] for each gut to allow for comparison across them. For example, if *I*_{bnl}(*s*) is the measured intensity as a function of arclength for a single fly, the corresponding normalized intensity will be

$$\mathop{I}\limits^{ \sim }\equiv \frac{{I}_{{\rm{b}}{\rm{n}}{\rm{l}}}-min({I}_{{\rm{b}}{\rm{n}}{\rm{l}}})}{max({I}_{{\rm{b}}{\rm{n}}{\rm{l}}})-min({I}_{{\rm{b}}{\rm{n}}{\rm{l}}})}$$

with a similar expression for the centreline curvature. Each centreline curvature was paired with a *bnl* intensity curve from a fly of the same sex and an elastic registration was performed between them as mentioned above and then the Pearson correlation coefficient was computed. For the females, there are 39 measured centreline curvatures and 28 *bnl* intensity curves, leading to 39 × 28 = 1,092 correlation coefficients whose values are given in the orange histogram in Extended Data Fig. 4b. Similarly, for the males there are 41 measured centreline curvature and 27 *bnl* intensity curves, leading to 41 × 27 = 1,107 correlation coefficients whose values are given in the blue histogram in Extended Data Fig. 4b.

To obtain a control for the measured histogram, *bnl* intensity curves were simulated by fitting the actual *bnl* intensity curves to an autoregressive stochastic process (using the command ARProcess in Mathematica). Repeating the analysis above leads to the histograms shown in grey in Extended Data Fig. 4b. Code is available on GitHub through Zenodo (https://doi.org/10.5281/zenodo.10905446)^{87}.

#### Tilt

To estimate the tilt of the midgut loop region relative to the entire gut centreline, the main axis of each gut was calculated as the largest eigendirection of the covariance matrix. The covariance matrix *C* for a given set of points in 3D, where each point is labelled by the index *i* and position vector **x**_{i}, is given by

$$C=\frac{1}{n-1}\mathop{\sum }\limits_{i=1}^{n}{({{\bf{x}}}_{i}-\bar{{\bf{x}}})}^{T}({{\bf{x}}}_{i}-\bar{{\bf{x}}})$$

where *n* is the total number of points and \(\bar{{\bf{x}}}\) is the average position of all the points. The main axis of the midgut loop region is denoted by **V**_{m} and the entire gut by **V**_{g}; the angle between them was determined as *φ* = cos^{−1}(**V**_{g }. **V**_{m})/(|V_{g}||V_{m}|).

#### Measurements of proximity

The proximity between meshes was measured in R v.3.6.0. All surface meshes from the organ segmentations were simplified using quadric edge collapse decimation in Meshlab (v.2020.07)^{94} to reduce the number of faces to 1%, other than the testes apical tip meshes which contained few faces so were instead reduced to 10%. Mesh vertex coordinates were then read into R and the minimal distance between each vertex on organX and all the vertices on organY was calculated using a nearest neighbour algorithm using the RANN package (v.2.6.1)^{110}. For reference to the midgut loops of the gut or for plotting along gut length, the centreline coordinates were replotted as 100 equally spaced points using the nat package (v.1.8.18)^{100}. The centreline is then related to the gut mesh by finding the nearest 20 vertices on the mesh for every centreline point. The minimum distance of these 20 vertices to organY is then assigned to the centreline point for averaging and for plotting. For restricting to midgut loops, the landmarks were used to cut the centreline. Code is available on GitHub through Zenodo (https://doi.org/10.5281/zenodo.10905446)^{87}.

For visualization of proximities as shown in figures, the Hausdorff Distance function in Meshlab^{94,111} was used which samples each vertex of meshX and finds the closest point on meshY to generate a minimal distance value between meshes for each vertex. These minimal distances were then displayed on the mesh as a heatmap in the Paraview software (v.5.10.0)^{112}.

#### Crop duct quantifications

The directions of the crop duct leaving the proventriculus and travelling through the thorax to enter the crop were manually recorded from viewing the microCT scans from several planes in ITK-snap. Four different configurations were recorded: passing from left to right in an s-shaped pattern, passing from left to right in a straight line, staying on one side of gut and inverted passing from right to left.

Position of the crop and contact it made with the ovaries was manually scored from viewing the microCT scans in several planes in ITK-snap.

### Experimental design and statistical analyses

For each experiment, a minimum of nine samples per group were examined per genotype or condition. Fly numbers are not limiting so no power calculations were used to predetermine sample size. Oversampling was mitigated by choosing sample sizes on the basis of previous knowledge of phenotypic variability in controls and other mutants. Similar sample sizes for different animal groups (for example, downregulations versus controls) were tested in the same experimental design. Exact sample sizes are provided in the Supplementary Information. Experimental and control flies were bred in identical conditions and were randomized whenever possible (for example, with regard to housing and position in tray). Control and experimental samples were processed at the same time and mounted on the same slides for confocal imaging or the same tips for microCT scanning. All replicates were biological rather than technical and all measurements were taken from distinct samples. Experiments were typically repeated two to three times and only those experiments for which repeats resulted in comparable outcomes are included in the manuscript. Experiments were controlled for sex, mating status, genotype, age and physiological state (for example, starved or ad libitum-fed). Details are provided elsewhere in the Methods and Supplementary Information. No data points or outliers were excluded from our experiments and blinding was performed for a subset of experiments. Quantification of DSRF stainings, filament tracing of fluorescently labelled trachea and quantifications of *bnl* expression along gut length was done on data blinded for genotype. Blinding for sex was not possible as this is visually obvious by differences in the length and diameter of the *Drosophila* gut. Similarly, blinding for sex was not possible for microCT scans as ovaries and testes were visible in the images.

All statistical analyses were carried out using R including use of ‘dplyr’ package (v.1.0.10). For multiple comparisons between groups, data were analysed using one-way ANOVA followed by a post-hoc TukeyHSD test. For single pairwise comparisons, we used Student’s *t*-tests. Boxplots and line graphs were plotted in R using the ‘ggplot2’ package (v.3.4.0). For boxplots, the minimum, maximum, median, first quartile and third quartile are indicated with all data points shown as dots. In all figures, *n* denotes the number of biologically independent samples and *P* values are indicated as asterisks highlighting the significance of comparisons (non-significant (NS): *P* > 0.05; **P* < 0.05; ***P* < 0.01; ****P* < 0.001). For Procrustes ANOVA, *P* values are capped at a minimum of *P* = 0.001 as the RRPP procedure uses 1,000 iterations. Further information about sample size, *P* values and statistical tests used for each experiment can be found in the Supplementary Information.

### Reporting summary

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

Source link