Nacryos commited on
Commit
05fda2e
·
unverified ·
1 Parent(s): 6d2b534

Update cognate pair scripts + borrowing/similarity data (P0-P2 fixes)

Browse files
data/training/cognate_pairs/cognate_pairs_borrowing.tsv CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9f47de196443c307429b5e50fff4fb1888779bed16f7ba8999f8973dd607921b
3
- size 1888180
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7d7716625f51aded69e1b8d0552d2db0d1e23a9c9baec4ca0a94f6b5dfd02fd2
3
+ size 1902720
data/training/cognate_pairs/cognate_pairs_similarity.tsv CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7e7e7d4afb94c19667282056348d1a16c68ccb3294eab41029a48c5e064beefb
3
- size 25518124
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9c8b9317d4395721cd9c8a89761fe2aa6ca7dacf16d64a7b3aac9955f863b44
3
+ size 49930045
docs/DATABASE_REFERENCE.md CHANGED
@@ -1,6 +1,6 @@
1
  # Ancient Scripts Datasets — Master Database Reference
2
 
3
- > **Last updated:** 2026-03-13 | **Commit:** `3e3fdf1` | **Total entries:** 3,466,000+ across 1,178 languages
4
 
5
  This document is the single source of truth for understanding, modifying, and extending this database. It is designed for both human researchers and AI agents.
6
 
@@ -137,18 +137,20 @@ Lang_A Word_A IPA_A Lang_B Word_B IPA_B Concept_ID Relationship Score S
137
 
138
  | File | Rows | Description |
139
  |------|------|-------------|
140
- | `cognate_pairs_inherited.tsv` | 21,298,208 | Expert-classified cognates + concept-aligned pairs (score ≥ 0.5) |
141
- | `cognate_pairs_borrowing.tsv` | 17,924 | Verified donor→recipient borrowings from WOLD BorrowingTable |
142
- | `cognate_pairs_similarity.tsv` | 231,784 | Phonetically similar pairs (0.3 ≤ score < 0.5), no overlap with inherited |
143
-
144
- **Sources:**
145
- - ABVD CognateTable (21.6M expert cognate pairs, 1,682 Austronesian languages)
146
- - IE-CoR CognateTable (412K Indo-European cognate pairs)
147
- - Sino-Tibetan CognateTable (4.2K pairs, borrowings filtered)
148
- - WOLD BorrowingTable (17.9K verified donor-recipient pairs)
149
- - Internal concept-aligned pairs (233K) + similarity pairs (254K)
150
-
151
- **Deduplication:** Priority ordering expert_cognate > borrowing > concept_aligned > similarity_only. Cross-file dedup ensures no language-concept combo appears in both inherited and similarity files. See `docs/prd/PRD_COGNATE_PAIRS_V2.md` for full specification.
 
 
152
 
153
  ---
154
 
 
1
  # Ancient Scripts Datasets — Master Database Reference
2
 
3
+ > **Last updated:** 2026-03-14 | **Commit:** `bfb61c2` | **Total entries:** 3,466,000+ across 1,178 languages
4
 
5
  This document is the single source of truth for understanding, modifying, and extending this database. It is designed for both human researchers and AI agents.
6
 
 
137
 
138
  | File | Rows | Description |
139
  |------|------|-------------|
140
+ | `cognate_pairs_inherited.tsv` | 21,067,818 | Expert-classified cognates ONLY (ABVD + IE-CoR + Sino-Tibetan) |
141
+ | `cognate_pairs_borrowing.tsv` | 17,147 | Verified donor→recipient borrowings from WOLD BorrowingTable |
142
+ | `cognate_pairs_similarity.tsv` | 465,233 | Algorithmic phonetic similarity: concept_aligned (219,519, score ≥ 0.5) + similarity_only (245,714, 0.3 ≤ score < 0.5) |
143
+
144
+ **Sources & provenance:**
145
+ - **ABVD** CognateTable (20,697,739 pairs, 1,682 Austronesian languages) — Expert-classified by Greenhill, Blust & Gray (2008). Sister-sister relationships within cognate sets. `loan_flagged` for 160,768 pairs where ABVD Loan column non-empty.
146
+ - **IE-CoR** CognateTable (365,913 pairs, 159 Indo-European languages) — Expert-classified by Heggarty et al. (2023, Science). Mixed PIE-level (32%) and branch-level (55%) cognacy. `loan_involved` for 3,598 pairs where cognateset appears in loans.csv.
147
+ - **Sino-Tibetan** CognateTable (4,166 pairs) Expert-classified from STEDT-derived data (Jacques & List). Borrowings (146 entries) pre-filtered at extraction.
148
+ - **WOLD** BorrowingTable (17,147 pairs) — Expert borrowing judgments from Haspelmath & Tadmor (2009). `borrowed_immediate` (13,967) vs `borrowed_earlier` (3,180). Score = -1 sentinel for pseudo-IPA entries. Entries with "no evidence for borrowing" (802) filtered out.
149
+ - **Concept-aligned** (219,519 pairs) + **Similarity-only** (245,714 pairs) — Algorithmically generated via SCA phonetic comparison within same language family. NOT expert cognates. Isolate and constructed languages excluded.
150
+
151
+ **Deduplication:** Priority ordering expert_cognate > borrowing > concept_aligned > similarity_only. Pass 1.5 pre-populates expert language-concept keys across ALL files before writing, ensuring no concept_aligned/similarity pair duplicates an expert pair. See `docs/prd/PRD_COGNATE_PAIRS_V2.md` for full specification.
152
+
153
+ **Adversarial audit status (2026-03-14):** All 3 output files PASS final audit. Zero cross-file contamination, zero self-pairs, zero isolate/constructed language leakage, all Source_Record_IDs traceable to source databases.
154
 
155
  ---
156
 
scripts/extract_abvd_cognates_v2.py CHANGED
@@ -89,7 +89,7 @@ def main():
89
  lang_iso[lid] = iso
90
  print(f" Languages with ISO codes: {len(lang_iso)}")
91
 
92
- # Step 2: Read forms.csv → Form_ID → {language, word, ipa, concept}
93
  forms_path = SOURCES_DIR / "forms.csv"
94
  forms = {}
95
  with open(forms_path, "r", encoding="utf-8") as f:
@@ -107,11 +107,13 @@ def main():
107
  # Extract concept from Parameter_ID (e.g., "1_hand" → "hand")
108
  concept = param_id.split("_", 1)[1] if "_" in param_id else param_id
109
  ipa = form_to_pseudo_ipa(form)
 
110
  forms[fid] = {
111
  "iso": iso,
112
  "word": form,
113
  "ipa": ipa,
114
  "concept": concept,
 
115
  }
116
  print(f" Forms loaded: {len(forms)}")
117
 
@@ -145,6 +147,7 @@ def main():
145
  # Step 4: Generate cross-language pairs within each cognate set
146
  output_path = STAGING_DIR / "abvd_cognate_pairs.tsv"
147
  pair_count = 0
 
148
  with open(output_path, "w", encoding="utf-8") as out:
149
  out.write(HEADER)
150
  for cogset_id, members in cogsets.items():
@@ -164,17 +167,26 @@ def main():
164
  continue
165
  score = sca_similarity(a["ipa"], b["ipa"])
166
  confidence = "doubtful" if (a["doubt"] or b["doubt"]) else "certain"
 
 
 
 
 
 
 
 
167
  out.write(
168
  f"{a['iso']}\t{a['word']}\t{a['ipa']}\t"
169
  f"{b['iso']}\t{b['word']}\t{b['ipa']}\t"
170
  f"{a['concept']}\texpert_cognate\t{score}\tabvd\t"
171
- f"inherited\t-\t{confidence}\t{cogset_id}\n"
172
  )
173
  pair_count += 1
174
  if pair_count % 500000 == 0:
175
  print(f" ... {pair_count:,} pairs written")
176
 
177
  print(f"\n Total pairs: {pair_count:,}")
 
178
  print(f" Output: {output_path}")
179
  print("=" * 60)
180
 
 
89
  lang_iso[lid] = iso
90
  print(f" Languages with ISO codes: {len(lang_iso)}")
91
 
92
+ # Step 2: Read forms.csv → Form_ID → {language, word, ipa, concept, loan}
93
  forms_path = SOURCES_DIR / "forms.csv"
94
  forms = {}
95
  with open(forms_path, "r", encoding="utf-8") as f:
 
107
  # Extract concept from Parameter_ID (e.g., "1_hand" → "hand")
108
  concept = param_id.split("_", 1)[1] if "_" in param_id else param_id
109
  ipa = form_to_pseudo_ipa(form)
110
+ loan = row.get("Loan", "").strip()
111
  forms[fid] = {
112
  "iso": iso,
113
  "word": form,
114
  "ipa": ipa,
115
  "concept": concept,
116
+ "loan": loan,
117
  }
118
  print(f" Forms loaded: {len(forms)}")
119
 
 
147
  # Step 4: Generate cross-language pairs within each cognate set
148
  output_path = STAGING_DIR / "abvd_cognate_pairs.tsv"
149
  pair_count = 0
150
+ loan_flagged_count = 0
151
  with open(output_path, "w", encoding="utf-8") as out:
152
  out.write(HEADER)
153
  for cogset_id, members in cogsets.items():
 
167
  continue
168
  score = sca_similarity(a["ipa"], b["ipa"])
169
  confidence = "doubtful" if (a["doubt"] or b["doubt"]) else "certain"
170
+ # Check if either form is flagged as a loan
171
+ a_loan = a.get("loan", "")
172
+ b_loan = b.get("loan", "")
173
+ if (a_loan and a_loan.lower() != "false") or (b_loan and b_loan.lower() != "false"):
174
+ relation_detail = "loan_flagged"
175
+ loan_flagged_count += 1
176
+ else:
177
+ relation_detail = "inherited"
178
  out.write(
179
  f"{a['iso']}\t{a['word']}\t{a['ipa']}\t"
180
  f"{b['iso']}\t{b['word']}\t{b['ipa']}\t"
181
  f"{a['concept']}\texpert_cognate\t{score}\tabvd\t"
182
+ f"{relation_detail}\t-\t{confidence}\t{cogset_id}\n"
183
  )
184
  pair_count += 1
185
  if pair_count % 500000 == 0:
186
  print(f" ... {pair_count:,} pairs written")
187
 
188
  print(f"\n Total pairs: {pair_count:,}")
189
+ print(f" Loan-flagged pairs: {loan_flagged_count:,}")
190
  print(f" Output: {output_path}")
191
  print("=" * 60)
192
 
scripts/extract_iecor_cognates.py CHANGED
@@ -122,7 +122,19 @@ def main():
122
  }
123
  print(f" Forms loaded: {len(forms)}")
124
 
125
- # Step 4: Read cognates.csv → group by Cognateset_ID
 
 
 
 
 
 
 
 
 
 
 
 
126
  cognates_path = SOURCES_DIR / "cognates.csv"
127
  cogsets: dict[str, list[dict]] = defaultdict(list)
128
  doubt_count = 0
@@ -151,9 +163,13 @@ def main():
151
  # Step 5: Generate cross-language pairs
152
  output_path = STAGING_DIR / "iecor_cognate_pairs.tsv"
153
  pair_count = 0
 
 
154
  with open(output_path, "w", encoding="utf-8") as out:
155
  out.write(HEADER)
156
  for cogset_id, members in cogsets.items():
 
 
157
  for a, b in combinations(members, 2):
158
  if a["iso"] == b["iso"]:
159
  continue
@@ -163,13 +179,19 @@ def main():
163
  f"{a['iso']}\t{a['word']}\t{a['ipa']}\t"
164
  f"{b['iso']}\t{b['word']}\t{b['ipa']}\t"
165
  f"{a['concept']}\texpert_cognate\t{score}\tiecor\t"
166
- f"inherited\t-\t{confidence}\t{cogset_id}\n"
167
  )
168
  pair_count += 1
 
 
 
 
169
  if pair_count % 100000 == 0:
170
  print(f" ... {pair_count:,} pairs written")
171
 
172
  print(f"\n Total pairs: {pair_count:,}")
 
 
173
  print(f" Output: {output_path}")
174
  print("=" * 60)
175
 
 
122
  }
123
  print(f" Forms loaded: {len(forms)}")
124
 
125
+ # Step 4a: Read loans.csv → collect Cognateset_IDs involved in loans
126
+ loans_path = SOURCES_DIR / "loans.csv"
127
+ loan_cogset_ids: set[str] = set()
128
+ if loans_path.exists():
129
+ with open(loans_path, "r", encoding="utf-8") as f:
130
+ reader = csv.DictReader(f)
131
+ for row in reader:
132
+ cid = row.get("Cognateset_ID", "").strip()
133
+ if cid:
134
+ loan_cogset_ids.add(cid)
135
+ print(f" Loan-involved cognate sets: {len(loan_cogset_ids)}")
136
+
137
+ # Step 4b: Read cognates.csv → group by Cognateset_ID
138
  cognates_path = SOURCES_DIR / "cognates.csv"
139
  cogsets: dict[str, list[dict]] = defaultdict(list)
140
  doubt_count = 0
 
163
  # Step 5: Generate cross-language pairs
164
  output_path = STAGING_DIR / "iecor_cognate_pairs.tsv"
165
  pair_count = 0
166
+ loan_pair_count = 0
167
+ inherited_pair_count = 0
168
  with open(output_path, "w", encoding="utf-8") as out:
169
  out.write(HEADER)
170
  for cogset_id, members in cogsets.items():
171
+ is_loan = cogset_id in loan_cogset_ids
172
+ relation_detail = "loan_involved" if is_loan else "inherited"
173
  for a, b in combinations(members, 2):
174
  if a["iso"] == b["iso"]:
175
  continue
 
179
  f"{a['iso']}\t{a['word']}\t{a['ipa']}\t"
180
  f"{b['iso']}\t{b['word']}\t{b['ipa']}\t"
181
  f"{a['concept']}\texpert_cognate\t{score}\tiecor\t"
182
+ f"{relation_detail}\t-\t{confidence}\t{cogset_id}\n"
183
  )
184
  pair_count += 1
185
+ if is_loan:
186
+ loan_pair_count += 1
187
+ else:
188
+ inherited_pair_count += 1
189
  if pair_count % 100000 == 0:
190
  print(f" ... {pair_count:,} pairs written")
191
 
192
  print(f"\n Total pairs: {pair_count:,}")
193
+ print(f" Loan-involved pairs: {loan_pair_count:,}")
194
+ print(f" Purely inherited pairs: {inherited_pair_count:,}")
195
  print(f" Output: {output_path}")
196
  print("=" * 60)
197
 
scripts/extract_wold_borrowings_v2.py CHANGED
@@ -35,6 +35,29 @@ HEADER = (
35
  )
36
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def segments_to_ipa(segments: str) -> str:
39
  """Convert CLDF Segments column to IPA string."""
40
  if not segments:
@@ -103,9 +126,10 @@ def main():
103
  concept = row.get("Concepticon_Gloss", row.get("Name", pid)).strip()
104
  param_concept[pid] = concept
105
 
106
- # Step 3: Read forms.csv → Form_ID → {language, word, ipa, concept}
107
  forms_path = SOURCES_DIR / "forms.csv"
108
  forms = {}
 
109
  with open(forms_path, "r", encoding="utf-8") as f:
110
  reader = csv.DictReader(f)
111
  for row in reader:
@@ -119,6 +143,8 @@ def main():
119
  ipa = segments_to_ipa(segments) if segments else form.lower()
120
  param_id = row.get("Parameter_ID", "").strip()
121
  concept = param_concept.get(param_id, param_id)
 
 
122
  forms[fid] = {
123
  "iso": iso,
124
  "word": form,
@@ -133,6 +159,7 @@ def main():
133
  pair_count = 0
134
  skipped_no_target = 0
135
  skipped_no_source = 0
 
136
 
137
  with open(output_path, "w", encoding="utf-8") as out:
138
  out.write(HEADER)
@@ -153,7 +180,14 @@ def main():
153
  skipped_no_target += 1
154
  continue
155
 
 
 
 
 
 
 
156
  # Source can come from Source_Form_ID or Source_word
 
157
  if source_fid and source_fid in forms:
158
  source = forms[source_fid]
159
  source_iso = source["iso"]
@@ -162,39 +196,55 @@ def main():
162
  elif source_word:
163
  # Source form not in database — use Source_word + Source_languoid
164
  source_iso = lang_name_to_iso.get(source_lang, "-")
165
- source_word_str = source_word
166
- source_ipa = source_word.lower() # best-effort pseudo-IPA
 
167
  else:
168
  skipped_no_source += 1
169
  continue
170
 
171
- # Donor language
172
- donor_lang = source_iso if source_iso != "-" else source_lang
 
 
173
 
174
  # Confidence
175
  confidence = "certain" if source_certain == "yes" else (
176
  "uncertain" if source_certain == "no" else source_certain if source_certain else "-"
177
  )
178
 
179
- # Score
180
- score = sca_similarity(target["ipa"], source_ipa)
 
 
 
 
181
 
182
  # Filter self-loans (same language borrowing from itself)
183
  if target["iso"] == source_iso:
184
  continue
185
 
 
 
 
 
 
 
 
 
186
  # Lang_A = target (borrower), Lang_B = source (donor)
187
  out.write(
188
  f"{target['iso']}\t{target['word']}\t{target['ipa']}\t"
189
  f"{source_iso}\t{source_word_str}\t{source_ipa}\t"
190
  f"{target['concept']}\tborrowing\t{score}\twold\t"
191
- f"borrowed\t{donor_lang}\t{confidence}\twold_{borrowing_id}\n"
192
  )
193
  pair_count += 1
194
 
195
  print(f"\n Total borrowing pairs: {pair_count:,}")
196
  print(f" Skipped (no target form): {skipped_no_target}")
197
  print(f" Skipped (no source info): {skipped_no_source}")
 
198
  print(f" Output: {output_path}")
199
  print("=" * 60)
200
 
 
35
  )
36
 
37
 
38
+ def clean_source_word(raw: str) -> str:
39
+ """Clean a source word for pseudo-IPA use.
40
+
41
+ Strips parenthetical notes, proto-form asterisks, bracketed annotations,
42
+ and takes only the first alternative when multiple are separated by
43
+ comma, slash, or tilde. Result is still pseudo-IPA (not real IPA) but
44
+ free of annotations that would produce garbage.
45
+ """
46
+ if not raw:
47
+ return ""
48
+ s = raw
49
+ # 1. Strip parenthetical notes: "(Written Tibetan)" etc.
50
+ s = re.sub(r"\([^)]*\)", "", s)
51
+ # 2. Strip bracketed annotations: "[loan]" etc.
52
+ s = re.sub(r"\[[^\]]*\]", "", s)
53
+ # 3. Strip proto-form leading asterisks
54
+ s = re.sub(r"^\*+", "", s.strip())
55
+ # 4. Take only first alternative (split on , / ~)
56
+ s = re.split(r"[,/~]", s)[0]
57
+ # 5. Strip whitespace and lowercase
58
+ return s.strip().lower()
59
+
60
+
61
  def segments_to_ipa(segments: str) -> str:
62
  """Convert CLDF Segments column to IPA string."""
63
  if not segments:
 
126
  concept = row.get("Concepticon_Gloss", row.get("Name", pid)).strip()
127
  param_concept[pid] = concept
128
 
129
+ # Step 3: Read forms.csv → Form_ID → {language, word, ipa, concept} + Borrowed score
130
  forms_path = SOURCES_DIR / "forms.csv"
131
  forms = {}
132
+ form_borrowed: dict[str, str] = {} # Form_ID → Borrowed score string
133
  with open(forms_path, "r", encoding="utf-8") as f:
134
  reader = csv.DictReader(f)
135
  for row in reader:
 
143
  ipa = segments_to_ipa(segments) if segments else form.lower()
144
  param_id = row.get("Parameter_ID", "").strip()
145
  concept = param_concept.get(param_id, param_id)
146
+ borrowed = row.get("Borrowed", "").strip()
147
+ form_borrowed[fid] = borrowed
148
  forms[fid] = {
149
  "iso": iso,
150
  "word": form,
 
159
  pair_count = 0
160
  skipped_no_target = 0
161
  skipped_no_source = 0
162
+ skipped_no_evidence = 0
163
 
164
  with open(output_path, "w", encoding="utf-8") as out:
165
  out.write(HEADER)
 
180
  skipped_no_target += 1
181
  continue
182
 
183
+ # Skip entries where target form has "no evidence for borrowing"
184
+ target_borrowed = form_borrowed.get(target_fid, "")
185
+ if target_borrowed.startswith("5"):
186
+ skipped_no_evidence += 1
187
+ continue
188
+
189
  # Source can come from Source_Form_ID or Source_word
190
+ pseudo_ipa = False
191
  if source_fid and source_fid in forms:
192
  source = forms[source_fid]
193
  source_iso = source["iso"]
 
196
  elif source_word:
197
  # Source form not in database — use Source_word + Source_languoid
198
  source_iso = lang_name_to_iso.get(source_lang, "-")
199
+ source_word_str = clean_source_word(source_word)
200
+ source_ipa = source_word_str # cleaned pseudo-IPA (not real IPA)
201
+ pseudo_ipa = True
202
  else:
203
  skipped_no_source += 1
204
  continue
205
 
206
+ # Donor_Language: always use the WOLD language name (Source_languoid)
207
+ # for consistency. The field is a human-readable language name,
208
+ # NOT an ISO 639-3 code. Use source_iso (Lang_B) for the code.
209
+ donor_lang = source_lang if source_lang else "-"
210
 
211
  # Confidence
212
  confidence = "certain" if source_certain == "yes" else (
213
  "uncertain" if source_certain == "no" else source_certain if source_certain else "-"
214
  )
215
 
216
+ # Score: -1 sentinel when source IPA is pseudo-IPA (cleaned
217
+ # orthography, not real IPA) — SCA similarity is unreliable
218
+ if pseudo_ipa:
219
+ score = -1
220
+ else:
221
+ score = sca_similarity(target["ipa"], source_ipa)
222
 
223
  # Filter self-loans (same language borrowing from itself)
224
  if target["iso"] == source_iso:
225
  continue
226
 
227
+ # Relation_Detail: distinguish immediate vs earlier borrowings
228
+ if source_relation == "immediate":
229
+ relation_detail = "borrowed_immediate"
230
+ elif source_relation == "earlier":
231
+ relation_detail = "borrowed_earlier"
232
+ else:
233
+ relation_detail = "borrowed"
234
+
235
  # Lang_A = target (borrower), Lang_B = source (donor)
236
  out.write(
237
  f"{target['iso']}\t{target['word']}\t{target['ipa']}\t"
238
  f"{source_iso}\t{source_word_str}\t{source_ipa}\t"
239
  f"{target['concept']}\tborrowing\t{score}\twold\t"
240
+ f"{relation_detail}\t{donor_lang}\t{confidence}\twold_{borrowing_id}\n"
241
  )
242
  pair_count += 1
243
 
244
  print(f"\n Total borrowing pairs: {pair_count:,}")
245
  print(f" Skipped (no target form): {skipped_no_target}")
246
  print(f" Skipped (no source info): {skipped_no_source}")
247
+ print(f" Skipped (no evidence for borrowing): {skipped_no_evidence}")
248
  print(f" Output: {output_path}")
249
  print("=" * 60)
250
 
scripts/merge_cognate_pairs.py CHANGED
@@ -89,12 +89,29 @@ def main():
89
  print(f" Total input rows: {total_input:,}")
90
  print(f" Unique pairs: {len(seen_pairs):,}")
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  # Second pass: write output files, keeping only best-priority entries
93
  print("\n Pass 2: Writing output files...")
94
  written_keys: set[str] = set()
95
- # Track (lang_pair, concept) combos that appear in inherited/borrowing
96
- # to prevent the same language-concept pair from also appearing in similarity
97
- inherited_lang_concepts: set[str] = set()
98
  counts = {"inherited": 0, "borrowing": 0, "similarity": 0}
99
  self_pair_skips = 0
100
 
@@ -137,20 +154,23 @@ def main():
137
  lc_a, lc_b = sorted([lang_a, lang_b])
138
  lang_concept_key = f"{lc_a}||{lc_b}||{concept}"
139
 
140
- written_keys.add(key)
141
-
142
  # Route to correct output file
143
  if relationship == "expert_cognate":
144
  f_inh.write(line)
145
  counts["inherited"] += 1
146
- inherited_lang_concepts.add(lang_concept_key)
147
  elif relationship == "borrowing":
148
  f_bor.write(line)
149
  counts["borrowing"] += 1
 
150
  elif relationship == "concept_aligned":
151
- f_inh.write(line)
152
- counts["inherited"] += 1
153
- inherited_lang_concepts.add(lang_concept_key)
 
 
 
 
154
  elif relationship == "similarity_only":
155
  # Skip if this language-concept combo already
156
  # has an inherited/expert pair (prevents cross-file
@@ -159,6 +179,7 @@ def main():
159
  continue
160
  f_sim.write(line)
161
  counts["similarity"] += 1
 
162
 
163
  total_written = sum(counts.values())
164
  if total_written % 1000000 == 0:
 
89
  print(f" Total input rows: {total_input:,}")
90
  print(f" Unique pairs: {len(seen_pairs):,}")
91
 
92
+ # Pass 1.5: Pre-populate inherited_lang_concepts from ALL expert_cognate
93
+ # entries across ALL files. This ensures concept_aligned and similarity_only
94
+ # pairs are correctly suppressed even when expert_cognate files are
95
+ # alphabetically after concept_aligned files.
96
+ print("\n Pass 1.5: Collecting expert_cognate language-concept keys...")
97
+ inherited_lang_concepts: set[str] = set()
98
+ for sf in staging_files:
99
+ with open(sf, "r", encoding="utf-8") as f:
100
+ header = f.readline()
101
+ for line in f:
102
+ parts = line.rstrip("\n").split("\t")
103
+ if len(parts) < 8:
104
+ continue
105
+ relationship = parts[7]
106
+ if relationship == "expert_cognate":
107
+ la, lb = sorted([parts[0], parts[3]])
108
+ concept = parts[6]
109
+ inherited_lang_concepts.add(f"{la}||{lb}||{concept}")
110
+ print(f" Expert language-concept keys: {len(inherited_lang_concepts):,}")
111
+
112
  # Second pass: write output files, keeping only best-priority entries
113
  print("\n Pass 2: Writing output files...")
114
  written_keys: set[str] = set()
 
 
 
115
  counts = {"inherited": 0, "borrowing": 0, "similarity": 0}
116
  self_pair_skips = 0
117
 
 
154
  lc_a, lc_b = sorted([lang_a, lang_b])
155
  lang_concept_key = f"{lc_a}||{lc_b}||{concept}"
156
 
 
 
157
  # Route to correct output file
158
  if relationship == "expert_cognate":
159
  f_inh.write(line)
160
  counts["inherited"] += 1
161
+ written_keys.add(key)
162
  elif relationship == "borrowing":
163
  f_bor.write(line)
164
  counts["borrowing"] += 1
165
+ written_keys.add(key)
166
  elif relationship == "concept_aligned":
167
+ # concept_aligned goes to similarity (not inherited)
168
+ # per PRD: expert cognates in inherited ONLY
169
+ if lang_concept_key in inherited_lang_concepts:
170
+ continue
171
+ f_sim.write(line)
172
+ counts["similarity"] += 1
173
+ written_keys.add(key)
174
  elif relationship == "similarity_only":
175
  # Skip if this language-concept combo already
176
  # has an inherited/expert pair (prevents cross-file
 
179
  continue
180
  f_sim.write(line)
181
  counts["similarity"] += 1
182
+ written_keys.add(key)
183
 
184
  total_written = sum(counts.values())
185
  if total_written % 1000000 == 0: