Nice — thanks for sharing both your code and the paper. I checked the paper (Dowell et al., Group communication analysis, 2018) and compared the math/definitions to your implementation. Below I list what matches, then the bugs / mismatches / gotchas, and then minimal fixes / code snippets you can drop into your code to bring it into alignment. I cite the paper where I rely on its equations.
Quick summary — what already matches
Participation definition: you compute p_a_mean = |p_a| / n and participation_score = p_a_mean - 1/k. That corresponds to Eq.5 and Eq.9 in the paper.
(Note: paper mentions an alternate reviewer-suggested normalization k*pa - 1 if you want cross-group comparability; see footnote near Eq.9.)
Cross-cohesion / averaging: your calc_cross_cohesion_matrix computes average cosine over τ-lagged pairs and normalizes by the number of such pairs — this matches the cross-cohesion definition (ξ_ab(τ), Eq.15–16).
Responsivity, internal cohesion, social impact: your calc_responsivity, calculate_internal_cohesion, calculate_overall_responsivity, and calculate_social_impact implement the 1/w average of X(τ) (R(w), Eq.17), diagonal internal cohesion (r_aa(w), Eq.18), row-mean overall responsivity (Eq.19) and column-mean social impact (Eq.20).
Given–new & communication density formulas: your new_semantic_content computes ||n||/(||n||+||g||) and calc_single_density returns ||d|| / number_of_words which correspond to Eq.25 and Eq.27.
So the overall design follows the paper. Good job.
Problems I found (priority order — these will cause incorrect results / runtime errors)
calculate_participation returns a Python list but later code expects Series-like operations (.sum(), .index)
Example: in calculate_newness you do norm_p_a = participation_seq.sum() and participation_seq.index.to_series().apply(...). Those will fail because participation_seq is a list. You must return a numpy array or pandas.Series indexed by time positions (t = 1..n) so later code can multiply elementwise and access indices.
Indexing confusion: paper indexes by time position (t = 1..n); your code sometimes mixes contribution_id with sequence index
The paper assumes contributions are ordered and indexed by position t (1..n). Your functions like calc_semantic_similarity use contribution_id - 1 to index the participation sequence. That only works if contribution_id equals the sequential position (1..n). If your contribution_id column is not exactly the sequence index, results will be wrong. Ensure you map contribution_id → sequence index (and use that mapping everywhere).
span_given is incorrect (major):
You intended to compute an orthonormal basis Q of the span of all previous contribution vectors G_t = span(d_1*, …, d_{t-1}*) (Eq.21). Instead your span_given grabs the current contribution vector (get_lsa_embedding_by_id(discussion_data, time)) and then calls orth on its transpose. That produces a trivial 1-vector basis (or fails) and does not represent the subspace of previous contributions.
calc_cos_by_id / similarity computation — shapes and types
get_lsa_embedding_by_id returns a 1-D vector (shape (dim,)). cosine_similarity from sklearn expects 2-D arrays (1,dim). Passing 1-D arrays typically errors or behaves unpredictably. Use v.reshape(1,-1) or np.dot with normalization.
calc_semantic_similarity uses calculate_participation(...) repeatedly (inefficient) and may index using contribution_id -1 (index mapping bug)
Recomputing participation for every similarity call is expensive; compute participation once and reuse. Also the indexing issue above applies here.
span_given uses tfidf_embeddings = get_lsa_embedding_by_id(discussion_data, time) and then orth(tfidf_embeddings.T) — incorrect shapes & wrong vectors. (same as 3)
calculate_newness and calculate_communication_density use list indexes / .index and other Pandas ops on lists — same root as (1). Also newness should iterate over time positions (1..n) and sum p_a(t) * n(c_t) over t and divide by norm_p_a as in Eq.26.
Edge cases / empty subspace: project_and_residual checks if given_space.size == 0: but if given_space is shape (dim, 0) that check works; be careful about passing None vs empty arrays.
Performance: you call svd.transform and vectorizer.transform repeatedly per contribution; better to precompute embeddings for the whole discussion once and reuse (saves repeated SVD calls).
Concrete fixes — minimal, tested-style snippets (drop these in)
- Make participation return np.array with explicit time indexing and add mapping from contribution_id → time position
pythonCopyEditdef calculate_participation(discussion_data: pd.DataFrame, participant: str):
assume discussion_data is ordered by time (row order == t=1..n)
contributors = discussion_data['author'].tolist()
n = len(contributors)
k = discussion_data['author'].nunique()
p_a = np.array([1 if c == participant else 0 for c in contributors], dtype=int) # shape (n,)
p_a_total = int(p_a.sum())
p_a_mean = p_a_total / n if n > 0 else 0.0
participation_score = p_a_mean - (1 / k) if k > 0 else 0.0
also return a mapping from contribution_id to time index (1-based) for safety
contrib_ids = discussion_data['contribution_id'].tolist()
id2pos = {cid: pos+1 for pos, cid in enumerate(contrib_ids)} # 1-based t
return {
'participation_score': float(participation_score),
'participation_seq': p_a, # numpy array indexed by position 0..n-1 (t=1 maps to index 0)
'id2pos': id2pos,
'n': n,
'k': k
}
Use id2pos everywhere to translate contribution_id → t (or zero-based index).
- Fix cosine similarity (use 2-D arrays or manual normalized dot)
pythonCopyEditfrom sklearn.metrics.pairwise import cosine_similarity
def calc_cos_by_id(discussion_data: pd.DataFrame, id1: int, id2: int) -> float:
v1 = get_lsa_embedding_by_id(discussion_data, id1) # shape (dim,)
v2 = get_lsa_embedding_by_id(discussion_data, id2)
# ensure 2D
return float(cosine_similarity(v1.reshape(1, -1), v2.reshape(1, -1))[0,0])
Or faster (no sklearn call):
pythonCopyEditdef cosine_sim_vecs(v1, v2):
denom = (np.linalg.norm(v1) * np.linalg.norm(v2))
return float(np.dot(v1, v2) / denom) if denom > 0 else 0.0
- Correct span_given to build an orthonormal basis from previous contributions
pythonCopyEditfrom scipy.linalg import orth
def span_given(discussion_data: pd.DataFrame, time: int) -> np.ndarray:
"""
Return Q with shape (dim, k) where columns are orthonormal basis vectors
spanning all contributions with position t' < time (i.e., previous contributions).
time must be a 1-based sequence index (t=1..n). Use id2pos mapping to convert
contribution_id -> position if needed.
"""
# ensure discussion data is ordered by time: row order -> t = 1..n
# get vectors for previous positions (t' = 1 .. time-1)
if time <= 1:
# empty basis: return empty array with shape (dim, 0)
return np.zeros((svd.n_components, 0))
prev_vectors = []
# If you have precomputed embeddings for all rows, use that instead of get_lsa_embedding_by_id
for t_idx in range(1, time): # 1-based
# fetch by position: iloc[t_idx-1] is the row for t_idx
contribution_id = discussion_data.iloc[t_idx - 1]['contribution_id']
prev_vectors.append(get_lsa_embedding_by_id(discussion_data, contribution_id))
V = np.vstack(prev_vectors) # shape (m, dim)
# we want matrix with shape (dim, m) for orth to produce orthonormal columns
Q = orth(V.T) # shape (dim, k)
return Q
(Important: precompute embeddings once for discussion_data — see note below.)
-
Fix project_and_residual — your code is essentially correct; keep but ensure shapes are consistent
pythonCopyEditdef project_and_residual(Q: np.ndarray, cur_vector: np.ndarray):
v = np.atleast_2d(cur_vector) # shape (1, dim)
if Q.size == 0 or Q.shape[1] == 0:
proj = np.zeros_like(v)
return proj, v.copy()
proj = (v @ Q) @ Q.T
resid = v - proj
return proj.squeeze(), resid.squeeze() # return 1d arrays
-
Fix newness and communication_density computation to iterate over t positions (use id2pos)
Example corrected calculate_newness (vectorized approach):
pythonCopyEditdef new_semantic_content_by_pos(discussion_data, pos, id2pos):
pos is 1-based
map pos -> contribution_id
contribution_id = discussion_data.iloc[pos-1]['contribution_id']
Q = span_given(discussion_data, pos)
cur_vec = get_lsa_embedding_by_id(discussion_data, contribution_id)
proj, resid = project_and_residual(Q, cur_vec)
g_norm = np.linalg.norm(proj)
n_norm = np.linalg.norm(resid)
return n_norm / (n_norm + g_norm) if (n_norm + g_norm) > 0 else 0.0
def calculate_newness(discussion_data: pd.DataFrame, participant: str) -> float:
part = calculate_participation(discussion_data, participant)
p_seq = part['participation_seq'] # numpy array length n, indexed 0..n-1 (t=1 -> idx 0)
norm_p_a = p_seq.sum()
if norm_p_a == 0:
return 0.0
n = part['n']
# compute newness for each position t once (cache if repeated)
new_scores = np.array([new_semantic_content_by_pos(discussion_data, t, part['id2pos']) for t in range(1, n+1)])
weighted = (p_seq * new_scores).sum()
return float(weighted / norm_p_a)
Same pattern for communication density: compute Di for each t with ||d_t|| / n_words_t and average over participant's contributions using p_seq.
- Precompute LSA embeddings for the discussion (huge speedup & consistency)
At start of processing a discussion (subset), build a dict pos -> embedding or contribution_id -> embedding:
pythonCopyEditdef precompute_embeddings_for_discussion(discussion_data):
texts = discussion_data['text'].tolist()
tfidf = vectorizer.transform(texts)
lsa = svd.transform(tfidf) # shape (n, dim)
contrib_ids = discussion_data['contribution_id'].tolist()
id2vec = {cid: lsa[i] for i, cid in enumerate(contrib_ids)}
return id2vec
then replace get_lsa_embedding_by_id to simply do:
def get_lsa_embedding_by_id_from_cache(id2vec, contribution_id):
return id2vec[contribution_id]
Using a cache avoids repeated vectorizer.transform + svd.transform per call.
Additional notes / recommendations
Ensure discussion_data is ordered by chronological sequence (the paper treats t as sequence position). If contribution_id is arbitrary, sort by timestamp or sequence column and then use iloc consistently.
Be explicit about indexing: choose whether internal code uses 0-based indices (numpy) or 1-based positions (paper). I recommend keeping internal arrays 0-based, but always provide mapping id2pos and pos2id for clarity.
Numerical stability: when projecting, very small norms may cause division by zero in cosine or in newness computation — you already guard (n_norm + g_norm) > 0 in one place; do similar guards for cosine.
Memory / efficiency: for large discussions, calc_cross_cohesion_matrix does nested loops over all author pairs and then over sequence positions — that's O(k^2 * n). It matches the algorithmic intent but can be slow; consider vectorizing over time or using sparse data structures when many pairs have zero counts.
Short checklist you can run to validate
Confirm discussion_data sorted by time and contribution positions are 1..n (or build mapping).
Precompute embeddings for the discussion and confirm ||d_t|| for a few t (sanity).
Compute participation_seq and verify sum(participation_seq) == number_of_contributions_by_participant.
Compute a small hand-checked cross-cohesion for τ=1 for two authors in a tiny discussion and ensure your function matches the hand calculation per Eq.15.
If you want, I can:
produce corrected versions of the broken functions inserted into your script (I can produce a patch-like code block),
or run a small unit test pseudocode showing expected outputs for a tiny synthetic discussion so you can confirm correctness locally.
Which would you prefer?