Nice — this is a great question and you’ve already implemented most of the core ideas. I checked your code against the paper “Group communication analysis (GCA)” (Dowell et al., 2019) (your uploaded PDF) and below I give a concise, careful mapping: what aligns, where it diverges or contains bugs, and concrete fixes / code snippets you can drop into your project.
Where I cite the paper I use the internal file markers from your uploaded PDF: .
Quick summary
Participation, cross-cohesion, responsivity, internal cohesion, social impact — your code mostly implements the right formulas from the paper (Eqs. 2–20). See citations for participation (Eq.5 & Eq.9), semantic similarity & sab (Eq.14), cross-cohesion (Eq.15–16), and responsivity/internal/social impact (Eqs.17–20).
Major divergences / bugs are in the semantic modeling (embeddings / LSA vs per-pair TF-IDF), the given–new (newness) calculation (incomplete / incorrect basis computation), indexing / API mismatches, and some inefficiencies (recomputing embeddings/participation repeatedly).
Below I map each major function → paper definition → action items + example fixes.
- Participation — your calculate_participation
Paper: mean participation pa=∣pa∣/np_a = |p_a|/npa=∣pa∣/n and group-relative participation p^^a=pa−1/k\hat{\hat p}_a = p_a - 1/kp^^a=pa−1/k (paper Eq.5 & Eq.9).
Your code: computes p_a_mean = p_a_total / n_contributors and participation_score = p_a_mean - 1/k. ✅ This matches Eq.9 (the paper also notes a reviewer-suggested rescaling k*p_a - 1 — you currently implement the original Eq.9).
Notes / suggestions
Return types: your docstring says “returns float” but you return a dict. That’s fine, but keep consistent.
Efficiency: you call calculate_participation repeatedly in other functions. Cache/separate participant sequences once per discussion.
- Semantic similarity (sab) & cross-cohesion — calc_cos, calc_semantic_similarity, calc_cross_cohesion_matrix
Paper: semantic similarity between contributions is cosine of LSA vectors; semantic similarity with participation mask is sab(t,u)=pa(t)pb(u)cos(dt∗,du∗)s_{ab}(t,u)=p_a(t) p_b(u) \cos(d_t^, d_u^)sab(t,u)=pa(t)pb(u)cos(dt∗,du∗) (Eq.14). Cross-cohesion averages these at lag τ and normalizes by the number of τ-lagged pairs pab(τ) (Eqs.15–16).
Your code:
calc_semantic_similarity computes exactly pa(t)pb(u)cosp_a(t)p_b(u)\cospa(t)pb(u)cos (via calculate_participation and cosine), so the logic mirrors Eq.14.
calc_cross_cohesion_matrix loops over contributions, checks (c_prev.author == a and c_curr.author == b), sums cosine and divides by count — this mirrors Eq.15 normalization. ✅
BUT — critical semantic embedding mismatch (important):
Your calc_cos calls get_embedding([c1, c2]) which builds a TF-IDF on just those two texts (or SVD on just those two). That does not produce document vectors in a consistent semantic space across the whole discussion/corpus. The paper uses LSA / an LSA space built on an extended corpus so all contributions share the same vector basis; cosine similarity is meaningful across the entire dialogue only if everyone’s vectors are in the same space.
Fix (high priority) — compute one global embedding space for the discussion (or, better, an extended corpus) and reuse:
pythonCopyEdit# Build once per discussion (or global corpus)
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
vectorizer = TfidfVectorizer(ngram_range=(1,2), min_df=1) # tune
X_tfidf = vectorizer.fit_transform(discussion_data['text'].tolist()) # shape (n, vocab)
svd = TruncatedSVD(n_components=100, random_state=SEED)
D = svd.fit_transform(X_tfidf) # shape (n, dim) -> LSA-style document vectors
Then cos between contribution i and j
def cos_sim_by_index(D, i, j):
vi = D[i]
vj = D[j]
return float( (vi @ vj) / (np.linalg.norm(vi)*np.linalg.norm(vj) + 1e-12) )
Use D (rows = contributions in conversation order) throughout calc_cross_cohesion_matrix and newness computations.
- Responsivity, internal cohesion, social impact — calc_responsivity, calculate_overall_responsivity, calculate_internal_cohesion, calculate_social_impact
Paper: responsivity R(w)=1w∑τ=1wX(τ)R(w)=\frac{1}{w}\sum_{\tau=1}^w X(\tau)R(w)=w1∑τ=1wX(τ) where X(τ)X(\tau)X(τ) is τ-lagged cross-cohesion matrix; overall responsivity is mean of a row (excluding self), internal cohesion is diagonal entry, social impact is mean of column (excluding self).
Your code: implements this correctly in structure: it sums cross-cohesion matrices for τ=1..w and averages. The row/column averaging excludes the self index. ✅
Notes
Make sure calc_cross_cohesion_matrix uses the same global embedding D (see previous fix) and that the ordering used in authors list matches how you map rows/columns in your matrix (i.e., the author index mapping must be consistent across functions).
Watch out for contributions index vs contribution_id: you currently use iloc[t - lag] / iloc[t] — that is fine if the DataFrame is sorted and zero-indexed indices align with contribution order. But paper indexes t = 1..n, so confirm your DataFrame’s contribution_id and its row order are aligned. (If you use contribution_id as the canonical time you should use that to index arrays.)
- Given–new (newness) — span_given, project_and_residual, new_semantic_content, calculate_newness
Paper: given subspace Gt=span{d1∗,...,dt−1∗}G_t = \mathrm{span}{ d_1^, ..., d_{t-1}^ }Gt=span{d1∗,...,dt−1∗}. Project dt∗d_t^dt∗ onto GtG_tGt to get given gt∗g_t^gt∗ and onto orthogonal complement to get new nt∗n_t^nt∗. Newness of a contribution: n(ct)=∥nt∗∥/(∥nt∗∥+∥gt∗∥)n(c_t) = |n_t^| / (|n_t^| + |g_t^|)n(ct)=∥nt∗∥/(∥nt∗∥+∥gt∗∥). Then average over a participant’s contributions (Eq.21–26).
Your code — current problems
span_given returns a TF-IDF matrix (get_embedding(contributions)), not an orthonormal basis for GtG_tGt (you return raw vectors instead of orthonormal Q). The paper expects orthonormal projections (equations 22–25).
new_semantic_content is incomplete; it fetches given_space but does not finish computing projections nor the newness ratio.
get_embedding builds TF-IDF / truncated SVD per call. You must compute a single LSA matrix for all contributions and use those LSA vectors to compute projections for newness.
calculate_newness treats participation_seq as if it has .sum() / .index (but you returned a python list), and it calls new_semantic_content expecting a t index starting at 1 — mismatch and will error.
Correct approach (concrete code)
Precompute LSA document vectors D for the entire discussion (see earlier snippet).
To compute newness for contribution t:
pythonCopyEditfrom scipy.linalg import orth
D: shape (n, dim) rows = contributions in time order (index 0 => t=1)
def newness_of_contribution(D, t): # t is 1-based contribution index
v = D[t-1] # current contribution vector (dim,)
if t <= 1:
return 1.0 # first contribution is 100% new (or handle as paper does)
D_prev = D[:t-1] # shape (t-1, dim)
# get orthonormal basis for span of previous vectors
Q = orth(D_prev.T) # shape (dim, r)
proj = Q @ (Q.T @ v) # projection onto given-subspace
residual = v - proj # new content vector
proj_norm = np.linalg.norm(proj)
res_norm = np.linalg.norm(residual)
denom = res_norm + proj_norm
if denom < 1e-12:
return 0.0
return float(res_norm / denom)
Then calculate_newness for a participant: average newness_of_contribution over that participant’s contribution times ttt, weighted as the paper (they use unweighted average across that participant’s contributions; your code’s formula matches Eq.26).
Important: use the same D vectors for cosine similarity, newness, and density.
-
Communication density — calc_single_density, calculate_communication_density
Paper: density Di=∥di∥/∥ci∥D_i = | d_i | / | c_i |Di=∥di∥/∥ci∥ where ∥ci∥|c_i|∥ci∥ is number of words in contribution i and ∥di∥|d_i|∥di∥ is norm of LSA vector (Eq.27–28).
Your code: calc_single_density computes norm of cur_vector (from get_embedding(contribution)) and divides by number of words. If cur_vector is from per-call TF-IDF/SVD you must switch to global LSA vector D[t-1] and compute np.linalg.norm(D[t-1]) / words_count. Otherwise densities are not comparable across contributions. Fix by using D.
-
Other practical / correctness issues found
Indexing / contribution_id: your code sometimes uses contribution_id as time (time_1 = row_1.contribution_id) but elsewhere iterates by iloc (zero-based). Be explicit: either use zero-based row indices or map contribution_id → row index. (Paper uses 1..n indexing; your code must convert consistently.)
Repeated expensive calls: calculate_participation recomputes per participant every time; get_embedding recomputes TF-IDF/SVD repeatedly. Precompute participation matrix, participation sequences, and D (embedding matrix) once per discussion and pass them to functions.
Function signatures mismatch in analyze_group_discussions: you call calculate_participation(discussion_data, participant, discussion_id) but function defined with two args — fix call sites.
Data types: your code expects pandas Series in places but uses lists; convert to numpy/pandas consistently and document whether indexes are 0- or 1-based.
Minimal prioritized TODO (what to change now)
Build a single global LSA embedding D for each discussion (or extended corpus) using TfidfVectorizer fit on all texts then TruncatedSVD (or use a pretrained embedding if you prefer). Use D everywhere for cosines, projections, density, newness. (This is the most important fix.)
Cache contribution vectors and participants sequences for the discussion; do not recompute them inside inner loops.
Implement newness_of_contribution with orthonormal basis via scipy.linalg.orth as shown above and return the ratio from Eq.25.
Ensure indexing is consistent (if contribution_id is 1..n, convert to/from zero-based indices for arrays D).
Fix minor API bugs in analyze_group_discussions (argument mismatches, using .sum() on lists, etc.).
Short vetted patch (essential parts)
Below is a concise snippet that you can integrate (replace your get_embedding, span_given, new_semantic_content, calc_cos usage). This uses one LSA matrix per discussion and then implements newness and cosine consistently:
pythonCopyEdit# After you filter discussion_data for the discussion and sort by time:
texts = discussion_data['text'].tolist() # in time order
vectorizer = TfidfVectorizer(ngram_range=(1,1), min_df=1)
X = vectorizer.fit_transform(texts)
svd = TruncatedSVD(n_components=100, random_state=SEED)
D = svd.fit_transform(X) # shape (n, dim) -> use everywhere
cosine between contribution indices i and j (0-based)
def cos_by_idx(D, i, j):
vi = D[i]; vj = D[j]
denom = (np.linalg.norm(vi)*np.linalg.norm(vj) + 1e-12)
return float((vi @ vj) / denom)
newness of contribution t (1-based)
from scipy.linalg import orth
def newness_of_contribution(D, t):
v = D[t-1]
if t <= 1:
return 1.0
Dprev = D[:t-1] # (t-1, dim)
if Dprev.size == 0:
return 1.0
Q = orth(Dprev.T) # (dim, r)
proj = Q @ (Q.T @ v)
residual = v - proj
rp = np.linalg.norm(residual)
gp = np.linalg.norm(proj)
if rp + gp < 1e-12:
return 0.0
return float(rp / (rp + gp))
Use cos_by_idx in calc_cross_cohesion_matrix instead of calc_cos (which created per-pair vectorizers). Use newness_of_contribution inside calculate_newness for each t where participant contributed.
Final checklist you can run through quickly
Precompute LSA D per discussion (do not call TF-IDF per pair).
Ensure all cosine similarities use the same D.
Implement given/new projection using orthonormal basis (orth) as above; compute the norm ratio per Eq.25.
Make sure contribution ordering and indexing are consistent (use DataFrame sorted by contribution_id and then 0-based array indices).
Fix API mismatches and repeated recomputation (cache participation sequences, cached D).
After fixes, compare outputs with toy example and compute a sanity check: e.g., first contribution newness ≈ 1, cross-cohesion at lag 1 equals average cosine of pairs that are author a at t-1 and b at t.
If you want, I can:
(a) produce a drop-in patch for your script (I will rewrite the main embedding / newness / cross-cohesion parts) using your current variable names, or
(b) run a small unit test on a tiny synthetic discussion to show the corrected numbers (I can provide the test code and expected outputs).
Tell me which you prefer and I’ll produce the patch/test right away (I’ll include only code changes that keep the original function names and call structure where possible).