Nice — good work getting a full implementation started. Short answer first:
Yes — your code is trying to implement the GCA measures from Dowell et al. (2018) (participation, cross-cohesion/responsivity, internal cohesion, social impact, given/new newness, communication density, LSA-based similarity). However, there are a number of important mismatches and bugs (some semantic, some API/implementation) that will cause the code to produce incorrect numbers or runtime errors. I'll list the conceptual alignment, then the concrete problems I found, cite the relevant paper equations, and give compact, copy-pasteable fixes for the most important functions.
- Conceptual alignment (paper ↔ your code)
You correctly represent Participation as a binary time series pa(t)p_a(t)pa(t) and compute a group-relative mean participation (paper eqs. 2, 5, 9).
Your cross-cohesion & averaging over lag to produce a responsivity matrix implements the same idea as the paper’s ξab(τ)\xi_{ab}(\tau)ξab(τ) and R(w)=1w∑τ=1wX(τ)R(w)=\frac1w\sum_{\tau=1}^w X(\tau)R(w)=w1∑τ=1wX(τ). Conceptually matched.
Your internal cohesion, overall responsivity, and social impact calculations follow the paper’s definitions: diagonal of R(w), average row (excluding self), average column (excluding self).
The given–new / newness idea (project onto subspace spanned by previous docs, measure new component magnitude ratio) matches the paper’s approach (Eqs. 21–26).
Communication density (norm of LSA vector divided by number of words) is implemented the same idea (Eqs. 27–28).
So the design matches the paper. The problems are mostly in how you compute LSA vectors, reuse vectorizer/SVD, indexing, and some implementation errors that change the math.
- Critical implementation problems (bulleted summary)
TEXT_IDX_MAP construction bug
pythonCopyEditTEXT_IDX_MAP = {}
for idx, txt in enumerate(all_data['text'].tolist()):
TEXT_IDX_MAP[txt].append(idx) # KeyError: key not present
-> needs defaultdict(list) or dict.setdefault.
You re-fit the SVD in get_lsa_embedding instead of transforming
pythonCopyEdittfidf_vec = vectorizer.transform([text])
WRONG: svd.fit_transform(X_tfidf) # refits on global X_tfidf
The paper projects unseen contributions into the already-built LSA space (i.e., use svd.transform, do not re-fit SVD). Re-fitting changes the basis and breaks cosine comparisons.
get_embedding fits a brand new TF-IDF on the input texts
That makes embeddings incompatible with the global LSA space you used elsewhere. You must reuse the same vectorizer + fitted svd (the LSA space) everywhere so cosine similarities and projections are in the same vector space. The paper uses an LSA space built on an extended corpus and projects contributions into that fixed space.
span_given doesn't orthonormalize / returns wrong shape
The paper requires Gt=span{d1∗,...,dt−1∗}G_t = \mathrm{span}{d^_1, ..., d^_{t-1}}Gt=span{d1∗,...,dt−1∗} and then projects onto that subspace (preferably an orthonormal basis Q so projection is QQ⊤vQQ^\top vQQ⊤v). Your span_given returns a TF-IDF matrix (and uses get_embedding that itself fits a new vectorizer), so projection math is inconsistent.
project_and_residual assumes shapes and uses inv without pinv; also not using orthonormal Q
If you use orthonormal Q, projection is simple: proj = Q @ Q.T @ v. If Q is not orthonormal, use np.linalg.pinv or least squares (numerical stability). Using inv(g.T@g) can fail (singular matrix). Use pinv.
Indexing / off-by-one and API mismatches
Paper indexes contributions t = 1..n; code uses contribution_id sometimes and iloc sometimes. Make the indexing consistent (decide: contribution_id ∈ {1..n}, and always convert to 0-based iloc when indexing rows).
Many functions (e.g., analyze_group_discussions) call calculate_participation(discussion_data, participant, discussion_id) but your calculate_participation signature takes only (discussion_data, participant) — mismatch causing runtime errors.
calculate_newness / new_semantic_content incomplete / incorrect
new_semantic_content is incomplete and never returns a value.
calculate_newness treats participation_seq like a pandas Series (calls .index, .sum()), but earlier calculate_participation returns a Python list. Use consistent types (prefer np.array or pd.Series). The weight and averaging logic should match paper eq. 26.
Cosine computation for duplicates and unseen texts
Your calc_cos averages pairwise cosine similarities when each contribution maps to multiple LSA rows (duplicates). This is OK if all vectors live in same LSA space, but because of re-fitting SVD / vectorizer mismatches, numbers will be meaningless unless fixed.
Use of global variables but also local re-fitters — inconsistent and bug prone. Build a single LSA object (vectorizer + fitted svd) and pass or reference it.
- Concrete fixes / replacement snippets
Below are minimal replacements (drop in or adapt) for the key functions. These assume you have built a single global TF-IDF vectorizer and a fitted svd (TruncatedSVD) on your extended corpus and computed LSA_DOC_VECTORS = svd.transform(X_tfidf) already — which you already attempted to do at top (but avoid refitting later).
3.1 Build TEXT_IDX_MAP safely
pythonCopyEditfrom collections import defaultdict
TEXT_IDX_MAP = defaultdict(list)
for idx, txt in enumerate(all_data['text'].tolist()):
TEXT_IDX_MAP[txt].append(idx)
3.2 Consistent LSA embedding getter (no re-fit)
pythonCopyEditdef get_lsa_embedding(text: str) -> np.ndarray:
"""
Return LSA vector(s) in the same LSA space used to compute LSA_DOC_VECTORS.
- If exact text occurs in all_data, return those precomputed vectors (shape (m, dim)).
- Otherwise, transform using the fitted vectorizer + svd (shape (1, dim)).
"""
idxs = TEXT_IDX_MAP.get(text, [])
if idxs:
return LSA_DOC_VECTORS[idxs] # already in LSA space
tfidf_vec = vectorizer.transform([text]) # TF-IDF in same vocab
lsa_vec = svd.transform(tfidf_vec) # ONLY transform — DO NOT fit
return lsa_vec # shape (1, dim)
3.3 Single get_embedding for lists (reuses global vectorizer + svd)
pythonCopyEditdef get_embedding(texts: list[str]) -> np.ndarray:
"""
Return embeddings for a list of texts in the global LSA space.
"""
tfidf = vectorizer.transform(texts) # vectorizer MUST already be fitted
return svd.transform(tfidf) # shape (n_texts, dim)
3.4 span_given → return orthonormal Q (columns are basis vectors)
pythonCopyEditfrom scipy.linalg import orth
def span_given(discussion_data: pd.DataFrame, time: int) -> np.ndarray:
# contributions strictly before time t (paper uses t index; ensure time is int index)
prev_texts = discussion_data[discussion_data['contribution_id'] < time]['text'].tolist()
if len(prev_texts) == 0:
return np.empty((svd.n_components, 0)) # empty basis (dim, 0)
doc_vectors = get_embedding(prev_texts) # shape (m, dim)
# transpose to (dim, m) then orthonormalize columns
Q = orth(doc_vectors.T) # returns (dim, k) with orthonormal columns
return Q
This produces an orthonormal basis QQQ (columns orthonormal) matching the paper’s projection form.
3.5 project_and_residual when given orthonormal Q
pythonCopyEditdef project_and_residual(Q: np.ndarray, cur_vector: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""
Q: orthonormal basis (dim, k) ; cur_vector: shape (1, dim) or (dim,) or (n_samples, dim)
Returns projection and residual in same orientation as cur_vector.
"""
v = np.atleast_2d(cur_vector) # (n, dim)
# If Q empty
if Q.size == 0:
proj = np.zeros_like(v)
return proj, v.copy()
# project each row vector in v: proj = v @ Q @ Q.T
proj = (v @ Q) @ Q.T
residual = v - proj
return proj, residual
If Q is not orthonormal, substitute Q_pinv = np.linalg.pinv(Q) and compute via least squares, but orthonormal Q is preferred (and matches the paper).
3.6 new_semantic_content implementing Eq. 25
pythonCopyEditdef new_semantic_content(discussion_data: pd.DataFrame, time: int) -> float:
"""
Return n(c_t) = ||n*_t|| / (||n*_t|| + ||g*_t||) per paper eq.25
Assumes contribution_id is 1..n and time is that 1-based id.
"""
# current doc vector (in LSA space)
cur_text = discussion_data.loc[discussion_data['contribution_id'] == time, 'text'].values
if len(cur_text) == 0:
return 0.0
cur_vec = get_lsa_embedding(cur_text[0]) # shape (1, dim)
# span of previous contributions
Q = span_given(discussion_data, time) # (dim, k)
proj, resid = project_and_residual(Q, cur_vec) # shapes (1, dim)
g_norm = np.linalg.norm(proj)
n_norm = np.linalg.norm(resid)
denom = n_norm + g_norm
return float(n_norm / denom) if denom > 0 else 0.0
3.7 calculate_newness corrected (use numpy arrays)
pythonCopyEditdef calculate_newness(discussion_data: pd.DataFrame, participant: str) -> float:
p_res = calculate_participation(discussion_data, participant)
participation_seq = np.array(p_res['participation_seq'], dtype=int) # shape (n,)
norm_p_a = participation_seq.sum()
if norm_p_a == 0:
return 0.0
# times are 1-based: contribution index t -> contribution_id t
newness_vals = []
for idx, flag in enumerate(participation_seq):
if flag == 1:
time = idx + 1
newness_vals.append(new_semantic_content(discussion_data, time))
return float(np.mean(newness_vals))
3.8 Misc: safer projection inversion if you must
pythonCopyEdit# avoid inv; use pinv
proj = given_space @ np.linalg.pinv(given_space.T @ given_space) @ given_space.T @ cur_vector
But prefer orthonormal basis + Q @ Q.T.
- Additional recommendations & sanity checks
Build the LSA space once (on the extended corpus recommended by the paper) and never re-fit the vectorizer or SVD during metric calculations. The paper explicitly notes building a domain-specific LSA with external/background docs so contributions map to a stable semantic basis.
Replace all ad-hoc TF-IDF/Re-fit uses with the global vectorizer and svd objects. get_embedding must call vectorizer.transform + svd.transform.
Make indexing explicit: choose whether contribution_id is 1..n (paper) and convert to 0-based when using .iloc. Add assertions in code to check that contribution_id runs 1..n and matches row order.
Use np.linalg.pinv instead of inv for robustness.
Turn TEXT_IDX_MAP into a defaultdict(list) and/or dedupe identical texts if you want unique mapping semantics.
Add unit tests on a tiny toy conversation so known values (e.g., if everyone alternates, participation_score should be near 0) — this will catch off-by-one errors early.
Check calc_cos handling of zero vectors; ensure cosine_similarity is called on arrays with matching dims and stability (you already guard NaNs which is good).
- Which parts correspond to paper equations (key citations)
LSA cosine similarity (Eq. 13) & projection idea — implemented by calc_cos / get_lsa_embedding.
Cross-cohesion ξab(τ)\xi_{ab}(\tau)ξab(τ) and normalization (Eq. 15) — implemented in calc_cross_cohesion_matrix. Ensure you count and normalize using p_ab(τ) as the paper does.
Responsivity R(w) (Eq. 17), internal cohesion (Eq. 18), overall responsivity (Eq. 19), social impact (Eq. 20).
Given–new projections (Eqs. 21–25) and newness average (Eq. 26) — implement using orthonormal Q and the ratio ∥nt∗∥∥nt∗∥+∥gt∗∥\frac{|n^_t|}{|n^_t|+|g^*_t|}∥nt∗∥+∥gt∗∥∥nt∗∥.
Communication density (Eqs. 27–28) — calc_single_density is on the right track (norm / word count).
- Final notes — priority fixes for you to apply now
Stop re-fitting vectorizers/SVDs inside functions. Use one global fitted LSA pipeline. (High priority)
Fix TEXT_IDX_MAP initialization. (Immediate)
Replace svd.fit_transform(X_tfidf) occurrences with svd.transform(...). (High)
Implement orthonormal span_given (use scipy.linalg.orth) and use proj = Q Q^T v. (High for newness correctness)
Fix function signatures and indexing mismatches in analyze_group_discussions so calls match definitions. (Medium)
Make calculate_newness actually call new_semantic_content and handle arrays properly. (High)
If you want, I can produce a cleaned, consolidated version of your module (single class/LSA object, fixed functions, and small unit tests on a toy conversation) so you can run it and verify the numbers — tell me whether you want:
a) a drop-in patch with only minimal changes (safer, smaller diffs), or
b) a refactor into a single class (recommended: vectorizer+svd+helpers in one object, easier to maintain and test).
Tell me which and I’ll produce the code ready to paste into your repo.