You're right — that snippet assumed you already had judge CSVs on disk. Below I replaced that part with a full density_eval() implementation that computes four sensible variants of "communication density" from your raw du_all_contributions.csv (no judge files required), saves each computed version as a CSV, and — if the GCA file du_results_6_aspects_129_discussions.csv exists — compares each computed version to the GCA communication_density_score via Pearson correlation and saves plots & merged CSVs.
Paste this function into your file replacing the current density_eval() stub:
pythonCopy codedef density_eval():
"""
Compute 4 variants of communication density from the raw DU contributions and
(optionally) correlate each variant with the GCA communication_density_score.
Variants computed per (discussion, participant):
- avg_words_per_turn : mean words per contribution
- median_words_per_turn: median words per contribution
- unique_word_ratio : unique words / total words
- turn_share : participant_turns / total_discussion_turns
Outputs:
outs/all/GPT4_1/communication_density/computed_<variant>.csv
outs/all/GPT4_1/communication_density/plots/ (overlay + scatter + merged)
outs/all/GPT4_1/communication_density/computed_density_summary.csv (if GCA present)
"""
model = "GPT4_1"
base_out_dir = f"outs/all/{model}"
out_dir = os.path.join(base_out_dir, "communication_density")
os.makedirs(out_dir, exist_ok=True)
# raw DU contributions (per create_test_split mapping)
du_path = f"{DATA_PATH}/du_all_contributions.csv"
if not os.path.exists(du_path):
print(f"Missing raw data file: {du_path}. Aborting density computation.")
return
df = pd.read_csv(du_path)
# normalize column names: this script expects 'discussion', 'participant' (or 'author'), 'text'
if "author" in df.columns and "participant" not in df.columns:
df = df.rename(columns={"author": "participant"})
if "text" not in df.columns:
# try alternative common names, otherwise abort
if "content" in df.columns:
df = df.rename(columns={"content": "text"})
else:
print("No 'text' column found in DU data. Columns are:", df.columns.tolist())
return
# ensure strings
df["text"] = df["text"].fillna("").astype(str)
# simple whitespace tokenization (language-agnostic).
df["tokens_list"] = df["text"].str.split()
df["tokens"] = df["tokens_list"].apply(len)
# total turns per discussion (for turn_share)
disc_total_turns = df.groupby("discussion").size().to_dict()
# aggregate per (discussion, participant)
agg_rows = []
grouped = df.groupby(["discussion", "participant"])
for (discussion, participant), g in grouped:
n_turns = len(g)
total_words = int(g["tokens"].sum())
per_turn_list = list(g["tokens"].values)
avg_words = float(pd.Series(per_turn_list).mean()) if per_turn_list else 0.0
median_words = float(pd.Series(per_turn_list).median()) if per_turn_list else 0.0
# unique words (lowercased)
unique_set = set()
for lst in g["tokens_list"]:
# skip empty tokens
for w in lst:
if w and str(w).strip():
unique_set.add(str(w).lower())
unique_words = len(unique_set)
unique_ratio = unique_words / total_words if total_words > 0 else 0.0
total_disc_turns = disc_total_turns.get(discussion, n_turns)
turn_share = n_turns / total_disc_turns if total_disc_turns > 0 else 0.0
agg_rows.append({
"discussion": discussion,
"participant": participant,
"n_turns": n_turns,
"total_words": total_words,
"avg_words_per_turn": avg_words,
"median_words_per_turn": median_words,
"unique_word_ratio": unique_ratio,
"turn_share": turn_share,
})
metrics_df = pd.DataFrame(agg_rows)
if metrics_df.empty:
print("No aggregated rows computed (empty metrics_df). Aborting.")
return
# save computed versions and (optionally) compare with GCA
versions = {
"avg_words_per_turn": "avg_words_per_turn",
"median_words_per_turn": "median_words_per_turn",
"unique_word_ratio": "unique_word_ratio",
"turn_share": "turn_share",
}
# Try to load GCA communication density column if available
gca_path = f"{DATA_PATH}/du_results_6_aspects_129_discussions.csv"
gca_df = None
if os.path.exists(gca_path):
gca_df = pd.read_csv(gca_path)
if "discussion_id" in gca_df.columns:
gca_df = gca_df.rename(columns={"discussion_id": "discussion"})
# ensure participant column name matches
if "participant" not in gca_df.columns and "author" in gca_df.columns:
gca_df = gca_df.rename(columns={"author": "participant"})
# expected column:
if "communication_density_score" not in gca_df.columns:
print(f"Warning: GCA file {gca_path} does not contain 'communication_density_score'. Correlations will be skipped.")
gca_df = None
else:
print(f"GCA file not found at {gca_path} — computed density files will still be saved, but no correlation will be run.")
plots_dir = os.path.join(out_dir, "plots")
os.makedirs(plots_dir, exist_ok=True)
summary_records = []
for vname, col in versions.items():
comp_df = metrics_df[["discussion", "participant", col]].rename(columns={col: "score"})
computed_path = os.path.join(out_dir, f"computed_{vname}.csv")
comp_df.to_csv(computed_path, index=False)
print(f"Saved computed density variant '{vname}' -> {computed_path}")
# if we have GCA, merge and compute correlation and plots
if gca_df is not None:
merged = pd.merge(
comp_df,
gca_df[["discussion", "participant", "communication_density_score"]],
on=["discussion", "participant"],
how="inner",
).dropna(subset=["score", "communication_density_score"])
if merged.empty:
print(f"No overlap between computed '{vname}' and GCA rows — skipping correlation for {vname}.")
continue
try:
pearson_r, pearson_p = pearsonr(merged["score"], merged["communication_density_score"])
except Exception as e:
print(f"Could not compute Pearson for {vname}: {e}")
pearson_r, pearson_p = None, None
n = len(merged)
summary_records.append({
"variant": vname,
"n": n,
"pearson_r": pearson_r,
"pearson_p": pearson_p
})
# normalized overlay hist
max_score = merged["score"].max()
max_gca = merged["communication_density_score"].max()
merged["score_norm"] = merged["score"] / max_score if max_score and max_score > 0 else merged["score"]
merged["gca_norm"] = merged["communication_density_score"] / max_gca if max_gca and max_gca > 0 else merged["communication_density_score"]
plt.figure()
plt.hist(merged["score_norm"], bins=10, alpha=0.6, label="Computed (norm)", edgecolor="grey")
plt.hist(merged["gca_norm"], bins=10, alpha=0.6, label="GCA (norm)", edgecolor="grey")
plt.xlabel("Normalized score (0–1)")
plt.ylabel("Count")
plt.title(f"Density overlay - {vname}")
plt.legend()
plt.tight_layout()
overlay_path = os.path.join(plots_dir, f"{vname}_normalized_overlay.png")
plt.savefig(overlay_path)
plt.close()
# scatter
plt.figure()
plt.scatter(merged["communication_density_score"], merged["score"], s=10, alpha=0.7)
plt.xlabel("GCA communication_density_score")
plt.ylabel(f"Computed {vname}")
plt.title(f"{vname} — Computed vs GCA (r={pearson_r:.3f} p={pearson_p:.3g})" if pearson_r is not None else f"{vname} — Computed vs GCA")
plt.tight_layout()
scatter_path = os.path.join(plots_dir, f"{vname}_scatter.png")
plt.savefig(scatter_path)
plt.close()
merged_out = os.path.join(plots_dir, f"merged_computed_{vname}.csv")
merged.to_csv(merged_out, index=False)
print(f"Saved merged data and plots for variant '{vname}' (N={n}).")
# summary
if summary_records:
summary_df = pd.DataFrame(summary_records)
summary_path = os.path.join(out_dir, "computed_density_summary.csv")
summary_df.to_csv(summary_path, index=False)
print("\nComputed density summary:")
print(summary_df.to_string(index=False))
else:
print("No correlation summary produced (either missing GCA or no overlaps).")
Notes & rationale
I used four simple, robust, language-agnostic variants (avg/median words per turn, unique-word ratio, turn share). They are easy to compute from du_all_contributions.csv and should be meaningful starting points.
Tokenization is whitespace-based (fast and robust). If you want language-aware tokenization (Hebrew), we can plug in a proper tokenizer later.
The function always saves the computed CSVs; correlations/plots are produced only if your GCA file with communication_density_score is present and overlaps.
If you'd prefer different density definitions (e.g. lexical density using part-of-speech counts, or normalizing to the 1–5 GCA range), tell me which definitions you want and I’ll adapt the code.
Want me to also:
rescale the computed scores to the GCA score range (e.g. min–max map to 0–5) before correlation?
add per-discussion z-scoring (to control for discussion length/time)?
I can change the code accordingly — I went with a minimal, interpretable baseline.