OSCR

Stable clique membership in male mouse societies requires oxytocin-enabled social sensory states.

Code ↔ Paper

10 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 10 matches · 4 of them tie a paragraph to a whole file, not to given lines: weak matches, whose lines are not tinted
  1. [1] § Methods › Graph-theoretical metrics ↔ scripts/old_scripts/temporal_graph_metrics.py, lines 39–91 · score 0.67 · graph theoretical metrics, directed graphs, aggregating, NEF, temporal, medians
  2. [2] § Methods › Graph-theoretical metrics ↔ scripts/undirected_temporal_graph_metrics.py, lines 44–96 · score 0.67 · graph theoretical metrics, directed graphs, aggregating, NEF, temporal, medians
  3. [3] § Methods › Video recording of social interactions › Video recording and processing ↔ Documentation/SoftwareDocumentation/html/_static/jquery.js, the whole file · a weak match · score 0.62 · clips, phases, fading, pixel, post, field
  4. [4] § Results › Stable RCs emerge in social networks of group-housed mice ↔ scripts/old_scripts/rc_membership.py, lines 32–118 · score 0.61 · mutual nearest neighbor, RC membership, weak, day, windows, graphs
  5. [5] § Results › OXTRΔAON mice display quantitatively normal social activity in groups ↔ scripts/old_scripts/temporal_graph_metrics.py, lines 39–91 · score 0.60 · mutual nearest neighbors, graph cut, preserves edges, wild, filtered, day
  6. [6] § Results › OXTRΔAON mice display quantitatively normal social activity in groups ↔ scripts/old_undirected_graph_metrics.py, lines 50–102 · score 0.60 · mutual nearest neighbors, graph cut, preserves edges, wild, filtered, day
  7. [7] § Methods › NoSeMaze system ↔ Documentation/SoftwareDocumentation/html/searchindex.js, the whole file · a weak match · score 0.55 · Autonomouse, readers, NoSeMaze, delivered, module, cameras
  8. [8] § Methods › Dyadic social interaction experiment › Analysis of interaction videos ↔ Documentation/SoftwareDocumentation/html/searchindex.js, the whole file · a weak match · score 0.55 · animal ID, exported, MATLAB, tool, post, video
  9. [9] § Methods › Animal strains, husbandry and preparation › Virus vectors and stereotactic surgery ↔ Documentation/SoftwareDocumentation/html/_static/jquery.js, the whole file · a weak match · score 0.51 · FT, encoding, pre, head, attached, post
  10. [10] § Results › Stable RCs emerge in social networks of group-housed mice ↔ scripts/graph_metrics.py, lines 840–966 · score 0.51 · mutual nearest neighbor, RC members, pruned, day, edges, graphs

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 · 513 lines · 26 KB · CC-BY-NC-ND-4.0 · 2 matches

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import igraph as ig
  4. import networkx as nx
  5. import os
  6. import sys
  7. import seaborn as sns
  8. from scipy import stats
  9. import pandas as pd
  10. from scipy.stats import sem
  11. # from sklearn.decomposition import PCA
  12. # from sklearn.preprocessing import StandardScaler, MinMaxScaler, MaxAbsScaler, normalize
  13. from tqdm import tqdm
  14. # from sklearn.manifold import TSNE
  15. # from sklearn import manifold
  16. sys.path.append('..\\src\\')
  17. from read_graph import read_graph, read_labels
  18. from utils import get_category_indices, spread_points_around_center, add_group_significance
  19. import mpl_toolkits.mplot3d # noqa: F401
  20. from scipy.stats import ttest_ind
  21. from scipy import stats
  22. from graph_metrics import add_significance
  23. datapath = "..\\data\\chasing\\single\\"
  24. datapath = "..\\data\\averaged\\"
  25. labels = ["G1"]#, "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G10", "G11", "G12", "G13", "G14", "G15", "G16", "G17"]
  26. def default_on_error(graph_idx, variable, window):
  27. """
  28. If the data for a graph on a specific day is not available because of detection issue, nans should be returned.
  29. To preserve the structure of the data array, the number of returned nans should reflect the number of mutants, rc members and wt in the cohort.
  30. """
  31. mutants, rc, others, wt, RFIDs = get_category_indices(graph_idx, "approaches", window) # load data from exp day 1 as a template, because all group were properly detected.
  32. return [np.nan]*len(mutants), [np.nan]*len(rc), [np.nan]*len(others), \
  33. [np.nan]*len(wt), [np.nan]*len(RFIDs), \
  34. {"Mouse_RFID": [np.nan]*len(RFIDs), "mutant": [np.nan]*len(RFIDs), "RC": [np.nan]*len(RFIDs), "Group_ID": int(labels[graph_idx][1:])}
  35. def time_measures(measure, graph_idx, window = 1, variable = "approaches",
  36. mnn = None, mutual = True, weighted = False, threshold = 0.0,
  37. summation = "mean", normalization = None, in_group_norm = False, logscale = False):
  38. """
  39. Computes specified time graph-theoretical metric for a given group, and time window.
  40. This function processes a time series of adjacency matrices (graphs) representing animal interactions,
  41. computes a variety of metrics (e.g., burstiness, inter-contact interval), and returns values for
  42. different animal subgroups (mutants, wild-type, RC, etc.).
  43. Parameters:
  44. - measure (str): Name of the metric to compute. Supported values are:
  45. - "summed outICI", "summed inICI"
  46. - "summed outburstiness", "summed inburstiness"
  47. - "summed outburstiness rank", "summed inburstiness rank"
  48. - "summed outNEF", "summed inNEF"
  49. - "summed outNEF rank", "summed inNEF rank"
  50. - graph_idx (int): Index of the group to analyze (corresponds to an entry in the global 'labels' list).
  51. - window (int, optional): Size of the time window for graph aggregation. Supported values are 1, 3, or 7 (days). Default is 1.
  52. - variable (str, optional): Type of interaction to analyze. "approaches" (directed graph) or "interactions" (undirected graph).
  53. - mnn (int or None, optional): Minimum number of neighbors for graph cutting. If None, no neighbor filtering is applied.
  54. - mutual (bool, optional): If True, uses mutual nearest neighbors when building graphs. Ignored if `mnn` is None.
  55. - weighted (bool, optional): If True, preserves edge weights in graph; otherwise binarizes the graph.
  56. - threshold (float, optional): Percentage threshold for edge pruning in the adjacency matrix. Default is 0.0.
  57. - summation (str, optional): Aggregation function across time:
  58. "mean": Computes the mean value per node.
  59. "median": Computes the median value per node.
  60. - normalization (str or None, optional): Type of normalization to apply to some metrics. Options include:
  61. "Poisson", "poisson", "CV" and "median CV". If None, no normalization is applied.
  62. - in_group_norm (bool, optional): If True, normalizes final metric values by the group maximum.
  63. - logscale (bool, optional): If True, applies logarithmic scaling to the final metric values.
  64. Returns:
  65. tuple: (scores_mutants, scores_rc, scores_rest, scores_wt, scores_all, metadata)
  66. - scores_mutants (list): Metric values for mutant mice.
  67. - scores_rc (list): Metric values for rich-club (RC) mice.
  68. - scores_rest (list): Metric values for mice that are neither mutants nor RC.
  69. - scores_wt (list): Metric values for wild-type mice.
  70. - scores_all (list): Metric values for all mice in the group.
  71. - metadata (dict): Metadata dictionary for the group containing:
  72. - "Mouse_RFID" (list of str): RFID identifiers for all mice in the group.
  73. - "mutant" (list of bool): Boolean list indicating mutant status.
  74. - "RC" (list of bool): Boolean list indicating RC status.
  75. - "Group_ID" (int): Numerical group identifier.
  76. """
  77. metadata_path = "..\\data\\meta_data.csv"
  78. metadata_df = pd.read_csv(metadata_path)
  79. if window not in [1, 3, 7]:
  80. print("Incorrect time window")
  81. return
  82. ## figuring out position of mutants, wt and rc within the indexing of the csv file
  83. datapath = f"..\\data\\both_cohorts_{window}days\\"+labels[graph_idx]+"\\"+variable+f"_resD{window}_1.csv"
  84. try:
  85. data_ref = read_graph([datapath], percentage_threshold = threshold, mnn = mnn, mutual = mutual)[0]
  86. arr = np.loadtxt(datapath, delimiter=",", dtype=str)
  87. RFIDs = arr[0, 1:].astype(str)
  88. except Exception as e:
  89. print(e)
  90. return default_on_error(graph_idx, variable, window)
  91. if variable == "interactions":
  92. mode = 'undirected'
  93. data_ref = (data_ref + np.transpose(data_ref))/2 # ensure symmetry
  94. elif variable == "approaches":
  95. mode = 'directed'
  96. else:
  97. raise NameError("Incorrect input argument for 'variable'.")
  98. data_ref = np.where(data_ref > 0.01, data_ref, 0)
  99. curr_metadata_df = metadata_df.loc[metadata_df["Group_ID"] == int(labels[graph_idx][1:]), :]
  100. # figuring out index of true mutants in current group
  101. mutant_map = curr_metadata_df.set_index('Mouse_RFID')['mutant'].to_dict()
  102. is_mutant = [mutant_map.get(rfid, False) for rfid in RFIDs] # if RFID is missing, animal is assumed to be neurotypical
  103. is_RC = [] # no list comprehension allowed because of deprenciation warning due to RFID mismatch
  104. for rfid in RFIDs:
  105. if curr_metadata_df.loc[curr_metadata_df["Mouse_RFID"] == rfid, "RC"].values.size > 0:
  106. if curr_metadata_df.loc[curr_metadata_df["Mouse_RFID"] == rfid, "RC"].values[0]:
  107. is_RC.append(True)
  108. else:
  109. is_RC.append(False)
  110. else:
  111. is_RC.append(False)
  112. graph_length = data_ref.shape[0]
  113. mutants = np.where(is_mutant)[0] if len(np.where(is_mutant)) != 0 else [] # indices of mutants in this group
  114. rc = np.where(is_RC)[0] if len(np.where(is_RC)) != 0 else [] # indices of RC in this group
  115. others = np.arange(graph_length)[np.logical_and(~np.isin(np.arange(graph_length), rc), ~np.isin(np.arange(graph_length), mutants))]
  116. wt = np.arange(graph_length)[~np.isin(np.arange(graph_length), mutants)]
  117. graphs = []
  118. ## extracting graphs for each experimental day/session
  119. for day in np.arange(1, 16, window):
  120. datapath = f"..\\data\\both_cohorts_{window}days\\"+labels[graph_idx]+"\\"+variable+f"_resD{window}_"+str(day)+".csv"
  121. try:
  122. data = read_graph([datapath], percentage_threshold = threshold, mnn = mnn, mutual = mutual)[0]
  123. arr = np.loadtxt(datapath, delimiter=",", dtype=str)
  124. RFIDs = arr[0, 1:].astype(str)
  125. except Exception as e:
  126. print(e)
  127. data = data_ref*np.nan
  128. if variable == "interactions":
  129. mode = 'undirected'
  130. data = (data + np.transpose(data))/2 # ensure symmetry
  131. elif variable == "approaches":
  132. mode = 'directed'
  133. else:
  134. raise NameError("Incorrect input argument for 'variable'.")
  135. if weighted:
  136. data = np.where(data > 0.01, data, 0)
  137. else:
  138. data = np.where(data > 0.01, 1, 0)
  139. # g = ig.Graph.Weighted_Adjacency(data, mode=mode)
  140. graphs.append(data)
  141. if measure == "summed outICI" or measure == "summed inICI": # summed average inter conter interval
  142. all_data = np.array(graphs)
  143. num_mice = all_data.shape[1]
  144. time_std, time_mean = np.zeros((num_mice, num_mice)), np.zeros((num_mice, num_mice))
  145. for i in range(num_mice):
  146. for j in range(num_mice):
  147. try:
  148. time_std[i, j] = np.nanstd(np.where(all_data[:, i, j] > 0)[0][1:] - np.where(all_data[:, i, j] > 0)[0][:-1])
  149. except:
  150. time_std[i, j] = np.nan
  151. try:
  152. time_mean[i, j] = np.nanmean(np.where(all_data[:, i, j] > 0)[0][1:] - np.where(all_data[:, i, j] > 0)[0][:-1])
  153. except:
  154. time_mean[i, j] = np.nan
  155. all_scores = time_mean
  156. elif measure == "summed outburstiness" or measure == "summed inburstiness" or \
  157. measure == "summed outburstiness rank" or measure == "summed inburstiness rank":
  158. all_data = np.array(graphs)
  159. num_mice = all_data.shape[1]
  160. time_std, time_mean = np.zeros((num_mice, num_mice)), np.zeros((num_mice, num_mice))
  161. for i in range(num_mice):
  162. for j in range(num_mice):
  163. try:
  164. time_std[i, j] = np.nanstd(np.where(all_data[:, i, j] > 0)[0][1:] - np.where(all_data[:, i, j] > 0)[0][:-1])
  165. except:
  166. time_std[i, j] = np.nan
  167. try:
  168. time_mean[i, j] = np.nanmean(np.where(all_data[:, i, j] > 0)[0][1:] - np.where(all_data[:, i, j] > 0)[0][:-1])
  169. except:
  170. time_mean[i, j] = np.nan
  171. all_scores = (time_std - time_mean)/(time_std + time_mean)
  172. elif measure == "summed outNEF" or measure == "summed inNEF" or \
  173. measure == "summed outNEF rank" or measure == "summed inNEF rank":
  174. all_data = np.array(graphs)
  175. time_std, time_mean, time_median = np.nanstd(all_data, axis = 0), np.nanmean(all_data, axis = 0), np.nanmedian(all_data, axis = 0)
  176. if normalization == "Poisson" or normalization == "poisson": # variant of the CV aimed at studying poissonicity
  177. all_scores = (time_std - time_mean)/(time_std + time_mean)
  178. elif normalization == "CV":
  179. all_scores = time_std/time_mean
  180. elif normalization == "median CV":
  181. all_scores = time_std/time_median
  182. else:
  183. all_scores = time_std
  184. else:
  185. raise Exception("Unknown or misspelled input measurement.")
  186. return
  187. if "out" in measure:
  188. if summation == "mean":
  189. all_scores = np.nanmean(all_scores, axis = 1)
  190. if summation == "median":
  191. all_scores = np.nanmedian(all_scores, axis = 1)
  192. if logscale:
  193. all_scores = np.log(all_scores)
  194. if "rank" in measure:
  195. all_scores = all_scores.argsort().argsort()
  196. if in_group_norm:
  197. all_scores = all_scores/np.max(all_scores)
  198. metric_mutants = [all_scores[i] for i in mutants]
  199. metric_rc = [all_scores[i] for i in rc]
  200. metric_wt = [all_scores[i] for i in wt]
  201. metric_others = [all_scores[i] for i in others]
  202. metric_all = [all_scores[i] for i in range(len(RFIDs))]
  203. elif "in" in measure:
  204. if summation == "mean":
  205. all_scores = np.nanmean(all_scores, axis = 0)
  206. if summation == "median":
  207. all_scores = np.nanmedian(all_scores, axis = 0)
  208. if logscale:
  209. all_scores = np.log(all_scores)
  210. if "rank" in measure:
  211. all_scores = all_scores.argsort().argsort()
  212. if in_group_norm:
  213. all_scores = all_scores/np.max(all_scores)
  214. metric_mutants = [all_scores[i] if all_scores[i] != np.inf else np.nan for i in mutants]
  215. metric_rc = [all_scores[i] if all_scores[i] != np.inf else np.nan for i in rc]
  216. metric_wt = [all_scores[i] if all_scores[i] != np.inf else np.nan for i in wt]
  217. metric_others = [all_scores[i] if all_scores[i] != np.inf else np.nan for i in others]
  218. metric_all = [all_scores[i] if all_scores[i] != np.inf else np.nan for i in range(len(RFIDs))]
  219. return metric_mutants, metric_rc, metric_others, metric_wt, metric_all, {"Mouse_RFID": RFIDs, "mutant": is_mutant, "RC": is_RC, "Group_ID": int(labels[graph_idx][1:])}
  220. def get_time_metric_df(measure, window = 1, variable = "approaches", mnn = None, mutual = True, weighted = False):
  221. scores_mutants, scores_rc, scores_wt, scores_others, scores_all = [], [], [], [], []
  222. RFIDs, mutants, RCs = [], [], []
  223. for graph_idx in range(len(labels)):
  224. res = time_measures(measure, graph_idx, window, variable, mnn, mutual, weighted)
  225. scores_mutants.extend(res[0])
  226. scores_rc.extend(res[1])
  227. scores_others.extend(res[2])
  228. scores_wt.extend(res[3])
  229. scores_all.extend(res[4])
  230. RFIDs.extend(res[5]["Mouse_RFID"])
  231. mutants.extend(res[5]["mutant"])
  232. RCs.extend(res[5]["RC"])
  233. df = pd.DataFrame()
  234. df[measure] = scores_all
  235. df["mutant"] = mutants
  236. df["RC"] = RCs
  237. df["Mouse_RFID"] = RFIDs
  238. return df
  239. def bp_metric(measure, window = 1, variable = "approaches",
  240. mnn = None, mutual = True, weighted = False, threshold = 0.0,
  241. summation = "mean", normalization = None, in_group_norm = False, logscale = False, stat = "mean", ax = None):
  242. """
  243. Plots and compares the specified graph metric between RC and non mutant mice across all groups.
  244. Generates a boxplot (and optional swarm/violin plots) to visualize differences in a time-resolved
  245. graph-theoretical measure, with statistical testing between groups. For more details on input parameters,
  246. see the documentation of the time_measures function.
  247. """
  248. scores_mutants, scores_RC, scores_wt, scores_others, scores_all = [], [], [], [], []
  249. RFIDs, mutants, RCs = [], [], []
  250. for graph_idx in range(len(labels)):
  251. res = time_measures(measure, graph_idx, window, variable, mnn, mutual,
  252. weighted, threshold, summation, normalization, in_group_norm, logscale)
  253. scores_mutants.extend(res[0])
  254. scores_RC.extend(res[1])
  255. scores_others.extend(res[2])
  256. scores_wt.extend(res[3])
  257. scores_all.extend(res[4])
  258. RFIDs.extend(res[5]["Mouse_RFID"])
  259. mutants.extend(res[5]["mutant"])
  260. RCs.extend(res[5]["RC"])
  261. df = pd.DataFrame()
  262. df[measure] = scores_all
  263. df["mutant"] = mutants
  264. df["RC"] = RCs
  265. df["Mouse_RFID"] = RFIDs
  266. data = [df.loc[df["RC"] == True, ['Mouse_RFID', measure]], df.loc[np.logical_and(df["mutant"] == False, df["RC"] == False), ['Mouse_RFID', measure]],
  267. df.loc[np.logical_and(df["mutant"] == True, df["RC"] == False), ['Mouse_RFID', measure]] ]
  268. data[0][data[0] == np.inf] = np.nan
  269. data[1][data[1] == np.inf] = np.nan
  270. data[2][data[2] == np.inf] = np.nan
  271. data[0].dropna()
  272. data[1].dropna()
  273. data[2].dropna()
  274. if ax is None:
  275. fig, ax = plt.subplots(1, 1, figsize=(4, 6))
  276. size, alpha = 60, 0.4
  277. positions = [0.75, 1.25, 1.75]
  278. bp = ax.boxplot([data[0][measure].dropna(), data[1][measure].dropna(), data[2][measure].dropna()], positions = positions, labels=["sRC", "Non-members WT", "mutants"],
  279. showfliers = False, meanline=False, showmeans = False, medianprops={'visible': False})
  280. x_RC, scores_RC = spread_points_around_center(scores_RC, center=positions[0], bin_width = 0.1, interpoint=0.04)
  281. ax.scatter(x_RC, scores_RC, alpha=alpha, s=size, color="blue",edgecolor='none')
  282. x_others, scores_others = spread_points_around_center(scores_others, center=positions[1], bin_width = 0.1, interpoint=0.03)
  283. ax.scatter(x_others, scores_others, alpha=alpha, s=size, color="gray", label="Non-member",edgecolor='none')
  284. x_mutants, scores_mutants = spread_points_around_center(scores_mutants, center=positions[2], bin_width = 0.1, interpoint=0.03)
  285. ax.scatter(x_mutants, scores_mutants, alpha=alpha, s=size, color="red", label="Non-member",edgecolor='none')
  286. vp = plt.violinplot([data[0][measure], data[1][measure], data[2][measure]], positions, widths = [0.25, 0.38, 0.25], showextrema = False, showmedians=True)
  287. vp['bodies'][0].set_facecolor('blue')
  288. vp['bodies'][1].set_facecolor('gray')
  289. vp['bodies'][2].set_facecolor('red')
  290. if 'cmedians' in vp: # Safety check
  291. vp['cmedians'].set_linewidth(5) # Directly set width on LineCollection
  292. vp['cmedians'].set_color('k') # Set color
  293. vp['cmedians'].set_linestyle('-') # Ensure solid line
  294. add_significance(data, measure, ax, bp, stat)
  295. title = f"{measure}\n mnn = {mnn} thresh = {threshold}, summation = {summation}\n norm. = {normalization}, inGroupNorm = {in_group_norm}\n logscale = {logscale}, permutation test on the {stat}."
  296. ax.set_title(title)
  297. plt.tight_layout()
  298. plt.show()
  299. return bp
  300. def bp_metric_RC(measure, window = 1, variable = "approaches",
  301. mnn = None, mutual = True, weighted = False, threshold = 0.0,
  302. summation = "mean", normalization = None, in_group_norm = False, logscale = False, stat = "mean", swarmplot = True, ax = None):
  303. """
  304. Plots and compares the specified graph metric between RC and non mutant mice across all groups.
  305. Generates a boxplot (and optional swarm/violin plots) to visualize differences in a time-resolved
  306. graph-theoretical measure, with statistical testing between groups. For more details on input parameters,
  307. see the documentation of the time_measures function.
  308. """
  309. scores_mutants, scores_RC, scores_wt, scores_others, scores_all = [], [], [], [], []
  310. RFIDs, mutants, RCs = [], [], []
  311. for graph_idx in range(len(labels)):
  312. res = time_measures(measure, graph_idx, window, variable, mnn, mutual,
  313. weighted, threshold, summation, normalization, in_group_norm, logscale)
  314. scores_mutants.extend(res[0])
  315. scores_RC.extend(res[1])
  316. scores_others.extend(res[2])
  317. scores_wt.extend(res[3])
  318. scores_all.extend(res[4])
  319. RFIDs.extend(res[5]["Mouse_RFID"])
  320. mutants.extend(res[5]["mutant"])
  321. RCs.extend(res[5]["RC"])
  322. df = pd.DataFrame()
  323. df[measure] = scores_all
  324. df["mutant"] = mutants
  325. df["RC"] = RCs
  326. df["Mouse_RFID"] = RFIDs
  327. data = [ df.loc[np.logical_and(df["mutant"] == False, df["RC"] == False), ['Mouse_RFID', measure]],
  328. df.loc[df["RC"] == True, ['Mouse_RFID', measure]] ]
  329. data[0][data[0] == np.inf] = np.nan
  330. data[1][data[1] == np.inf] = np.nan
  331. data[0].dropna()
  332. data[1].dropna()
  333. if ax is None:
  334. fig, ax = plt.subplots(1, 1, figsize=(4, 6))
  335. size, alpha = 60, 0.4
  336. positions = [0.75, 1.25]
  337. bp = ax.boxplot([data[0][measure].dropna(), data[1][measure].dropna()], positions = positions, labels=["Non-members WT", "sRC"],
  338. showfliers = False, meanline=False, showmeans = False, medianprops={'visible': False})
  339. if swarmplot:
  340. x_others, scores_others = spread_points_around_center(scores_others, center=positions[0], bin_width = 0.1, interpoint=0.03)
  341. ax.scatter(x_others, scores_others, alpha=alpha, s=size, color="gray", label="Non-member",edgecolor='none')
  342. x_RC, scores_R = spread_points_around_center(scores_RC, center=positions[1], bin_width = 0.1, interpoint=0.04)
  343. ax.scatter(x_RC, scores_RC, alpha=alpha, s=size, color="blue",edgecolor='none')
  344. else:
  345. ax.scatter([positions[0] + np.random.normal()*0.05 for i in range(len(scores_others))],
  346. scores_others, alpha = alpha, s = size, color = "gray", label = "Non-member",edgecolor='none')
  347. ax.scatter([positions[1] + np.random.normal()*0.05 for i in range(len(scores_mutants))],
  348. scores_mutants, alpha = alpha, s = size, color = "blue",edgecolor='none', label = "sRC");
  349. vp = plt.violinplot([data[0][measure], data[1][measure]], positions, widths = [0.38, 0.25], showextrema = False, showmedians=True)
  350. vp['bodies'][0].set_facecolor('gray')
  351. vp['bodies'][1].set_facecolor('blue')
  352. if 'cmedians' in vp: # Safety check
  353. vp['cmedians'].set_linewidth(5) # Directly set width on LineCollection
  354. vp['cmedians'].set_color('k') # Set color
  355. vp['cmedians'].set_linestyle('-') # Ensure solid line
  356. add_significance(data, measure, ax, bp, stat)
  357. title = f"{measure}\n mnn = {mnn} thresh = {threshold}, summation = {summation}\n norm. = {normalization}, inGroupNorm = {in_group_norm}\n logscale = {logscale}, permutation test on the {stat}."
  358. ax.set_title(title)
  359. plt.tight_layout()
  360. plt.show()
  361. return bp
  362. def bp_metric_mutants(measure, window = 1, variable = "approaches",
  363. mnn = None, mutual = True, weighted = False, threshold = 0.0,
  364. summation = "mean", normalization = None, in_group_norm = False, logscale = False, stat = "mean", swarmplot = True, ax = None):
  365. """
  366. Plots and compares the specified graph metric between mutant and non-mutant mice across all groups.
  367. Generates a boxplot (and optional swarm/violin plots) to visualize differences in a time-resolved
  368. graph-theoretical measure, with statistical testing between groups. For more details on input parameters,
  369. see the documentation of the time_measures function.
  370. """
  371. scores_mutants, scores_rc, scores_wt, scores_others, scores_all = [], [], [], [], []
  372. RFIDs, mutants, RCs = [], [], []
  373. for graph_idx in range(len(labels)):
  374. res = time_measures(measure, graph_idx, window, variable, mnn, mutual,
  375. weighted, threshold, summation, normalization, in_group_norm, logscale)
  376. scores_mutants.extend(res[0])
  377. scores_rc.extend(res[1])
  378. scores_others.extend(res[2])
  379. scores_wt.extend(res[3])
  380. scores_all.extend(res[4])
  381. RFIDs.extend(res[5]["Mouse_RFID"])
  382. mutants.extend(res[5]["mutant"])
  383. RCs.extend(res[5]["RC"])
  384. df = pd.DataFrame()
  385. df[measure] = scores_all
  386. df["mutant"] = mutants
  387. df["RC"] = RCs
  388. df["Mouse_RFID"] = RFIDs
  389. data = [ df.loc[np.logical_and(df["mutant"], df["RC"] == False), ['Mouse_RFID', measure]],
  390. df.loc[np.logical_and(df["mutant"] == False, df["RC"] == False), ['Mouse_RFID', measure]] ]
  391. data[0][data[0] == np.inf] = np.nan
  392. data[1][data[1] == np.inf] = np.nan
  393. data[0].dropna()
  394. data[1].dropna()
  395. if ax is None:
  396. fig, ax = plt.subplots(1, 1, figsize=(4, 6))
  397. size, alpha = 60, 0.4
  398. positions = [0.75, 1.25]
  399. bp = ax.boxplot([data[1][measure].dropna(), data[0][measure].dropna()], positions = positions, labels=["Non-members WT", "OXTRΔAON"],
  400. showfliers = False, meanline=False, showmeans = False, medianprops={'visible': False})
  401. if swarmplot:
  402. x_mutants, scores_mutants = spread_points_around_center(scores_mutants, center=positions[1], bin_width = 0.1, interpoint=0.04)
  403. ax.scatter(x_mutants, scores_mutants, alpha=alpha, s=size, color="red",edgecolor='none')
  404. x_others, scores_others = spread_points_around_center(scores_others, center=positions[0], bin_width = 0.1, interpoint=0.03)
  405. ax.scatter(x_others, scores_others, alpha=alpha, s=size, color="gray", label="Non-member",edgecolor='none')
  406. else:
  407. ax.scatter([positions[1] + np.random.normal()*0.05 for i in range(len(scores_mutants))],
  408. scores_mutants, alpha = alpha, s = size, color = "red",edgecolor='none');
  409. ax.scatter([positions[0] + np.random.normal()*0.05 for i in range(len(scores_others))],
  410. scores_others, alpha = alpha, s = size, color = "gray", label = "Non-member",edgecolor='none')
  411. vp = plt.violinplot([data[1][measure], data[0][measure]], positions, widths = [0.38, 0.25], showextrema = False, showmedians=True)
  412. vp['bodies'][1].set_facecolor('lightcoral')
  413. vp['bodies'][0].set_facecolor('gray')
  414. if 'cmedians' in vp: # Safety check
  415. vp['cmedians'].set_linewidth(5) # Directly set width on LineCollection
  416. vp['cmedians'].set_color('k') # Set color
  417. vp['cmedians'].set_linestyle('-') # Ensure solid line
  418. add_significance(data, measure, ax, bp, stat)
  419. title = f"{measure}\n mnn = {mnn} thresh = {threshold}, summation = {summation}\n norm. = {normalization}, inGroupNorm = {in_group_norm}\n logscale = {logscale}, permutation test on the {stat}."
  420. ax.set_title(title)
  421. plt.tight_layout()
  422. plt.show()
  423. return bp
  424. if __name__ == "__main__":
  425. ## Main
  426. bp_metric_mutants("summed outNEF", mnn = None, mutual = True, weighted = True, threshold = 0,
  427. summation = "mean", normalization="CV", logscale = False, stat = "median", swarmplot = True)
  428. bp_metric_mutants("summed inNEF", mnn = None, mutual = True, weighted = True, threshold = 0,
  429. summation = "mean", normalization="CV", logscale = False, stat = "median")
  430. ## Supplement
  431. bp_metric_mutants("summed inburstiness", mnn = 7, mutual = True, weighted = False, threshold = 0,
  432. summation = "mean", normalization=None, in_group_norm = False, logscale = False, stat = "median", swarmplot = True)
  433. bp_metric_mutants("summed outburstiness", mnn = 7, mutual = True, weighted = False, threshold = 0,
  434. summation = "mean", normalization = None, in_group_norm = False, logscale = False, stat = "median", swarmplot = True)
  435. bp_metric("summed outNEF", mnn = None, mutual = True, weighted = True, threshold = 0,
  436. summation = "mean", normalization="CV", logscale = False, stat = "median")
  437. bp_metric("summed inNEF", mnn = None, mutual = True, weighted = True, threshold = 0,
  438. summation = "mean", normalization="CV", logscale = False, stat = "median")
  439. print("Warning: only G1 of the dataset is available on this repo. If you want to reproduce the paper, ask us for the full dataset, and uncomment labels on L27 of this script.")

temporal_graph_metrics.py at commit 8b67fdb, under CC-BY-NC-ND-4.0 · at the source

Overview

Authors: Corentin Nelias1,2, Sarah Ghanayem1,2, David Wolf1,2, Marcel Moor1, Danai Nikolantonaki1,2, Eda Dilara Turgut1,2, Max F. Scheller1, Valery Grinevich3, Jonathan R. Reinwald1,2, Wolfgang Kelsch1,2
  1. Department of Psychiatry and Psychotherapy, University Medical Center Mainz, Johannes-Gutenberg University,Mainz, Germany
  2. Department of Psychiatry and Psychotherapy, Central Institute of Mental Health, Medical Faculty Mannheim, Heidelberg University,Mannheim, Germany
  3. Department Neuropeptide Research in Psychiatry, Central Institute of Mental Health, Medical Faculty Mannheim, Heidelberg University,Mannheim, Germany
Journal: Nature communications, volume 17, issue 1, article 8493
Dates: received 24 September 2025; accepted 7 August 2026; published online 17 August 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1038/s41467-026-76841-5 · PMID 42608410 · PMCID PMC13484484 · OpenAlex W7203633812
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: human (organism), mouse (organism), cellular / molecular (subfield)
Methods: Statistics, Machine learning, Evoked potentials
Keywords: Social behaviour, Sensory processing, Social neuroscience
MeSH: Oxytocin*, Social Behavior*, Animals, Behavior, Animal, Humans, Male, Mice, Mice, Inbred C57BL, Mice, Knockout, Olfactory Cortex, Receptors, Oxytocin (* major topic)
Topic: Neuroendocrine regulation and behavior (Social Psychology, Psychology), according to OpenAlex
Funding: Leibniz-Gemeinschaft (K430/2021); Boehringer Ingelheim (‘Complex Systems’ to W.K); BMBF 3R consortium grants ‘NoSeMaze1’ (161L0277A) and ‘NoSeMaze2’ (16LW0333K) to Wolfgang Kelsch BMBF CRCNS grant ‘Oxystate’ (01GQ1708) to Wolfgang Kelsch DFG CRC 379 Project C03 to Wolfgang Kelsch DFG Clinician Scientist Program ‘Interfaces and Interventions in Complex Chronic Conditions’ (EB187/8-1) to Jonathan Reinwald
Citations: cited by 2 papers (Europe PMC); 57 references in the paper

Abstract

The ability to establish stable de novo relationships in complex environments is essential for social functioning but disrupted in disorders such as autism. Yet, the mechanisms supporting higher-order bonding in large groups remain unclear. Here, we introduce a naturalistic model of clique formation in mouse societies, using longitudinal tracking from large-scale video data. We show that small, stable cliques emerged from the specific group configurations. Consistently, also kinship did not significantly facilitate entry. These cohesive cliques resembled human mutually interacting rich-clubs, exhibiting high social rank and influence over non-members. We next examined whether oxytocin signaling in the olfactory cortex supports such higher-order bonding. Despite preserved social motivation, mice with conditional oxytocin receptor deletion in this sensory cortex failed to join rich-clubs, approached peers less consistently, and received unstable reciprocal connections. This network-level disorganization demonstrates how social dynamics can magnify individual deficits. Our findings identify oxytocin-dependent social sensory states as a necessary mechanism for forming stable relationships in complex social networks.

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 10 matches between paragraphs and lines of code.

KelschLAB/NoSeMaze

License: GPL-3.0
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 404250889f232264c4c9111e2f37bb78583969ce, 27 April 2026
Languages: Python (79), JavaScript (9)
Size: 342 files, 88 scripts
Software Heritage: not archived
Found in: the text, “NoSeMaze system”
Holds: README, license file, documentation
Not found: CITATION.cff, environment file, tests, continuous integration
Tools: NumPy (21 files), SciPy (6 files), Matplotlib (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
90 files

KelschLAB/NoSeMaze-stableRichClubs

License: CC-BY-NC-ND-4.0
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 8b67fdb2489f61712a4d8d3daefc232a053494f0, 21 July 2026
Languages: Python (34), MATLAB (6)
Size: 314 files, 40 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, license file
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (34 files), Matplotlib (32 files), pandas (26 files), igraph (24 files), NetworkX (24 files), SciPy (24 files), seaborn (21 files), scikit-learn (10 files), statsmodels (8 files), PyTorch (2 files)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
42 files

Code availability

The code used for the data analysis57 is available online via https://github.com/KelschLAB/NoSeMaze-stableRichClubs

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

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;
  • 128 scripts, each with its path and the digest of its content;
  • 10 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

The data generated in this study are under active use by the reporting laboratory; all data presented in this manuscript are available upon request from the Lead Contact. Source data are provided with this paper.

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, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 10 authors, 3 keywords, 11 MeSH terms, 3 funders, 53 references, 2 RRIDs.

Cite

This paper

Nelias, C., Ghanayem, S., Wolf, D., Moor, M., Nikolantonaki, D., Turgut, E. D., Scheller, M. F., Grinevich, V., Reinwald, J. R., & Kelsch, W. (2026). Stable clique membership in male mouse societies requires oxytocin-enabled social sensory states. Nature communications, 17(1), 8493. https://doi.org/10.1038/s41467-026-76841-5

BibTeX

@article{nelias2026stable,
author = {Nelias, Corentin and Ghanayem, Sarah and Wolf, David and Moor, Marcel and Nikolantonaki, Danai and Turgut, Eda Dilara and Scheller, Max F. and Grinevich, Valery and Reinwald, Jonathan R. and Kelsch, Wolfgang},
title = {{Stable clique membership in male mouse societies requires oxytocin-enabled social sensory states}},
journal = {Nature communications},
year = {2026},
month = aug,
volume = {17},
number = {1},
pages = {8493},
publisher = {Nature Publishing Group},
issn = {2041-1723},
doi = {10.1038/s41467-026-76841-5},
url = {https://doi.org/10.1038/s41467-026-76841-5},
pmid = {42608410},
pmcid = {PMC13484484}
}

RIS

TY - JOUR
AU - Nelias, Corentin
AU - Ghanayem, Sarah
AU - Wolf, David
AU - Moor, Marcel
AU - Nikolantonaki, Danai
AU - Turgut, Eda Dilara
AU - Scheller, Max F.
AU - Grinevich, Valery
AU - Reinwald, Jonathan R.
AU - Kelsch, Wolfgang
TI - Stable clique membership in male mouse societies requires oxytocin-enabled social sensory states
T2 - Nature communications
J2 - Nat Commun
PY - 2026
DA - 2026/08/17
VL - 17
IS - 1
SP - 8493
SN - 2041-1723
PB - Nature Publishing Group
DO - 10.1038/s41467-026-76841-5
UR - https://doi.org/10.1038/s41467-026-76841-5
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41467-026-76841-5",
"type": "article-journal",
"title": "Stable clique membership in male mouse societies requires oxytocin-enabled social sensory states",
"container-title": "Nature communications",
"author": [
{
"family": "Nelias",
"given": "Corentin"
},
{
"family": "Ghanayem",
"given": "Sarah"
},
{
"family": "Wolf",
"given": "David"
},
{
"family": "Moor",
"given": "Marcel"
},
{
"family": "Nikolantonaki",
"given": "Danai"
},
{
"family": "Turgut",
"given": "Eda Dilara"
},
{
"family": "Scheller",
"given": "Max F."
},
{
"family": "Grinevich",
"given": "Valery"
},
{
"family": "Reinwald",
"given": "Jonathan R."
},
{
"family": "Kelsch",
"given": "Wolfgang"
}
],
"container-title-short": "Nat Commun",
"volume": "17",
"issue": "1",
"page": "8493",
"DOI": "10.1038/s41467-026-76841-5",
"PMID": "42608410",
"PMCID": "PMC13484484",
"ISSN": "2041-1723",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41467-026-76841-5",
"language": "en",
"issued": {
"date-parts": [
[
2026,
8,
17
]
]
}
}

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.1016/j.isci.2026.116825 [code]
Social hierarchy shapes behavioral and transcriptional responses to chronic stress and ketamine in male mice.
Journal: iScience
In common: NetworkX, statsmodels, PyTorch, 6 other tools, mouse, 2 references
[2] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: igraph, NetworkX, statsmodels, 7 other tools, mouse, cellular / molecular
[3] doi:10.1016/j.isci.2026.116055 [code]
Mapping the transcriptional diversity of calcium signaling in the mouse and human brain.
Journal: iScience
In common: igraph, NetworkX, statsmodels, 7 other tools, mouse
[4] doi:10.1186/s12864-026-12965-8 [code]
Systematic evaluation of single-cell foundation model interpretability: attention-derived edge scores add no incremental value over gene-level features for perturbation-target prediction.
Journal: BMC genomics
In common: igraph, NetworkX, statsmodels, 7 other tools, cellular / molecular
[5] doi:10.1016/j.isci.2026.115604 [code]
FOXP1 is differentially active during development of murine vasopressin and oxytocin magnocellular neurons.
Journal: iScience
In common: PyTorch, pandas, SciPy, 1 other tool, mouse, 1 reference, author Valery Grinevich
[6] doi:10.1038/s41586-026-10629-x [code]
Whole-genome duplication shaped cell-type evolution in the vertebrate brain.
Journal: Nature
In common: igraph, NetworkX, statsmodels, 6 other tools, mouse, cellular / molecular
[7] doi:10.1038/s41593-026-02232-0 [code]
Entorhinal cortex represents task-relevant remote locations independently of CA1.
Journal: Nature neuroscience
In common: NetworkX, statsmodels, PyTorch, 6 other tools, mouse, 1 reference
[8] doi:10.1038/s41467-026-74357-6 [code]
Hippocampo-neocortical interaction as compressive retrieval-augmented generation.
Journal: Nature communications
In common: NetworkX, statsmodels, PyTorch, 6 other tools, 1 reference
[9] doi:10.1038/s41467-026-76676-0 [code]
Determinants of functional burden pleiotropy and gene dosage responses across human traits.
Journal: Nature communications
In common: igraph, NetworkX, statsmodels, 6 other tools, cellular / molecular
[10] doi:10.1073/pnas.2531706123 [code]
Metabolism-weighted brain connectome reveals synaptic integration and vulnerability to neurodegeneration.
Journal: Proceedings of the National Academy of Sciences of the United States of America
In common: igraph, NetworkX, statsmodels, 6 other tools, cellular / molecular

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.