OSCR

Visual recognition of the anteroposterior female body axis drives spatial elements of male courtship in Drosophila.

Code ↔ Paper

2 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 2 matches
  1. [1] § Materials and methods › Tracking, classification, and machine-assisted analyses of male courtship behavior ↔ courtship/ml/classifiers.py, lines 262–319 · score 0.64 · decision tree classifier, cross validation, accuracies
  2. [2] § Materials and methods › Tracking, classification, and machine-assisted analyses of male courtship behavior › Anterior-posterior distance ratio (DA/DP) ↔ courtship/experiment.py, lines 630–669 · score 0.55 · front half, rear half, ratio, distance, female

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 365 lines · 12 KB · MIT · 1 match

  1. # -*- coding: utf-8 -*-
  2. """
  3. .. module:: ml
  4. :synopsis: Contains class for generating classifiers.
  5. .. moduleauthor:: Ross McKinney
  6. """
  7. import pickle
  8. import sys
  9. import numpy as np
  10. import pandas as pd
  11. from sklearn.tree import DecisionTreeClassifier
  12. from sklearn.ensemble import AdaBoostClassifier
  13. from sklearn.metrics import roc_curve, auc
  14. def from_csv(csv_file):
  15. """Reads in training/testing/validation data from a .csv file.
  16. .. note:: Classified frames from all files will be concatenated
  17. into a single feature matrix and classification array.
  18. Parameters
  19. ----------
  20. csv_file : string
  21. Path to a .csv file to read.
  22. This file should have the following column names:
  23. 1. feature_matrix_file
  24. 2. start
  25. 3. stop
  26. 4. classification
  27. 5. behavior_name
  28. Returns
  29. -------
  30. X : np.ndarray | shape = [n_frames, n_features]
  31. Feature matrix for all classified frames in csv_file.
  32. y : np.ndarray | shape = [n_frames]
  33. Classification array (0 or 1) for all classified frames
  34. in csv_file.
  35. """
  36. # load csv into pandas DataFrame
  37. df = pd.read_csv(csv_file)
  38. # loop through all unique feature_matrix_files
  39. for i, unique_file in enumerate(df['feature_matrix_file'].unique()):
  40. subset = df[df['feature_matrix_file'] == unique_file]
  41. start = subset['start'].values
  42. stop = subset['stop'].values
  43. classifications = subset['classification'].values
  44. for j in range(len(start)):
  45. if j == 0:
  46. ix = np.arange(start[j], stop[j] + 1)
  47. y = np.repeat(classifications[j], stop[j] - start[j] + 1)
  48. else:
  49. ix = np.hstack((ix, np.arange(start[j], stop[j] + 1)))
  50. y = np.hstack(
  51. (y, np.repeat(classifications[j], stop[j] - start[j] + 1))
  52. )
  53. with open(unique_file, 'rb') as f:
  54. fmat = pickle.load(f)
  55. X = fmat.get_X()
  56. if i == 0:
  57. all_X = X[ix, :]
  58. all_y = y
  59. else:
  60. all_X = np.vstack((X[ix, :], all_X))
  61. all_y = np.hstack((y, all_y))
  62. return all_X, all_y
  63. def list_from_csv(csv_file):
  64. """Reads a csv file and returns all {X_train, y_train} as a list of dicts.
  65. Parameters
  66. ----------
  67. csv_file : string
  68. Path to a .csv file to read.
  69. This file should have the following column names:
  70. 1. feature_matrix_file
  71. 2. start
  72. 3. stop
  73. 4. classification
  74. 5. behavior_name
  75. Returns
  76. -------
  77. [{'X': X, 'y': y}, ...] : list of dictionaries
  78. Contains all X and y for each unique feature_matrix_file
  79. in csv_file.
  80. """
  81. # load csv into pandas DataFrame
  82. # and drop any rows that have np.nan in them
  83. df = pd.read_csv(csv_file).dropna(how='all')
  84. all_data = []
  85. # loop through all unique feature_matrix_files
  86. for i, unique_file in enumerate(df['feature_matrix_file'].unique()):
  87. subset = df[df['feature_matrix_file'] == unique_file]
  88. start = subset['start'].values
  89. stop = subset['stop'].values
  90. classifications = subset['classification'].values
  91. for j in range(len(start)):
  92. if j == 0:
  93. ix = np.arange(start[j], stop[j] + 1)
  94. y = np.repeat(classifications[j], stop[j] - start[j] + 1)
  95. else:
  96. ix = np.hstack((ix, np.arange(start[j], stop[j] + 1)))
  97. y = np.hstack(
  98. (y, np.repeat(classifications[j], stop[j] - start[j] + 1))
  99. )
  100. ix = ix.astype(np.int)
  101. print 'loading: ', type(unique_file), unique_file
  102. with open(unique_file, 'rb') as f:
  103. fmat = pickle.load(f)
  104. X = fmat.get_X()
  105. all_data.append({'X': X[ix, :], 'y': y})
  106. return all_data
  107. class Classifier(AdaBoostClassifier):
  108. """Adaboost classifier with convenience functions.
  109. Classifier inherits from sklearn.ensemble.AdaBoostClassifier,
  110. and calls super with the following parameters:
  111. super(
  112. sklearn.tree.DecisionTreeClassifier(
  113. max_depth = 2,
  114. min_samples_leaf = 1
  115. ),
  116. algorithm = 'SAMME',
  117. n_estimators = 100
  118. )
  119. Parameters
  120. ----------
  121. behavior_name : string
  122. Name of behavior that classifier is being used for.
  123. Attributes
  124. ----------
  125. training_data : list of dictionaries
  126. Each dictionary should be organized as follows, and
  127. represents ground truth data from one video/fly pair:
  128. {
  129. 'X': np.ndarray | shape = [n_frames, n_features],
  130. 'y': np.ndarray | shape = [n_frames]
  131. }
  132. validations : list of dictionaries
  133. Contains information about any cross validaition
  134. made with data in self.training_data. Keys are as
  135. follows: 'accuracy', 'fpr', 'tpr', 'auc', 'predicted_classifications',
  136. 'true_classifications'.
  137. """
  138. def __init__(self, behavior_name):
  139. dt_stump = DecisionTreeClassifier(max_depth=2, min_samples_leaf=1)
  140. super(Classifier, self).__init__(
  141. dt_stump,
  142. algorithm="SAMME",
  143. n_estimators=100
  144. )
  145. self.behavior_name = behavior_name
  146. self.training_data = None
  147. self.validations = []
  148. def load_training_data(self, training_file):
  149. """Load training data from file.
  150. This will set the attribute self.training_data
  151. to be a list containing dictionaries as entries.
  152. [{'X': X, 'y': y}, ...].
  153. Parameters
  154. ----------
  155. training_file : string
  156. Path to .csv file containing training data.
  157. """
  158. self.training_data = list_from_csv(training_file)
  159. def get_training_data(self):
  160. """Combines all training data into a single feature matrix, X,
  161. and classification array, y.
  162. Returns
  163. -------
  164. X : np.ndarray | shape = [n_frames, n_features]
  165. Feature matrix generated from all X in self.training_data.
  166. y : np.ndarray | shape = [n_frames]
  167. Classification array (0 or 1) generated from all y in
  168. self.training_data.
  169. """
  170. if self.training_data is None:
  171. print "Need to set/load training data first."
  172. return
  173. else:
  174. for i in xrange(len(self.training_data)):
  175. if i == 0:
  176. X = self.training_data[i]['X']
  177. y = self.training_data[i]['y']
  178. else:
  179. X = np.vstack((self.training_data[i]['X'], X))
  180. y = np.hstack((self.training_data[i]['y'], y))
  181. return X, y
  182. def leave_one_out(self, chunk_to_leave_out):
  183. """Splits data into two training/testing sets for leave-one-out
  184. cross validation.
  185. Parameters
  186. ----------
  187. chunk_to_leave_out : int
  188. Which item within self.training_data to leave out. This item will
  189. be used as testing data. Note that chunk_to_leave_out must be less
  190. than len(self.training_data).
  191. Returns
  192. -------
  193. X_train : np.ndarray | shape = [n_frames, n_features]
  194. Training feature matrix containing all data within
  195. self.training_data other than that specified by chunk_to_leave_out.
  196. y_train : np.ndarray | shape = [n_frames]
  197. Training classification array containing all data within
  198. self.training_data other than that specified by chunk_to_leave_out.
  199. X_test : np.ndarray | shape = [m_frames, m_features]
  200. Testing feature matrix. This should be the feature matrix contained
  201. within self.training_data at index chunk_to_leave_out.
  202. y_test : np.ndarray | shape = [m_frames]
  203. Testing classification array. This should be the classification
  204. array contained within self.training_data at index
  205. chunk_to_leave_out.
  206. """
  207. if self.training_data is None:
  208. print "Need to set/load training data first."
  209. return
  210. if chunk_to_leave_out >= len(self.training_data):
  211. print (
  212. "Error in Classifier.Classifier.leave_one_out: \n" +
  213. "chunk_to_leave_out > len(self.training_data)"
  214. )
  215. return
  216. X_train = np.zeros(1)
  217. y_train = np.zeros(1)
  218. for i in xrange(len(self.training_data)):
  219. if i == chunk_to_leave_out:
  220. X_test = self.training_data[i]['X']
  221. y_test = self.training_data[i]['y']
  222. else:
  223. if X_train.size == 1:
  224. X_train = self.training_data[i]['X']
  225. y_train = self.training_data[i]['y']
  226. else:
  227. X_train = np.vstack((self.training_data[i]['X'], X_train))
  228. y_train = np.hstack((self.training_data[i]['y'], y_train))
  229. return X_train, y_train, X_test, y_test
  230. def cross_validate(self):
  231. """Performs leave-one-out cross validation using the training
  232. data contained within self.training_data.
  233. Updates self.validations with new validation data after each
  234. iteration.
  235. """
  236. if self.training_data is None:
  237. print "Training data has not been set. Aborting."
  238. return
  239. dt_stump = DecisionTreeClassifier(max_depth=2, min_samples_leaf=1)
  240. classifier = AdaBoostClassifier(
  241. dt_stump,
  242. algorithm="SAMME",
  243. n_estimators=100
  244. )
  245. for i in xrange(len(self.training_data)):
  246. X_train, y_train, X_test, y_test = self.leave_one_out(i)
  247. classifier.fit(X_train, y_train)
  248. proba = classifier.predict_proba(X_test)
  249. fpr, tpr, _ = roc_curve(y_test, proba[:, 1])
  250. self.validations.append({
  251. 'accuracy': classifier.score(X_test, y_test),
  252. 'fpr': fpr,
  253. 'tpr': tpr,
  254. 'auc': np.round(auc(fpr, tpr), decimals=2),
  255. 'predicted_classifications': classifier.predict(X_test),
  256. 'true_classifications': y_test
  257. })
  258. print '\tAccuracy: {}'.format(
  259. np.round(self.validations[i]['accuracy'], 2)
  260. )
  261. print '\tAuc: {}'.format(
  262. self.validations[i]['auc']
  263. )
  264. sys.stdout.flush()
  265. def plot_cross_validation(self, ax, colors=['k', 'm']):
  266. """Generates plots to see how well the classifier is working.
  267. Parameters
  268. ----------
  269. ax : matplotlib.pyplot axis object
  270. Plots will be generated within this axis handle.
  271. colors : list of string, or list of tuple
  272. Colors to use for ground truth and predicted bars
  273. in eventplot.
  274. """
  275. true_where = []
  276. predicted_where = []
  277. for val in self.validations:
  278. true_where.append(
  279. np.where(val['true_classifications'])[0]
  280. )
  281. predicted_where.append(
  282. np.where(val['predicted_classifications'])[0]
  283. )
  284. true_plot_positions = np.arange(0, len(true_where)) * 3
  285. predicted_plot_positions = np.arange(0, len(true_where)) * 3 + 1
  286. ax.eventplot(
  287. true_where,
  288. lineoffsets=true_plot_positions,
  289. colors=colors[0]
  290. )
  291. ax.eventplot(
  292. predicted_where,
  293. lineoffsets=predicted_plot_positions,
  294. colors=colors[1]
  295. )

classifiers.py at commit a40249e, under MIT · at the source

Overview

Authors: Ross M McKinney1, Christian Monroy Hernandez1, Yehuda Ben-Shahar1
  1. Department of Biology, Washington University in St. Louis, St. Louis, MO 63130, United States
Institutions: Washington University in St. Louis (United States)
Journal: G3 (Bethesda, Md.), volume 16, issue 4, article jkag037
Dates: received 5 December 2025; accepted 31 January 2026; published online 16 February 2026; in print April 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1093/g3journal/jkag037 · PMID 41699762 · PMCID PMC13042310 · OpenAlex W7129641084
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: drosophila (organism), cognitive (subfield)
Methods: Machine learning
Keywords: Drosophila melanogaster, mating behavior, fruit fly, vinegar fly, machine-assisted analysis of behavior
MeSH: Body Patterning*, Courtship*, Sexual Behavior, Animal*, Visual Perception*, Animals, Female, Male (* major topic)
Journal subjects: Neurogenetics
Topic: Neurobiology and Insect Physiology Research (Cellular and Molecular Neuroscience, Neuroscience), according to OpenAlex
Funding: Howard A. Schneiderman Graduate Fellowship; Washington University in St. Louis; Genome Analysis Training Program; NIH (NS089834, ES025991, 1545778, 1707221)
Citations: cited by 1 paper (Europe PMC); 61 references in the paper

Abstract

Drosophila males exhibit a highly stereotypic courtship ritual toward virgin females, which is comprised of a sequence of specific behavioral elements that depend on inputs from diverse sensory modalities. Particularly, the visual system of the male plays an important role in detecting salient patterns, colors, and motion cues from conspecifics, which can promote or inhibit specific aspects of male courtship such as chase and song production. Here, we use a computer vision and machine learning-based approach, with a simplified courtship paradigm, to show that males also depend on visual cues to determine the anterior–posterior body axis of females, which drives the specific spatial patterns of distinct behavioral courtship elements. We show that the recognition of the female body axis depends, at least in part, on the visual recognition of female eyes as an anterior landmark. Furthermore, we find that in the absence of visual input, courting males adjust not only their relative spatial courtship positioning but also the relative frequencies at which they engage in each specific courtship element. Finally, analyses of the contributions of specific visual projection neurons to the recognition of the female body axis indicate that, although it is driven by a seemingly simple visual cue, the spatiotemporal release patterns of each individual courtship element appear to depend on the activity of multiple independent populations of visual projection neurons. Together, our results provide novel insights into the possible role of visual anatomical features in driving complex social interactions between conspecifics.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

Its files are read in the Code ↔ Paper reader above, with 2 matches between paragraphs and lines of code.

Zenodo 18274754

License: MIT
State: the link answers, verified on 28 September 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: “Data availability”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (46 files), pandas (15 files), Matplotlib (9 files), scikit-image (8 files), CircStat (4 files), SciPy (3 files), h5py (1 file), scikit-learn (1 file)
Availability: 1 check, the latest on 28 September 2026: the link answers (HTTP 200)
  • 28 September 2026: the link answers (HTTP 200)
65 files
At the source:

benshahary/drosophila-courtship

License: MIT
State: the link answers, verified on 28 September 2026
Evidence: files inventoried
Commit: a40249ee538a73f66b25d55c47e06f8505ba10f2, 26 July 2019
Languages: Python (61), Jupyter (2)
Size: 118 files, 63 scripts
Software Heritage: archived
Found in: the Zenodo archive record
Holds: README, license file, environment (environment-full.yml, environment.yml, requirements.txt, setup.py), tests, documentation, 2 notebooks
Not found: CITATION.cff, continuous integration
Tools: NumPy (46 files), pandas (15 files), Matplotlib (9 files), scikit-image (8 files), CircStat (4 files), SciPy (3 files), h5py (1 file), scikit-learn (1 file)
Availability: 1 check, the latest on 28 September 2026: the link answers
  • 28 September 2026: the link answers
65 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 126 scripts, each with its path and the digest of its content;
  • 2 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data availability

All software and scripts used for tracking, classification, and data analysis are publicly available at 10.5281/zenodo.18274754.

Supplemental material available at G3 online.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 28 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 3 authors, 5 keywords, 7 MeSH terms, 4 funders, 61 references.

Cite

This paper

McKinney, R. M., Monroy Hernandez, C., & Ben-Shahar, Y. (2026). Visual recognition of the anteroposterior female body axis drives spatial elements of male courtship in Drosophila. G3 (Bethesda, Md.), 16(4), jkag037. https://doi.org/10.1093/g3journal/jkag037

BibTeX

@article{mckinney2026visual,
author = {McKinney, Ross M and Monroy Hernandez, Christian and Ben-Shahar, Yehuda},
title = {{Visual recognition of the anteroposterior female body axis drives spatial elements of male courtship in Drosophila}},
journal = {G3 (Bethesda, Md.)},
year = {2026},
month = apr,
volume = {16},
number = {4},
pages = {jkag037},
publisher = {Oxford University Press},
issn = {2160-1836},
doi = {10.1093/g3journal/jkag037},
url = {https://doi.org/10.1093/g3journal/jkag037},
pmid = {41699762},
pmcid = {PMC13042310}
}

RIS

TY - JOUR
AU - McKinney, Ross M
AU - Monroy Hernandez, Christian
AU - Ben-Shahar, Yehuda
TI - Visual recognition of the anteroposterior female body axis drives spatial elements of male courtship in Drosophila
T2 - G3 (Bethesda, Md.)
J2 - G3 (Bethesda)
PY - 2026
DA - 2026/04/01
VL - 16
IS - 4
SP - jkag037
SN - 2160-1836
PB - Oxford University Press
DO - 10.1093/g3journal/jkag037
UR - https://doi.org/10.1093/g3journal/jkag037
LA - en
ER -

CSL-JSON

{
"id": "10.1093/g3journal/jkag037",
"type": "article-journal",
"title": "Visual recognition of the anteroposterior female body axis drives spatial elements of male courtship in Drosophila",
"container-title": "G3 (Bethesda, Md.)",
"author": [
{
"family": "McKinney",
"given": "Ross M"
},
{
"family": "Monroy Hernandez",
"given": "Christian"
},
{
"family": "Ben-Shahar",
"given": "Yehuda"
}
],
"container-title-short": "G3 (Bethesda)",
"volume": "16",
"issue": "4",
"page": "jkag037",
"DOI": "10.1093/g3journal/jkag037",
"PMID": "41699762",
"PMCID": "PMC13042310",
"ISSN": "2160-1836",
"publisher": "Oxford University Press",
"URL": "https://doi.org/10.1093/g3journal/jkag037",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
1
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s41467-026-72057-9 [code]
Sex-specific behavioral feedback modulates sensorimotor processing and drives flexible social behavior.
Journal: Nature communications
In common: scikit-image, h5py, scikit-learn, 4 other tools, drosophila, 8 references
[2] doi:10.3389/fnsys.2026.1822122 [code]
Convergence-divergence circuits for multimodal integration of innate and learned opponent valences.
Journal: Frontiers in systems neuroscience
In common: scikit-image, h5py, scikit-learn, 4 other tools, 6 references
[3] doi:10.1038/s41586-026-10735-w [code]
Distributed control circuits across a brain-and-cord connectome.
Journal: Nature
In common: scikit-image, scikit-learn, pandas, 3 other tools, drosophila, 6 references
[4] doi:10.7554/elife.108529 [code]
Inhibitory columnar feedback neurons are involved in motion processing in <i>Drosophila</i>.
Journal: eLife
In common: CircStat, h5py, SciPy, 2 other tools, drosophila, 2 references
[5] doi:10.1038/s41467-026-72437-1 [code]
High-speed whole-brain imaging in Drosophila.
Journal: Nature communications
In common: scikit-image, h5py, scikit-learn, 4 other tools, drosophila, 1 reference
[6] doi:10.1038/s41593-026-02232-0 [code]
Entorhinal cortex represents task-relevant remote locations independently of CA1.
Journal: Nature neuroscience
In common: CircStat, scikit-image, h5py, 5 other tools
[7] doi:10.7554/elife.107276 [code]
Deployment of endocytic machinery to periactive zones of nerve terminals is independent of active zone assembly and evoked release.
Journal: eLife
In common: scikit-image, scikit-learn, pandas, 3 other tools, drosophila, 1 reference
[8] doi:10.1038/s41593-026-02357-2 [code]
Experience reorganizes content-specific memory traces in macaques.
Journal: Nature neuroscience
In common: CircStat, scikit-image, scikit-learn, 4 other tools
[9] doi:10.1038/s41467-026-75347-4 [code]
Sleep reveals dynamics integrating and segregating movement and stimulus representations in V1.
Journal: Nature communications
In common: CircStat, scikit-image, scikit-learn, 4 other tools
[10] doi:10.1038/s41467-026-76581-6 [code]
Thalamocortical bursts encode reward contingencies and drive associative learning.
Journal: Nature communications
In common: CircStat, h5py, scikit-learn, 4 other tools

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.