#!/usr/bin/env python3
"""Weightome v1 "recipe" releases: connectomes whose upstream files are public but carry no explicit data license.

For these datasets the neuron-level weight tables are NOT redistributed. The release ships
  * this script (as `rebuild.py`), which downloads the upstream files and rebuilds the full tables locally,
  * the cell-type-level weight matrix (`<rid>-types.csv`) and the summary/validation JSON,
  * content checksums of the full tables, so a rebuild can be verified to be identical (`--verify`).

Releases (ids follow docs/NAMING_CONVENTION.md):
  weightome-tg-pb-bg-v1   zebra finch Area X (basal ganglia), j0251 (Rother et al. 2025, bioRxiv
                          10.1101/2025.10.25.684569); SyConn per-synapse area (um^2), v8 cell types
  weightome-mm-pb-cb-v1   mouse cerebellar cortex, CB2 (Nguyen, Thomas et al. 2023, Nature 613, 543);
                          per-synapse cleft mesh area (um^2) from the authors' NetworkX graphs
  weightome-mm-pb-sc-v1   mouse barrel cortex L4 (Motta et al. 2019, Science 366, eaay3134); published axon x target
                          synapse-count connectome (connectome.csv), count x sign

Weight definition (as in Weightome v1.1): w_rel = synapse area / A_ref, A_ref = median area of the synapses with
sign +1 in the release (one anchor for E and I); count-based (w_rel = 1 per synapse) where no area is available.
Sign from the presynaptic cell type.

Usage:
  python rebuild.py weightome-tg-pb-bg-v1 --download            # fetch upstream files, build, verify
  python rebuild.py weightome-mm-pb-cb-v1 --raw DIR --out DIR
Inside the Weightome repository the defaults are data/extra/<dataset> (raw), data/extra_full/<rid> (full tables)
and data/extra_release/<rid> (publishable files). Needs numpy, pandas, scipy, pyarrow (+ networkx for CB2).
"""

from __future__ import annotations

import argparse
import gzip
import hashlib
import json
import pickle
import shutil
import sys
import urllib.request
from pathlib import Path

import numpy as np
import pandas as pd
from scipy import stats

ROOT = Path(__file__).resolve().parents[1]
SEED = 20261203

DATASETS = {
    "weightome-tg-pb-bg-v1": {
        "raw": "finch",
        "base": "https://syconn.esc.mpcdf.mpg.de/connectome/data_v8/",
        "files": ["j0251_synapses.npy", "j0251_neurons.npy", "celltype_mapping.txt", "post_morph_mapping.txt", "version.txt"],
    },
    "weightome-mm-pb-cb-v1": {
        "raw": "cerebellum",
        "base": "https://github.com/htem/cb2_project_analysis_files/releases/download/",
        "files": ["230103/graph_mf_grc_synapse_210518_coalesced.gz", "230103/graph_mf_grc_binary_210519.gz",
                  "230306/graph_grc_pc_synapse_210429_coalesced.gz", "230306/graph_pfs_pc_synapse_210429_coalesced.gz"],
    },
}


# --------------------------------------------------------------------------- helpers
def jdump(p: Path, obj: dict) -> None:
    p.write_text(json.dumps(obj, indent=2, default=lambda o: o.item() if hasattr(o, "item") else str(o)))


def spearman(a, b) -> float:
    return round(float(stats.spearmanr(a, b)[0]), 4)


def content_sha256(df: pd.DataFrame, cols: list[str]) -> str:
    """Checksum of a table's content, independent of parquet/pyarrow versions: sorted CSV, floats rounded to 6 digits."""
    d = df[cols].copy()
    for c in cols:
        if pd.api.types.is_float_dtype(d[c]):
            d[c] = d[c].astype(np.float64).round(6)
    d = d.sort_values(cols[:2], kind="mergesort").reset_index(drop=True)
    return hashlib.sha256(d.to_csv(index=False, float_format="%.6f").encode()).hexdigest()


def download(rid: str, raw: Path) -> None:
    spec = DATASETS[rid]
    raw.mkdir(parents=True, exist_ok=True)
    for f in spec["files"]:
        dst = raw / Path(f).name
        if dst.exists() and dst.stat().st_size > 0:
            continue
        print("downloading", spec["base"] + f, flush=True)
        with urllib.request.urlopen(spec["base"] + f, timeout=600) as r, open(dst, "wb") as o:
            shutil.copyfileobj(r, o, 1 << 20)


class SafeUnpickler(pickle.Unpickler):
    """Loads the CB2 NetworkX pickles without executing arbitrary code: only networkx and plain builtins allowed."""
    ALLOWED = {("builtins", n) for n in ("dict", "list", "tuple", "set", "frozenset", "int", "float", "str", "bool")}

    def find_class(self, module, name):
        if (module, name) in self.ALLOWED or module.startswith("networkx."):
            return super().find_class(module, name)
        raise pickle.UnpicklingError(f"blocked class {module}.{name}")


def load_nx(p: Path):
    with gzip.open(p, "rb") as f:
        return SafeUnpickler(f).load()


def type_matrix(e: pd.DataFrame, area: str) -> pd.DataFrame:
    t = e.groupby(["pre_type", "post_type"]).agg(n_pairs=("n_synapses", "size"), n_synapses=("n_synapses", "sum"),
                                                 area_um2_sum=(area, "sum"), w_rel_sum=("w_rel_sum", "sum"),
                                                 sign=("sign", "first")).reset_index()
    t["w_rel_signed_sum"] = t.w_rel_sum * t.sign
    t["frac_of_pre_output_area"] = t.area_um2_sum / t.groupby("pre_type").area_um2_sum.transform("sum")
    t["frac_of_post_input_area"] = t.area_um2_sum / t.groupby("post_type").area_um2_sum.transform("sum")
    return t.sort_values(["pre_type", "post_type"]).reset_index(drop=True)


def pair_consistency(syn: pd.DataFrame, value: str, group_cols: list[str], strat: str) -> dict:
    """Do two synapses of the same pre->post pair have more similar sizes than two random synapses of the same pathway?

    For every pair with >= 2 synapses, two of its synapses are drawn (fixed seed). Observed: Spearman between the two.
    Null: the second synapse is replaced by a random synapse of the same pathway (`strat`), 20 repeats.
    """
    rng = np.random.default_rng(SEED)
    s = syn[[*group_cols, strat, value]].copy()
    s["_r"] = rng.random(len(s))
    s = s.sort_values([*group_cols, "_r"])
    s["_k"] = s.groupby(group_cols).cumcount()
    a = s[s._k == 0].set_index(group_cols)
    b = s[s._k == 1].set_index(group_cols)
    j = a[[strat, value]].join(b[[value]], rsuffix="_2", how="inner")
    if len(j) < 20:
        return {"n_pairs": int(len(j))}
    obs = float(stats.spearmanr(j[value], j[f"{value}_2"])[0])
    null = []
    pool = {k: g[value].to_numpy() for k, g in syn.groupby(strat)}
    codes = j[strat].to_numpy()
    for _ in range(20):
        rnd = np.empty(len(j))
        for k in np.unique(codes):
            m = codes == k
            rnd[m] = rng.choice(pool[k], int(m.sum()))
        null.append(float(stats.spearmanr(j[value], rnd)[0]))
    return {"n_pairs_with_ge2_synapses": int(len(j)), "spearman_within_pair": round(obs, 4),
            "spearman_null_mean": round(float(np.mean(null)), 4), "spearman_null_sd": round(float(np.std(null)), 4)}


# --------------------------------------------------------------------------- zebra finch Area X (j0251)
FINCH_SIGN = {"HVC": 1, "LMAN": 1, "STN": 1, "DA": 0, "TAN": 0,
              "MSN": -1, "GPe": -1, "GPi": -1, "INT1": -1, "INT2": -1, "INT3": -1, "INT4": -1, "LTS": -1}
FINCH_NT = {"HVC": "glutamate", "LMAN": "glutamate", "STN": "glutamate", "DA": "dopamine", "TAN": "acetylcholine",
            "MSN": "gaba", "GPe": "gaba", "GPi": "gaba", "INT1": "gaba", "INT2": "gaba", "INT3": "gaba", "INT4": "gaba",
            "LTS": "gaba"}
FINCH_AXON_ONLY = ["HVC", "LMAN", "DA"]


def finch(raw: Path, full: Path, stage: Path) -> dict:
    rid = "weightome-tg-pb-bg-v1"
    ct = {int(l.split(":")[0]): l.split(":")[1].strip() for l in open(raw / "celltype_mapping.txt") if ":" in l}
    version = (raw / "version.txt").read_text().splitlines()[0].strip()
    n = pd.DataFrame(np.load(raw / "j0251_neurons.npy", allow_pickle=False))
    n["cell_type_name"] = n.cell_type.map(ct)
    for c in ("skel_length_axon", "skel_length_soma", "skel_length_dendrite"):
        n[c] = n[c].astype(np.float32)
    full_cell = (n.cell_type_name.isin([k for k in FINCH_SIGN if k not in FINCH_AXON_ONLY]) & (n.skel_length_soma > 0)
                 & (n.skel_length_axon >= 200) & (n.skel_length_dendrite >= 200))
    proj_axon = n.cell_type_name.isin(FINCH_AXON_ONLY) & (n.skel_length_axon >= 50)
    neurons = n[full_cell | proj_axon].copy()
    neurons["role"] = np.where(full_cell[full_cell | proj_axon], "full_cell", "projection_axon_fragment")
    neurons = neurons.rename(columns={"id": "neuron_id", "cell_type_name": "cell_type", "cell_type": "cell_type_id_v8"})
    neurons["celltype_certainty"] = neurons.celltype_certainty.astype(np.float32)
    neurons["neurotransmitter"] = neurons.cell_type.map(FINCH_NT)
    neurons["sign"] = neurons.cell_type.map(FINCH_SIGN).astype(np.int8)
    full_ids = set(neurons.loc[neurons.role == "full_cell", "neuron_id"])
    all_ids = set(neurons.neuron_id)

    s = pd.DataFrame(np.load(raw / "j0251_synapses.npy", allow_pickle=False))
    n_up = len(s)
    s["size"] = s["size"].astype(np.float32)
    s["prob"] = s["prob"].astype(np.float32)
    keep = (s.prob >= 0.6) & (s["size"] >= 0.1)
    n_thr = int(keep.sum())
    s = s[keep & s.pre_id.isin(all_ids) & s.post_id.isin(full_ids)]
    n_autapse = int((s.pre_id == s.post_id).sum())
    s = s[s.pre_id != s.post_id].copy()
    s["pre_type"] = s.pre_celltype.map(ct)
    s["post_type"] = s.post_celltype.map(ct)
    s["sign"] = s.pre_type.map(FINCH_SIGN).astype(np.int8)
    a_ref = float(s.loc[s.sign == 1, "size"].median())
    s["w_rel"] = (s["size"] / a_ref).astype(np.float32)
    s["w_rel_signed"] = s.w_rel * s.sign
    morph = {0: "spine_neck", 1: "spine_head", 2: "shaft", 3: "soma", 255: "unknown"}
    s["post_compartment"] = s.post_morph.map(morph)
    syn = pd.DataFrame({"pre_id": s.pre_id, "post_id": s.post_id, "area_um2": s["size"], "prob": s.prob,
                        "x_nm": s.x.astype(np.int64) * 10, "y_nm": s.y.astype(np.int64) * 10, "z_nm": s.z.astype(np.int64) * 25,
                        "post_compartment": s.post_compartment, "pre_type": s.pre_type, "post_type": s.post_type,
                        "sign": s.sign, "w_rel": s.w_rel, "w_rel_signed": s.w_rel_signed}).reset_index(drop=True)

    e = syn.groupby(["pre_id", "post_id"]).agg(n_synapses=("w_rel", "size"), area_um2_sum=("area_um2", "sum"),
                                                w_rel_sum=("w_rel", "sum"), w_rel_mean=("w_rel", "mean"),
                                                sign=("sign", "first"), pre_type=("pre_type", "first"),
                                                post_type=("post_type", "first")).reset_index()
    e["w_rel_signed_sum"] = e.w_rel_sum * e.sign
    nt = neurons.set_index("neuron_id")
    nt["out_synapses"] = e.groupby("pre_id").n_synapses.sum().reindex(nt.index).fillna(0).astype(np.int64)
    nt["in_synapses"] = e.groupby("post_id").n_synapses.sum().reindex(nt.index).fillna(0).astype(np.int64)
    nt["out_w_rel_sum"] = e.groupby("pre_id").w_rel_sum.sum().reindex(nt.index).fillna(0)
    for lab, sg in (("exc", 1), ("inh", -1), ("zero", 0)):
        nt[f"in_{lab}_w_rel_sum"] = e[e.sign == sg].groupby("post_id").w_rel_sum.sum().reindex(nt.index).fillna(0)
    nt = nt.reset_index()
    nt = nt[["neuron_id", "cell_type", "cell_type_id_v8", "celltype_certainty", "role", "neurotransmitter", "sign",
             "skel_length_axon", "skel_length_soma", "skel_length_dendrite", "out_synapses", "in_synapses",
             "out_w_rel_sum", "in_exc_w_rel_sum", "in_inh_w_rel_sum", "in_zero_w_rel_sum"]]

    full.mkdir(parents=True, exist_ok=True)
    syn.to_parquet(full / f"{rid}-synapses.parquet", index=False)
    e.to_parquet(full / f"{rid}-edges.parquet", index=False)
    nt.to_parquet(full / f"{rid}-neurons.parquet", index=False)
    tm = type_matrix(e, "area_um2_sum")
    tm.to_csv(stage / f"{rid}-types.csv", index=False, float_format="%.6g")

    # ---- validation: reproduce published statistics (Rother et al. 2025)
    def frac(pre, post, side):
        r = tm[(tm.pre_type == pre) & (tm.post_type == post)]
        return round(float(r[f"frac_of_{side}_area"].iloc[0]), 4) if len(r) else 0.0
    msn = nt[nt.cell_type == "MSN"].neuron_id
    msn_gpi = e[(e.pre_type == "MSN") & (e.post_type == "GPi")]
    msn_gpe = e[(e.pre_type == "MSN") & (e.post_type == "GPe")]
    gpi = nt[nt.cell_type == "GPi"].neuron_id
    repro = {
        "n_full_cells": {"release": int(len(full_ids)), "published": 8576},
        "msn_output_area_to_gpi": {"release": frac("MSN", "GPi", "pre_output"), "published": 0.629},
        "msn_output_area_to_gpe": {"release": frac("MSN", "GPe", "pre_output"), "published": 0.211},
        "stn_input_area_from_gpe": {"release": frac("GPe", "STN", "post_input"), "published": 0.069},
        "gpe_output_area_to_stn": {"release": frac("GPe", "STN", "pre_output"), "published": 0.168},
        "synapses_per_msn_onto_gpi": {"release": round(float(msn_gpi.groupby("pre_id").n_synapses.sum().reindex(msn).fillna(0).mean()), 2),
                                      "published": "9.6 +- 7.2"},
        "synapses_per_msn_onto_gpe": {"release": round(float(msn_gpe.groupby("pre_id").n_synapses.sum().reindex(msn).fillna(0).mean()), 2),
                                      "published": "3.54 +- 5.4"},
        "msn_synapses_per_gpi_neuron": {"release": round(float(msn_gpi.groupby("post_id").n_synapses.sum().reindex(gpi).fillna(0).mean()), 1),
                                        "published": "1624 +- 881"},
        "note": "published values from Rother et al. 2025 (bioRxiv), which used the v6 cell types; this release uses "
                "the v8 cell types (adds INT4 and OPC), so small differences are expected",
    }
    syn["pathway"] = syn.pre_type + ">" + syn.post_type
    summ = {
        "release_id": rid,
        "release_kind": "recipe (neuron-level tables are rebuilt locally from the upstream files, not redistributed)",
        "upstream": "j0251, adult male zebra finch Area X; Rother, Januszewski, Jain, Fee, Kornfeld 2025, bioRxiv "
                    "10.1101/2025.10.25.684569; SyConn connectome download (syconn.esc.mpcdf.mpg.de/connectome/data_v8/)",
        "upstream_version": version,
        "upstream_license": "none stated for the dataset (preprint text CC BY 4.0); therefore no redistribution of "
                            "neuron- or synapse-level tables",
        "volume": "zebra finch Area X (song-related basal ganglia), 256 x 256 x 384 um, 10 x 10 x 25 nm voxels (SBEM)",
        "selection": "full cells = soma + >= 200 um axon + >= 200 um dendrite skeleton (as in the paper); presynaptic "
                     "projection axons (HVC, LMAN, DA; axon-only in the volume) with >= 50 um axon; synapses with "
                     "probability >= 0.6 and area >= 0.1 um^2, presynaptic partner in the set, postsynaptic partner a full "
                     "cell; autapses removed",
        "size_measure": "area_um2 = SyConn synapse (cleft contact) area in um^2. w_rel = area_um2 / A_ref, A_ref = median "
                        "area of synapses from glutamatergic cell types (HVC, LMAN, STN)",
        "a_ref_area_um2": a_ref,
        "sign_convention": "glutamate (HVC, LMAN, STN) +1; GABA (MSN, GPe, GPi, INT1-4, LTS) -1; dopamine (DA) and "
                           "acetylcholine (TAN) 0. Transmitter by cell type (literature), not measured per neuron",
        "n_synapses_upstream": int(n_up), "n_synapses_prob_and_size_threshold": n_thr,
        "n_synapses": int(len(syn)), "n_autapses_removed": n_autapse, "n_edges": int(len(e)),
        "n_neurons": int(len(nt)), "n_neurons_by_role": {k: int(v) for k, v in nt.role.value_counts().items()},
        "n_full_cells_by_type": {k: int(v) for k, v in nt[nt.role == "full_cell"].cell_type.value_counts().items()},
        "sign_counts_synapses": {str(int(k)): int(v) for k, v in syn.sign.value_counts().items()},
        "content_sha256": {"edges": content_sha256(e, ["pre_id", "post_id", "n_synapses", "area_um2_sum", "w_rel_sum", "sign"]),
                           "neurons": content_sha256(nt, ["neuron_id", "cell_type", "role", "sign", "out_synapses", "in_synapses"]),
                           "synapses": content_sha256(syn, ["pre_id", "post_id", "x_nm", "y_nm", "z_nm", "area_um2", "w_rel"])},
        "validation": {
            "reproduction_of_published_statistics": repro,
            "synapse_detection_upstream": "F1 0.88 for all sizes, 93% true positives under the filter used here "
                                          "(manual validation in Rother et al. 2025, Extended Data Fig. 1d)",
            "size_pair_consistency": pair_consistency(syn, "area_um2", ["pre_id", "post_id"], "pathway"),
            "size_by_post_compartment_median_um2": {k: round(float(v), 4) for k, v in syn.groupby("post_compartment").area_um2.median().items()},
            "e_vs_i_area": {"median_exc": round(float(syn[syn.sign == 1].area_um2.median()), 4),
                            "median_inh": round(float(syn[syn.sign == -1].area_um2.median()), 4)},
            "spearman_w_rel_sum_vs_count": spearman(e.w_rel_sum, e.n_synapses),
        },
    }
    return summ


# --------------------------------------------------------------------------- mouse cerebellum (CB2)
CB_SIGN = {"mf": 1, "grc": 1, "pf": 1, "cf": 1}
CB_MIN_AREA = 0.01125  # um^2; the authors' weight function sets smaller areas to 0


def cb_area(d: dict) -> float:
    p = d.get("props", {}).get("area_erode0", {})
    a = float(p.get("mesh_area", 0.0))
    return a if a >= CB_MIN_AREA else 0.0


def cerebellum(raw: Path, full: Path, stage: Path) -> dict:
    rid = "weightome-mm-pb-cb-v1"
    graphs = {"mf_grc": "graph_mf_grc_synapse_210518_coalesced.gz", "grc_pc_local": "graph_grc_pc_synapse_210429_coalesced.gz",
              "pf_pc_remote": "graph_pfs_pc_synapse_210429_coalesced.gz"}
    rows, nodes = [], {}
    for path, fn in graphs.items():
        g = load_nx(raw / fn)
        for nid, a in g.nodes(data=True):
            if nid not in nodes or nodes[nid].get("cell_type") is None:
                xyz = a.get("xyz") or (None, None, None)
                nodes[nid] = {"cell_type": a.get("cell_type"), "x": xyz[0], "y": xyz[1], "z": xyz[2]}
        for u, v, d in g.edges(data=True):
            loc = d.get("syn_loc0") or (None, None, None)
            rows.append((u, v, path, cb_area(d), loc[0], loc[1], loc[2]))
    syn = pd.DataFrame(rows, columns=["pre_id", "post_id", "pathway", "area_um2", "x_nm", "y_nm", "z_nm"])
    n_raw = len(syn)
    n_zero = int((syn.area_um2 == 0).sum())
    syn = syn[(syn.area_um2 > 0) & (syn.pre_id != syn.post_id)].copy()
    ctype = {k: v["cell_type"] for k, v in nodes.items()}
    syn["pre_type"] = syn.pre_id.map(ctype).fillna("unknown")
    syn["post_type"] = syn.post_id.map(ctype).fillna("unknown")
    syn["sign"] = syn.pre_type.map(CB_SIGN).fillna(0).astype(np.int8)
    a_ref = float(syn.loc[syn.sign == 1, "area_um2"].median())
    syn["w_rel"] = (syn.area_um2 / a_ref).astype(np.float32)
    syn["w_rel_signed"] = syn.w_rel * syn.sign
    syn = syn.reset_index(drop=True)
    e = syn.groupby(["pre_id", "post_id"]).agg(n_synapses=("w_rel", "size"), area_um2_sum=("area_um2", "sum"),
                                                w_rel_sum=("w_rel", "sum"), w_rel_mean=("w_rel", "mean"),
                                                sign=("sign", "first"), pre_type=("pre_type", "first"),
                                                post_type=("post_type", "first"), pathway=("pathway", "first")).reset_index()
    e["w_rel_signed_sum"] = e.w_rel_sum * e.sign
    ids = sorted(set(syn.pre_id) | set(syn.post_id))
    nt = pd.DataFrame({"neuron_id": ids})
    nt["cell_type"] = nt.neuron_id.map(ctype).fillna("unknown")
    for c in ("x", "y", "z"):
        nt[f"soma_{c}"] = nt.neuron_id.map({k: v[c] for k, v in nodes.items()})
    nt["sign"] = nt.cell_type.map(CB_SIGN).fillna(0).astype(np.int8)
    nt = nt.set_index("neuron_id")
    nt["out_synapses"] = e.groupby("pre_id").n_synapses.sum().reindex(nt.index).fillna(0).astype(np.int64)
    nt["in_synapses"] = e.groupby("post_id").n_synapses.sum().reindex(nt.index).fillna(0).astype(np.int64)
    nt["out_w_rel_sum"] = e.groupby("pre_id").w_rel_sum.sum().reindex(nt.index).fillna(0)
    nt["in_w_rel_sum"] = e.groupby("post_id").w_rel_sum.sum().reindex(nt.index).fillna(0)
    nt = nt.reset_index()

    full.mkdir(parents=True, exist_ok=True)
    syn.to_parquet(full / f"{rid}-synapses.parquet", index=False)
    e.to_parquet(full / f"{rid}-edges.parquet", index=False)
    nt.to_parquet(full / f"{rid}-neurons.parquet", index=False)
    tm = type_matrix(e, "area_um2_sum")
    tm.to_csv(stage / f"{rid}-types.csv", index=False, float_format="%.6g")

    # ---- validation
    b = load_nx(raw / "graph_mf_grc_binary_210519.gz")
    binary = {(str(u).split("__")[0], str(v)) for u, v in b.edges()}
    mg = e[e.pathway == "mf_grc"]
    by_thr = {}
    for k in (1, 2, 3, 5):
        pairs = set(zip(mg[mg.n_synapses >= k].pre_id, mg[mg.n_synapses >= k].post_id))
        inter = len(pairs & binary)
        by_thr[f"ge{k}_synapses"] = {"n_pairs": len(pairs), "recall_of_binary": round(inter / len(binary), 4),
                                     "precision_vs_binary": round(inter / max(len(pairs), 1), 4)}
    in_bin = mg.set_index(["pre_id", "post_id"]).index.isin(list(binary))
    grc_pc = syn[syn.pathway != "mf_grc"]
    summ = {
        "release_id": rid,
        "release_kind": "recipe (neuron-level tables are rebuilt locally from the upstream files, not redistributed)",
        "upstream": "CB2 mouse cerebellar cortex; Nguyen, Thomas et al. 2023, Nature 613, 543-549; NetworkX graphs from "
                    "github.com/htem/cb2_project_analysis_files (releases 230103, 230306); EM on BossDB (nguyen_thomas2022)",
        "upstream_license": "graph files carry no license (the analysis code repository is MIT); therefore no "
                            "redistribution of neuron- or synapse-level tables",
        "volume": "mouse cerebellar cortex (lobule V), granular + molecular layer; GridTape TEM",
        "selection": "authors' 'coalesced' synapse graphs (duplicates within a pair merged): mossy fibre -> granule cell, "
                     "local granule cell axons -> Purkinje cell, remote parallel fibres -> Purkinje cell; synapses with "
                     f"mesh area < {CB_MIN_AREA} um^2 dropped (the authors set these to weight 0)",
        "size_measure": "area_um2 = props.area_erode0.mesh_area (cleft mesh area, um^2), the measure used in the "
                        "authors' analyses. w_rel = area_um2 / A_ref, A_ref = median area over all synapses (all excitatory)",
        "a_ref_area_um2": a_ref,
        "sign_convention": "mossy fibres, granule cells / parallel fibres and climbing fibres are glutamatergic: +1. "
                           "Purkinje cells (GABA) appear only as postsynaptic partners here",
        "n_synapse_rows_upstream": int(n_raw), "n_synapses_area_below_threshold": n_zero,
        "n_synapses": int(len(syn)), "n_edges": int(len(e)), "n_neurons": int(len(nt)),
        "n_synapses_by_pathway": {k: int(v) for k, v in syn.pathway.value_counts().items()},
        "n_edges_by_pathway": {k: int(v) for k, v in e.pathway.value_counts().items()},
        "n_neurons_by_type": {k: int(v) for k, v in nt.cell_type.value_counts().items()},
        "content_sha256": {"edges": content_sha256(e, ["pre_id", "post_id", "n_synapses", "area_um2_sum", "w_rel_sum", "sign"]),
                           "neurons": content_sha256(nt, ["neuron_id", "cell_type", "sign", "out_synapses", "in_synapses"]),
                           "synapses": content_sha256(syn, ["pre_id", "post_id", "x_nm", "y_nm", "z_nm", "area_um2", "w_rel"])},
        "validation": {
            "reproduction_of_published_statistics": {
                "n_synapses": {"release": int(len(syn)), "published": "> 150,000"},
                "n_unitary_connections": {"release": int(len(e)), "published": "> 36,000"},
            },
            "mf_grc_vs_authors_binary_graph": {"n_binary_edges": len(binary), "by_min_synapses": by_thr,
                                               "median_area_sum_in_binary": round(float(mg[in_bin].area_um2_sum.median()), 4),
                                               "median_area_sum_not_in_binary": round(float(mg[~in_bin].area_um2_sum.median()), 4)},
            "size_pair_consistency": {p: pair_consistency(syn[syn.pathway == p], "area_um2", ["pre_id", "post_id"], "pathway")
                                      for p in ("mf_grc", "grc_pc_local", "pf_pc_remote")},
            "median_area_um2_by_pathway": {k: round(float(v), 4) for k, v in syn.groupby("pathway").area_um2.median().items()},
            "local_vs_remote_grc_pc_area": {"median_local": round(float(grc_pc[grc_pc.pathway == "grc_pc_local"].area_um2.median()), 4),
                                            "median_remote": round(float(grc_pc[grc_pc.pathway == "pf_pc_remote"].area_um2.median()), 4)},
            "spearman_w_rel_sum_vs_count": spearman(e.w_rel_sum, e.n_synapses),
        },
    }
    return summ


# --------------------------------------------------------------------------- mouse barrel cortex L4 (Motta et al. 2019)
MOTTA_SIGN = {"Corticocortical": 1, "Thalamocortical": 1, "Inhibitory": -1, "Other": 0}


def motta(raw: Path, full: Path, stage: Path) -> dict:
    rid = "weightome-mm-pb-sc-v1"
    d = pd.read_csv(raw / "connectome.csv", header=None, low_memory=False)
    tgt_class = d.iloc[0, 1:].astype(str).to_numpy()
    ax_class = d.iloc[1:, 0].astype(str).to_numpy()
    m = d.iloc[1:, 1:].to_numpy(dtype=np.int64)
    ii, jj = np.nonzero(m)
    ax_id = np.array([f"axon_{i + 1:05d}" for i in range(m.shape[0])])
    tg_id = np.array([f"target_{j + 1:05d}" for j in range(m.shape[1])])
    e = pd.DataFrame({"pre_id": ax_id[ii], "post_id": tg_id[jj], "n_synapses": m[ii, jj],
                      "pre_type": ax_class[ii], "post_type": tgt_class[jj]})
    e["sign"] = e.pre_type.map(MOTTA_SIGN).astype(np.int8)
    e["w_rel_sum"] = e.n_synapses.astype(np.float64)
    e["w_rel_signed_sum"] = e.w_rel_sum * e.sign
    e["area_um2_sum"] = np.nan
    nt = pd.concat([pd.DataFrame({"neuron_id": ax_id, "kind": "axon", "cell_type": ax_class}),
                    pd.DataFrame({"neuron_id": tg_id, "kind": "postsynaptic_target", "cell_type": tgt_class})], ignore_index=True)
    nt["sign"] = nt.cell_type.map(MOTTA_SIGN).fillna(0).astype(np.int8)
    nt = nt.set_index("neuron_id")
    nt["out_synapses"] = e.groupby("pre_id").n_synapses.sum().reindex(nt.index).fillna(0).astype(np.int64)
    nt["in_synapses"] = e.groupby("post_id").n_synapses.sum().reindex(nt.index).fillna(0).astype(np.int64)
    for lab, sg in (("exc", 1), ("inh", -1), ("zero", 0)):
        nt[f"in_{lab}_w_rel_sum"] = e[e.sign == sg].groupby("post_id").w_rel_sum.sum().reindex(nt.index).fillna(0)
    nt = nt.reset_index()
    full.mkdir(parents=True, exist_ok=True)
    e.drop(columns=["area_um2_sum"]).to_parquet(full / f"{rid}-edges.parquet", index=False)
    nt.to_parquet(full / f"{rid}-neurons.parquet", index=False)
    t = e.groupby(["pre_type", "post_type"]).agg(n_pairs=("n_synapses", "size"), n_synapses=("n_synapses", "sum"),
                                                 w_rel_sum=("w_rel_sum", "sum"), sign=("sign", "first")).reset_index()
    t["w_rel_signed_sum"] = t.w_rel_sum * t.sign
    t["frac_of_pre_output"] = t.n_synapses / t.groupby("pre_type").n_synapses.transform("sum")
    t["frac_of_post_input"] = t.n_synapses / t.groupby("post_type").n_synapses.transform("sum")
    t.to_csv(stage / f"{rid}-types.csv", index=False, float_format="%.6g")
    soma = t[t.post_type == "Soma"].set_index("pre_type").frac_of_pre_output
    ais = t[t.post_type == "AxonInitialSegment"].set_index("pre_type").frac_of_pre_output
    summ = {
        "release_id": rid,
        "release_kind": "recipe (neuron-level tables are rebuilt locally from the upstream files, not redistributed)",
        "upstream": "Motta, Berning, Boergens, Staffler et al. 2019, Science 366, eaay3134; connectome.csv of the data "
                    "repository l4dense2019.brain.mpg.de (currently offline; copy in the Internet Archive, snapshot "
                    "2024-06-25)",
        "upstream_license": "none stated (the repository asks for citation only); therefore no redistribution of the "
                            "axon/target-level tables",
        "volume": "mouse primary somatosensory (barrel) cortex, layer 4, ~500,000 um^3, 11.24 x 11.24 x 28 nm (SBEM), P28",
        "selection": "the published connectome of Fig. 3E: all axons and postsynaptic targets with >= 10 synapses each",
        "weight_definition": "count x sign: w_rel per synapse = 1, edge weight = synapse count. The repository's per-synapse "
                             "axon-spine-interface areas (synapses.hdf5) are not available from the archived copy (truncated), "
                             "and they exist only for spine synapses",
        "sign_convention": "corticocortical and thalamocortical axons +1, inhibitory axons -1, other axons 0. The axon class "
                           "is connectomic (inhibitory = < 20 % of output synapses onto spines), not a transmitter measurement",
        "n_synapses": int(m.sum()), "n_edges": int(len(e)), "n_axons": int(m.shape[0]), "n_targets": int(m.shape[1]),
        "n_neurons": int(m.shape[0] + m.shape[1]),
        "n_axons_by_class": {k: int(v) for k, v in pd.Series(ax_class).value_counts().items()},
        "n_targets_by_class": {k: int(v) for k, v in pd.Series(tgt_class).value_counts().items()},
        "sign_counts_synapses": {str(int(k)): int(v) for k, v in e.groupby("sign").n_synapses.sum().items()},
        "content_sha256": {"edges": content_sha256(e, ["pre_id", "post_id", "n_synapses", "w_rel_sum", "sign"]),
                           "neurons": content_sha256(nt, ["neuron_id", "cell_type", "sign", "out_synapses", "in_synapses"])},
        "validation": {
            "reproduction_of_published_statistics": {
                "n_axons": {"release": int(m.shape[0]), "published": 6979},
                "n_targets": {"release": int(m.shape[1]), "published": 3719},
                "n_synapses": {"release": int(m.sum()), "published": 153171},
                "n_inhibitory_axons": {"release": int((ax_class == "Inhibitory").sum()), "published": "893 (12.8 %)"},
            },
            "plausibility_soma_and_ais_targeting": {
                "frac_output_onto_somata": {k: round(float(v), 4) for k, v in soma.items()},
                "frac_output_onto_axon_initial_segments": {k: round(float(v), 4) for k, v in ais.items()},
                "note": "inhibitory axons target somata about 7x more often than corticocortical axons, as expected",
            },
            "note": "single animal and a ~500,000 um^3 volume; no replicate and no per-synapse size, so the weights are "
                    "synapse counts within the volume",
        },
    }
    return summ


DATASETS["weightome-mm-pb-sc-v1"] = {
    "raw": "motta",
    "base": "https://web.archive.org/web/20240625002556id_/https://l4dense2019.brain.mpg.de/webdav/",
    "files": ["connectome.csv"],
}
BUILDERS = {"weightome-tg-pb-bg-v1": finch, "weightome-mm-pb-cb-v1": cerebellum, "weightome-mm-pb-sc-v1": motta}


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("release_id", choices=sorted(BUILDERS))
    ap.add_argument("--raw", type=Path, help="folder with the upstream files")
    ap.add_argument("--out", type=Path, help="folder for the full (local) tables")
    ap.add_argument("--stage", type=Path, help="folder for the publishable files (types.csv, summary.json)")
    ap.add_argument("--download", action="store_true", help="download missing upstream files first")
    ap.add_argument("--verify", type=Path, help="published <rid>-summary.json to compare the content checksums against")
    a = ap.parse_args()
    rid = a.release_id
    in_repo = Path(__file__).name == "build_recipe_releases.py" and (ROOT / "data" / "extra").is_dir()
    raw = a.raw or (ROOT / "data" / "extra" / DATASETS[rid]["raw"] if in_repo else Path(DATASETS[rid]["raw"]))
    full = a.out or (ROOT / "data" / "extra_full" / rid if in_repo else Path(rid))
    stage = a.stage or (ROOT / "data" / "extra_release" / rid if in_repo else full)
    stage.mkdir(parents=True, exist_ok=True)
    if a.download:
        download(rid, raw)
    summ = BUILDERS[rid](raw, full, stage)
    jdump(stage / f"{rid}-summary.json", summ)
    if stage != full:
        shutil.copy2(stage / f"{rid}-summary.json", full / f"{rid}-summary.json")
    print(json.dumps(summ, indent=1, default=str)[:6000])
    if a.verify:
        ref = json.loads(a.verify.read_text())["content_sha256"]
        ok = {k: ref.get(k) == v for k, v in summ["content_sha256"].items()}
        print("verify:", ok)
        if not all(ok.values()):
            sys.exit(1)


if __name__ == "__main__":
    main()
