Restoring access to long-term social recognition memories disrupted by sleep deprivation.
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] § 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] § 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] § 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] § 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] § 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] § 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
- """
- run_analysis.py — V5.1
- =======================
- Pipeline reproducible V5.1. Genera exactamente los outputs del manuscrito.
- Correcciones V5.1 respecto a V5:
- - bootstrap_rmse_difference: predicciones fijas, índices remuestreados (N=1000)
- - power_formation_contrast: parámetros por marcador (EGFP/mCherry), N_sim=5000
- - Model averaging: agregado (acc/mix/sto fixR) con varianza incondicional
- - AICc individual corregido: k = k_mech + 8, n = 275
- - Ceros declarados; sensibilidad pseudocuenta
- - version = V5.1 en CONFIG y run_metadata
- Para publicación: N_STARTS=100, N_BOOT=1000, N_SIM_REC=500
- """
- import sys, json, time, shutil, hashlib, datetime
- import numpy as np, pandas as pd
- from pathlib import Path
- sys.path.insert(0, str(Path(__file__).parent))
- from src.config import TABLE_DIR, MODEL_DIR, FIG_DIR, OUTPUT_DIR, DATA_DIR
- from src import data_loader, stats, fitting, validation, plots
- from src.model import (identifiability_proposition, cellular_analytic_estimate,
- omega_lambda_compatibility_map, latent_states_summary,
- parameter_spec, test_equivalence, model_averaged_estimates,
- power_formation_contrast, power_decay_detection,
- cellular_individual_nll)
- # ══════════════════════════════════════════════════════════════════════════════
- # CONFIGURACIÓN
- # ══════════════════════════════════════════════════════════════════════════════
- CONFIG = {
- "N_STARTS": 50,
- "N_BOOT": 500,
- "N_SIM_REC": 100,
- "CELL_WEIGHT": 1.0,
- "SEED": 12345,
- "version": "V5.1",
- }
- # ══════════════════════════════════════════════════════════════════════════════
- def _s(obj):
- if isinstance(obj, (bool, np.bool_)): return bool(obj)
- if isinstance(obj, np.integer): return int(obj)
- if isinstance(obj, (float, np.floating)): return float(obj)
- if isinstance(obj, np.ndarray): return obj.tolist()
- return obj
- def _verify_sync(config):
- meta = json.loads((MODEL_DIR / "run_metadata.json").read_text())
- for key in ("N_STARTS", "N_BOOT", "N_SIM_REC", "SEED", "version"):
- assert str(meta.get(key)) == str(config.get(key)), \
- f"DESINCRONIZACIÓN: {key} metadata={meta.get(key)} config={config.get(key)}"
- print(" ✓ Sincronización verificada")
- def _aicc_individual_corrected(fits_ind, n_obs_correct=275):
- """
- AICc individual con k = k_mech + 8 (cuatro intercepts + cuatro varianzas)
- y n = 275 (189 beh + 44 form + 42 reac).
- """
- rows = []
- for key, fit in fits_ind.items():
- k_mech = len(fit["names"])
- k_corr = k_mech + 8
- ll = -fit["result"].fun
- aic = 2*k_corr - 2*ll
- aicc = aic + (2*k_corr*(k_corr+1)) / max(n_obs_correct - k_corr - 1, 1)
- bic = k_corr * np.log(n_obs_correct) - 2*ll
- rows.append({"key": key, "k_mech": k_mech, "k_corr": k_corr,
- "logLik": ll, "AICc_corrected": aicc, "BIC_corrected": bic})
- df = pd.DataFrame(rows).sort_values("AICc_corrected").reset_index(drop=True)
- d = df["AICc_corrected"] - df["AICc_corrected"].min()
- w = np.exp(-0.5 * d)
- df["delta_AICc"] = d; df["AICc_weight"] = w / w.sum()
- return df
- def _model_averaging_unconditional(fits_fixR, ic_fixR, boot_raw_df):
- """
- Model averaging con varianza incondicional = within + between.
- Within-model variance: bootstrap de access_fixR (solo el disponible).
- Between-model variance: dispersión entre estimaciones ponderadas.
- """
- rows = []
- for key, fit in fits_fixR.items():
- w = ic_fixR.loc[ic_fixR["key"] == key, "AICc_weight"].values
- if len(w) == 0: continue
- rows.append({"key": key, "weight": float(w[0]),
- "d_E": fit["parameters"].get("d_E", 0.0),
- "d_C": fit["parameters"].get("d_C", 0.0)})
- df_w = pd.DataFrame(rows)
- d_C_MA = float((df_w["weight"] * df_w["d_C"]).sum())
- d_E_MA = float((df_w["weight"] * df_w["d_E"]).sum())
- # within-model (bootstrap access_fixR)
- var_within_C = float(boot_raw_df["d_C"].var(ddof=1)) if "d_C" in boot_raw_df else 0.0
- # between-model
- var_between_C = float((df_w["weight"] * (df_w["d_C"] - d_C_MA)**2).sum())
- var_total_C = var_within_C + var_between_C
- sd_total_C = var_total_C**0.5
- ci_lo = d_C_MA - 1.96 * sd_total_C
- ci_hi = d_C_MA + 1.96 * sd_total_C
- return {
- "d_E_MA": d_E_MA, "d_C_MA": d_C_MA,
- "var_within_d_C": var_within_C, "var_between_d_C": var_between_C,
- "var_total_d_C": var_total_C, "sd_total_d_C": sd_total_C,
- "ci_lo_unconditional": float(ci_lo), "ci_hi_unconditional": float(ci_hi),
- "note": ("Aggregate-model MA: access/mixed/storage-fixR weighted by AICc. "
- "Unconditional CI = within (bootstrap access_fixR) + between models."),
- "details": df_w.to_dict(orient="records"),
- }
- def _pseudocount_sensitivity(data, best_fit_ind):
- """Sensibilidad de d_C a ceros celulares con pseudocuenta log(v+0.5)."""
- from scipy.optimize import minimize
- cell_raw = data["cell_raw"]
- p12 = cell_raw[(cell_raw["protocol_id"] == "P12_dual_engram_tagging")
- & (cell_raw["blade"] == "whole_DG")]
- reac_specs = [("engram_reactivation_colocalization", "EGFP+cFos", 0),
- ("engram_reactivation_colocalization", "mCherry+cFos", 1)]
- form_specs = [("EGFP_positive_cells", "EGFP", 0),
- ("mCherry_positive_cells", "mCherry", 1)]
- log_yF = []; sdF = []; mF = []
- for meas, marker, midx in form_specs:
- d = p12[(p12["measurement"] == meas) & (p12["marker"] == marker)]
- for _, row in d.iterrows():
- v = row["value"]
- if v <= 0: continue
- log_yF.append(np.log(v)); sdF.append(1 if row["sleep_status"] == "SD" else 0)
- mF.append(midx)
- log_yR_p = []; sdR_p = []; mR_p = []
- for meas, marker, midx in reac_specs:
- d = p12[(p12["measurement"] == meas) & (p12["marker"] == marker)]
- for _, row in d.iterrows():
- log_yR_p.append(np.log(row["value"] + 0.5)) # pseudocuenta
- sdR_p.append(1 if row["sleep_status"] == "SD" else 0)
- mR_p.append(midx)
- cell_pseudo = {
- "log_y_F_arr": np.array(log_yF), "sd_flag_F_arr": np.array(sdF), "m_idx_F_arr": np.array(mF),
- "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),
- "n_F": len(log_yF), "n_R": len(log_yR_p),
- }
- model = best_fit_ind["model"]; decay = best_fit_ind["decay"]; fix_r = best_fit_ind["fix_rescues"]
- names, lower, upper = parameter_spec(model, decay, fix_r)
- bounds = list(zip(lower, upper))
- rng = np.random.default_rng(42)
- from src.model import cellular_individual_nll_theta
- best = None
- for _ in range(20):
- x0 = rng.uniform(lower, upper)
- res = minimize(cellular_individual_nll_theta, x0=x0,
- args=(data["cal_arr"], model, cell_pseudo, decay, fix_r),
- method="L-BFGS-B", bounds=bounds,
- options={"maxiter": 4000, "ftol": 1e-12})
- if best is None or res.fun < best.fun: best = res
- params_p = dict(zip(names, best.x))
- return {
- "method": "pseudocount_log_v_plus_0.5",
- "n_R_with_pseudo": len(log_yR_p),
- "n_zeros_included": 2,
- "d_C_pseudo": float(params_p.get("d_C", float("nan"))),
- "d_C_original": float(best_fit_ind["parameters"].get("d_C", float("nan"))),
- "difference": float(abs(params_p.get("d_C", 0) - best_fit_ind["parameters"].get("d_C", 0))),
- "note": ("Two reactivation values were exactly zero in the original data. "
- "The primary analysis excludes them (log-transformation). "
- "This sensitivity uses log(v+0.5)."),
- }
- def main():
- t0 = time.time()
- print("=" * 65)
- print(" Sleep Memory Model V5.1 — Pipeline reproducible")
- print("=" * 65)
- print("\n[0] Limpiando output/...")
- if OUTPUT_DIR.exists(): shutil.rmtree(OUTPUT_DIR)
- for d in (FIG_DIR, TABLE_DIR, MODEL_DIR): d.mkdir(parents=True, exist_ok=True)
- # [1] Metadatos
- print("\n[1] Metadatos...")
- data_hash = fitting.compute_data_hash(
- DATA_DIR / "behavior_paired.csv", DATA_DIR / "cellular_long.csv")
- code_hash = fitting.compute_code_hash()
- fitting.save_run_metadata(CONFIG, data_hash, code_hash)
- print(f" data={data_hash} code={code_hash}")
- # [2] Datos
- print("\n[2] Datos...")
- data = data_loader.load_all()
- audit = data["spi_audit"]
- print(f" SPI audit: {'✓' if audit['passed'] else '✗'} "
- f"Cal={len(data['cal'])} Val={len(data['val'])}")
- print(f" cell_ind: n_F={data['cell_ind']['n_F']} n_R={data['cell_ind']['n_R']} "
- f"(2 zeros excluidos de reactivación)")
- # [3] Equivalencia
- print("\n[3] Test de equivalencia...")
- eq = test_equivalence(data["cal_arr"])
- assert eq["all_passed"], "EQUIVALENCIA FALLIDA"
- print(" ✓ storage ≡ access en conducta (max_diff = 0)")
- # [4] Estadísticas descriptivas
- print("\n[4] Estadística descriptiva...")
- stats.behavior_summary(data["memory"]).to_csv(TABLE_DIR / "table1_behavior_summary.csv", index=False)
- stats.one_sample_spi_tests(data["memory"]).to_csv(TABLE_DIR / "table1b_spi_vs_zero.csv", index=False)
- cell_cont = stats.cellular_contrasts(data["cell_raw"])
- cell_cont.to_csv(TABLE_DIR / "table2_cellular_contrasts.csv", index=False)
- stats.exploration_confound_tests(data["memory"]).to_csv(TABLE_DIR / "tableS1_exploration_confound.csv", index=False)
- cell_est = cellular_analytic_estimate(data["cell_obs"])
- print(f" {cell_est['message']}")
- (TABLE_DIR / "cell_analytic_estimate.json").write_text(
- json.dumps({k: _s(v) for k, v in cell_est.items()}, indent=2))
- prop = identifiability_proposition(data["cell_obs"])
- (TABLE_DIR / "identifiability_proposition.json").write_text(
- json.dumps({k: _s(v) for k, v in prop.items()
- if k not in ("d_E_equipotential", "d_C_equipotential")}, indent=2))
- # [5] Ajuste familia simétrica (agregado — sensibilidad/secundario)
- print(f"\n[5] Familia simétrica (N_STARTS={CONFIG['N_STARTS']})...")
- fits, ic = fitting.run_fitting(data["cal_arr"], data["cell_obs"],
- n_starts=CONFIG["N_STARTS"],
- cell_weight=CONFIG["CELL_WEIGHT"],
- seed=CONFIG["SEED"], verbose=True)
- best_key = fitting.best_fit_key(ic)
- best_fit = fits[best_key]
- fitting.parameter_table(best_fit).to_csv(TABLE_DIR / "table3_parameters.csv", index=False)
- ic.to_csv(TABLE_DIR / "table3_model_comparison.csv", index=False)
- print(f"\n Mejor agregado: {best_key}")
- # Solo conducta
- validation.sensitivity_behavior_only(data["cal_arr"], data["cell_obs"],
- n_starts=CONFIG["N_STARTS"] // 2,
- seed=CONFIG["SEED"] + 10)["ic"].to_csv(
- TABLE_DIR / "tableS3_sensitivity_beh_only.csv", index=False)
- # [5b] Modelo celular individual (PRIMARIO)
- print("\n[5b] Modelo celular individual (PRIMARIO)...")
- fits_ind = {}
- for model in ("storage", "access", "mixed"):
- fits_ind[f"{model}_IND"] = fitting.fit_model_individual(
- model, data["cal_arr"], data["cell_ind"],
- n_starts=CONFIG["N_STARTS"], decay=False, fix_rescues=True,
- seed=CONFIG["SEED"], verbose=True)
- # AICc corregido: k = k_mech + 8, n = 275
- ic_ind_corr = _aicc_individual_corrected(fits_ind, n_obs_correct=275)
- ic_ind_corr.to_csv(TABLE_DIR / "table3b_model_comparison_individual_corrected.csv", index=False)
- print("\n AICc individual CORREGIDO (k+8, n=275):")
- print(ic_ind_corr[["key", "k_corr", "AICc_corrected", "delta_AICc", "AICc_weight"]].to_string(index=False))
- best_fit_ind = fits_ind["access_IND"]
- print(f"\n d_C individual MLE: {best_fit_ind['parameters'].get('d_C', 0):.3f}")
- # [5c] Sensibilidades
- print("\n[5c] Sensibilidades...")
- sw = fitting.sensitivity_cell_weight(data["cal_arr"], data["cell_obs"],
- n_starts=CONFIG["N_STARTS"] // 2, seed=77)
- sw.to_csv(TABLE_DIR / "tableS_sensitivity_cell_weight.csv", index=False)
- se_sens = fitting.sensitivity_cell_error(data["cal_arr"], data["cell_obs"],
- n_starts=CONFIG["N_STARTS"] // 2, seed=88)
- se_sens.to_csv(TABLE_DIR / "tableS_sensitivity_cell_error.csv", index=False)
- fitting.baselines_beh_aic(data["cal_arr"], len(data["cal_arr"]["y"])).to_csv(
- TABLE_DIR / "tableS_baselines_beh_aic.csv", index=False)
- # Pseudocuenta sensibilidad
- print(" Pseudocuenta sensibilidad...")
- zero_sens = _pseudocount_sensitivity(data, best_fit_ind)
- (TABLE_DIR / "tableS_zero_sensitivity.json").write_text(json.dumps(zero_sens, indent=2))
- print(f" d_C original={zero_sens['d_C_original']:.3f} "
- f"d_C_pseudo={zero_sens['d_C_pseudo']:.3f} diff={zero_sens['difference']:.3f}")
- # [5d] Potencia con parámetros reales por marcador, N_sim=5000
- print("\n[5d] Potencia (N_sim=5000, parámetros por marcador)...")
- power_rows = []
- for d_E in [0.082, 0.10, 0.15, 0.20, 0.30, 0.40]:
- for n in [8, 10, 12, 20]:
- for marker in ["EGFP", "mCherry"]:
- p = power_formation_contrast(n, d_E, marker=marker,
- n_sim=5000, seed=42)
- power_rows.append({"d_E_true": d_E, "n_per_group": n,
- "marker": marker, "power": round(p, 3)})
- power_df = pd.DataFrame(power_rows)
- power_df.to_csv(TABLE_DIR / "tableS_power_formation.csv", index=False)
- print(" Potencia n=10:")
- print(power_df[power_df["n_per_group"] == 10].pivot(
- index="d_E_true", columns="marker", values="power").to_string())
- pd_rows = []
- for muq in [0.05, 0.10, 0.20, 0.30]:
- p = power_decay_detection(muq, n_per_group=10, n_sim=2000, seed=43)
- pd_rows.append({"mu_q_true": muq, "power": round(p, 3)})
- pd.DataFrame(pd_rows).to_csv(TABLE_DIR / "tableS_power_decay.csv", index=False)
- # [6] Calibración y validación
- print("\n[6] Calibración y validación...")
- cal_out, cal_diag, cal_group = validation.calibration_diagnostics(
- data["cal"], data["cal_arr"], best_fit)
- val_out, val_metrics, group_metrics = validation.external_validation(
- data["val"], data["val_arr"], best_fit)
- print(f" Cal RMSE={cal_diag['rmse']:.4f} "
- f"Val RMSE={val_metrics['rmse']:.4f} R²={val_metrics['r2']:.4f}")
- lopo_df = validation.leave_one_protocol_out(
- data["cal"], data["cell_obs"], best_fit,
- n_starts=20, cell_weight=CONFIG["CELL_WEIGHT"], seed=CONFIG["SEED"] + 1)
- lopo_df.to_csv(TABLE_DIR / "table5_lopo.csv", index=False)
- lopo_valid = lopo_df[~lopo_df["is_stress_test"]]
- lopo_stress = lopo_df[lopo_df["is_stress_test"]]
- print(f" LOPO válido={lopo_valid['rmse'].mean():.4f} "
- f"stress={lopo_stress['rmse'].mean():.4f}")
- fitting.compare_mechanistic_vs_baselines_rmse(
- fits, data["cal_arr"], data["val_arr"], data["val"]).to_csv(
- TABLE_DIR / "table_rmse_vs_baselines.csv", index=False)
- validation.save_validation_results(
- val_out, val_metrics, group_metrics, pd.DataFrame(), cal_diag, cal_group)
- bci = TABLE_DIR / "bootstrap_ci.csv"
- if bci.exists() and bci.stat().st_size < 50: bci.unlink()
- # Decay comparison
- fits_d = {}
- for model in ("access", "mixed"):
- for dec in (True, False):
- key = f"{model}_fixR_{'decay' if dec else 'nodecay'}"
- fits_d[key] = fitting.fit_model(
- model, data["cal_arr"], data["cell_obs"],
- n_starts=CONFIG["N_STARTS"] // 2, cell_weight=1.0,
- decay=dec, fix_rescues=True, seed=CONFIG["SEED"] + 99, verbose=True)
- fitting.information_criteria(
- fits_d, len(data["cal_arr"]["y"]) + len(data["cell_obs"])).to_csv(
- TABLE_DIR / "tableS_decay_comparison.csv", index=False)
- # [7] Bootstrap
- print(f"\n[7] Bootstrap (n={CONFIG['N_BOOT']})...")
- boot_df = validation.run_bootstrap(
- cal_df=data["cal"], cell_df=data["cell_raw"], best_fit=best_fit,
- n_boot=CONFIG["N_BOOT"], n_starts_boot=3,
- cell_weight=CONFIG["CELL_WEIGHT"], seed=CONFIG["SEED"] + 2, verbose=True)
- ci_df = validation.bootstrap_ci(boot_df)
- identif = validation.parameter_identifiability(boot_df)
- boot_df.to_csv(TABLE_DIR / "bootstrap_raw.csv", index=False)
- ci_df.to_csv(TABLE_DIR / "table4_bootstrap_ci.csv", index=False)
- identif.to_csv(TABLE_DIR / "tableS2_identifiability_corr.csv", index=False)
- print(ci_df[["parameter", "mean", "ci_low", "ci_high"]].to_string(index=False))
- print(" Bootstrap individual (n=200)...")
- boot_ind = validation.run_bootstrap_individual(
- cal_df=data["cal"], cell_ind=data["cell_ind"],
- best_fit=best_fit_ind, n_boot=200, n_starts_boot=3,
- seed=CONFIG["SEED"] + 3, verbose=True)
- ci_ind = validation.bootstrap_ci(boot_ind)
- boot_ind.to_csv(TABLE_DIR / "bootstrap_individual_raw.csv", index=False)
- ci_ind.to_csv(TABLE_DIR / "table4b_bootstrap_ci_individual.csv", index=False)
- # Model averaging con varianza incondicional (usando bootstrap ya calculado)
- # Usa modelos agregados (access/mixed/storage fixR) — declarado como tal
- fits_fixR = {k: v for k, v in fits.items() if k in ("access_fixR", "mixed_fixR", "storage_fixR")}
- ic_fixR = ic[ic["key"].isin(fits_fixR.keys())].copy()
- ma = _model_averaging_unconditional(fits_fixR, ic_fixR, boot_df)
- (TABLE_DIR / "model_averaging.json").write_text(
- json.dumps({k: _s(v) for k, v in ma.items() if k != "details"}, indent=2))
- print(f" MA (agregado): d_C={ma['d_C_MA']:.3f} "
- f"CI_uncond=[{ma['ci_lo_unconditional']:.3f},{ma['ci_hi_unconditional']:.3f}]")
- # [8] Perfiles, recuperación, ΔRMSE correcto, omega-lambda
- print(f"\n[8] Perfiles, recuperación, ΔRMSE, omega-lambda...")
- model_b = best_fit["model"]; decay_b = best_fit["decay"]; fix_r_b = best_fit["fix_rescues"]
- names_b, lo_b, hi_b = parameter_spec(model_b, decay_b, fix_r_b)
- profiles = {}
- for pname in ["d_C", "theta_r"]:
- if pname not in names_b: continue
- idx_p = names_b.index(pname)
- p_range = np.linspace(lo_b[idx_p] + 0.01, hi_b[idx_p] - 0.02, 40)
- print(f" Perfil {pname}...")
- prof = fitting.likelihood_profile(pname, p_range, best_fit,
- data["cal_arr"], data["cell_obs"],
- cell_weight=CONFIG["CELL_WEIGHT"],
- n_starts_refit=5, seed=CONFIG["SEED"] + 3)
- profiles[pname] = prof
- prof.to_csv(TABLE_DIR / f"profile_{pname}.csv", index=False)
- if prof["in_ci95"].any():
- print(f" [{prof.loc[prof['in_ci95'], 'param_value'].min():.3f},"
- f"{prof.loc[prof['in_ci95'], 'param_value'].max():.3f}]")
- # Recuperación cuadrícula
- dc_grid = [0.20, 0.35, 0.50, 0.65, 0.80]
- frames = []; base_params = best_fit["parameters"].copy()
- for dc_true in dc_grid:
- rdf = fitting.synthetic_recovery(
- true_params={**base_params, "d_C": dc_true}, model=model_b,
- arrays_template=data["cal_arr"], cell_obs_template=data["cell_obs"],
- n_sim=CONFIG["N_SIM_REC"] // len(dc_grid), n_starts=5,
- cell_weight=1.0, decay=decay_b, fix_rescues=fix_r_b,
- seed=CONFIG["SEED"] + 4 + int(dc_true * 100))
- frames.append(rdf)
- rec_df = pd.concat(frames, ignore_index=True)
- rec_df.to_csv(TABLE_DIR / "synthetic_recovery_raw.csv", index=False)
- fitting.recovery_summary(rec_df, ["d_C"]).to_csv(TABLE_DIR / "tableS4_recovery_summary.csv", index=False)
- fitting.recovery_summary_detailed(rec_df).to_csv(TABLE_DIR / "tableS4b_recovery_detailed.csv", index=False)
- # ΔRMSE correcto: predicciones fijas, índices remuestreados (N=1000)
- print(" Bootstrap ΔRMSE (N=1000, predicciones fijas)...")
- delta_rmse = fitting.bootstrap_rmse_difference(
- data["val"], data["val_arr"], best_fit,
- cal_arr=data["cal_arr"], n_boot=1000, seed=55)
- (TABLE_DIR / "delta_rmse_bootstrap.json").write_text(json.dumps(delta_rmse, indent=2))
- print(f" ΔRMSE: [{delta_rmse['ci_low']:.4f},{delta_rmse['ci_high']:.4f}] "
- f"P(+)={delta_rmse['pct_positive']:.2f} incl.cero={delta_rmse['ci_low']<0}")
- # Omega-lambda
- omega_map = None
- p11 = data["struct"][data["struct"]["protocol_id"] == "P11_selective_opto_retrieval"]
- g1 = p11[p11["condition_label"] == "Group 1"]["spi_for_model"].dropna().values
- g2 = p11[p11["condition_label"] == "Group 2"]["spi_for_model"].dropna().values
- if len(g1) >= 3 and len(g2) >= 3:
- omega_map = omega_lambda_compatibility_map(
- best_fit["result"].x, model_b, g1, g2,
- decay=decay_b, fix_rescues=fix_r_b, n_omega=80, n_lam=80)
- print(f" omega-lambda: {omega_map['n_compatible']}/6400 compatible")
- (TABLE_DIR / "omega_lambda_map.json").write_text(json.dumps({
- "obs_mean": omega_map["obs_mean"], "obs_se": omega_map["obs_se"],
- "n_compatible": omega_map["n_compatible"], "note": omega_map["note"]}, indent=2))
- # [9] Figuras
- print("\n[9] Figuras...")
- plots.fig1_behavior(data["memory"])
- plots.fig2_cellular(data["cell_raw"])
- plots.fig3_identifiability(data["cell_obs"])
- plots.fig4_model_comparison(ic)
- plots.fig5_calibration(cal_out, cal_group)
- plots.fig6_validation(val_out, group_metrics, val_metrics, lopo_df)
- plots.fig7_latent_trajectories(best_fit)
- plots.fig8_two_memories(best_fit, omega_map)
- plots.figS1_bootstrap(boot_df, ci_df)
- if profiles: plots.figS2_likelihood_profiles(profiles)
- if not rec_df.empty: plots.figS3_synthetic_recovery(rec_df, ["d_C"])
- # [10] Summary y verificación
- elapsed = time.time() - t0
- dc_ind_ci = ci_ind[ci_ind["parameter"] == "d_C"]
- summary = {
- "version": "V5.1",
- "run_date": datetime.datetime.now().isoformat(),
- "data_sha256": data_hash, "code_sha256": code_hash,
- "config": {k: _s(v) for k, v in CONFIG.items()},
- "equivalence_test_passed": True,
- # Individual (PRIMARY)
- "individual_model": {
- "best_key": "access_IND",
- "d_C_MLE": float(best_fit_ind["parameters"].get("d_C", 0)),
- "d_C_boot_mean": float(dc_ind_ci["mean"].values[0]) if len(dc_ind_ci) else None,
- "d_C_boot_ci": [float(dc_ind_ci["ci_low"].values[0]),
- float(dc_ind_ci["ci_high"].values[0])] if len(dc_ind_ci) else None,
- "AICc_corrected": float(ic_ind_corr.loc[ic_ind_corr["key"] == "access_IND",
- "AICc_corrected"].values[0]),
- "delta_AICc_mixed": float(ic_ind_corr.loc[ic_ind_corr["key"] == "mixed_IND",
- "delta_AICc"].values[0]),
- "delta_AICc_storage": float(ic_ind_corr.loc[ic_ind_corr["key"] == "storage_IND",
- "delta_AICc"].values[0]),
- },
- # Aggregate (SENSITIVITY)
- "aggregate_model": {
- "best_key": best_key,
- "d_C_MLE": float(best_fit["parameters"].get("d_C", 0)),
- "d_C_boot_ci": [float(ci_df.loc[ci_df["parameter"] == "d_C", "ci_low"].values[0]),
- float(ci_df.loc[ci_df["parameter"] == "d_C", "ci_high"].values[0])],
- },
- # Model averaging (aggregate fixR models)
- "model_averaging_aggregate": {
- "d_E_MA": ma["d_E_MA"], "d_C_MA": ma["d_C_MA"],
- "ci_lo_unconditional": ma["ci_lo_unconditional"],
- "ci_hi_unconditional": ma["ci_hi_unconditional"],
- },
- # Pseudocount
- "zero_sensitivity": zero_sens,
- # Predictive check
- "val_metrics": {k: _s(v) for k, v in val_metrics.items()},
- "delta_rmse_bootstrap": {k: _s(v) for k, v in delta_rmse.items()},
- "lopo_rmse_valid": float(lopo_valid["rmse"].mean()),
- "omega_compatible": omega_map["n_compatible"] if omega_map else None,
- "elapsed_s": elapsed,
- }
- (MODEL_DIR / "analysis_summary.json").write_text(json.dumps(summary, indent=2))
- _verify_sync(CONFIG)
- print(f"\n{'='*65}")
- print(f" V5.1 completado en {elapsed:.0f}s")
- print(f" Individual: d_C MLE={summary['individual_model']['d_C_MLE']:.3f} "
- f"ΔAICc_storage={summary['individual_model']['delta_AICc_storage']:.2f}")
- print(f" Aggregate: d_C MLE={summary['aggregate_model']['d_C_MLE']:.3f}")
- print(f" MA: d_C={summary['model_averaging_aggregate']['d_C_MA']:.3f} "
- f"CI=[{summary['model_averaging_aggregate']['ci_lo_unconditional']:.3f},"
- f"{summary['model_averaging_aggregate']['ci_hi_unconditional']:.3f}]")
- print(f" ΔRMSE CI=[{delta_rmse['ci_low']:.4f},{delta_rmse['ci_high']:.4f}] incl.0={delta_rmse['ci_low']<0}")
- print(f" Val RMSE={val_metrics['rmse']:.4f}")
- print("=" * 65)
- return summary
- if __name__ == "__main__":
- main()
run_analysis.py, under MIT · at the source
Overview
- Neurobiology Expertise Group, Groningen Institute for Evolutionary Life Sciences (GELIFES), University of Groningen, Groningen, Netherlands
- Evolutionary Genetics, Development & Behaviour Group, Groningen Institute for Evolutionary Life Sciences (GELIFES), University of Groningen, Groningen, Netherlands
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
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
- 27 September 2026: the link answers (HTTP 200)
13 files
- run_analysis.py, Python, 515 lines, 2 matches
- src/
__init__.py , Python, 1 line - src/
config.py , Python, 67 lines - src/
data_loader.py , Python, 127 lines, 2 matches - src/
fitting.py , Python, 389 lines - src/
model.py , Python, 351 lines - src/
plots.py , Python, 583 lines, 1 match - src/
simulate_threshold_model , Python, 195 lines_v1.py - src/
stats.py , Python, 221 lines, 1 match - src/
validation.py , Python, 231 lines - verify_inputs.py, Python, 142 lines
- LICENSE, License, 23 lines
- README.md, Text, 153 lines
Zenodo 20786380
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
- 27 September 2026: the link answers (HTTP 200)
13 files
- run_analysis.py, Python, 515 lines
- src/
__init__.py , Python, 1 line - src/
config.py , Python, 67 lines - src/
data_loader.py , Python, 127 lines - src/
fitting.py , Python, 389 lines - src/
model.py , Python, 351 lines - src/
plots.py , Python, 583 lines - src/
simulate_threshold_model , Python, 195 lines_v1.py - src/
stats.py , Python, 221 lines - src/
validation.py , Python, 231 lines - verify_inputs.py, Python, 142 lines
- LICENSE, License, 23 lines
- README.md, Text, 153 lines
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/
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://
BibTeX
@article{sarma2026restor
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/
url = {https://
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/
VL - 12
IS - 24
SP - eadu9805
SN - 2375-2548
PB - American Association for the Advancement of Science
DO - 10.1126/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1126/
"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":
"volume": "12",
"issue": "24",
"page": "eadu9805",
"DOI": "10.1126/
"PMID": "42268954",
"PMCID": "PMC13251821",
"ISSN": "2375-2548",
"publisher": "American Association for the Advancement of Science",
"URL": "https://
"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: SleepIn common: mouse, 7 references
- [2] doi:10.7554/elife.92860 [code]
- Natural forgetting reversibly modulates engram expression.Journal: eLifeIn 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 brainIn 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 communicationsIn 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: iScienceIn 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 communicationsIn 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 communicationsIn 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 communicationsIn 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 neuroscienceIn 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 psychiatryIn 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.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 2 repositories of the authors' code, each at its verified commit and with its license, 22 scripts, and 6 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:3570b02882a1c7f8…
Add the badge to the code's README
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 -->
[](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:endHTML
<!-- 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.
