Nice — I read your code and compared it line-by-line to the paper (“Group communication analysis …” by Dowell et al., 2018) and flagged where your implementation matches, where it differs (bug / mismatch / fragile), and gave concrete fixes you can drop into your code. I cite the paper where each measure is defined so you can cross-check.
Short verdict
Conceptually you implemented the paper’s six GCA measures (Participation, Cross-cohesion → Responsivity / Internal cohesion / Social impact, Newness (given–new), Communication density) and the LSA-based similarity idea. Good — the mapping of concepts → functions is correct.
However, there are several implementation bugs and deviations (indexing mistakes, wrong data types, fragile matching by text, API mismatches) that will cause wrong results or runtime errors. Many of these are fixable with small, targeted changes (I list recommended fixes and short code snippets below).
Where your code does match the paper (good)
Participation: you compute per-time indicator p_a(t) and mean p_a_mean = |p_a| / n and then participation_score = p_a_mean - 1/k, which implements Eq.9 in the paper.
Cross-cohesion: calc_cross_cohesion_matrix sums cosines for pairs at lag τ and divides by the count — that is the same high-level operation as ξ_ab(τ) in Eq.15 (paper).
Responsivity / Internal cohesion / Social impact: your averaging over lags and averaging rows/columns matches R(w) Eq.17 and definitions Eq.18–20.
Given–New and Newness: you attempt to form subspace of previous docs, project current vector to given/new and compute newness ratio ||new||/(||new||+||given||) — matches Eq.21–26.
Communication density: ||d_t|| / (# words) implemented as LSA norm over word count — matches Eq.27.
Bugs / mismatches (detailed) and suggested fixes
I list each issue, why it matters (paper reference where relevant), and the concrete fix.
- Fragile / incorrect identification of contributions by text
What you do: many functions (e.g. calc_semantic_similarity, parts of get_lsa_embedding) locate a row with discussion_data[discussion_data.text == contribution_1].iloc[0] or rely on a global TEXT→indices map keyed by the raw text.
Why it's a problem: different contributions can have identical text (reposts, quoting) or very similar text; the paper treats contributions indexed by time/turn (t = 1..n) and uses those indexes. Relying on string equality loses time information and is ambiguous.
Fix: always identify contributions by an explicit contribution_id (time index / row order) or by DataFrame row index, not by text. Change APIs to accept contribution_id (int) where possible, or return both (text, id). Example change for calc_cos:
pyCopyEdit# new signature: accept contribution ids (ints) or raw text; prefer ids
def calc_cos_by_id(discussion_data: pd.DataFrame, id1: int, id2: int) -> float:
t1 = discussion_data.loc[discussion_data['contribution_id'] == id1, 'text'].iloc[0]
t2 = discussion_data.loc[discussion_data['contribution_id'] == id2, 'text'].iloc[0]
v1 = get_lsa_embedding_by_id(discussion_data, id1) # returns (1,dim)
v2 = get_lsa_embedding_by_id(discussion_data, id2)
return float(cosine_similarity(v1, v2)[0,0])
(And implement get_lsa_embedding_by_id to use the row index / id mapping.) This puts you in line with the paper’s time-indexed notation.
- get_lsa_embedding / TEXT_IDX_MAP API mismatch & list input bug
What you do: get_lsa_embedding(text: str) sometimes receives a list (e.g. span_given passes a list) and sometimes a string, and returns either multiple vectors (for duplicate texts) or a single vector. That makes downstream code assume ambiguous array shapes.
Why it matters: the paper expects a single LSA document vector per contribution (d*_t) to compute cosines and projections (Eqs.13,22–25). Mixing shapes causes wrong cosine computations or broadcasting errors.
Fix (two parts):
Make get_lsa_embedding accept either a contribution id or a single string, but always return a 1D vector of shape (dim,) corresponding to that contribution/time. If you want to return multiple vectors (rare), provide a separate function get_lsa_embeddings_for_text_duplicates(...).
When you need vectors for several contributions (span), call get_lsa_embedding_by_id in a loop and stack them explicitly.
Example:
pyCopyEditdef get_lsa_embedding_by_id(discussion_data, contribution_id) -> np.ndarray:
text = discussion_data.loc[discussion_data['contribution_id'] == contribution_id, 'text'].iloc[0]
tfidf_vec = vectorizer.transform([text])
lsa_vec = svd.transform(tfidf_vec) # shape (1,dim)
return lsa_vec.ravel() # return shape (dim,)
And for a list of contribution ids:
pyCopyEditdef get_lsa_matrix_by_ids(discussion_data, ids: list[int]) -> np.ndarray:
return np.vstack([get_lsa_embedding_by_id(discussion_data, i) for i in ids]) # shape (m,dim)
This preserves the 1 vector per contribution assumption used throughout the paper (Eqs.13,22–25).
- calculate_participation return types & usage errors
What you do: calculate_participation returns {'participation_score':..., 'participation_seq': p_a} where p_a is a Python list. Later code expects .sum() and .index and calls like participation_seq.index.to_series() — that will fail. Also analyze_group_discussions calls it with three args, but function signature has two.
Fix: return participation_seq as a pandas.Series (indexed by contribution time 1..n) so downstream code can do .sum(), .index, .loc, etc. Also fix analyze_group_discussions to call functions with the correct parameters.
Suggested implementation:
pyCopyEditdef calculate_participation(discussion_data: pd.DataFrame, participant: str):
contributors = discussion_data['author'].tolist()
n = len(contributors)
k = discussion_data['author'].nunique()
p_a = pd.Series([1 if c==participant else 0 for c in contributors], index=range(1, n+1))
p_a_total = int(p_a.sum())
p_a_mean = p_a_total / n
participation_score = p_a_mean - (1 / k)
return {'participation_score': float(participation_score), 'participation_seq': p_a}
This matches the paper’s p_a(t), |p_a| and p̂̂_a = p_a − 1/k.
-
analyze_group_discussions calls functions with wrong signatures
What you do: you call calculate_participation(discussion_data, participant, discussion_id) and similar calls with discussion_id passed though the target functions don’t accept that argument. That will raise runtime TypeErrors.
Fix: remove the extra argument or change function signatures consistently. I recommend making per-metric functions accept only (discussion_data, participant, window_or_other) as required by the formula; discussion_id is unnecessary because you already filtered the rows for the discussion.
-
Span / subspace code: span_given and projection shapes
What you do: span_given collects contributions up to time then does tfidf_embeddings = get_lsa_embedding(contributions) (passing a list) and then orth(tfidf_embeddings.T). As noted above, get_lsa_embedding returns a shape inconsistent with that usage. Also if there are 0 previous contributions, orth will fail or return empty in unexpected shape.
Why: the paper defines G_t = span{d_1 ... d_{t-1}} (Eq.21). You must form a matrix with columns = previous contribution vectors (dim × m) and get an orthonormal basis Q.
Fix (clear and robust):
pyCopyEditdef span_given(discussion_data: pd.DataFrame, time: int) -> np.ndarray:
contributions with contribution_id < time (paper uses up to t-1)
prev_ids = discussion_data.loc[discussion_data['contribution_id'] < time, 'contribution_id'].tolist()
if len(prev_ids) == 0:
return np.empty((svd.n_components, 0)) # empty basis with correct row-dim
mat = get_lsa_matrix_by_ids(discussion_data, prev_ids) # shape (m, dim)
Q = orth(mat.T) # orth expects (dim, m) -> returns (dim, k)
return Q
Then project_and_residual(Q, cur_vector) should accept cur_vector as a 1D vector of shape (dim,) or 2D (1,dim) and compute proj = Q @ (Q.T @ v) (one vector case), or vectorized version for many rows:
pyCopyEditdef project_and_residual(Q: np.ndarray, cur_vector: np.ndarray):
v = np.atleast_2d(cur_vector) # (n, dim)
if Q.size == 0:
proj = np.zeros_like(v)
resid = v.copy()
return proj, resid
proj = (v @ Q) @ Q.T # v (n,dim) @ Q (dim,k) -> (n,k) then @ Q.T -> (n,dim)
resid = v - proj
return proj, resid
This matches Eq.22–23 (paper) where g_t = Proj_G(d_t), nt = Proj{G^⊥}(d_t).
- new_semantic_content and calculate_newness indexing mistakes & inefficiencies
What you do: new_semantic_content pulls contribution = discussion_data[discussion_data['contribution_id'] == time]['text'].values[0] — OK if time is a contribution id. But calculate_newness builds participation_seq incorrectly (see item 3) and then calls participation_seq.index.to_series().apply(lambda t: new_semantic_content(..., t)) — this is wrong: .index of a Series gives an Index object, and participation_seq is a binary vector; you should iterate over contribution ids t where p_a(t) == 1 and average n(c_t) across those contributions per Eq.26.
Fix: compute the list of times where participant contributed, compute newness per those times, then average:
pyCopyEditdef calculate_newness(discussion_data, participant):
part = calculate_participation(discussion_data, participant)['participation_seq'] # pd.Series indexed by time
contrib_times = part[part==1].index.tolist() # times where participant contributed
if not contrib_times:
return 0.0
scores = [ new_semantic_content(discussion_data, t) for t in contrib_times ]
return float(np.mean(scores))
This implements Eq.26 (Na) exactly (average of n(c_t) over participant’s contributions).
-
calc_cos averaging duplicates — semantic vectors should be per contribution
What you do: get_lsa_embedding may return multiple vectors for the same text (if text duplicates were present) and calc_cos computes cosine_similarity(V1, V2) then np.mean(sims) across all pairwise combinations. The paper uses contribution vectors d*_t and d*_u for the specific contributions t and u (single vectors) and computes cosine(d_t, d_u) (Eq.13). Averaging pairwise similarities for duplicate text occurrences can distort semantics.
Fix: after you switch to get_lsa_embedding_by_id (one vector per contribution id), calc_cos should compute the single cosine between the two contribution vectors. If you still want to support text lookups that map to multiple IDs, aggregate by time (e.g., choose the specific contribution id you intend) rather than averaging pairwise text duplicates.
-
Performance: recomputing participation and LSA many times
What you do: functions like calc_semantic_similarity call calculate_participation(...) repeatedly and re-transform texts with vectorizer/svd many times. That’s slow for long discussions.
Fix: precompute once per discussion: a Series of p_a for all participants, an array matrix of LSA vectors (n × dim) for all contributions, and reuse them. E.g., build doc_vectors = get_lsa_matrix_by_ids(discussion_data, discussion_data['contribution_id'].tolist()) once and pass it around. This is both faster and avoids inconsistent recomputation.
-
calc_responsivity calls calc_cross_cohesion_matrix repeatedly; ordering assumptions
What you do: calc_cross_cohesion_matrix iterates contributions using DataFrame .iloc[...] and range(lag, num_contributions). This assumes the DataFrame is in strict time order and that row positions correspond to time t=1..n. The paper uses the contributions sequence C in time order (Eq.1). If your DataFrame is not sorted by contribution_id you’ll get wrong results.
Fix: sort discussion_data = discussion_data.sort_values('contribution_id').reset_index(drop=True) before computations or always index by contribution_id values explicitly. Also ensure contribution_id values are contiguous 1..n or map them to positions.
-
LSA space construction difference (practical note)
What you do: you build TF-IDF + TruncatedSVD on all_data from your CSV. The paper emphasizes constructing a domain-appropriate LSA (seed corpus + supplement with external docs like Wikipedia) for good semantic space coverage. Using your dataset might be okay if large and topical, but beware small corpora causing poor LSA vectors. If you cannot build a large seed space, consider using domain augmenting (paper’s method) or modern sentence embeddings (not in paper but practical).
Minimal corrected snippets (drop-in)
Below are compact corrected replacements for the most critical routines. You can paste them into your module and adapt variable names.
pyCopyEdit# 1) participation (returns pd.Series for seq)
def calculate_participation(discussion_data: pd.DataFrame, participant: str):
discussion_data = discussion_data.sort_values('contribution_id').reset_index(drop=True)
n = len(discussion_data)
k = discussion_data['author'].nunique()
p_a = pd.Series([1 if a==participant else 0 for a in discussion_data['author']], index=discussion_data['contribution_id'].tolist())
p_a_mean = p_a.sum() / n
participation_score = p_a_mean - (1 / k)
return {'participation_score': float(participation_score), 'participation_seq': p_a}
2) LSA per contribution id
def get_lsa_embedding_by_id(discussion_data: pd.DataFrame, contribution_id: int) -> np.ndarray:
txt = discussion_data.loc[discussion_data['contribution_id'] == contribution_id, 'text'].iloc[0]
tfidf_vec = vectorizer.transform([txt])
lsa_vec = svd.transform(tfidf_vec) # (1,dim)
return lsa_vec.ravel() # (dim,)
def get_lsa_matrix_by_ids(discussion_data, ids):
return np.vstack([get_lsa_embedding_by_id(discussion_data, i) for i in ids]) # (m,dim)
3) span_given and project
def span_given(discussion_data: pd.DataFrame, time: int) -> np.ndarray:
prev_ids = discussion_data.loc[discussion_data['contribution_id'] < time, 'contribution_id'].tolist()
if not prev_ids:
return np.empty((svd.n_components, 0))
mat = get_lsa_matrix_by_ids(discussion_data, prev_ids) # (m,dim)
return orth(mat.T) # (dim,k)
def project_and_residual(Q: np.ndarray, cur_vec: np.ndarray):
v = np.atleast_2d(cur_vec) # (n,dim)
if Q.size == 0:
return np.zeros_like(v), v.copy()
proj = (v @ Q) @ Q.T
resid = v - proj
return proj, resid
4) newness per contribution (n(c_t))
def new_semantic_content(discussion_data: pd.DataFrame, time: int):
cur_vec = get_lsa_embedding_by_id(discussion_data, time) # (dim,)
Q = span_given(discussion_data, time) # (dim,k) or empty
proj, resid = project_and_residual(Q, cur_vec)
g_norm = np.linalg.norm(proj)
n_norm = np.linalg.norm(resid)
return float(n_norm / (n_norm + g_norm)) if (n_norm + g_norm) > 0 else 0.0
5) calculate_newness for a participant
def calculate_newness(discussion_data: pd.DataFrame, participant: str) -> float:
part = calculate_participation(discussion_data, participant)['participation_seq']
contrib_times = part[part==1].index.tolist()
if not contrib_times:
return 0.0
scores = [new_semantic_content(discussion_data, t) for t in contrib_times]
return float(np.mean(scores))
Additional checks & recommendations
Sort and reindex your discussion_data by contribution_id once at start of analysis. The paper assumes an ordered sequence.
Precompute an n × dim array of all document vectors for a discussion and pass it to cross-cohesion/responsivity code to avoid repeated .transform() calls.
Unit tests: create a tiny synthetic discussion (3 participants, 6 contributions) and compute ξ_ab(1) by hand with simple vectors so you can assert your matrix entries are as expected. The paper’s equations (Eqs.13–20) give you the exact expected calculations.
Consider whether you want the paper’s raw participation formula (p̂̂a = p_a_mean − 1/k) or the reviewer-suggested rescaling that makes participation comparable across group sizes (k*pa − 1). The paper includes the former as Eq.9 (and discussion about scaling). If you expect to compare across groups with very different k, rescale.
Wrap-up (quick checklist you can use)
Make contribution_id the canonical identifier everywhere.
Return participation_seq as pd.Series (indexed by contribution_id).
Ensure get_lsa_embedding_by_id returns a single 1-D vector per contribution.
Fix span_given to build Q from contributions up to t−1 and use orth(mat.T).
Replace text equality lookups with id lookups.
Precompute doc vectors and participation series for performance.
If you want, I can:
produce a refactored single-file module that applies the fixes above and is consistent with the paper (I’ll produce working functions + small unit tests), or
run a short unit test on a tiny synthetic discussion (3 participants, 6 turns) and show the expected cross-cohesion/responsivity matrices so you can verify your real data pipeline.
Which of those would you like me to do next? (I won’t change anything in your repo — I’ll show the code here so you can copy/paste.)