OSCR

Restoring access to long-term social recognition memories disrupted by sleep deprivation.

Code ↔ Paper

6 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.

5 blocks of code here have a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.

The 6 matches
  1. [1] § MATERIALS AND METHODS › Statistical analysis ↔ src/stats.py, lines 101 to 150 · score 0.69 · EGFP positive cells, dual engram, cFos, engram reactivation, mCherry, overlap · block oscr:b:AKEYTRXDX5G5Z-J · Report a mismatch
  2. [2] § MATERIALS AND METHODS › Statistical analysis ↔ src/plots.py, lines 99 to 128 · score 0.68 · EGFP positive cells, dual engram, cFos, engram reactivation, mCherry, overlap · block oscr:b:E1KBHA4VJY110-Q · Report a mismatch
  3. [3] § RESULTS › Optogenetic stimulation of DG engram cells enables persistent retrieval of social memory several days later by increasing engram reactivation ↔ run_analysis.py, lines 118 to 178 · score 0.60 · positive cells, engram reactivation, cFos, mCherry, blade, colocalization · block oscr:b:HGWVX2J8QBF0S-Y · Report a mismatch
  4. [4] § RESULTS › Optogenetic stimulation of DG engram cells enables persistent retrieval of social memory several days later by increasing engram reactivation ↔ src/data_loader.py, lines 68 to 88 · score 0.60 · positive cells, engram reactivation, cFos, mCherry, blade, colocalization · block oscr:b:SCDEC99WSAT7D-E · Report a mismatch
  5. [5] § MATERIALS AND METHODS › Cell counting ↔ run_analysis.py, lines 118 to 178 · score 0.60 · EGFP positive cells, cFos, mCherry, blades, colocalization, model · block oscr:b:HGWVX2J8QBF0S-Y · Report a mismatch
  6. [6] § MATERIALS AND METHODS › Cell counting ↔ src/data_loader.py, lines 90 to 114 · score 0.59 · EGFP positive cells, cFos, mCherry, blades, colocalization, animal · block oscr:b:47WRXND1N120K-Z · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 515 lines · 25 KB · MIT · 2 matches

  1. """
  2. run_analysis.py — V5.1
  3. =======================
  4. Pipeline reproducible V5.1. Genera exactamente los outputs del manuscrito.
  5. Correcciones V5.1 respecto a V5:
  6. - bootstrap_rmse_difference: predicciones fijas, índices remuestreados (N=1000)
  7. - power_formation_contrast: parámetros por marcador (EGFP/mCherry), N_sim=5000
  8. - Model averaging: agregado (acc/mix/sto fixR) con varianza incondicional
  9. - AICc individual corregido: k = k_mech + 8, n = 275
  10. - Ceros declarados; sensibilidad pseudocuenta
  11. - version = V5.1 en CONFIG y run_metadata
  12. Para publicación: N_STARTS=100, N_BOOT=1000, N_SIM_REC=500
  13. """
  14. import sys, json, time, shutil, hashlib, datetime
  15. import numpy as np, pandas as pd
  16. from pathlib import Path
  17. sys.path.insert(0, str(Path(__file__).parent))
  18. from src.config import TABLE_DIR, MODEL_DIR, FIG_DIR, OUTPUT_DIR, DATA_DIR
  19. from src import data_loader, stats, fitting, validation, plots
  20. from src.model import (identifiability_proposition, cellular_analytic_estimate,
  21. omega_lambda_compatibility_map, latent_states_summary,
  22. parameter_spec, test_equivalence, model_averaged_estimates,
  23. power_formation_contrast, power_decay_detection,
  24. cellular_individual_nll)
  25. # ══════════════════════════════════════════════════════════════════════════════
  26. # CONFIGURACIÓN
  27. # ══════════════════════════════════════════════════════════════════════════════
  28. CONFIG = {
  29. "N_STARTS": 50,
  30. "N_BOOT": 500,
  31. "N_SIM_REC": 100,
  32. "CELL_WEIGHT": 1.0,
  33. "SEED": 12345,
  34. "version": "V5.1",
  35. }
  36. # ══════════════════════════════════════════════════════════════════════════════
  37. def _s(obj):
  38. if isinstance(obj, (bool, np.bool_)): return bool(obj)
  39. if isinstance(obj, np.integer): return int(obj)
  40. if isinstance(obj, (float, np.floating)): return float(obj)
  41. if isinstance(obj, np.ndarray): return obj.tolist()
  42. return obj
  43. def _verify_sync(config):
  44. meta = json.loads((MODEL_DIR / "run_metadata.json").read_text())
  45. for key in ("N_STARTS", "N_BOOT", "N_SIM_REC", "SEED", "version"):
  46. assert str(meta.get(key)) == str(config.get(key)), \
  47. f"DESINCRONIZACIÓN: {key} metadata={meta.get(key)} config={config.get(key)}"
  48. print(" ✓ Sincronización verificada")
  49. def _aicc_individual_corrected(fits_ind, n_obs_correct=275):
  50. """
  51. AICc individual con k = k_mech + 8 (cuatro intercepts + cuatro varianzas)
  52. y n = 275 (189 beh + 44 form + 42 reac).
  53. """
  54. rows = []
  55. for key, fit in fits_ind.items():
  56. k_mech = len(fit["names"])
  57. k_corr = k_mech + 8
  58. ll = -fit["result"].fun
  59. aic = 2*k_corr - 2*ll
  60. aicc = aic + (2*k_corr*(k_corr+1)) / max(n_obs_correct - k_corr - 1, 1)
  61. bic = k_corr * np.log(n_obs_correct) - 2*ll
  62. rows.append({"key": key, "k_mech": k_mech, "k_corr": k_corr,
  63. "logLik": ll, "AICc_corrected": aicc, "BIC_corrected": bic})
  64. df = pd.DataFrame(rows).sort_values("AICc_corrected").reset_index(drop=True)
  65. d = df["AICc_corrected"] - df["AICc_corrected"].min()
  66. w = np.exp(-0.5 * d)
  67. df["delta_AICc"] = d; df["AICc_weight"] = w / w.sum()
  68. return df
  69. def _model_averaging_unconditional(fits_fixR, ic_fixR, boot_raw_df):
  70. """
  71. Model averaging con varianza incondicional = within + between.
  72. Within-model variance: bootstrap de access_fixR (solo el disponible).
  73. Between-model variance: dispersión entre estimaciones ponderadas.
  74. """
  75. rows = []
  76. for key, fit in fits_fixR.items():
  77. w = ic_fixR.loc[ic_fixR["key"] == key, "AICc_weight"].values
  78. if len(w) == 0: continue
  79. rows.append({"key": key, "weight": float(w[0]),
  80. "d_E": fit["parameters"].get("d_E", 0.0),
  81. "d_C": fit["parameters"].get("d_C", 0.0)})
  82. df_w = pd.DataFrame(rows)
  83. d_C_MA = float((df_w["weight"] * df_w["d_C"]).sum())
  84. d_E_MA = float((df_w["weight"] * df_w["d_E"]).sum())
  85. # within-model (bootstrap access_fixR)
  86. var_within_C = float(boot_raw_df["d_C"].var(ddof=1)) if "d_C" in boot_raw_df else 0.0
  87. # between-model
  88. var_between_C = float((df_w["weight"] * (df_w["d_C"] - d_C_MA)**2).sum())
  89. var_total_C = var_within_C + var_between_C
  90. sd_total_C = var_total_C**0.5
  91. ci_lo = d_C_MA - 1.96 * sd_total_C
  92. ci_hi = d_C_MA + 1.96 * sd_total_C
  93. return {
  94. "d_E_MA": d_E_MA, "d_C_MA": d_C_MA,
  95. "var_within_d_C": var_within_C, "var_between_d_C": var_between_C,
  96. "var_total_d_C": var_total_C, "sd_total_d_C": sd_total_C,
  97. "ci_lo_unconditional": float(ci_lo), "ci_hi_unconditional": float(ci_hi),
  98. "note": ("Aggregate-model MA: access/mixed/storage-fixR weighted by AICc. "
  99. "Unconditional CI = within (bootstrap access_fixR) + between models."),
  100. "details": df_w.to_dict(orient="records"),
  101. }
  102. def _pseudocount_sensitivity(data, best_fit_ind):
  103. """Sensibilidad de d_C a ceros celulares con pseudocuenta log(v+0.5)."""
  104. from scipy.optimize import minimize
  105. cell_raw = data["cell_raw"]
  106. p12 = cell_raw[(cell_raw["protocol_id"] == "P12_dual_engram_tagging")
  107. & (cell_raw["blade"] == "whole_DG")]
  108. reac_specs = [("engram_reactivation_colocalization", "EGFP+cFos", 0),
  109. ("engram_reactivation_colocalization", "mCherry+cFos", 1)]
  110. form_specs = [("EGFP_positive_cells", "EGFP", 0),
  111. ("mCherry_positive_cells", "mCherry", 1)]
  112. log_yF = []; sdF = []; mF = []
  113. for meas, marker, midx in form_specs:
  114. d = p12[(p12["measurement"] == meas) & (p12["marker"] == marker)]
  115. for _, row in d.iterrows():
  116. v = row["value"]
  117. if v <= 0: continue
  118. log_yF.append(np.log(v)); sdF.append(1 if row["sleep_status"] == "SD" else 0)
  119. mF.append(midx)
  120. log_yR_p = []; sdR_p = []; mR_p = []
  121. for meas, marker, midx in reac_specs:
  122. d = p12[(p12["measurement"] == meas) & (p12["marker"] == marker)]
  123. for _, row in d.iterrows():
  124. log_yR_p.append(np.log(row["value"] + 0.5)) # pseudocuenta
  125. sdR_p.append(1 if row["sleep_status"] == "SD" else 0)
  126. mR_p.append(midx)
  127. cell_pseudo = {
  128. "log_y_F_arr": np.array(log_yF), "sd_flag_F_arr": np.array(sdF), "m_idx_F_arr": np.array(mF),
  129. "log_y_R_arr": np.array(log_yR_p), "sd_flag_R_arr": np.array(sdR_p), "m_idx_R_arr": np.array(mR_p),
  130. "n_F": len(log_yF), "n_R": len(log_yR_p),
  131. }
  132. model = best_fit_ind["model"]; decay = best_fit_ind["decay"]; fix_r = best_fit_ind["fix_rescues"]
  133. names, lower, upper = parameter_spec(model, decay, fix_r)
  134. bounds = list(zip(lower, upper))
  135. rng = np.random.default_rng(42)
  136. from src.model import cellular_individual_nll_theta
  137. best = None
  138. for _ in range(20):
  139. x0 = rng.uniform(lower, upper)
  140. res = minimize(cellular_individual_nll_theta, x0=x0,
  141. args=(data["cal_arr"], model, cell_pseudo, decay, fix_r),
  142. method="L-BFGS-B", bounds=bounds,
  143. options={"maxiter": 4000, "ftol": 1e-12})
  144. if best is None or res.fun < best.fun: best = res
  145. params_p = dict(zip(names, best.x))
  146. return {
  147. "method": "pseudocount_log_v_plus_0.5",
  148. "n_R_with_pseudo": len(log_yR_p),
  149. "n_zeros_included": 2,
  150. "d_C_pseudo": float(params_p.get("d_C", float("nan"))),
  151. "d_C_original": float(best_fit_ind["parameters"].get("d_C", float("nan"))),
  152. "difference": float(abs(params_p.get("d_C", 0) - best_fit_ind["parameters"].get("d_C", 0))),
  153. "note": ("Two reactivation values were exactly zero in the original data. "
  154. "The primary analysis excludes them (log-transformation). "
  155. "This sensitivity uses log(v+0.5)."),
  156. }
  157. def main():
  158. t0 = time.time()
  159. print("=" * 65)
  160. print(" Sleep Memory Model V5.1 — Pipeline reproducible")
  161. print("=" * 65)
  162. print("\n[0] Limpiando output/...")
  163. if OUTPUT_DIR.exists(): shutil.rmtree(OUTPUT_DIR)
  164. for d in (FIG_DIR, TABLE_DIR, MODEL_DIR): d.mkdir(parents=True, exist_ok=True)
  165. # [1] Metadatos
  166. print("\n[1] Metadatos...")
  167. data_hash = fitting.compute_data_hash(
  168. DATA_DIR / "behavior_paired.csv", DATA_DIR / "cellular_long.csv")
  169. code_hash = fitting.compute_code_hash()
  170. fitting.save_run_metadata(CONFIG, data_hash, code_hash)
  171. print(f" data={data_hash} code={code_hash}")
  172. # [2] Datos
  173. print("\n[2] Datos...")
  174. data = data_loader.load_all()
  175. audit = data["spi_audit"]
  176. print(f" SPI audit: {'✓' if audit['passed'] else '✗'} "
  177. f"Cal={len(data['cal'])} Val={len(data['val'])}")
  178. print(f" cell_ind: n_F={data['cell_ind']['n_F']} n_R={data['cell_ind']['n_R']} "
  179. f"(2 zeros excluidos de reactivación)")
  180. # [3] Equivalencia
  181. print("\n[3] Test de equivalencia...")
  182. eq = test_equivalence(data["cal_arr"])
  183. assert eq["all_passed"], "EQUIVALENCIA FALLIDA"
  184. print(" ✓ storage ≡ access en conducta (max_diff = 0)")
  185. # [4] Estadísticas descriptivas
  186. print("\n[4] Estadística descriptiva...")
  187. stats.behavior_summary(data["memory"]).to_csv(TABLE_DIR / "table1_behavior_summary.csv", index=False)
  188. stats.one_sample_spi_tests(data["memory"]).to_csv(TABLE_DIR / "table1b_spi_vs_zero.csv", index=False)
  189. cell_cont = stats.cellular_contrasts(data["cell_raw"])
  190. cell_cont.to_csv(TABLE_DIR / "table2_cellular_contrasts.csv", index=False)
  191. stats.exploration_confound_tests(data["memory"]).to_csv(TABLE_DIR / "tableS1_exploration_confound.csv", index=False)
  192. cell_est = cellular_analytic_estimate(data["cell_obs"])
  193. print(f" {cell_est['message']}")
  194. (TABLE_DIR / "cell_analytic_estimate.json").write_text(
  195. json.dumps({k: _s(v) for k, v in cell_est.items()}, indent=2))
  196. prop = identifiability_proposition(data["cell_obs"])
  197. (TABLE_DIR / "identifiability_proposition.json").write_text(
  198. json.dumps({k: _s(v) for k, v in prop.items()
  199. if k not in ("d_E_equipotential", "d_C_equipotential")}, indent=2))
  200. # [5] Ajuste familia simétrica (agregado — sensibilidad/secundario)
  201. print(f"\n[5] Familia simétrica (N_STARTS={CONFIG['N_STARTS']})...")
  202. fits, ic = fitting.run_fitting(data["cal_arr"], data["cell_obs"],
  203. n_starts=CONFIG["N_STARTS"],
  204. cell_weight=CONFIG["CELL_WEIGHT"],
  205. seed=CONFIG["SEED"], verbose=True)
  206. best_key = fitting.best_fit_key(ic)
  207. best_fit = fits[best_key]
  208. fitting.parameter_table(best_fit).to_csv(TABLE_DIR / "table3_parameters.csv", index=False)
  209. ic.to_csv(TABLE_DIR / "table3_model_comparison.csv", index=False)
  210. print(f"\n Mejor agregado: {best_key}")
  211. # Solo conducta
  212. validation.sensitivity_behavior_only(data["cal_arr"], data["cell_obs"],
  213. n_starts=CONFIG["N_STARTS"] // 2,
  214. seed=CONFIG["SEED"] + 10)["ic"].to_csv(
  215. TABLE_DIR / "tableS3_sensitivity_beh_only.csv", index=False)
  216. # [5b] Modelo celular individual (PRIMARIO)
  217. print("\n[5b] Modelo celular individual (PRIMARIO)...")
  218. fits_ind = {}
  219. for model in ("storage", "access", "mixed"):
  220. fits_ind[f"{model}_IND"] = fitting.fit_model_individual(
  221. model, data["cal_arr"], data["cell_ind"],
  222. n_starts=CONFIG["N_STARTS"], decay=False, fix_rescues=True,
  223. seed=CONFIG["SEED"], verbose=True)
  224. # AICc corregido: k = k_mech + 8, n = 275
  225. ic_ind_corr = _aicc_individual_corrected(fits_ind, n_obs_correct=275)
  226. ic_ind_corr.to_csv(TABLE_DIR / "table3b_model_comparison_individual_corrected.csv", index=False)
  227. print("\n AICc individual CORREGIDO (k+8, n=275):")
  228. print(ic_ind_corr[["key", "k_corr", "AICc_corrected", "delta_AICc", "AICc_weight"]].to_string(index=False))
  229. best_fit_ind = fits_ind["access_IND"]
  230. print(f"\n d_C individual MLE: {best_fit_ind['parameters'].get('d_C', 0):.3f}")
  231. # [5c] Sensibilidades
  232. print("\n[5c] Sensibilidades...")
  233. sw = fitting.sensitivity_cell_weight(data["cal_arr"], data["cell_obs"],
  234. n_starts=CONFIG["N_STARTS"] // 2, seed=77)
  235. sw.to_csv(TABLE_DIR / "tableS_sensitivity_cell_weight.csv", index=False)
  236. se_sens = fitting.sensitivity_cell_error(data["cal_arr"], data["cell_obs"],
  237. n_starts=CONFIG["N_STARTS"] // 2, seed=88)
  238. se_sens.to_csv(TABLE_DIR / "tableS_sensitivity_cell_error.csv", index=False)
  239. fitting.baselines_beh_aic(data["cal_arr"], len(data["cal_arr"]["y"])).to_csv(
  240. TABLE_DIR / "tableS_baselines_beh_aic.csv", index=False)
  241. # Pseudocuenta sensibilidad
  242. print(" Pseudocuenta sensibilidad...")
  243. zero_sens = _pseudocount_sensitivity(data, best_fit_ind)
  244. (TABLE_DIR / "tableS_zero_sensitivity.json").write_text(json.dumps(zero_sens, indent=2))
  245. print(f" d_C original={zero_sens['d_C_original']:.3f} "
  246. f"d_C_pseudo={zero_sens['d_C_pseudo']:.3f} diff={zero_sens['difference']:.3f}")
  247. # [5d] Potencia con parámetros reales por marcador, N_sim=5000
  248. print("\n[5d] Potencia (N_sim=5000, parámetros por marcador)...")
  249. power_rows = []
  250. for d_E in [0.082, 0.10, 0.15, 0.20, 0.30, 0.40]:
  251. for n in [8, 10, 12, 20]:
  252. for marker in ["EGFP", "mCherry"]:
  253. p = power_formation_contrast(n, d_E, marker=marker,
  254. n_sim=5000, seed=42)
  255. power_rows.append({"d_E_true": d_E, "n_per_group": n,
  256. "marker": marker, "power": round(p, 3)})
  257. power_df = pd.DataFrame(power_rows)
  258. power_df.to_csv(TABLE_DIR / "tableS_power_formation.csv", index=False)
  259. print(" Potencia n=10:")
  260. print(power_df[power_df["n_per_group"] == 10].pivot(
  261. index="d_E_true", columns="marker", values="power").to_string())
  262. pd_rows = []
  263. for muq in [0.05, 0.10, 0.20, 0.30]:
  264. p = power_decay_detection(muq, n_per_group=10, n_sim=2000, seed=43)
  265. pd_rows.append({"mu_q_true": muq, "power": round(p, 3)})
  266. pd.DataFrame(pd_rows).to_csv(TABLE_DIR / "tableS_power_decay.csv", index=False)
  267. # [6] Calibración y validación
  268. print("\n[6] Calibración y validación...")
  269. cal_out, cal_diag, cal_group = validation.calibration_diagnostics(
  270. data["cal"], data["cal_arr"], best_fit)
  271. val_out, val_metrics, group_metrics = validation.external_validation(
  272. data["val"], data["val_arr"], best_fit)
  273. print(f" Cal RMSE={cal_diag['rmse']:.4f} "
  274. f"Val RMSE={val_metrics['rmse']:.4f} R²={val_metrics['r2']:.4f}")
  275. lopo_df = validation.leave_one_protocol_out(
  276. data["cal"], data["cell_obs"], best_fit,
  277. n_starts=20, cell_weight=CONFIG["CELL_WEIGHT"], seed=CONFIG["SEED"] + 1)
  278. lopo_df.to_csv(TABLE_DIR / "table5_lopo.csv", index=False)
  279. lopo_valid = lopo_df[~lopo_df["is_stress_test"]]
  280. lopo_stress = lopo_df[lopo_df["is_stress_test"]]
  281. print(f" LOPO válido={lopo_valid['rmse'].mean():.4f} "
  282. f"stress={lopo_stress['rmse'].mean():.4f}")
  283. fitting.compare_mechanistic_vs_baselines_rmse(
  284. fits, data["cal_arr"], data["val_arr"], data["val"]).to_csv(
  285. TABLE_DIR / "table_rmse_vs_baselines.csv", index=False)
  286. validation.save_validation_results(
  287. val_out, val_metrics, group_metrics, pd.DataFrame(), cal_diag, cal_group)
  288. bci = TABLE_DIR / "bootstrap_ci.csv"
  289. if bci.exists() and bci.stat().st_size < 50: bci.unlink()
  290. # Decay comparison
  291. fits_d = {}
  292. for model in ("access", "mixed"):
  293. for dec in (True, False):
  294. key = f"{model}_fixR_{'decay' if dec else 'nodecay'}"
  295. fits_d[key] = fitting.fit_model(
  296. model, data["cal_arr"], data["cell_obs"],
  297. n_starts=CONFIG["N_STARTS"] // 2, cell_weight=1.0,
  298. decay=dec, fix_rescues=True, seed=CONFIG["SEED"] + 99, verbose=True)
  299. fitting.information_criteria(
  300. fits_d, len(data["cal_arr"]["y"]) + len(data["cell_obs"])).to_csv(
  301. TABLE_DIR / "tableS_decay_comparison.csv", index=False)
  302. # [7] Bootstrap
  303. print(f"\n[7] Bootstrap (n={CONFIG['N_BOOT']})...")
  304. boot_df = validation.run_bootstrap(
  305. cal_df=data["cal"], cell_df=data["cell_raw"], best_fit=best_fit,
  306. n_boot=CONFIG["N_BOOT"], n_starts_boot=3,
  307. cell_weight=CONFIG["CELL_WEIGHT"], seed=CONFIG["SEED"] + 2, verbose=True)
  308. ci_df = validation.bootstrap_ci(boot_df)
  309. identif = validation.parameter_identifiability(boot_df)
  310. boot_df.to_csv(TABLE_DIR / "bootstrap_raw.csv", index=False)
  311. ci_df.to_csv(TABLE_DIR / "table4_bootstrap_ci.csv", index=False)
  312. identif.to_csv(TABLE_DIR / "tableS2_identifiability_corr.csv", index=False)
  313. print(ci_df[["parameter", "mean", "ci_low", "ci_high"]].to_string(index=False))
  314. print(" Bootstrap individual (n=200)...")
  315. boot_ind = validation.run_bootstrap_individual(
  316. cal_df=data["cal"], cell_ind=data["cell_ind"],
  317. best_fit=best_fit_ind, n_boot=200, n_starts_boot=3,
  318. seed=CONFIG["SEED"] + 3, verbose=True)
  319. ci_ind = validation.bootstrap_ci(boot_ind)
  320. boot_ind.to_csv(TABLE_DIR / "bootstrap_individual_raw.csv", index=False)
  321. ci_ind.to_csv(TABLE_DIR / "table4b_bootstrap_ci_individual.csv", index=False)
  322. # Model averaging con varianza incondicional (usando bootstrap ya calculado)
  323. # Usa modelos agregados (access/mixed/storage fixR) — declarado como tal
  324. fits_fixR = {k: v for k, v in fits.items() if k in ("access_fixR", "mixed_fixR", "storage_fixR")}
  325. ic_fixR = ic[ic["key"].isin(fits_fixR.keys())].copy()
  326. ma = _model_averaging_unconditional(fits_fixR, ic_fixR, boot_df)
  327. (TABLE_DIR / "model_averaging.json").write_text(
  328. json.dumps({k: _s(v) for k, v in ma.items() if k != "details"}, indent=2))
  329. print(f" MA (agregado): d_C={ma['d_C_MA']:.3f} "
  330. f"CI_uncond=[{ma['ci_lo_unconditional']:.3f},{ma['ci_hi_unconditional']:.3f}]")
  331. # [8] Perfiles, recuperación, ΔRMSE correcto, omega-lambda
  332. print(f"\n[8] Perfiles, recuperación, ΔRMSE, omega-lambda...")
  333. model_b = best_fit["model"]; decay_b = best_fit["decay"]; fix_r_b = best_fit["fix_rescues"]
  334. names_b, lo_b, hi_b = parameter_spec(model_b, decay_b, fix_r_b)
  335. profiles = {}
  336. for pname in ["d_C", "theta_r"]:
  337. if pname not in names_b: continue
  338. idx_p = names_b.index(pname)
  339. p_range = np.linspace(lo_b[idx_p] + 0.01, hi_b[idx_p] - 0.02, 40)
  340. print(f" Perfil {pname}...")
  341. prof = fitting.likelihood_profile(pname, p_range, best_fit,
  342. data["cal_arr"], data["cell_obs"],
  343. cell_weight=CONFIG["CELL_WEIGHT"],
  344. n_starts_refit=5, seed=CONFIG["SEED"] + 3)
  345. profiles[pname] = prof
  346. prof.to_csv(TABLE_DIR / f"profile_{pname}.csv", index=False)
  347. if prof["in_ci95"].any():
  348. print(f" [{prof.loc[prof['in_ci95'], 'param_value'].min():.3f},"
  349. f"{prof.loc[prof['in_ci95'], 'param_value'].max():.3f}]")
  350. # Recuperación cuadrícula
  351. dc_grid = [0.20, 0.35, 0.50, 0.65, 0.80]
  352. frames = []; base_params = best_fit["parameters"].copy()
  353. for dc_true in dc_grid:
  354. rdf = fitting.synthetic_recovery(
  355. true_params={**base_params, "d_C": dc_true}, model=model_b,
  356. arrays_template=data["cal_arr"], cell_obs_template=data["cell_obs"],
  357. n_sim=CONFIG["N_SIM_REC"] // len(dc_grid), n_starts=5,
  358. cell_weight=1.0, decay=decay_b, fix_rescues=fix_r_b,
  359. seed=CONFIG["SEED"] + 4 + int(dc_true * 100))
  360. frames.append(rdf)
  361. rec_df = pd.concat(frames, ignore_index=True)
  362. rec_df.to_csv(TABLE_DIR / "synthetic_recovery_raw.csv", index=False)
  363. fitting.recovery_summary(rec_df, ["d_C"]).to_csv(TABLE_DIR / "tableS4_recovery_summary.csv", index=False)
  364. fitting.recovery_summary_detailed(rec_df).to_csv(TABLE_DIR / "tableS4b_recovery_detailed.csv", index=False)
  365. # ΔRMSE correcto: predicciones fijas, índices remuestreados (N=1000)
  366. print(" Bootstrap ΔRMSE (N=1000, predicciones fijas)...")
  367. delta_rmse = fitting.bootstrap_rmse_difference(
  368. data["val"], data["val_arr"], best_fit,
  369. cal_arr=data["cal_arr"], n_boot=1000, seed=55)
  370. (TABLE_DIR / "delta_rmse_bootstrap.json").write_text(json.dumps(delta_rmse, indent=2))
  371. print(f" ΔRMSE: [{delta_rmse['ci_low']:.4f},{delta_rmse['ci_high']:.4f}] "
  372. f"P(+)={delta_rmse['pct_positive']:.2f} incl.cero={delta_rmse['ci_low']<0}")
  373. # Omega-lambda
  374. omega_map = None
  375. p11 = data["struct"][data["struct"]["protocol_id"] == "P11_selective_opto_retrieval"]
  376. g1 = p11[p11["condition_label"] == "Group 1"]["spi_for_model"].dropna().values
  377. g2 = p11[p11["condition_label"] == "Group 2"]["spi_for_model"].dropna().values
  378. if len(g1) >= 3 and len(g2) >= 3:
  379. omega_map = omega_lambda_compatibility_map(
  380. best_fit["result"].x, model_b, g1, g2,
  381. decay=decay_b, fix_rescues=fix_r_b, n_omega=80, n_lam=80)
  382. print(f" omega-lambda: {omega_map['n_compatible']}/6400 compatible")
  383. (TABLE_DIR / "omega_lambda_map.json").write_text(json.dumps({
  384. "obs_mean": omega_map["obs_mean"], "obs_se": omega_map["obs_se"],
  385. "n_compatible": omega_map["n_compatible"], "note": omega_map["note"]}, indent=2))
  386. # [9] Figuras
  387. print("\n[9] Figuras...")
  388. plots.fig1_behavior(data["memory"])
  389. plots.fig2_cellular(data["cell_raw"])
  390. plots.fig3_identifiability(data["cell_obs"])
  391. plots.fig4_model_comparison(ic)
  392. plots.fig5_calibration(cal_out, cal_group)
  393. plots.fig6_validation(val_out, group_metrics, val_metrics, lopo_df)
  394. plots.fig7_latent_trajectories(best_fit)
  395. plots.fig8_two_memories(best_fit, omega_map)
  396. plots.figS1_bootstrap(boot_df, ci_df)
  397. if profiles: plots.figS2_likelihood_profiles(profiles)
  398. if not rec_df.empty: plots.figS3_synthetic_recovery(rec_df, ["d_C"])
  399. # [10] Summary y verificación
  400. elapsed = time.time() - t0
  401. dc_ind_ci = ci_ind[ci_ind["parameter"] == "d_C"]
  402. summary = {
  403. "version": "V5.1",
  404. "run_date": datetime.datetime.now().isoformat(),
  405. "data_sha256": data_hash, "code_sha256": code_hash,
  406. "config": {k: _s(v) for k, v in CONFIG.items()},
  407. "equivalence_test_passed": True,
  408. # Individual (PRIMARY)
  409. "individual_model": {
  410. "best_key": "access_IND",
  411. "d_C_MLE": float(best_fit_ind["parameters"].get("d_C", 0)),
  412. "d_C_boot_mean": float(dc_ind_ci["mean"].values[0]) if len(dc_ind_ci) else None,
  413. "d_C_boot_ci": [float(dc_ind_ci["ci_low"].values[0]),
  414. float(dc_ind_ci["ci_high"].values[0])] if len(dc_ind_ci) else None,
  415. "AICc_corrected": float(ic_ind_corr.loc[ic_ind_corr["key"] == "access_IND",
  416. "AICc_corrected"].values[0]),
  417. "delta_AICc_mixed": float(ic_ind_corr.loc[ic_ind_corr["key"] == "mixed_IND",
  418. "delta_AICc"].values[0]),
  419. "delta_AICc_storage": float(ic_ind_corr.loc[ic_ind_corr["key"] == "storage_IND",
  420. "delta_AICc"].values[0]),
  421. },
  422. # Aggregate (SENSITIVITY)
  423. "aggregate_model": {
  424. "best_key": best_key,
  425. "d_C_MLE": float(best_fit["parameters"].get("d_C", 0)),
  426. "d_C_boot_ci": [float(ci_df.loc[ci_df["parameter"] == "d_C", "ci_low"].values[0]),
  427. float(ci_df.loc[ci_df["parameter"] == "d_C", "ci_high"].values[0])],
  428. },
  429. # Model averaging (aggregate fixR models)
  430. "model_averaging_aggregate": {
  431. "d_E_MA": ma["d_E_MA"], "d_C_MA": ma["d_C_MA"],
  432. "ci_lo_unconditional": ma["ci_lo_unconditional"],
  433. "ci_hi_unconditional": ma["ci_hi_unconditional"],
  434. },
  435. # Pseudocount
  436. "zero_sensitivity": zero_sens,
  437. # Predictive check
  438. "val_metrics": {k: _s(v) for k, v in val_metrics.items()},
  439. "delta_rmse_bootstrap": {k: _s(v) for k, v in delta_rmse.items()},
  440. "lopo_rmse_valid": float(lopo_valid["rmse"].mean()),
  441. "omega_compatible": omega_map["n_compatible"] if omega_map else None,
  442. "elapsed_s": elapsed,
  443. }
  444. (MODEL_DIR / "analysis_summary.json").write_text(json.dumps(summary, indent=2))
  445. _verify_sync(CONFIG)
  446. print(f"\n{'='*65}")
  447. print(f" V5.1 completado en {elapsed:.0f}s")
  448. print(f" Individual: d_C MLE={summary['individual_model']['d_C_MLE']:.3f} "
  449. f"ΔAICc_storage={summary['individual_model']['delta_AICc_storage']:.2f}")
  450. print(f" Aggregate: d_C MLE={summary['aggregate_model']['d_C_MLE']:.3f}")
  451. print(f" MA: d_C={summary['model_averaging_aggregate']['d_C_MA']:.3f} "
  452. f"CI=[{summary['model_averaging_aggregate']['ci_lo_unconditional']:.3f},"
  453. f"{summary['model_averaging_aggregate']['ci_hi_unconditional']:.3f}]")
  454. print(f" ΔRMSE CI=[{delta_rmse['ci_low']:.4f},{delta_rmse['ci_high']:.4f}] incl.0={delta_rmse['ci_low']<0}")
  455. print(f" Val RMSE={val_metrics['rmse']:.4f}")
  456. print("=" * 65)
  457. return summary
  458. if __name__ == "__main__":
  459. main()

run_analysis.py, under MIT · at the source

Overview

  1. Neurobiology Expertise Group, Groningen Institute for Evolutionary Life Sciences (GELIFES), University of Groningen, Groningen, Netherlands
  2. Evolutionary Genetics, Development & Behaviour Group, Groningen Institute for Evolutionary Life Sciences (GELIFES), University of Groningen, Groningen, Netherlands
Institutions: University of Groningen (Netherlands)
Journal: Science advances, volume 12, issue 24, article eadu9805
Dates: received 29 November 2024; accepted 1 May 2026; published online 10 June 2026; in print June 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1126/sciadv.adu9805 · PMID 42268954 · PMCID PMC13251821 · OpenAlex W7164130601
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: mouse (organism)
Methods: Statistics, fMRI & imaging, Smoothing, state filtering, decompositions
MeSH: Memory, Long-Term*, Recognition, Psychology*, Sleep Deprivation*, Social Behavior*, Amnesia, Animals, Dentate Gyrus, Male, Mice, Optogenetics (* major topic)
Journal subjects: Neuroscience
Topic: Sleep and Wakefulness Research (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: Rijksuniversiteit Groningen (Adaptive Life Program Fellowship); Nederlandse Organisatie voor Wetenschappelijk Onderzoek (OCENW.M.23.219); United States Air Force Office of Scientific Research (FA9550-21-1-0310)
Citations: not cited yet (Europe PMC); 68 references in the paper

Abstract

Long-term social memories are vital for forming and maintaining relationships, and social amnesia can disrupt daily life. Using a new paradigm to study these hippocampus-dependent memories, we show that mice can distinguish between multiple social experiences even when they occur in the same context across days. Sleep deprivation immediately after socialization disrupts memory consolidation, leading to social amnesia. Treatment with the Food and Drug Administration–approved phosphodiesterase type 4 inhibitor roflumilast during sleep deprivation protects memory consolidation, while administration immediately before testing reverses social amnesia temporarily. Optogenetic reactivation of dentate gyrus engram cells restores social memory access and enables selective retrieval of individual memories. In addition, using two cFos-based engram-tagging strategies, we find that sleep deprivation selectively affects reactivation of experience-specific engrams while not affecting engram formation or overlap. These results suggest that impaired engram reactivation contributes to sleep deprivation–induced social amnesia and highlights the role of the hippocampal dentate gyrus in maintaining and distinguishing social experiences in a single context.

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

Zenodo 20786379

License: MIT
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: DataCite
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (8 files), pandas (8 files), SciPy (6 files), Matplotlib (2 files), statsmodels (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
  • 27 September 2026: the link answers (HTTP 200)
13 files

Zenodo 20786380

License: MIT
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: DataCite
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (8 files), pandas (8 files), SciPy (6 files), Matplotlib (2 files), statsmodels (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
  • 27 September 2026: the link answers (HTTP 200)
13 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;
  • 22 scripts, each with its path and the digest of its content;
  • 6 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, code, and materials availability

All data and code needed to evaluate and reproduce the results in the paper are present in the paper and/or the Supplementary Materials. This study did not generate new materials. The datasets generated and codes used during this study are made publicly available on Dataverse-NL (permalink: https://doi.org/10.34894/0VQF4B) at the date of acceptance.

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, 13 authors, 10 MeSH terms, 3 funders, 65 references.

Cite

This paper

Sarma, A., Paraciani, C., Cao, J., Tyumeneva, E., Stacchiola, C., Meijer, E. L., de Vries, N., Smit, S., Meijer, F., Bonne, M., Billeter, J.-C., Meerlo, P., & Havekes, R. (2026). Restoring access to long-term social recognition memories disrupted by sleep deprivation. Science advances, 12(24), eadu9805. https://doi.org/10.1126/sciadv.adu9805

BibTeX

@article{sarma2026restoring,
author = {Sarma, Adithya and Paraciani, Camilla and Cao, Junfei and Tyumeneva, Evgeniya and Stacchiola, Caterina and Meijer, Elroy L. and de Vries, Nienke and Smit, Soraya and Meijer, Fleur and Bonne, Marit and Billeter, Jean-Christophe and Meerlo, Peter and Havekes, Robbert},
title = {{Restoring access to long-term social recognition memories disrupted by sleep deprivation}},
journal = {Science advances},
year = {2026},
month = jun,
volume = {12},
number = {24},
pages = {eadu9805},
publisher = {American Association for the Advancement of Science},
issn = {2375-2548},
doi = {10.1126/sciadv.adu9805},
url = {https://doi.org/10.1126/sciadv.adu9805},
pmid = {42268954},
pmcid = {PMC13251821}
}

RIS

TY - JOUR
AU - Sarma, Adithya
AU - Paraciani, Camilla
AU - Cao, Junfei
AU - Tyumeneva, Evgeniya
AU - Stacchiola, Caterina
AU - Meijer, Elroy L.
AU - de Vries, Nienke
AU - Smit, Soraya
AU - Meijer, Fleur
AU - Bonne, Marit
AU - Billeter, Jean-Christophe
AU - Meerlo, Peter
AU - Havekes, Robbert
TI - Restoring access to long-term social recognition memories disrupted by sleep deprivation
T2 - Science advances
J2 - Sci Adv
PY - 2026
DA - 2026/06/10
VL - 12
IS - 24
SP - eadu9805
SN - 2375-2548
PB - American Association for the Advancement of Science
DO - 10.1126/sciadv.adu9805
UR - https://doi.org/10.1126/sciadv.adu9805
LA - en
ER -

CSL-JSON

{
"id": "10.1126/sciadv.adu9805",
"type": "article-journal",
"title": "Restoring access to long-term social recognition memories disrupted by sleep deprivation",
"container-title": "Science advances",
"author": [
{
"family": "Sarma",
"given": "Adithya"
},
{
"family": "Paraciani",
"given": "Camilla"
},
{
"family": "Cao",
"given": "Junfei"
},
{
"family": "Tyumeneva",
"given": "Evgeniya"
},
{
"family": "Stacchiola",
"given": "Caterina"
},
{
"family": "Meijer",
"given": "Elroy L."
},
{
"family": "de Vries",
"given": "Nienke"
},
{
"family": "Smit",
"given": "Soraya"
},
{
"family": "Meijer",
"given": "Fleur"
},
{
"family": "Bonne",
"given": "Marit"
},
{
"family": "Billeter",
"given": "Jean-Christophe"
},
{
"family": "Meerlo",
"given": "Peter"
},
{
"family": "Havekes",
"given": "Robbert"
}
],
"container-title-short": "Sci Adv",
"volume": "12",
"issue": "24",
"page": "eadu9805",
"DOI": "10.1126/sciadv.adu9805",
"PMID": "42268954",
"PMCID": "PMC13251821",
"ISSN": "2375-2548",
"publisher": "American Association for the Advancement of Science",
"URL": "https://doi.org/10.1126/sciadv.adu9805",
"language": "en",
"issued": {
"date-parts": [
[
2026,
6,
10
]
]
}
}

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.1093/sleep/zsac301
Atypical hypnotic compound ML297 restores sleep architecture immediately following emotionally valenced learning, to promote memory consolidation and hippocampal network activation during recall.
Journal: Sleep
In common: mouse, 7 references
[2] doi:10.7554/elife.92860 [code]
Natural forgetting reversibly modulates engram expression.
Journal: eLife
In common: pandas, SciPy, Matplotlib, 1 other tool, mouse, 5 references
[3] doi:10.1186/s13041-026-01298-y
Repeated sleep deprivation selectively reactivates hippocampal CA1 pyramidal neurons.
Journal: Molecular brain
In common: mouse, 6 references
[4] doi:10.1038/s41467-023-37248-8 [code]
Activation of the CA2-ventral CA1 pathway reverses social discrimination dysfunction in Shank3B knockout mice.
Journal: Nature communications
In common: pandas, SciPy, Matplotlib, 1 other tool, mouse, 5 references
[5] doi:10.1016/j.isci.2024.109408 [code]
Sleep-dependent engram reactivation during hippocampal memory consolidation associated with subregion-specific biosynthetic changes.
Journal: iScience
In common: 6 references
[6] doi:10.1038/s41467-026-75162-x [code]
Dyscoordination of thalamic reticular spindles is associated with social memory deficits in mice and humans with autism spectrum disorder.
Journal: Nature communications
In common: mouse, 6 references
[7] doi:10.1038/s41467-023-38338-3
Dynamic and stable hippocampal representations of social identity and reward expectation support associative social memory in male mice.
Journal: Nature communications
In common: mouse, 6 references
[8] doi:10.1038/s41467-023-42751-z [code]
Spatial transcriptomics reveals unique gene expression changes in different brain regions after sleep deprivation.
Journal: Nature communications
In common: mouse, 5 references
[9] doi:10.3389/fnins.2025.1633386 [code]
Differential susceptibility to prenatal stress exposure in serotonin transporter-deficient female mice-an epigenetic exploration.
Journal: Frontiers in neuroscience
In common: statsmodels, pandas, SciPy, 2 other tools, mouse, 3 references
[10] doi:10.1038/s41380-021-01430-5
Disrupted social memory ensembles in the ventral hippocampus underlie social amnesia in autism-associated Shank3 mutant mice.
Journal: Molecular psychiatry
In common: mouse, 5 references

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.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1126/sciadv.adu9805.svg)](https://openscicode.org/badge/doi/10.1126/sciadv.adu9805)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1126/sciadv.adu9805.svg
   :target: https://openscicode.org/badge/doi/10.1126/sciadv.adu9805
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1126/sciadv.adu9805"><img src="https://openscicode.org/badge/doi/10.1126/sciadv.adu9805.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge 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: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

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