paperminertoolkit 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. paperminertoolkit/__init__.py +10 -0
  2. paperminertoolkit/_version.py +11 -0
  3. paperminertoolkit/cli.py +1053 -0
  4. paperminertoolkit/corpus/__init__.py +1 -0
  5. paperminertoolkit/corpus/database.py +1542 -0
  6. paperminertoolkit/corpus/documents.py +313 -0
  7. paperminertoolkit/corpus/filtering.py +1390 -0
  8. paperminertoolkit/corpus/metadata.py +532 -0
  9. paperminertoolkit/extraction/__init__.py +1 -0
  10. paperminertoolkit/extraction/compression.py +486 -0
  11. paperminertoolkit/extraction/extract.py +573 -0
  12. paperminertoolkit/extraction/models.py +784 -0
  13. paperminertoolkit/extraction/recipes.py +241 -0
  14. paperminertoolkit/extraction/scrape.py +737 -0
  15. paperminertoolkit/extraction/store.py +244 -0
  16. paperminertoolkit/extraction/tokenizer.py +313 -0
  17. paperminertoolkit/providers/__init__.py +1 -0
  18. paperminertoolkit/providers/arxiv.py +760 -0
  19. paperminertoolkit/providers/base.py +514 -0
  20. paperminertoolkit/providers/biorxiv.py +561 -0
  21. paperminertoolkit/providers/chemrxiv.py +1115 -0
  22. paperminertoolkit/providers/core.py +423 -0
  23. paperminertoolkit/providers/crossref.py +649 -0
  24. paperminertoolkit/providers/elsevier.py +455 -0
  25. paperminertoolkit/providers/medrxiv.py +548 -0
  26. paperminertoolkit/providers/openalex.py +471 -0
  27. paperminertoolkit/providers/pubmed.py +1272 -0
  28. paperminertoolkit/providers/registry.py +521 -0
  29. paperminertoolkit/providers/rxiv.py +936 -0
  30. paperminertoolkit/providers/unpaywall.py +162 -0
  31. paperminertoolkit/resources/recipes.json +1670 -0
  32. paperminertoolkit/settings.py +661 -0
  33. paperminertoolkit/workflows/__init__.py +1 -0
  34. paperminertoolkit/workflows/download.py +1748 -0
  35. paperminertoolkit/workflows/enrichment.py +1906 -0
  36. paperminertoolkit/workflows/imports.py +121 -0
  37. paperminertoolkit/workflows/search.py +877 -0
  38. paperminertoolkit/workflows/topics.py +2837 -0
  39. paperminertoolkit/workflows/utilities.py +73 -0
  40. paperminertoolkit-1.0.0.dist-info/METADATA +126 -0
  41. paperminertoolkit-1.0.0.dist-info/RECORD +45 -0
  42. paperminertoolkit-1.0.0.dist-info/WHEEL +5 -0
  43. paperminertoolkit-1.0.0.dist-info/entry_points.txt +2 -0
  44. paperminertoolkit-1.0.0.dist-info/licenses/LICENSE +21 -0
  45. paperminertoolkit-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2837 @@
1
+ """Train, inspect, name, and apply reproducible LDA topic models.
2
+
3
+ Topic models are stored outside the paper corpus as versioned artifacts. The
4
+ corpus remains the source of paper metadata and text assets; predictions are
5
+ exported in long CSV form and can be explicitly registered for filtering.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import csv
11
+ import hashlib
12
+ import heapq
13
+ import html
14
+ import json
15
+ import math
16
+ import re
17
+ import sqlite3
18
+ import tempfile
19
+ import time
20
+ import unicodedata
21
+ import warnings
22
+ from collections import Counter
23
+ from collections.abc import Iterable, Iterator, Mapping, Sequence
24
+ from datetime import datetime, timezone
25
+ from itertools import combinations, groupby
26
+ from os import PathLike
27
+ from pathlib import Path
28
+ from typing import Any, NotRequired, TypedDict
29
+
30
+ import joblib
31
+ import numpy as np
32
+ import sklearn
33
+ from numpy.typing import NDArray
34
+ from scipy import sparse
35
+ from scipy.sparse import spmatrix
36
+ from sklearn.decomposition import LatentDirichletAllocation
37
+ from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS, CountVectorizer
38
+
39
+ from paperminertoolkit.corpus.database import connect, get_asset
40
+ from paperminertoolkit.corpus.documents import trim_reference_section
41
+
42
+
43
+ SUPPORTED_TEXT_FIELDS = {'title', 'abstract', 'text'}
44
+ MODEL_FILENAME = 'lda_model.joblib'
45
+ VECTORIZER_FILENAME = 'vectorizer.joblib'
46
+ CONFIG_FILENAME = 'config.json'
47
+ REPORT_FILENAME = 'training_report.json'
48
+ FINGERPRINT_FILENAME = 'corpus_fingerprint.json'
49
+ TOPICS_FILENAME = 'topics.csv'
50
+ TOPIC_NAMES_FILENAME = 'topic_names.json'
51
+ REPRESENTATIVES_FILENAME = 'representative_papers.csv'
52
+ PREDICTIONS_FILENAME = 'paper_topics.csv'
53
+ STOPWORDS_FILENAME = 'stopwords.txt'
54
+ COMPARISON_CSV_FILENAME = 'model_comparison.csv'
55
+ COMPARISON_JSON_FILENAME = 'model_comparison.json'
56
+ TRENDS_CSV_FILENAME = 'topic_trends.csv'
57
+ TRENDS_REPORT_FILENAME = 'trend_report.json'
58
+ TRENDS_PLOT_FILENAME = 'topic_trends_plot.png'
59
+ ARTIFACT_VERSION = 2
60
+ TOKEN_PATTERN = r'(?u)\b[a-z][a-z0-9]{1,}\b'
61
+ TOKEN_RE = re.compile(TOKEN_PATTERN)
62
+ URL_RE = re.compile(r'https?://\S+', re.IGNORECASE)
63
+ DOI_RE = re.compile(r'\b10\.\d{4,9}/\S+', re.IGNORECASE)
64
+ DEFAULT_BATCH_SIZE = 128
65
+ DEFAULT_EVALUATION_SAMPLE_SIZE = 10000
66
+
67
+
68
+ class _TopicDocument(TypedDict):
69
+ """Normalized corpus document used by topic-model workflows."""
70
+
71
+ paper_id: str
72
+ doi: str
73
+ title: str
74
+ publication_date: str
75
+ text: str
76
+ token_count: int
77
+
78
+
79
+ class _TopicRow(TypedDict):
80
+ """Exportable topic description."""
81
+
82
+ topic_id: int
83
+ topic_name: str
84
+ top_terms: list[str]
85
+ representative_papers: NotRequired[list[dict[str, str]]]
86
+
87
+
88
+ class TopicAnalyzer:
89
+ """Generate domain-aware features for topic models.
90
+
91
+ Parameters
92
+ ----------
93
+ domain_stopwords : iterable of str, optional
94
+ Domain-specific words to omit as standalone features.
95
+ ngram_max : int, default=2
96
+ Maximum n-gram size to emit.
97
+
98
+ Attributes
99
+ ----------
100
+ domain_stopwords : frozenset of str
101
+ Normalized collection of standalone features to omit.
102
+ ngram_max : int
103
+ Maximum configured n-gram size.
104
+ """
105
+
106
+ def __init__(self, domain_stopwords: Iterable[str] = (), ngram_max: int = 2) -> None:
107
+ """Initialize the topic analyzer.
108
+
109
+ Parameters
110
+ ----------
111
+ domain_stopwords : Iterable[str], optional
112
+ Domain-specific words to omit as standalone features.
113
+ ngram_max : int, default=2
114
+ Maximum n-gram size to emit.
115
+ """
116
+ self.domain_stopwords = frozenset(domain_stopwords)
117
+ self.ngram_max = ngram_max
118
+
119
+ def __call__(self, document: str) -> list[str]:
120
+ """Extract topic-model features from a document.
121
+
122
+ Parameters
123
+ ----------
124
+ document : str
125
+ Normalized document text to analyze.
126
+
127
+ Returns
128
+ -------
129
+ list[str]
130
+ Unigram and optional bigram features.
131
+ """
132
+ features = []
133
+ for segment in re.split(r'[.!?;:\n]+', document):
134
+ tokens = [token for token in TOKEN_RE.findall(segment) if token not in ENGLISH_STOP_WORDS]
135
+ features.extend(token for token in tokens if token not in self.domain_stopwords)
136
+ if self.ngram_max >= 2:
137
+ for left, right in zip(tokens, tokens[1:]):
138
+ if left in self.domain_stopwords and right in self.domain_stopwords:
139
+ continue
140
+ features.append(f'{left}_{right}')
141
+ return features
142
+
143
+
144
+ def _utc_now() -> str:
145
+ """Return a stable UTC timestamp for model metadata.
146
+
147
+ Returns
148
+ -------
149
+ str
150
+ ISO-8601 UTC timestamp with second precision.
151
+ """
152
+ return datetime.now(timezone.utc).isoformat(timespec='seconds')
153
+
154
+
155
+ def normalize_topic_text(value: object) -> str:
156
+ """Normalize text while preserving words and chemical formulae.
157
+
158
+ Parameters
159
+ ----------
160
+ value : object
161
+ Document text or a value coercible to text.
162
+
163
+ Returns
164
+ -------
165
+ str
166
+ Unicode-normalized, case-folded plain text without URLs or DOIs.
167
+ """
168
+ if value is None:
169
+ return ''
170
+ text = html.unescape(str(value))
171
+ text = unicodedata.normalize('NFKC', text)
172
+ text = re.sub(r'<[^>]+>', ' ', text)
173
+ text = URL_RE.sub(' ', text)
174
+ text = DOI_RE.sub(' ', text)
175
+ text = text.casefold()
176
+ return re.sub(r'\s+', ' ', text).strip()
177
+
178
+
179
+ def load_domain_stopwords(stopwords_file: str | PathLike[str] | None) -> list[str]:
180
+ """Load corpus-specific stopwords from a text file.
181
+
182
+ Parameters
183
+ ----------
184
+ stopwords_file : str, os.PathLike[str], or None
185
+ File containing one word per non-comment line, or ``None``.
186
+
187
+ Returns
188
+ -------
189
+ list[str]
190
+ Sorted unique normalized stopwords.
191
+
192
+ Raises
193
+ ------
194
+ OSError
195
+ If the stopword file cannot be read.
196
+ ValueError
197
+ If a non-comment line does not contain exactly one normalized word.
198
+ """
199
+ if stopwords_file is None:
200
+ return []
201
+ path = Path(stopwords_file)
202
+ words = []
203
+ for line_number, raw_line in enumerate(path.read_text(encoding='utf-8-sig').splitlines(), start=1):
204
+ value = raw_line.split('#', 1)[0].strip()
205
+ if not value:
206
+ continue
207
+ normalized = normalize_topic_text(value)
208
+ tokens = TOKEN_RE.findall(normalized)
209
+ if len(tokens) != 1 or tokens[0] != normalized:
210
+ raise ValueError(
211
+ f'{path}:{line_number}: expected exactly one word per line; found {value!r}.'
212
+ )
213
+ words.append(tokens[0])
214
+ return sorted(set(words))
215
+
216
+
217
+ def _validate_text_fields(text_fields: Iterable[str]) -> tuple[str, ...]:
218
+ """Validate and deduplicate topic-model text fields.
219
+
220
+ Parameters
221
+ ----------
222
+ text_fields : Iterable[str]
223
+ Requested corpus text fields.
224
+
225
+ Returns
226
+ -------
227
+ tuple[str, ...]
228
+ Unique fields in first-seen order.
229
+
230
+ Raises
231
+ ------
232
+ ValueError
233
+ If no fields are supplied or any field is unsupported.
234
+ """
235
+ fields = tuple(dict.fromkeys(text_fields))
236
+ if not fields:
237
+ raise ValueError('At least one topic-model text field is required.')
238
+ unsupported = set(fields) - SUPPORTED_TEXT_FIELDS
239
+ if unsupported:
240
+ raise ValueError(f'Unsupported topic-model text fields: {", ".join(sorted(unsupported))}')
241
+ return fields
242
+
243
+
244
+ def _topic_document(
245
+ paper: Mapping[str, Any],
246
+ assets: Mapping[str, Mapping[str, Any] | None],
247
+ fields: Iterable[str],
248
+ ) -> _TopicDocument:
249
+ """Build one normalized topic document from metadata and loaded assets.
250
+
251
+ Parameters
252
+ ----------
253
+ paper : Mapping[str, Any]
254
+ Corpus paper row.
255
+ assets : Mapping[str, Mapping[str, Any] or None]
256
+ Newest stored asset for each requested content role.
257
+ fields : Iterable[str]
258
+ Metadata and asset fields to combine.
259
+
260
+ Returns
261
+ -------
262
+ _TopicDocument
263
+ Paper metadata, normalized modeling text, and token count.
264
+ """
265
+ pieces = []
266
+ for field in fields:
267
+ if field == 'title':
268
+ value = paper.get('title') or ''
269
+ else:
270
+ asset = assets.get(field)
271
+ value = asset['content'].decode('utf-8', errors='replace') if asset else ''
272
+ if field == 'text' and value:
273
+ value = trim_reference_section(value)
274
+ if str(value).strip():
275
+ pieces.append(str(value))
276
+ text = normalize_topic_text(' '.join(pieces))
277
+ return {
278
+ 'paper_id': paper['paper_id'],
279
+ 'doi': paper.get('doi') or '',
280
+ 'title': paper.get('title') or '',
281
+ 'publication_date': paper.get('publication_date') or '',
282
+ 'text': text,
283
+ 'token_count': len(TOKEN_RE.findall(text)),
284
+ }
285
+
286
+
287
+ def iter_topic_document_batches(
288
+ db_path: str | PathLike[str],
289
+ text_fields: Iterable[str] = ('title', 'abstract'),
290
+ batch_size: int = DEFAULT_BATCH_SIZE,
291
+ ) -> Iterator[list[_TopicDocument]]:
292
+ """Yield stable, bounded batches of normalized corpus documents.
293
+
294
+ Parameters
295
+ ----------
296
+ db_path : str or os.PathLike[str]
297
+ Path to the SQLite paper corpus.
298
+ text_fields : Iterable[str], default=('title', 'abstract')
299
+ Metadata and asset fields to combine into each document.
300
+ batch_size : int, default=128
301
+ Maximum number of papers loaded per batch.
302
+
303
+ Yields
304
+ ------
305
+ list[_TopicDocument]
306
+ Normalized documents ordered by paper ID.
307
+
308
+ Raises
309
+ ------
310
+ ValueError
311
+ If a requested text field is unsupported or ``batch_size`` is not
312
+ positive.
313
+ """
314
+ fields = _validate_text_fields(text_fields)
315
+ if batch_size < 1:
316
+ raise ValueError('batch_size must be positive.')
317
+ asset_roles = [field for field in fields if field in {'abstract', 'text'}]
318
+ with connect(db_path) as conn:
319
+ last_paper_id = ''
320
+ while True:
321
+ rows = conn.execute(
322
+ 'SELECT * FROM papers WHERE paper_id > ? ORDER BY paper_id LIMIT ?',
323
+ (last_paper_id, batch_size),
324
+ ).fetchall()
325
+ if not rows:
326
+ break
327
+ documents = []
328
+ for row in rows:
329
+ paper = dict(row)
330
+ assets = {
331
+ role: get_asset(conn, paper['paper_id'], role)
332
+ for role in asset_roles
333
+ }
334
+ documents.append(_topic_document(paper, assets, fields))
335
+ yield documents
336
+ last_paper_id = rows[-1]['paper_id']
337
+
338
+
339
+ def load_topic_documents(
340
+ db_path: str | PathLike[str],
341
+ text_fields: Iterable[str] = ('title', 'abstract'),
342
+ ) -> list[_TopicDocument]:
343
+ """Load normalized topic-model documents from a corpus.
344
+
345
+ Parameters
346
+ ----------
347
+ db_path : str or pathlib.Path
348
+ Path to the SQLite paper corpus.
349
+ text_fields : Iterable[str], default=('title', 'abstract')
350
+ Metadata and asset fields to combine into each document.
351
+
352
+ Returns
353
+ -------
354
+ list[_TopicDocument]
355
+ Paper metadata, normalized text, and token counts.
356
+
357
+ Raises
358
+ ------
359
+ ValueError
360
+ If any requested text field is unsupported.
361
+ """
362
+ fields = _validate_text_fields(text_fields)
363
+ return [
364
+ document
365
+ for batch in iter_topic_document_batches(db_path, fields)
366
+ for document in batch
367
+ ]
368
+
369
+
370
+ def _median(values: Sequence[int | float]) -> int | float:
371
+ """Calculate the median of numeric values.
372
+
373
+ Parameters
374
+ ----------
375
+ values : Sequence[int or float]
376
+ Values whose median is required.
377
+
378
+ Returns
379
+ -------
380
+ int or float
381
+ Median value, or zero for an empty sequence.
382
+ """
383
+ if not values:
384
+ return 0
385
+ ordered = sorted(values)
386
+ midpoint = len(ordered) // 2
387
+ if len(ordered) % 2:
388
+ return ordered[midpoint]
389
+ return (ordered[midpoint - 1] + ordered[midpoint]) / 2
390
+
391
+
392
+ def assess_topic_corpus(
393
+ documents: Sequence[_TopicDocument],
394
+ num_topics: int,
395
+ ) -> dict[str, Any]:
396
+ """Assess corpus quality for LDA topic modeling.
397
+
398
+ Parameters
399
+ ----------
400
+ documents : Sequence[_TopicDocument]
401
+ Topic documents containing ``token_count`` values.
402
+ num_topics : int
403
+ Requested number of latent topics.
404
+
405
+ Returns
406
+ -------
407
+ dict[str, Any]
408
+ Corpus counts, length diagnostics, and heuristic warnings.
409
+
410
+ Raises
411
+ ------
412
+ ValueError
413
+ If fewer than two topics are requested or too few usable documents
414
+ exist.
415
+ """
416
+ if num_topics < 2:
417
+ raise ValueError('num_topics must be at least 2.')
418
+ usable = [document for document in documents if document['token_count'] > 0]
419
+ if len(usable) < num_topics:
420
+ raise ValueError(
421
+ f'LDA requires at least as many usable documents as topics; '
422
+ f'found {len(usable)} documents for {num_topics} topics.'
423
+ )
424
+
425
+ document_count = len(documents)
426
+ empty_count = document_count - len(usable)
427
+ token_counts = [document['token_count'] for document in usable]
428
+ warning_messages = []
429
+ recommended_documents = max(500, 50 * num_topics)
430
+ if len(usable) < recommended_documents:
431
+ warning_messages.append(
432
+ f'Small topic-model corpus: {len(usable)} usable documents for {num_topics} topics. '
433
+ f'Consider at least {recommended_documents} documents (50 per topic, minimum 500) '
434
+ 'for more stable topics.'
435
+ )
436
+ median_tokens = _median(token_counts)
437
+ if median_tokens < 50:
438
+ warning_messages.append(
439
+ f'Short topic-model documents: median usable length is {median_tokens:g} tokens; '
440
+ 'topic quality may be poor below roughly 50 tokens.'
441
+ )
442
+ if document_count and empty_count / document_count > 0.1:
443
+ warning_messages.append(
444
+ f'{empty_count} of {document_count} documents contain no usable text '
445
+ 'and will be excluded from training.'
446
+ )
447
+ return {
448
+ 'documents_total': document_count,
449
+ 'documents_usable_before_vectorization': len(usable),
450
+ 'documents_empty': empty_count,
451
+ 'median_tokens': median_tokens,
452
+ 'documents_per_topic': len(usable) / num_topics,
453
+ 'warnings': warning_messages,
454
+ }
455
+
456
+
457
+ def _emit_warnings(messages: Iterable[str]) -> None:
458
+ """Emit corpus diagnostics through Python's warnings interface.
459
+
460
+ Parameters
461
+ ----------
462
+ messages : Iterable[str]
463
+ Warning messages to emit.
464
+ """
465
+ for message in messages:
466
+ warnings.warn(message, UserWarning, stacklevel=3)
467
+
468
+
469
+ def _corpus_fingerprint(documents: Iterable[_TopicDocument]) -> str:
470
+ """Build a deterministic fingerprint for topic documents.
471
+
472
+ Parameters
473
+ ----------
474
+ documents : Iterable[_TopicDocument]
475
+ Documents containing paper IDs and normalized text.
476
+
477
+ Returns
478
+ -------
479
+ str
480
+ SHA-256 hexadecimal digest.
481
+ """
482
+ digest = hashlib.sha256()
483
+ for document in sorted(documents, key=lambda item: item['paper_id']):
484
+ digest.update(document['paper_id'].encode('utf-8'))
485
+ digest.update(b'\0')
486
+ digest.update(hashlib.sha256(document['text'].encode('utf-8')).digest())
487
+ digest.update(b'\0')
488
+ return digest.hexdigest()
489
+
490
+
491
+ def _topic_rows(
492
+ model: LatentDirichletAllocation,
493
+ vectorizer: CountVectorizer,
494
+ top_terms: int,
495
+ ) -> list[_TopicRow]:
496
+ """Extract the highest-weighted terms from each fitted topic.
497
+
498
+ Parameters
499
+ ----------
500
+ model : sklearn.decomposition.LatentDirichletAllocation
501
+ Fitted LDA model.
502
+ vectorizer : sklearn.feature_extraction.text.CountVectorizer
503
+ Fitted feature vectorizer.
504
+ top_terms : int
505
+ Maximum terms to retain per topic.
506
+
507
+ Returns
508
+ -------
509
+ list[_TopicRow]
510
+ Topic IDs, blank manual names, and weighted terms.
511
+ """
512
+ feature_names = vectorizer.get_feature_names_out()
513
+ rows = []
514
+ for topic_id, weights in enumerate(model.components_):
515
+ indices = weights.argsort()[::-1][:top_terms]
516
+ rows.append({
517
+ 'topic_id': topic_id,
518
+ 'topic_name': '',
519
+ 'top_terms': [str(feature_names[index]) for index in indices],
520
+ })
521
+ return rows
522
+
523
+
524
+ def _write_json(path: str | PathLike[str], value: Any) -> None:
525
+ """Write deterministic, readable JSON metadata.
526
+
527
+ Parameters
528
+ ----------
529
+ path : str or os.PathLike[str]
530
+ Destination JSON path.
531
+ value : Any
532
+ JSON-serializable value to write.
533
+
534
+ Raises
535
+ ------
536
+ OSError
537
+ If the destination cannot be written.
538
+ TypeError
539
+ If ``value`` is not JSON serializable.
540
+ """
541
+ Path(path).write_text(json.dumps(value, indent=2, sort_keys=True) + '\n', encoding='utf-8')
542
+
543
+
544
+ def _write_topics(
545
+ path: str | PathLike[str],
546
+ topic_rows: Iterable[_TopicRow],
547
+ ) -> None:
548
+ """Write manually nameable topic summaries.
549
+
550
+ Parameters
551
+ ----------
552
+ path : str or os.PathLike[str]
553
+ Destination CSV path.
554
+ topic_rows : Iterable[_TopicRow]
555
+ Topic IDs, names, and top-term lists.
556
+
557
+ Raises
558
+ ------
559
+ OSError
560
+ If the destination cannot be written.
561
+ """
562
+ with Path(path).open('w', encoding='utf-8', newline='') as handle:
563
+ writer = csv.DictWriter(handle, fieldnames=['topic_id', 'topic_name', 'top_terms'])
564
+ writer.writeheader()
565
+ for row in topic_rows:
566
+ writer.writerow({
567
+ 'topic_id': row['topic_id'],
568
+ 'topic_name': row.get('topic_name', ''),
569
+ 'top_terms': '; '.join(row['top_terms']),
570
+ })
571
+
572
+
573
+ def _refresh_csv_topic_names(
574
+ path: str | PathLike[str],
575
+ names: Mapping[str, str],
576
+ ) -> None:
577
+ """Refresh names in an existing topic artifact CSV.
578
+
579
+ Parameters
580
+ ----------
581
+ path : str or os.PathLike[str]
582
+ Artifact CSV to update when it exists.
583
+ names : Mapping[str, str]
584
+ Manual names keyed by string topic ID.
585
+
586
+ Raises
587
+ ------
588
+ OSError
589
+ If the artifact cannot be read, rewritten, or replaced.
590
+ """
591
+ path = Path(path)
592
+ if not path.exists():
593
+ return
594
+ with path.open(encoding='utf-8', newline='') as handle:
595
+ reader = csv.DictReader(handle)
596
+ fieldnames = reader.fieldnames
597
+ rows = list(reader)
598
+ if not fieldnames or 'topic_name' not in fieldnames:
599
+ return
600
+ for row in rows:
601
+ topic_id = row.get('topic_id', '')
602
+ if topic_id != '':
603
+ row['topic_name'] = names.get(str(topic_id), '')
604
+ temporary_path = path.with_suffix(path.suffix + '.tmp')
605
+ with temporary_path.open('w', encoding='utf-8', newline='') as handle:
606
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
607
+ writer.writeheader()
608
+ writer.writerows(rows)
609
+ temporary_path.replace(path)
610
+
611
+
612
+ def _topic_names(
613
+ model_dir: str | PathLike[str],
614
+ num_topics: int,
615
+ ) -> dict[str, str]:
616
+ """Load manual topic names from a model artifact.
617
+
618
+ Parameters
619
+ ----------
620
+ model_dir : str or os.PathLike[str]
621
+ Topic-model artifact directory.
622
+ num_topics : int
623
+ Number of topic IDs to include.
624
+
625
+ Returns
626
+ -------
627
+ dict[str, str]
628
+ Manual names keyed by topic ID, with missing names left blank.
629
+
630
+ Raises
631
+ ------
632
+ OSError
633
+ If the topic-name file cannot be read.
634
+ json.JSONDecodeError
635
+ If the topic-name file contains invalid JSON.
636
+ """
637
+ path = Path(model_dir) / TOPIC_NAMES_FILENAME
638
+ if path.exists():
639
+ values = json.loads(path.read_text(encoding='utf-8'))
640
+ else:
641
+ values = {}
642
+ return {str(topic_id): str(values.get(str(topic_id), '')) for topic_id in range(num_topics)}
643
+
644
+
645
+ def _write_predictions(
646
+ path: str | PathLike[str],
647
+ documents: Sequence[_TopicDocument],
648
+ distributions: Iterable[NDArray[np.float64]],
649
+ names: Mapping[str, str],
650
+ included_indices: Iterable[int],
651
+ ) -> None:
652
+ """Write long-form topic predictions and skipped-paper states.
653
+
654
+ Parameters
655
+ ----------
656
+ path : str or os.PathLike[str]
657
+ Destination CSV path.
658
+ documents : Sequence[_TopicDocument]
659
+ Paper documents in output order.
660
+ distributions : Iterable[numpy.ndarray]
661
+ Topic probability vectors for included documents.
662
+ names : Mapping[str, str]
663
+ Manual names keyed by string topic ID.
664
+ included_indices : Iterable[int]
665
+ Document indices corresponding to ``distributions``.
666
+
667
+ Raises
668
+ ------
669
+ OSError
670
+ If the destination cannot be written.
671
+ """
672
+ distribution_by_index = dict(zip(included_indices, distributions))
673
+ fieldnames = [
674
+ 'paper_id', 'doi', 'title', 'publication_date', 'topic_id',
675
+ 'topic_name', 'probability', 'is_dominant', 'status',
676
+ ]
677
+ with Path(path).open('w', encoding='utf-8', newline='') as handle:
678
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
679
+ writer.writeheader()
680
+ for document_index, document in enumerate(documents):
681
+ distribution = distribution_by_index.get(document_index)
682
+ base = {key: document[key] for key in ['paper_id', 'doi', 'title', 'publication_date']}
683
+ if distribution is None:
684
+ writer.writerow({**base, 'status': 'no_vocabulary_terms'})
685
+ continue
686
+ dominant_topic = int(distribution.argmax())
687
+ for topic_id, probability in enumerate(distribution):
688
+ writer.writerow({
689
+ **base,
690
+ 'topic_id': topic_id,
691
+ 'topic_name': names[str(topic_id)],
692
+ 'probability': f'{float(probability):.12g}',
693
+ 'is_dominant': topic_id == dominant_topic,
694
+ 'status': 'predicted',
695
+ })
696
+
697
+
698
+ def _write_representatives(
699
+ path: str | PathLike[str],
700
+ documents: Sequence[_TopicDocument],
701
+ distributions: NDArray[np.float64],
702
+ names: Mapping[str, str],
703
+ count: int,
704
+ ) -> None:
705
+ """Write representative papers for manual topic interpretation.
706
+
707
+ Parameters
708
+ ----------
709
+ path : str or os.PathLike[str]
710
+ Destination CSV path.
711
+ documents : Sequence[_TopicDocument]
712
+ Documents corresponding to distribution rows.
713
+ distributions : numpy.ndarray
714
+ Per-document topic probabilities.
715
+ names : Mapping[str, str]
716
+ Manual names keyed by string topic ID.
717
+ count : int
718
+ Maximum representative papers per topic.
719
+
720
+ Raises
721
+ ------
722
+ OSError
723
+ If the destination cannot be written.
724
+ """
725
+ fieldnames = ['topic_id', 'topic_name', 'rank', 'paper_id', 'probability', 'title', 'publication_date']
726
+ with Path(path).open('w', encoding='utf-8', newline='') as handle:
727
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
728
+ writer.writeheader()
729
+ for topic_id in range(distributions.shape[1]):
730
+ ranked = distributions[:, topic_id].argsort()[::-1][:count]
731
+ for rank, document_index in enumerate(ranked, start=1):
732
+ document = documents[int(document_index)]
733
+ writer.writerow({
734
+ 'topic_id': topic_id,
735
+ 'topic_name': names[str(topic_id)],
736
+ 'rank': rank,
737
+ 'paper_id': document['paper_id'],
738
+ 'probability': f'{float(distributions[document_index, topic_id]):.12g}',
739
+ 'title': document['title'],
740
+ 'publication_date': document['publication_date'],
741
+ })
742
+
743
+
744
+ def _prepare_output_directory(
745
+ output_dir: str | PathLike[str],
746
+ overwrite: bool,
747
+ ) -> Path:
748
+ """Prepare a topic-model artifact directory.
749
+
750
+ Parameters
751
+ ----------
752
+ output_dir : str or os.PathLike[str]
753
+ Artifact directory to create or reuse.
754
+ overwrite : bool
755
+ Whether a nonempty directory may be reused.
756
+
757
+ Returns
758
+ -------
759
+ pathlib.Path
760
+ Prepared artifact directory.
761
+
762
+ Raises
763
+ ------
764
+ OSError
765
+ If the directory cannot be inspected or created.
766
+ ValueError
767
+ If the directory is nonempty and ``overwrite`` is false.
768
+ """
769
+ path = Path(output_dir)
770
+ if path.exists() and any(path.iterdir()) and not overwrite:
771
+ raise ValueError(f'Model directory is not empty: {path}. Pass overwrite=True to replace model files.')
772
+ path.mkdir(parents=True, exist_ok=True)
773
+ return path
774
+
775
+
776
+ def _streaming_corpus_report(
777
+ prepared: Mapping[str, Any],
778
+ num_topics: int,
779
+ ) -> dict[str, Any]:
780
+ """Build topic-count-specific diagnostics from a prepared corpus cache.
781
+
782
+ Parameters
783
+ ----------
784
+ prepared : Mapping[str, Any]
785
+ Metadata produced while constructing the streaming corpus cache.
786
+ num_topics : int
787
+ Requested number of latent topics.
788
+
789
+ Returns
790
+ -------
791
+ dict[str, Any]
792
+ Corpus counts, timing data, vocabulary size, and quality warnings.
793
+
794
+ Raises
795
+ ------
796
+ ValueError
797
+ If too few usable or vectorized documents remain for ``num_topics``.
798
+ """
799
+ usable = prepared['documents_usable_before_vectorization']
800
+ used = prepared['documents_used']
801
+ if usable < num_topics:
802
+ raise ValueError(
803
+ f'LDA requires at least as many usable documents as topics; '
804
+ f'found {usable} documents for {num_topics} topics.'
805
+ )
806
+ if used < num_topics:
807
+ raise ValueError(
808
+ f'Only {used} documents contain retained vocabulary for {num_topics} topics. '
809
+ 'Lower min_df, raise max_df, or reduce the topic count.'
810
+ )
811
+ warnings_list = []
812
+ recommended = max(500, 50 * num_topics)
813
+ if usable < recommended:
814
+ warnings_list.append(
815
+ f'Small topic-model corpus: {usable} usable documents for {num_topics} topics. '
816
+ f'Consider at least {recommended} documents (50 per topic, minimum 500) '
817
+ 'for more stable topics.'
818
+ )
819
+ if prepared['median_tokens'] < 50:
820
+ warnings_list.append(
821
+ f'Short topic-model documents: median usable length is '
822
+ f'{prepared["median_tokens"]:g} tokens; topic quality may be poor below roughly 50 tokens.'
823
+ )
824
+ total = prepared['documents_total']
825
+ empty = prepared['documents_empty']
826
+ if total and empty / total > 0.1:
827
+ warnings_list.append(
828
+ f'{empty} of {total} documents contain no usable text and will be excluded from training.'
829
+ )
830
+ without_vocabulary = usable - used
831
+ if prepared['vocabulary_size'] < 2 * num_topics:
832
+ warnings_list.append(
833
+ f'Small topic vocabulary: {prepared["vocabulary_size"]} retained terms for '
834
+ f'{num_topics} topics. Consider lowering min_df, raising max_features, '
835
+ 'or reducing the topic count.'
836
+ )
837
+ if without_vocabulary:
838
+ warnings_list.append(
839
+ f'{without_vocabulary} usable documents contained no terms from the retained '
840
+ 'vocabulary and were excluded.'
841
+ )
842
+ return {
843
+ 'documents_total': total,
844
+ 'documents_usable_before_vectorization': usable,
845
+ 'documents_empty': empty,
846
+ 'median_tokens': prepared['median_tokens'],
847
+ 'documents_per_topic': usable / num_topics,
848
+ 'documents_used': used,
849
+ 'documents_without_vocabulary_terms': without_vocabulary,
850
+ 'vocabulary_size': prepared['vocabulary_size'],
851
+ 'vectorization_seconds': prepared['preparation_seconds'],
852
+ 'cache_size_bytes': prepared['cache_size_bytes'],
853
+ 'warnings': warnings_list,
854
+ }
855
+
856
+
857
+ def _prepare_streaming_corpus(
858
+ db_path: str | PathLike[str],
859
+ text_fields: Iterable[str],
860
+ domain_stopwords: Iterable[str],
861
+ ngram_max: int,
862
+ min_df: int,
863
+ max_df: float,
864
+ max_features: int,
865
+ batch_size: int,
866
+ evaluation_sample_size: int,
867
+ work_dir: str | PathLike[str],
868
+ ) -> dict[str, Any]:
869
+ """Build a deterministic vocabulary and disk-backed sparse batch cache.
870
+
871
+ Parameters
872
+ ----------
873
+ db_path : str or os.PathLike[str]
874
+ Path to the source SQLite paper corpus.
875
+ text_fields : Iterable[str]
876
+ Corpus fields combined into each modeling document.
877
+ domain_stopwords : Iterable[str]
878
+ Normalized corpus-specific words excluded from features.
879
+ ngram_max : {1, 2}
880
+ Maximum feature n-gram size.
881
+ min_df : int
882
+ Minimum document frequency for retained features.
883
+ max_df : float
884
+ Maximum document-frequency fraction for retained features.
885
+ max_features : int
886
+ Maximum retained vocabulary size.
887
+ batch_size : int
888
+ Maximum papers processed in each disk-backed batch.
889
+ evaluation_sample_size : int
890
+ Maximum deterministic sample size used for fit metrics.
891
+ work_dir : str or os.PathLike[str]
892
+ Temporary directory in which to store counts and sparse matrices.
893
+
894
+ Returns
895
+ -------
896
+ dict[str, Any]
897
+ Cache paths, fitted vectorizer, corpus diagnostics, and fingerprint.
898
+
899
+ Raises
900
+ ------
901
+ OSError
902
+ If cache files cannot be created or written.
903
+ ValueError
904
+ If no usable documents or vocabulary terms remain.
905
+ """
906
+ started = time.perf_counter()
907
+ text_fields = _validate_text_fields(text_fields)
908
+ work_path = Path(work_dir)
909
+ work_path.mkdir(parents=True, exist_ok=True)
910
+ counts_path = work_path / 'vocabulary_counts.db'
911
+ analyzer = TopicAnalyzer(domain_stopwords=domain_stopwords, ngram_max=ngram_max)
912
+ digest = hashlib.sha256()
913
+ token_counts = []
914
+ document_count = 0
915
+
916
+ with sqlite3.connect(counts_path) as vocab_conn:
917
+ vocab_conn.execute(
918
+ 'CREATE TABLE term_counts ('
919
+ 'term TEXT PRIMARY KEY, term_frequency INTEGER NOT NULL, '
920
+ 'document_frequency INTEGER NOT NULL)'
921
+ )
922
+ for documents in iter_topic_document_batches(db_path, text_fields, batch_size):
923
+ batch_tf = Counter()
924
+ batch_df = Counter()
925
+ for document in documents:
926
+ document_count += 1
927
+ digest.update(document['paper_id'].encode('utf-8'))
928
+ digest.update(b'\0')
929
+ digest.update(hashlib.sha256(document['text'].encode('utf-8')).digest())
930
+ digest.update(b'\0')
931
+ if document['token_count'] <= 0:
932
+ continue
933
+ token_counts.append(document['token_count'])
934
+ counts = Counter(analyzer(document['text']))
935
+ batch_tf.update(counts)
936
+ batch_df.update(counts.keys())
937
+ vocab_conn.executemany(
938
+ """
939
+ INSERT INTO term_counts (term, term_frequency, document_frequency)
940
+ VALUES (?, ?, ?)
941
+ ON CONFLICT(term) DO UPDATE SET
942
+ term_frequency = term_frequency + excluded.term_frequency,
943
+ document_frequency = document_frequency + excluded.document_frequency
944
+ """,
945
+ ((term, frequency, batch_df[term]) for term, frequency in batch_tf.items()),
946
+ )
947
+ vocab_conn.commit()
948
+
949
+ usable_count = len(token_counts)
950
+ if not usable_count:
951
+ raise ValueError('The corpus contains no usable topic-model text.')
952
+ if min_df > usable_count:
953
+ raise ValueError(f'min_df={min_df} exceeds the {usable_count} usable documents.')
954
+ max_documents = max_df * usable_count
955
+ rows = vocab_conn.execute(
956
+ """
957
+ SELECT term FROM term_counts
958
+ WHERE document_frequency >= ? AND document_frequency <= ?
959
+ ORDER BY term_frequency DESC, term ASC
960
+ LIMIT ?
961
+ """,
962
+ (min_df, max_documents, max_features),
963
+ ).fetchall()
964
+ selected_terms = sorted(row[0] for row in rows)
965
+ if not selected_terms:
966
+ raise ValueError(
967
+ 'Could not build the topic vocabulary: no terms remain after document-frequency filtering.'
968
+ )
969
+ vocabulary = {term: index for index, term in enumerate(selected_terms)}
970
+ vectorizer = CountVectorizer(analyzer=analyzer, vocabulary=vocabulary, dtype='int64')
971
+
972
+ batches = []
973
+ documents_used = 0
974
+ evaluation_heap = []
975
+ sequence = 0
976
+ for batch_number, documents in enumerate(
977
+ iter_topic_document_batches(db_path, text_fields, batch_size)):
978
+ matrix = vectorizer.transform(document['text'] for document in documents).tocsr()
979
+ matrix_path = work_path / f'batch-{batch_number:08d}.npz'
980
+ metadata_path = work_path / f'batch-{batch_number:08d}.json'
981
+ sparse.save_npz(matrix_path, matrix, compressed=True)
982
+ metadata = [
983
+ {key: document[key] for key in [
984
+ 'paper_id', 'doi', 'title', 'publication_date', 'token_count'
985
+ ]}
986
+ for document in documents
987
+ ]
988
+ metadata_path.write_text(json.dumps(metadata), encoding='utf-8')
989
+ batches.append((matrix_path, metadata_path))
990
+ nonzero_rows = np.flatnonzero(matrix.getnnz(axis=1) > 0)
991
+ documents_used += len(nonzero_rows)
992
+ for row_index in nonzero_rows:
993
+ if evaluation_sample_size <= 0:
994
+ continue
995
+ hash_value = int.from_bytes(
996
+ hashlib.sha256(documents[int(row_index)]['paper_id'].encode('utf-8')).digest()[:8],
997
+ 'big',
998
+ )
999
+ entry = (-hash_value, sequence, matrix.getrow(int(row_index)))
1000
+ sequence += 1
1001
+ if len(evaluation_heap) < evaluation_sample_size:
1002
+ heapq.heappush(evaluation_heap, entry)
1003
+ elif hash_value < -evaluation_heap[0][0]:
1004
+ heapq.heapreplace(evaluation_heap, entry)
1005
+
1006
+ if evaluation_heap:
1007
+ evaluation_rows = [entry[2] for entry in sorted(evaluation_heap, reverse=True)]
1008
+ evaluation_matrix = sparse.vstack(evaluation_rows, format='csr')
1009
+ else:
1010
+ evaluation_matrix = sparse.csr_matrix((0, len(vocabulary)), dtype='int64')
1011
+ evaluation_path = work_path / 'evaluation.npz'
1012
+ sparse.save_npz(evaluation_path, evaluation_matrix, compressed=True)
1013
+ cache_size_bytes = sum(
1014
+ path.stat().st_size for path in work_path.iterdir() if path.is_file()
1015
+ )
1016
+ return {
1017
+ 'batches': batches,
1018
+ 'vectorizer': vectorizer,
1019
+ 'evaluation_path': evaluation_path,
1020
+ 'documents_total': document_count,
1021
+ 'documents_usable_before_vectorization': usable_count,
1022
+ 'documents_empty': document_count - usable_count,
1023
+ 'median_tokens': _median(token_counts),
1024
+ 'documents_used': documents_used,
1025
+ 'vocabulary_size': len(vocabulary),
1026
+ 'preparation_seconds': time.perf_counter() - started,
1027
+ 'cache_size_bytes': cache_size_bytes,
1028
+ 'fingerprint': {
1029
+ 'algorithm': 'sha256-paper-id-and-normalized-text-v2',
1030
+ 'sha256': digest.hexdigest(),
1031
+ 'documents': document_count,
1032
+ 'text_fields': list(text_fields),
1033
+ },
1034
+ }
1035
+
1036
+
1037
+ def _cached_batches(
1038
+ prepared: Mapping[str, Any],
1039
+ ) -> Iterator[tuple[spmatrix, list[dict[str, Any]]]]:
1040
+ """Load sparse document matrices and metadata from a prepared cache.
1041
+
1042
+ Parameters
1043
+ ----------
1044
+ prepared : Mapping[str, Any]
1045
+ Streaming cache metadata containing matrix and metadata paths.
1046
+
1047
+ Yields
1048
+ ------
1049
+ tuple[scipy.sparse.spmatrix, list[dict[str, Any]]]
1050
+ Sparse document-term matrix and aligned paper metadata.
1051
+ """
1052
+ for matrix_path, metadata_path in prepared['batches']:
1053
+ yield sparse.load_npz(matrix_path), json.loads(metadata_path.read_text(encoding='utf-8'))
1054
+
1055
+
1056
+ def _model_identifier(
1057
+ model: LatentDirichletAllocation,
1058
+ vectorizer: CountVectorizer,
1059
+ config: Mapping[str, Any],
1060
+ fingerprint: Mapping[str, Any],
1061
+ ) -> str:
1062
+ """Build an immutable deterministic identifier for a fitted model.
1063
+
1064
+ Parameters
1065
+ ----------
1066
+ model : sklearn.decomposition.LatentDirichletAllocation
1067
+ Fitted LDA estimator.
1068
+ vectorizer : sklearn.feature_extraction.text.CountVectorizer
1069
+ Vectorizer containing the ordered model vocabulary.
1070
+ config : Mapping[str, Any]
1071
+ Model configuration; volatile identity fields are ignored.
1072
+ fingerprint : Mapping[str, Any]
1073
+ Fingerprint of the normalized training corpus.
1074
+
1075
+ Returns
1076
+ -------
1077
+ str
1078
+ Stable ``lda:`` identifier derived from configuration, corpus,
1079
+ vocabulary, and fitted components.
1080
+ """
1081
+ digest = hashlib.sha256()
1082
+ stable_config = {key: value for key, value in config.items() if key not in {'created_at', 'model_id'}}
1083
+ digest.update(json.dumps(stable_config, sort_keys=True).encode('utf-8'))
1084
+ digest.update(fingerprint['sha256'].encode('ascii'))
1085
+ digest.update('\0'.join(vectorizer.get_feature_names_out()).encode('utf-8'))
1086
+ digest.update(np.asarray(model.components_, dtype='<f8').tobytes())
1087
+ return f'lda:{digest.hexdigest()[:24]}'
1088
+
1089
+
1090
+ def _write_streamed_outputs(
1091
+ prepared: Mapping[str, Any],
1092
+ model: LatentDirichletAllocation,
1093
+ names: Mapping[str, str],
1094
+ predictions_path: str | PathLike[str],
1095
+ representatives_path: str | PathLike[str],
1096
+ representative_count: int,
1097
+ ) -> dict[str, Any]:
1098
+ """Write predictions and bounded representatives from cached batches.
1099
+
1100
+ Parameters
1101
+ ----------
1102
+ prepared : Mapping[str, Any]
1103
+ Streaming cache metadata.
1104
+ model : sklearn.decomposition.LatentDirichletAllocation
1105
+ Fitted topic model.
1106
+ names : Mapping[str, str]
1107
+ Manual topic names keyed by string topic ID.
1108
+ predictions_path : str or os.PathLike[str]
1109
+ Destination long-form prediction CSV.
1110
+ representatives_path : str or os.PathLike[str]
1111
+ Destination representative-paper CSV.
1112
+ representative_count : int
1113
+ Maximum papers retained for each topic.
1114
+
1115
+ Returns
1116
+ -------
1117
+ dict[str, Any]
1118
+ Prediction coverage and dominant-topic balance metrics.
1119
+ """
1120
+ prediction_fields = [
1121
+ 'paper_id', 'doi', 'title', 'publication_date', 'topic_id',
1122
+ 'topic_name', 'probability', 'is_dominant', 'status',
1123
+ ]
1124
+ representative_heaps = {topic_id: [] for topic_id in range(model.n_components)}
1125
+ dominant_counts = [0] * model.n_components
1126
+ predicted = 0
1127
+ sequence = 0
1128
+ with Path(predictions_path).open('w', encoding='utf-8', newline='') as handle:
1129
+ writer = csv.DictWriter(handle, fieldnames=prediction_fields)
1130
+ writer.writeheader()
1131
+ for matrix, documents in _cached_batches(prepared):
1132
+ included = np.flatnonzero(matrix.getnnz(axis=1) > 0)
1133
+ distributions = model.transform(matrix[included]) if len(included) else np.empty((0, model.n_components))
1134
+ distribution_by_row = dict(zip(included.tolist(), distributions))
1135
+ for row_index, document in enumerate(documents):
1136
+ base = {key: document[key] for key in ['paper_id', 'doi', 'title', 'publication_date']}
1137
+ distribution = distribution_by_row.get(row_index)
1138
+ if distribution is None:
1139
+ writer.writerow({**base, 'status': 'no_vocabulary_terms'})
1140
+ continue
1141
+ predicted += 1
1142
+ dominant_topic = int(distribution.argmax())
1143
+ dominant_counts[dominant_topic] += 1
1144
+ for topic_id, probability in enumerate(distribution):
1145
+ probability = float(probability)
1146
+ writer.writerow({
1147
+ **base,
1148
+ 'topic_id': topic_id,
1149
+ 'topic_name': names[str(topic_id)],
1150
+ 'probability': f'{probability:.12g}',
1151
+ 'is_dominant': topic_id == dominant_topic,
1152
+ 'status': 'predicted',
1153
+ })
1154
+ item = (probability, sequence, document)
1155
+ heap = representative_heaps[topic_id]
1156
+ if len(heap) < representative_count:
1157
+ heapq.heappush(heap, item)
1158
+ elif probability > heap[0][0]:
1159
+ heapq.heapreplace(heap, item)
1160
+ sequence += 1
1161
+
1162
+ fields = ['topic_id', 'topic_name', 'rank', 'paper_id', 'probability', 'title', 'publication_date']
1163
+ with Path(representatives_path).open('w', encoding='utf-8', newline='') as handle:
1164
+ writer = csv.DictWriter(handle, fieldnames=fields)
1165
+ writer.writeheader()
1166
+ for topic_id in range(model.n_components):
1167
+ ranked = sorted(representative_heaps[topic_id], reverse=True)
1168
+ for rank, (probability, _, document) in enumerate(ranked, start=1):
1169
+ writer.writerow({
1170
+ 'topic_id': topic_id,
1171
+ 'topic_name': names[str(topic_id)],
1172
+ 'rank': rank,
1173
+ 'paper_id': document['paper_id'],
1174
+ 'probability': f'{probability:.12g}',
1175
+ 'title': document['title'],
1176
+ 'publication_date': document['publication_date'],
1177
+ })
1178
+ proportions = [count / predicted for count in dominant_counts if count] if predicted else []
1179
+ entropy = -sum(value * math.log(value) for value in proportions)
1180
+ balance = entropy / math.log(model.n_components) if model.n_components > 1 and predicted else 0
1181
+ return {
1182
+ 'dominant_topic_counts': dominant_counts,
1183
+ 'dominant_topic_balance': balance,
1184
+ 'smallest_dominant_topic': min(dominant_counts),
1185
+ 'largest_dominant_topic': max(dominant_counts),
1186
+ 'papers_predicted': predicted,
1187
+ }
1188
+
1189
+
1190
+ def _model_quality_metrics(
1191
+ model: LatentDirichletAllocation,
1192
+ matrix: spmatrix,
1193
+ distributions: NDArray[np.float64],
1194
+ topic_rows: Sequence[_TopicRow],
1195
+ ) -> dict[str, Any]:
1196
+ """Calculate diagnostics for a fitted topic model.
1197
+
1198
+ Parameters
1199
+ ----------
1200
+ model : sklearn.decomposition.LatentDirichletAllocation
1201
+ Fitted LDA model.
1202
+ matrix : scipy.sparse.spmatrix
1203
+ Document-term matrix used to fit the model.
1204
+ distributions : numpy.ndarray
1205
+ Per-document topic probabilities.
1206
+ topic_rows : Sequence[_TopicRow]
1207
+ Extracted topic terms.
1208
+
1209
+ Returns
1210
+ -------
1211
+ dict[str, Any]
1212
+ Fit, topic-diversity, and dominant-topic balance metrics.
1213
+ """
1214
+ dominant_topics = distributions.argmax(axis=1)
1215
+ dominant_counts = [int((dominant_topics == topic_id).sum()) for topic_id in range(distributions.shape[1])]
1216
+ proportions = [count / len(distributions) for count in dominant_counts if count]
1217
+ entropy = -sum(proportion * math.log(proportion) for proportion in proportions)
1218
+ normalized_entropy = entropy / math.log(distributions.shape[1]) if distributions.shape[1] > 1 else 0
1219
+ all_top_terms = [term for topic in topic_rows for term in topic['top_terms']]
1220
+ topic_diversity = len(set(all_top_terms)) / len(all_top_terms) if all_top_terms else 0
1221
+ return {
1222
+ 'perplexity': float(model.perplexity(matrix)),
1223
+ 'log_likelihood': float(model.score(matrix)),
1224
+ 'topic_diversity': topic_diversity,
1225
+ 'dominant_topic_counts': dominant_counts,
1226
+ 'dominant_topic_balance': normalized_entropy,
1227
+ 'smallest_dominant_topic': min(dominant_counts),
1228
+ 'largest_dominant_topic': max(dominant_counts),
1229
+ }
1230
+
1231
+
1232
+ def _train_streaming_topic_model(
1233
+ output_dir: str | PathLike[str],
1234
+ prepared: Mapping[str, Any],
1235
+ num_topics: int,
1236
+ text_fields: Iterable[str],
1237
+ min_df: int,
1238
+ max_df: float,
1239
+ max_features: int,
1240
+ max_iter: int,
1241
+ random_state: int,
1242
+ top_terms: int,
1243
+ representative_papers: int,
1244
+ domain_stopwords: list[str],
1245
+ ngram_max: int,
1246
+ overwrite: bool,
1247
+ emit_warnings: bool,
1248
+ batch_size: int,
1249
+ evaluation_sample_size: int,
1250
+ ) -> dict[str, Any]:
1251
+ """Train and persist online LDA from a reusable streaming cache.
1252
+
1253
+ Parameters
1254
+ ----------
1255
+ output_dir : str or os.PathLike[str]
1256
+ Destination model artifact directory.
1257
+ prepared : Mapping[str, Any]
1258
+ Prepared streaming corpus cache and diagnostics.
1259
+ num_topics : int
1260
+ Number of latent topics.
1261
+ text_fields : Iterable[str]
1262
+ Corpus fields represented by the model.
1263
+ min_df : int
1264
+ Minimum feature document frequency.
1265
+ max_df : float
1266
+ Maximum feature document-frequency fraction.
1267
+ max_features : int
1268
+ Maximum vocabulary size.
1269
+ max_iter : int
1270
+ Number of complete passes over cached batches.
1271
+ random_state : int
1272
+ Model initialization seed.
1273
+ top_terms : int
1274
+ Terms exported for each topic.
1275
+ representative_papers : int
1276
+ Representative papers exported for each topic.
1277
+ domain_stopwords : list[str]
1278
+ Normalized corpus-specific stopwords.
1279
+ ngram_max : {1, 2}
1280
+ Maximum feature n-gram size.
1281
+ overwrite : bool
1282
+ Whether known artifacts may be replaced.
1283
+ emit_warnings : bool
1284
+ Whether to emit heuristic corpus warnings.
1285
+ batch_size : int
1286
+ Documents processed per online batch.
1287
+ evaluation_sample_size : int
1288
+ Maximum documents used for fit metrics.
1289
+
1290
+ Returns
1291
+ -------
1292
+ dict[str, Any]
1293
+ Artifact paths, configuration, diagnostics, fingerprint, and topics.
1294
+ """
1295
+ report = _streaming_corpus_report(prepared, num_topics)
1296
+ if emit_warnings:
1297
+ _emit_warnings(report['warnings'])
1298
+ model = LatentDirichletAllocation(
1299
+ n_components=num_topics,
1300
+ learning_method='online',
1301
+ max_iter=1,
1302
+ batch_size=batch_size,
1303
+ total_samples=prepared['documents_used'],
1304
+ random_state=random_state,
1305
+ )
1306
+ fitting_started = time.perf_counter()
1307
+ for _ in range(max_iter):
1308
+ for matrix, _metadata in _cached_batches(prepared):
1309
+ included = matrix.getnnz(axis=1) > 0
1310
+ if included.any():
1311
+ model.partial_fit(matrix[included])
1312
+ report['fitting_seconds'] = time.perf_counter() - fitting_started
1313
+
1314
+ vectorizer = prepared['vectorizer']
1315
+ topic_rows = _topic_rows(model, vectorizer, top_terms)
1316
+ all_top_terms = [term for topic in topic_rows for term in topic['top_terms']]
1317
+ report['topic_diversity'] = (
1318
+ len(set(all_top_terms)) / len(all_top_terms) if all_top_terms else 0
1319
+ )
1320
+ evaluation_matrix = sparse.load_npz(prepared['evaluation_path'])
1321
+ report['evaluation_documents'] = evaluation_matrix.shape[0]
1322
+ report['metrics_scope'] = (
1323
+ 'complete' if evaluation_matrix.shape[0] == prepared['documents_used'] else 'sample'
1324
+ )
1325
+ if evaluation_matrix.shape[0]:
1326
+ report['perplexity'] = float(model.perplexity(evaluation_matrix))
1327
+ report['log_likelihood'] = float(model.score(evaluation_matrix))
1328
+ else:
1329
+ report['perplexity'] = None
1330
+ report['log_likelihood'] = None
1331
+
1332
+ config = {
1333
+ 'artifact_version': ARTIFACT_VERSION,
1334
+ 'created_at': _utc_now(),
1335
+ 'num_topics': num_topics,
1336
+ 'text_fields': list(text_fields),
1337
+ 'min_df': min_df,
1338
+ 'max_df': max_df,
1339
+ 'max_features': max_features,
1340
+ 'learning_method': 'online',
1341
+ 'max_iter': max_iter,
1342
+ 'random_state': random_state,
1343
+ 'top_terms': top_terms,
1344
+ 'representative_papers': representative_papers,
1345
+ 'domain_stopwords': domain_stopwords,
1346
+ 'ngram_max': ngram_max,
1347
+ 'streaming': True,
1348
+ 'batch_size': batch_size,
1349
+ 'evaluation_sample_size': evaluation_sample_size,
1350
+ 'sklearn_version': sklearn.__version__,
1351
+ }
1352
+ fingerprint = prepared['fingerprint']
1353
+ config['model_id'] = _model_identifier(model, vectorizer, config, fingerprint)
1354
+ names = {str(topic_id): '' for topic_id in range(num_topics)}
1355
+ output_path = _prepare_output_directory(output_dir, overwrite)
1356
+
1357
+ inference_metrics = _write_streamed_outputs(
1358
+ prepared,
1359
+ model,
1360
+ names,
1361
+ output_path / PREDICTIONS_FILENAME,
1362
+ output_path / REPRESENTATIVES_FILENAME,
1363
+ representative_papers,
1364
+ )
1365
+ report.update(inference_metrics)
1366
+ joblib.dump(model, output_path / MODEL_FILENAME)
1367
+ joblib.dump(vectorizer, output_path / VECTORIZER_FILENAME)
1368
+ _write_json(output_path / CONFIG_FILENAME, config)
1369
+ _write_json(output_path / REPORT_FILENAME, report)
1370
+ _write_json(output_path / FINGERPRINT_FILENAME, fingerprint)
1371
+ _write_json(output_path / TOPIC_NAMES_FILENAME, names)
1372
+ (output_path / STOPWORDS_FILENAME).write_text(
1373
+ ''.join(f'{word}\n' for word in domain_stopwords), encoding='utf-8'
1374
+ )
1375
+ _write_topics(output_path / TOPICS_FILENAME, topic_rows)
1376
+ return {
1377
+ 'model_dir': str(output_path),
1378
+ 'config': config,
1379
+ 'report': report,
1380
+ 'fingerprint': fingerprint,
1381
+ 'topics': topic_rows,
1382
+ 'predictions_path': str(output_path / PREDICTIONS_FILENAME),
1383
+ }
1384
+
1385
+
1386
+ def train_topic_model(db_path: str | PathLike[str],
1387
+ output_dir: str | PathLike[str],
1388
+ num_topics: int = 10,
1389
+ text_fields: Iterable[str] = ('title', 'abstract'),
1390
+ min_df: int = 2,
1391
+ max_df: float = 0.95,
1392
+ max_features: int = 20000,
1393
+ learning_method: str = 'online',
1394
+ max_iter: int = 20,
1395
+ random_state: int = 0,
1396
+ top_terms: int = 15,
1397
+ representative_papers: int = 5,
1398
+ stopwords_file: str | PathLike[str] | None = None,
1399
+ ngram_max: int = 2,
1400
+ overwrite: bool = False,
1401
+ emit_warnings: bool = True,
1402
+ documents: Sequence[_TopicDocument] | None = None,
1403
+ streaming: bool = True,
1404
+ batch_size: int = DEFAULT_BATCH_SIZE,
1405
+ cache_dir: str | PathLike[str] | None = None,
1406
+ evaluation_sample_size: int = DEFAULT_EVALUATION_SAMPLE_SIZE,
1407
+ _prepared_streaming: Mapping[str, Any] | None = None) -> dict[str, Any]:
1408
+ """Train and persist an LDA model and its inspection artifacts.
1409
+
1410
+ Parameters
1411
+ ----------
1412
+ db_path : str or os.PathLike[str]
1413
+ Path to the source SQLite paper corpus.
1414
+ output_dir : str or os.PathLike[str]
1415
+ Directory in which to store model artifacts.
1416
+ num_topics : int, default=10
1417
+ Number of latent topics to fit.
1418
+ text_fields : Iterable[str], default=('title', 'abstract')
1419
+ Corpus fields combined into each modeling document.
1420
+ min_df : int, default=2
1421
+ Minimum number of documents in which a feature must occur.
1422
+ max_df : float, default=0.95
1423
+ Maximum fraction of documents in which a feature may occur.
1424
+ max_features : int, default=20000
1425
+ Maximum retained vocabulary size.
1426
+ learning_method : {'batch', 'online'}, default='online'
1427
+ Scikit-learn LDA learning strategy. Streaming mode requires ``online``.
1428
+ max_iter : int, default=20
1429
+ Training iterations or complete passes over streaming batches.
1430
+ random_state : int, default=0
1431
+ Seed controlling model initialization.
1432
+ top_terms : int, default=15
1433
+ Number of terms exported for each topic.
1434
+ representative_papers : int, default=5
1435
+ Number of high-probability papers exported per topic.
1436
+ stopwords_file : str, os.PathLike[str], or None, optional
1437
+ File containing domain-specific stopwords.
1438
+ ngram_max : {1, 2}, default=2
1439
+ Maximum feature n-gram size.
1440
+ overwrite : bool, default=False
1441
+ Whether to reuse a nonempty artifact directory.
1442
+ emit_warnings : bool, default=True
1443
+ Whether to emit heuristic corpus-quality warnings.
1444
+ documents : Sequence[_TopicDocument] or None, optional
1445
+ Preloaded documents used instead of reading ``db_path`` in in-memory
1446
+ mode.
1447
+ streaming : bool, default=True
1448
+ Whether to train from bounded disk-backed document batches.
1449
+ batch_size : int, default=128
1450
+ Maximum documents processed in each streaming batch.
1451
+ cache_dir : str, os.PathLike[str], or None, optional
1452
+ Parent directory for the temporary streaming cache.
1453
+ evaluation_sample_size : int, default=10000
1454
+ Maximum deterministic document sample used for streaming fit metrics.
1455
+ _prepared_streaming : Mapping[str, Any] or None, optional
1456
+ Internal reusable cache supplied by model comparison.
1457
+
1458
+ Returns
1459
+ -------
1460
+ dict[str, Any]
1461
+ Artifact paths, configuration, quality report, fingerprint, and topics.
1462
+
1463
+ Raises
1464
+ ------
1465
+ OSError
1466
+ If an input, cache, or artifact file cannot be accessed.
1467
+ ValueError
1468
+ If configuration, corpus size, or retained vocabulary is unsuitable.
1469
+ """
1470
+ fields = _validate_text_fields(text_fields)
1471
+ if learning_method not in {'online', 'batch'}:
1472
+ raise ValueError('learning_method must be one of: online, batch')
1473
+ if min_df < 1:
1474
+ raise ValueError('min_df must be at least 1.')
1475
+ if not 0 < max_df <= 1:
1476
+ raise ValueError('max_df must be greater than 0 and at most 1.')
1477
+ if max_features < num_topics:
1478
+ raise ValueError('max_features must be at least num_topics.')
1479
+ if ngram_max not in {1, 2}:
1480
+ raise ValueError('ngram_max must be either 1 or 2.')
1481
+ if max_iter < 1 or top_terms < 1 or representative_papers < 1:
1482
+ raise ValueError('max_iter, top_terms, and representative_papers must be positive.')
1483
+ if batch_size < 1 or evaluation_sample_size < 1:
1484
+ raise ValueError('batch_size and evaluation_sample_size must be positive.')
1485
+
1486
+ domain_stopwords = load_domain_stopwords(stopwords_file)
1487
+ if streaming:
1488
+ if learning_method != 'online':
1489
+ raise ValueError('Streaming training requires learning_method="online"; use in-memory mode for batch LDA.')
1490
+ if documents is not None:
1491
+ raise ValueError('Explicit documents are only supported by in-memory training.')
1492
+ if _prepared_streaming is not None:
1493
+ return _train_streaming_topic_model(
1494
+ output_dir, _prepared_streaming, num_topics, fields, min_df, max_df,
1495
+ max_features, max_iter, random_state, top_terms,
1496
+ representative_papers, domain_stopwords, ngram_max, overwrite,
1497
+ emit_warnings, batch_size, evaluation_sample_size,
1498
+ )
1499
+ if cache_dir is not None:
1500
+ Path(cache_dir).mkdir(parents=True, exist_ok=True)
1501
+ with tempfile.TemporaryDirectory(
1502
+ prefix='paperminertoolkit-topics-', dir=cache_dir) as temporary_dir:
1503
+ prepared = _prepare_streaming_corpus(
1504
+ db_path, fields, domain_stopwords, ngram_max, min_df, max_df,
1505
+ max_features, batch_size, evaluation_sample_size, temporary_dir,
1506
+ )
1507
+ return _train_streaming_topic_model(
1508
+ output_dir, prepared, num_topics, fields, min_df, max_df,
1509
+ max_features, max_iter, random_state, top_terms,
1510
+ representative_papers, domain_stopwords, ngram_max, overwrite,
1511
+ emit_warnings, batch_size, evaluation_sample_size,
1512
+ )
1513
+
1514
+ documents = documents if documents is not None else load_topic_documents(db_path, fields)
1515
+ report = assess_topic_corpus(documents, num_topics)
1516
+ usable_documents = [document for document in documents if document['token_count'] > 0]
1517
+ if min_df > len(usable_documents):
1518
+ raise ValueError(f'min_df={min_df} exceeds the {len(usable_documents)} usable documents.')
1519
+
1520
+ vectorizer = CountVectorizer(
1521
+ analyzer=TopicAnalyzer(domain_stopwords=domain_stopwords, ngram_max=ngram_max),
1522
+ min_df=min_df,
1523
+ max_df=max_df,
1524
+ max_features=max_features,
1525
+ dtype='int64',
1526
+ )
1527
+ vectorization_started = time.perf_counter()
1528
+ try:
1529
+ matrix = vectorizer.fit_transform(document['text'] for document in usable_documents)
1530
+ except ValueError as error:
1531
+ raise ValueError(f'Could not build the topic vocabulary: {error}') from error
1532
+ included_mask = matrix.getnnz(axis=1) > 0
1533
+ included_indices = [index for index, included in enumerate(included_mask) if included]
1534
+ training_documents = [usable_documents[index] for index in included_indices]
1535
+ matrix = matrix[included_mask]
1536
+ if len(training_documents) < num_topics:
1537
+ raise ValueError(
1538
+ f'Only {len(training_documents)} documents contain retained vocabulary for {num_topics} topics. '
1539
+ 'Lower min_df, raise max_df, or reduce the topic count.'
1540
+ )
1541
+
1542
+ feature_count = len(vectorizer.get_feature_names_out())
1543
+ report['documents_used'] = len(training_documents)
1544
+ report['documents_without_vocabulary_terms'] = len(usable_documents) - len(training_documents)
1545
+ report['vocabulary_size'] = feature_count
1546
+ report['vectorization_seconds'] = time.perf_counter() - vectorization_started
1547
+ if feature_count < 2 * num_topics:
1548
+ report['warnings'].append(
1549
+ f'Small topic vocabulary: {feature_count} retained terms for {num_topics} topics. '
1550
+ 'Consider lowering min_df, raising max_features, or reducing the topic count.'
1551
+ )
1552
+ if report['documents_without_vocabulary_terms']:
1553
+ report['warnings'].append(
1554
+ f'{report["documents_without_vocabulary_terms"]} usable documents contained no terms '
1555
+ 'from the retained vocabulary and were excluded.'
1556
+ )
1557
+ if emit_warnings:
1558
+ _emit_warnings(report['warnings'])
1559
+
1560
+ model = LatentDirichletAllocation(
1561
+ n_components=num_topics,
1562
+ learning_method=learning_method,
1563
+ max_iter=max_iter,
1564
+ random_state=random_state,
1565
+ )
1566
+ fitting_started = time.perf_counter()
1567
+ distributions = model.fit_transform(matrix)
1568
+ report['fitting_seconds'] = time.perf_counter() - fitting_started
1569
+ topic_rows = _topic_rows(model, vectorizer, top_terms)
1570
+ report.update(_model_quality_metrics(model, matrix, distributions, topic_rows))
1571
+ config = {
1572
+ 'artifact_version': ARTIFACT_VERSION,
1573
+ 'created_at': _utc_now(),
1574
+ 'num_topics': num_topics,
1575
+ 'text_fields': list(fields),
1576
+ 'min_df': min_df,
1577
+ 'max_df': max_df,
1578
+ 'max_features': max_features,
1579
+ 'learning_method': learning_method,
1580
+ 'max_iter': max_iter,
1581
+ 'random_state': random_state,
1582
+ 'top_terms': top_terms,
1583
+ 'representative_papers': representative_papers,
1584
+ 'domain_stopwords': domain_stopwords,
1585
+ 'ngram_max': ngram_max,
1586
+ 'streaming': False,
1587
+ 'batch_size': batch_size,
1588
+ 'evaluation_sample_size': evaluation_sample_size,
1589
+ 'sklearn_version': sklearn.__version__,
1590
+ }
1591
+ fingerprint = {
1592
+ 'algorithm': 'sha256-paper-id-and-normalized-text-v2',
1593
+ 'sha256': _corpus_fingerprint(documents),
1594
+ 'documents': len(documents),
1595
+ 'text_fields': list(fields),
1596
+ }
1597
+ config['model_id'] = _model_identifier(model, vectorizer, config, fingerprint)
1598
+ names = {str(topic_id): '' for topic_id in range(num_topics)}
1599
+ output_path = _prepare_output_directory(output_dir, overwrite)
1600
+
1601
+ joblib.dump(model, output_path / MODEL_FILENAME)
1602
+ joblib.dump(vectorizer, output_path / VECTORIZER_FILENAME)
1603
+ _write_json(output_path / CONFIG_FILENAME, config)
1604
+ _write_json(output_path / REPORT_FILENAME, report)
1605
+ _write_json(output_path / FINGERPRINT_FILENAME, fingerprint)
1606
+ _write_json(output_path / TOPIC_NAMES_FILENAME, names)
1607
+ (output_path / STOPWORDS_FILENAME).write_text(
1608
+ ''.join(f'{word}\n' for word in domain_stopwords),
1609
+ encoding='utf-8',
1610
+ )
1611
+ _write_topics(output_path / TOPICS_FILENAME, topic_rows)
1612
+ _write_representatives(
1613
+ output_path / REPRESENTATIVES_FILENAME,
1614
+ training_documents,
1615
+ distributions,
1616
+ names,
1617
+ representative_papers,
1618
+ )
1619
+ training_index_by_paper_id = {
1620
+ document['paper_id']: index for index, document in enumerate(training_documents)
1621
+ }
1622
+ all_included_indices = [
1623
+ index for index, document in enumerate(documents)
1624
+ if document['paper_id'] in training_index_by_paper_id
1625
+ ]
1626
+ ordered_distributions = [
1627
+ distributions[training_index_by_paper_id[documents[index]['paper_id']]]
1628
+ for index in all_included_indices
1629
+ ]
1630
+ _write_predictions(
1631
+ output_path / PREDICTIONS_FILENAME,
1632
+ documents,
1633
+ ordered_distributions,
1634
+ names,
1635
+ all_included_indices,
1636
+ )
1637
+ return {
1638
+ 'model_dir': str(output_path),
1639
+ 'config': config,
1640
+ 'report': report,
1641
+ 'fingerprint': fingerprint,
1642
+ 'topics': topic_rows,
1643
+ 'predictions_path': str(output_path / PREDICTIONS_FILENAME),
1644
+ }
1645
+
1646
+
1647
+ def load_topic_model(
1648
+ model_dir: str | PathLike[str],
1649
+ ) -> tuple[LatentDirichletAllocation, CountVectorizer, dict[str, Any], dict[str, str]]:
1650
+ """Load and validate a trusted local LDA artifact.
1651
+
1652
+ Parameters
1653
+ ----------
1654
+ model_dir : str or os.PathLike[str]
1655
+ Topic-model artifact directory.
1656
+
1657
+ Returns
1658
+ -------
1659
+ tuple[LatentDirichletAllocation, CountVectorizer, dict[str, Any], dict[str, str]]
1660
+ Fitted LDA model, fitted vectorizer, configuration, and manual names.
1661
+
1662
+ Raises
1663
+ ------
1664
+ FileNotFoundError
1665
+ If the model configuration is missing.
1666
+ OSError
1667
+ If an artifact cannot be read.
1668
+ ValueError
1669
+ If the artifact format version is unsupported.
1670
+ json.JSONDecodeError
1671
+ If JSON metadata is invalid.
1672
+
1673
+ Notes
1674
+ -----
1675
+ Joblib artifacts can execute code while loading and must come from a
1676
+ trusted source.
1677
+ """
1678
+ path = Path(model_dir)
1679
+ config_path = path / CONFIG_FILENAME
1680
+ if not config_path.exists():
1681
+ raise FileNotFoundError(f'Missing topic model configuration: {config_path}')
1682
+ config = json.loads(config_path.read_text(encoding='utf-8'))
1683
+ if config.get('artifact_version') != ARTIFACT_VERSION:
1684
+ raise ValueError(
1685
+ f'Unsupported topic model artifact version: {config.get("artifact_version")}; '
1686
+ f'expected {ARTIFACT_VERSION}.'
1687
+ )
1688
+ model = joblib.load(path / MODEL_FILENAME)
1689
+ vectorizer = joblib.load(path / VECTORIZER_FILENAME)
1690
+ names = _topic_names(path, config['num_topics'])
1691
+ return model, vectorizer, config, names
1692
+
1693
+
1694
+ def topic_descriptions(model_dir: str | PathLike[str]) -> list[_TopicRow]:
1695
+ """Load descriptions and representative papers for each topic.
1696
+
1697
+ Parameters
1698
+ ----------
1699
+ model_dir : str or os.PathLike[str]
1700
+ Topic-model artifact directory.
1701
+
1702
+ Returns
1703
+ -------
1704
+ list[_TopicRow]
1705
+ Topic terms, manual names, and representative paper rows.
1706
+
1707
+ Raises
1708
+ ------
1709
+ OSError
1710
+ If required artifacts cannot be read.
1711
+ ValueError
1712
+ If the artifact format version is unsupported.
1713
+ """
1714
+ model, vectorizer, config, names = load_topic_model(model_dir)
1715
+ topics = _topic_rows(model, vectorizer, config['top_terms'])
1716
+ representatives = {topic_id: [] for topic_id in range(config['num_topics'])}
1717
+ path = Path(model_dir) / REPRESENTATIVES_FILENAME
1718
+ if path.exists():
1719
+ with path.open(encoding='utf-8', newline='') as handle:
1720
+ for row in csv.DictReader(handle):
1721
+ representatives[int(row['topic_id'])].append(row)
1722
+ for topic in topics:
1723
+ topic['topic_name'] = names[str(topic['topic_id'])]
1724
+ topic['representative_papers'] = representatives[topic['topic_id']]
1725
+ return topics
1726
+
1727
+
1728
+ def set_topic_name(
1729
+ model_dir: str | PathLike[str],
1730
+ topic_id: int,
1731
+ topic_name: str,
1732
+ ) -> dict[str, str]:
1733
+ """Set a manual topic name and refresh artifact exports.
1734
+
1735
+ Parameters
1736
+ ----------
1737
+ model_dir : str or os.PathLike[str]
1738
+ Topic-model artifact directory.
1739
+ topic_id : int
1740
+ Zero-based topic identifier.
1741
+ topic_name : str
1742
+ Nonempty manual topic name.
1743
+
1744
+ Returns
1745
+ -------
1746
+ dict[str, str]
1747
+ Updated names keyed by string topic ID.
1748
+
1749
+ Raises
1750
+ ------
1751
+ OSError
1752
+ If model artifacts cannot be read or rewritten.
1753
+ ValueError
1754
+ If the artifact is unsupported, the ID is out of range, or the name is
1755
+ empty.
1756
+ """
1757
+ model, vectorizer, config, names = load_topic_model(model_dir)
1758
+ if topic_id < 0 or topic_id >= config['num_topics']:
1759
+ raise ValueError(f'topic_id must be between 0 and {config["num_topics"] - 1}.')
1760
+ name = str(topic_name).strip()
1761
+ if not name:
1762
+ raise ValueError('topic_name must not be empty.')
1763
+ names[str(topic_id)] = name
1764
+ path = Path(model_dir)
1765
+ _write_json(path / TOPIC_NAMES_FILENAME, names)
1766
+ rows = _topic_rows(model, vectorizer, config['top_terms'])
1767
+ for row in rows:
1768
+ row['topic_name'] = names[str(row['topic_id'])]
1769
+ _write_topics(path / TOPICS_FILENAME, rows)
1770
+ _refresh_csv_topic_names(path / REPRESENTATIVES_FILENAME, names)
1771
+ _refresh_csv_topic_names(path / PREDICTIONS_FILENAME, names)
1772
+ return names
1773
+
1774
+
1775
+ def topic_corpus_fingerprint(
1776
+ db_path: str | PathLike[str],
1777
+ text_fields: Iterable[str],
1778
+ batch_size: int = DEFAULT_BATCH_SIZE,
1779
+ ) -> dict[str, Any]:
1780
+ """Fingerprint normalized topic inputs for stale-score detection.
1781
+
1782
+ Parameters
1783
+ ----------
1784
+ db_path : str or os.PathLike[str]
1785
+ Path to the SQLite paper corpus.
1786
+ text_fields : Iterable[str]
1787
+ Fields normalized into each fingerprinted document.
1788
+ batch_size : int, default=128
1789
+ Maximum papers loaded per batch.
1790
+
1791
+ Returns
1792
+ -------
1793
+ dict[str, Any]
1794
+ Fingerprint algorithm, SHA-256 digest, document count, and text fields.
1795
+ """
1796
+ fields = _validate_text_fields(text_fields)
1797
+ digest = hashlib.sha256()
1798
+ documents = 0
1799
+ for batch in iter_topic_document_batches(db_path, fields, batch_size):
1800
+ for document in batch:
1801
+ documents += 1
1802
+ digest.update(document['paper_id'].encode('utf-8'))
1803
+ digest.update(b'\0')
1804
+ digest.update(hashlib.sha256(document['text'].encode('utf-8')).digest())
1805
+ digest.update(b'\0')
1806
+ return {
1807
+ 'algorithm': 'sha256-paper-id-and-normalized-text-v2',
1808
+ 'sha256': digest.hexdigest(),
1809
+ 'documents': documents,
1810
+ 'text_fields': list(fields),
1811
+ }
1812
+
1813
+
1814
+ def _iter_topic_predictions(
1815
+ model: LatentDirichletAllocation,
1816
+ vectorizer: CountVectorizer,
1817
+ config: Mapping[str, Any],
1818
+ db_path: str | PathLike[str],
1819
+ batch_size: int = DEFAULT_BATCH_SIZE,
1820
+ ) -> Iterator[dict[str, Any]]:
1821
+ """Yield fresh prediction records in bounded corpus batches.
1822
+
1823
+ Parameters
1824
+ ----------
1825
+ model : sklearn.decomposition.LatentDirichletAllocation
1826
+ Fitted model used for inference.
1827
+ vectorizer : sklearn.feature_extraction.text.CountVectorizer
1828
+ Saved training vectorizer.
1829
+ config : Mapping[str, Any]
1830
+ Saved model configuration.
1831
+ db_path : str or os.PathLike[str]
1832
+ Corpus whose papers are predicted.
1833
+ batch_size : int, default=128
1834
+ Maximum papers inferred at once.
1835
+
1836
+ Yields
1837
+ ------
1838
+ dict[str, Any]
1839
+ Document metadata, prediction status, topic distribution, dominant
1840
+ topic, and normalized-document fingerprint.
1841
+ """
1842
+ for documents in iter_topic_document_batches(db_path, config['text_fields'], batch_size):
1843
+ matrix = vectorizer.transform(document['text'] for document in documents).tocsr()
1844
+ included = np.flatnonzero(matrix.getnnz(axis=1) > 0)
1845
+ distributions = model.transform(matrix[included]) if len(included) else np.empty((0, config['num_topics']))
1846
+ by_row = dict(zip(included.tolist(), distributions))
1847
+ for row_index, document in enumerate(documents):
1848
+ distribution = by_row.get(row_index)
1849
+ yield {
1850
+ 'document': document,
1851
+ 'status': 'predicted' if distribution is not None else 'no_vocabulary_terms',
1852
+ 'distribution': distribution,
1853
+ 'dominant_topic': int(distribution.argmax()) if distribution is not None else None,
1854
+ 'document_fingerprint': hashlib.sha256(
1855
+ document['text'].encode('utf-8')
1856
+ ).hexdigest(),
1857
+ }
1858
+
1859
+
1860
+ def predict_topic_model(
1861
+ model_dir: str | PathLike[str],
1862
+ db_path: str | PathLike[str],
1863
+ output_path: str | PathLike[str],
1864
+ batch_size: int = DEFAULT_BATCH_SIZE,
1865
+ ) -> dict[str, int | str]:
1866
+ """Apply a saved topic model and export long-form scores.
1867
+
1868
+ Parameters
1869
+ ----------
1870
+ model_dir : str or os.PathLike[str]
1871
+ Topic-model artifact directory.
1872
+ db_path : str or os.PathLike[str]
1873
+ Path to the SQLite paper corpus to score.
1874
+ output_path : str or os.PathLike[str]
1875
+ Destination prediction CSV.
1876
+ batch_size : int, default=128
1877
+ Maximum papers inferred at once.
1878
+
1879
+ Returns
1880
+ -------
1881
+ dict[str, int or str]
1882
+ Counts of total, predicted, and skipped papers plus the output path.
1883
+
1884
+ Raises
1885
+ ------
1886
+ OSError
1887
+ If model artifacts, the corpus, or output path cannot be accessed.
1888
+ ValueError
1889
+ If the artifact is unsupported or the corpus contains no papers.
1890
+ """
1891
+ model, vectorizer, config, names = load_topic_model(model_dir)
1892
+ fields = [
1893
+ 'paper_id', 'doi', 'title', 'publication_date', 'topic_id',
1894
+ 'topic_name', 'probability', 'is_dominant', 'status',
1895
+ ]
1896
+ total = 0
1897
+ predicted = 0
1898
+ with Path(output_path).open('w', encoding='utf-8', newline='') as handle:
1899
+ writer = csv.DictWriter(handle, fieldnames=fields)
1900
+ writer.writeheader()
1901
+ for prediction in _iter_topic_predictions(
1902
+ model, vectorizer, config, db_path, batch_size):
1903
+ total += 1
1904
+ document = prediction['document']
1905
+ base = {key: document[key] for key in ['paper_id', 'doi', 'title', 'publication_date']}
1906
+ if prediction['status'] != 'predicted':
1907
+ writer.writerow({**base, 'status': prediction['status']})
1908
+ continue
1909
+ predicted += 1
1910
+ for topic_id, probability in enumerate(prediction['distribution']):
1911
+ writer.writerow({
1912
+ **base,
1913
+ 'topic_id': topic_id,
1914
+ 'topic_name': names[str(topic_id)],
1915
+ 'probability': f'{float(probability):.12g}',
1916
+ 'is_dominant': topic_id == prediction['dominant_topic'],
1917
+ 'status': 'predicted',
1918
+ })
1919
+ if not total:
1920
+ raise ValueError('The corpus contains no papers to predict.')
1921
+ return {
1922
+ 'papers_total': total,
1923
+ 'papers_predicted': predicted,
1924
+ 'papers_without_vocabulary_terms': total - predicted,
1925
+ 'output_path': str(output_path),
1926
+ }
1927
+
1928
+
1929
+ def store_topic_model_scores(
1930
+ model_dir: str | PathLike[str],
1931
+ db_path: str | PathLike[str],
1932
+ name: str | None = None,
1933
+ batch_size: int = DEFAULT_BATCH_SIZE,
1934
+ ) -> dict[str, Any]:
1935
+ """Predict and transactionally store one immutable model run.
1936
+
1937
+ Parameters
1938
+ ----------
1939
+ model_dir : str or os.PathLike[str]
1940
+ Topic-model artifact directory.
1941
+ db_path : str or os.PathLike[str]
1942
+ Corpus in which to store model metadata and paper scores.
1943
+ name : str or None, optional
1944
+ Stable display name; defaults to the model directory name.
1945
+ batch_size : int, default=128
1946
+ Maximum papers inferred at once.
1947
+
1948
+ Returns
1949
+ -------
1950
+ dict[str, Any]
1951
+ Model identity, prediction counts, and prediction fingerprint.
1952
+
1953
+ Raises
1954
+ ------
1955
+ OSError
1956
+ If model artifacts or the corpus cannot be accessed.
1957
+ ValueError
1958
+ If the model name conflicts with an existing immutable identity.
1959
+ """
1960
+ model, vectorizer, config, names = load_topic_model(model_dir)
1961
+ model_id = config['model_id']
1962
+ resolved_name = str(name or Path(model_dir).name).strip()
1963
+ if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]*', resolved_name):
1964
+ raise ValueError('Model name must use only letters, numbers, dots, underscores, and hyphens.')
1965
+ prediction_fingerprint = topic_corpus_fingerprint(
1966
+ db_path, config['text_fields'], batch_size
1967
+ )
1968
+ training_fingerprint = json.loads(
1969
+ (Path(model_dir) / FINGERPRINT_FILENAME).read_text(encoding='utf-8')
1970
+ )
1971
+ topic_rows = topic_descriptions(model_dir)
1972
+ predicted_at = _utc_now()
1973
+ predicted_count = 0
1974
+ missing_count = 0
1975
+
1976
+ with tempfile.TemporaryDirectory(prefix='paperminertoolkit-topic-store-') as temporary_dir:
1977
+ staging_path = Path(temporary_dir) / 'predictions.db'
1978
+ with sqlite3.connect(staging_path) as staging:
1979
+ staging.executescript(
1980
+ """
1981
+ CREATE TABLE predictions (
1982
+ paper_id TEXT PRIMARY KEY, status TEXT NOT NULL,
1983
+ dominant_topic_id INTEGER, document_fingerprint TEXT NOT NULL
1984
+ );
1985
+ CREATE TABLE scores (
1986
+ paper_id TEXT NOT NULL, topic_id INTEGER NOT NULL,
1987
+ probability REAL NOT NULL,
1988
+ PRIMARY KEY (paper_id, topic_id)
1989
+ );
1990
+ """
1991
+ )
1992
+ for prediction in _iter_topic_predictions(
1993
+ model, vectorizer, config, db_path, batch_size):
1994
+ document = prediction['document']
1995
+ staging.execute(
1996
+ 'INSERT INTO predictions VALUES (?, ?, ?, ?)',
1997
+ (
1998
+ document['paper_id'], prediction['status'],
1999
+ prediction['dominant_topic'], prediction['document_fingerprint'],
2000
+ ),
2001
+ )
2002
+ if prediction['status'] == 'predicted':
2003
+ predicted_count += 1
2004
+ staging.executemany(
2005
+ 'INSERT INTO scores VALUES (?, ?, ?)',
2006
+ (
2007
+ (document['paper_id'], topic_id, float(probability))
2008
+ for topic_id, probability in enumerate(prediction['distribution'])
2009
+ ),
2010
+ )
2011
+ else:
2012
+ missing_count += 1
2013
+ staging.commit()
2014
+
2015
+ with connect(db_path) as conn, sqlite3.connect(staging_path) as staging:
2016
+ existing_name = conn.execute(
2017
+ 'SELECT model_id FROM topic_models WHERE name = ?', (resolved_name,)
2018
+ ).fetchone()
2019
+ if existing_name is not None and existing_name['model_id'] != model_id:
2020
+ raise ValueError(
2021
+ f'Topic model name {resolved_name!r} already refers to a different model.'
2022
+ )
2023
+ existing_model = conn.execute(
2024
+ 'SELECT name FROM topic_models WHERE model_id = ?', (model_id,)
2025
+ ).fetchone()
2026
+ if existing_model is not None and existing_model['name'] != resolved_name:
2027
+ raise ValueError(
2028
+ f'Model {model_id} is already stored as {existing_model["name"]!r}.'
2029
+ )
2030
+ now = _utc_now()
2031
+ try:
2032
+ conn.execute('BEGIN')
2033
+ conn.execute(
2034
+ """
2035
+ INSERT INTO topic_models (
2036
+ model_id, name, artifact_path, artifact_version, config_json,
2037
+ training_corpus_fingerprint, prediction_corpus_fingerprint,
2038
+ text_fields_json, created_at, updated_at
2039
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2040
+ ON CONFLICT(model_id) DO UPDATE SET
2041
+ artifact_path=excluded.artifact_path,
2042
+ config_json=excluded.config_json,
2043
+ prediction_corpus_fingerprint=excluded.prediction_corpus_fingerprint,
2044
+ text_fields_json=excluded.text_fields_json,
2045
+ updated_at=excluded.updated_at
2046
+ """,
2047
+ (
2048
+ model_id, resolved_name, str(Path(model_dir).resolve()),
2049
+ config['artifact_version'], json.dumps(config, sort_keys=True),
2050
+ training_fingerprint['sha256'], prediction_fingerprint['sha256'],
2051
+ json.dumps(config['text_fields']), now, now,
2052
+ ),
2053
+ )
2054
+ conn.execute('DELETE FROM topic_definitions WHERE model_id = ?', (model_id,))
2055
+ conn.executemany(
2056
+ 'INSERT INTO topic_definitions VALUES (?, ?, ?, ?)',
2057
+ (
2058
+ (
2059
+ model_id, row['topic_id'], names[str(row['topic_id'])],
2060
+ json.dumps(row['top_terms']),
2061
+ )
2062
+ for row in topic_rows
2063
+ ),
2064
+ )
2065
+ conn.execute('DELETE FROM paper_topic_predictions WHERE model_id = ?', (model_id,))
2066
+ prediction_rows = staging.execute(
2067
+ 'SELECT paper_id, status, dominant_topic_id, document_fingerprint FROM predictions'
2068
+ )
2069
+ while batch := prediction_rows.fetchmany(1000):
2070
+ conn.executemany(
2071
+ 'INSERT INTO paper_topic_predictions VALUES (?, ?, ?, ?, ?, ?)',
2072
+ (
2073
+ (model_id, row[0], row[1], row[2], row[3], predicted_at)
2074
+ for row in batch
2075
+ ),
2076
+ )
2077
+ score_rows = staging.execute(
2078
+ 'SELECT paper_id, topic_id, probability FROM scores'
2079
+ )
2080
+ while batch := score_rows.fetchmany(5000):
2081
+ conn.executemany(
2082
+ 'INSERT INTO paper_topic_scores VALUES (?, ?, ?, ?)',
2083
+ ((model_id, row[0], row[1], row[2]) for row in batch),
2084
+ )
2085
+ conn.commit()
2086
+ except Exception:
2087
+ conn.rollback()
2088
+ raise
2089
+ try:
2090
+ from paperminertoolkit.corpus.filtering import refresh_topic_filters
2091
+ refresh_topic_filters(db_path, model_id)
2092
+ except ImportError:
2093
+ pass
2094
+ return {
2095
+ 'model_id': model_id,
2096
+ 'name': resolved_name,
2097
+ 'papers_predicted': predicted_count,
2098
+ 'papers_without_vocabulary_terms': missing_count,
2099
+ 'prediction_corpus_fingerprint': prediction_fingerprint['sha256'],
2100
+ }
2101
+
2102
+
2103
+ def stored_topic_models(
2104
+ db_path: str | PathLike[str],
2105
+ batch_size: int = DEFAULT_BATCH_SIZE,
2106
+ ) -> list[dict[str, Any]]:
2107
+ """List stored topic models with coverage and freshness information.
2108
+
2109
+ Parameters
2110
+ ----------
2111
+ db_path : str or os.PathLike[str]
2112
+ Path to the SQLite paper corpus.
2113
+ batch_size : int, default=128
2114
+ Maximum papers loaded while calculating current fingerprints.
2115
+
2116
+ Returns
2117
+ -------
2118
+ list[dict[str, Any]]
2119
+ Stored model rows augmented with topic count, prediction coverage,
2120
+ text fields, and current/stale state.
2121
+ """
2122
+ with connect(db_path) as conn:
2123
+ models = [dict(row) for row in conn.execute(
2124
+ 'SELECT * FROM topic_models ORDER BY name'
2125
+ ).fetchall()]
2126
+ for item in models:
2127
+ counts = dict(conn.execute(
2128
+ 'SELECT status, COUNT(*) FROM paper_topic_predictions '
2129
+ 'WHERE model_id = ? GROUP BY status', (item['model_id'],)
2130
+ ).fetchall())
2131
+ item['papers_predicted'] = counts.get('predicted', 0)
2132
+ item['papers_without_vocabulary_terms'] = counts.get('no_vocabulary_terms', 0)
2133
+ item['num_topics'] = conn.execute(
2134
+ 'SELECT COUNT(*) FROM topic_definitions WHERE model_id = ?',
2135
+ (item['model_id'],),
2136
+ ).fetchone()[0]
2137
+ item['text_fields'] = json.loads(item['text_fields_json'])
2138
+ fingerprints = {}
2139
+ for item in models:
2140
+ key = tuple(item['text_fields'])
2141
+ if key not in fingerprints:
2142
+ fingerprints[key] = topic_corpus_fingerprint(db_path, key, batch_size)['sha256']
2143
+ item['is_current'] = fingerprints[key] == item['prediction_corpus_fingerprint']
2144
+ return models
2145
+
2146
+
2147
+ def _prediction_papers(
2148
+ predictions_path: str | PathLike[str],
2149
+ ) -> Iterator[dict[str, Any]]:
2150
+ """Group a long-form prediction CSV into complete paper records.
2151
+
2152
+ Parameters
2153
+ ----------
2154
+ predictions_path : str or os.PathLike[str]
2155
+ Long-form topic prediction CSV ordered by paper.
2156
+
2157
+ Yields
2158
+ ------
2159
+ dict[str, Any]
2160
+ Paper ID, publication date, status, complete probability mapping, and
2161
+ dominant topic ID.
2162
+ """
2163
+ with Path(predictions_path).open(encoding='utf-8', newline='') as handle:
2164
+ rows = csv.DictReader(handle)
2165
+ for paper_id, grouped_rows in groupby(rows, key=lambda row: row['paper_id']):
2166
+ grouped = list(grouped_rows)
2167
+ first = grouped[0]
2168
+ status = first.get('status') or ''
2169
+ probabilities = {
2170
+ int(row['topic_id']): float(row['probability'])
2171
+ for row in grouped
2172
+ if row.get('status') == 'predicted' and row.get('topic_id') != ''
2173
+ }
2174
+ dominant = next(
2175
+ (int(row['topic_id']) for row in grouped
2176
+ if str(row.get('is_dominant')).lower() in {'true', '1'}),
2177
+ None,
2178
+ )
2179
+ yield {
2180
+ 'paper_id': paper_id,
2181
+ 'publication_date': first.get('publication_date') or '',
2182
+ 'status': status,
2183
+ 'probabilities': probabilities,
2184
+ 'dominant_topic': dominant,
2185
+ }
2186
+
2187
+
2188
+ def _publication_year(value: object) -> int | None:
2189
+ """Extract a plausible four-digit publication year.
2190
+
2191
+ Parameters
2192
+ ----------
2193
+ value : object
2194
+ Publication-date value from corpus metadata.
2195
+
2196
+ Returns
2197
+ -------
2198
+ int or None
2199
+ Year from 1000 through 2999, or ``None`` when no valid year exists.
2200
+ """
2201
+ match = re.search(r'(?<!\d)(\d{4})(?!\d)', str(value or ''))
2202
+ if not match:
2203
+ return None
2204
+ year = int(match.group(1))
2205
+ return year if 1000 <= year <= 2999 else None
2206
+
2207
+
2208
+ def plot_topic_trends(
2209
+ trends_path: str | PathLike[str],
2210
+ report_path: str | PathLike[str],
2211
+ output_path: str | PathLike[str] | None = None,
2212
+ ) -> str:
2213
+ """Plot topic prevalence and paper coverage from trend artifacts.
2214
+
2215
+ Parameters
2216
+ ----------
2217
+ trends_path : str or os.PathLike[str]
2218
+ Topic trend CSV produced by :func:`aggregate_topic_trends`.
2219
+ report_path : str or os.PathLike[str]
2220
+ JSON report describing the aggregation windows and corpus coverage.
2221
+ output_path : str, os.PathLike[str], or None, optional
2222
+ Destination image. A relative path is resolved inside the trend output
2223
+ directory, and a missing suffix defaults to PNG.
2224
+
2225
+ Returns
2226
+ -------
2227
+ str
2228
+ Path to the generated plot.
2229
+
2230
+ Raises
2231
+ ------
2232
+ OSError
2233
+ If trend artifacts cannot be read or the plot cannot be written.
2234
+ RuntimeError
2235
+ If Matplotlib is unavailable.
2236
+ ValueError
2237
+ If the trend CSV has no usable topic rows.
2238
+ """
2239
+ try:
2240
+ import matplotlib
2241
+ matplotlib.use('Agg')
2242
+ import matplotlib.pyplot as plt
2243
+ from matplotlib.ticker import MaxNLocator, PercentFormatter
2244
+ except ImportError as error:
2245
+ raise RuntimeError(
2246
+ 'Plotting topic trends requires matplotlib. Install PaperMinerToolkit dependencies '
2247
+ 'and rerun pmt topics trends with --plot.'
2248
+ ) from error
2249
+
2250
+ trends_path = Path(trends_path)
2251
+ report_path = Path(report_path)
2252
+ destination = (
2253
+ trends_path.parent / TRENDS_PLOT_FILENAME
2254
+ if output_path is None else Path(output_path)
2255
+ )
2256
+ if output_path is not None and not destination.is_absolute():
2257
+ destination = trends_path.parent / destination
2258
+ if not destination.suffix:
2259
+ destination = destination.with_suffix('.png')
2260
+ destination.parent.mkdir(parents=True, exist_ok=True)
2261
+ with trends_path.open(encoding='utf-8', newline='') as handle:
2262
+ rows = list(csv.DictReader(handle))
2263
+ if not rows:
2264
+ raise ValueError(f'Topic trend CSV contains no rows: {trends_path}')
2265
+ report = json.loads(report_path.read_text(encoding='utf-8'))
2266
+
2267
+ topic_series = {}
2268
+ window_counts = {}
2269
+ for row in rows:
2270
+ if row.get('mean_probability', '') == '':
2271
+ continue
2272
+ topic_id = int(row['topic_id'])
2273
+ item = {
2274
+ 'window_start': int(row['window_start']),
2275
+ 'window_end': int(row['window_end']),
2276
+ 'is_partial': str(row['is_partial']).lower() in {'true', '1'},
2277
+ 'mean_probability': float(row['mean_probability']),
2278
+ 'papers_total': int(row['papers_total']),
2279
+ 'topic_name': row.get('topic_name') or '',
2280
+ }
2281
+ topic_series.setdefault(topic_id, []).append(item)
2282
+ window_counts[item['window_start']] = item['papers_total']
2283
+ if not topic_series:
2284
+ raise ValueError(f'Topic trend CSV contains no predicted topic values: {trends_path}')
2285
+
2286
+ figure, (axis, count_axis) = plt.subplots(
2287
+ 2, 1, figsize=(13.5, 8.2), sharex=True,
2288
+ gridspec_kw={'height_ratios': [4, 1], 'hspace': 0.08},
2289
+ )
2290
+ color_map = plt.get_cmap('tab10')
2291
+ maximum_probability = 0.0
2292
+ first_partial = None
2293
+ for topic_id in sorted(topic_series):
2294
+ series = sorted(topic_series[topic_id], key=lambda item: item['window_start'])
2295
+ maximum_probability = max(
2296
+ maximum_probability,
2297
+ max(item['mean_probability'] for item in series),
2298
+ )
2299
+ label = (
2300
+ f'{topic_id}: {series[0]["topic_name"]}'
2301
+ if series[0]['topic_name'] else f'Topic {topic_id}'
2302
+ )
2303
+ partial_index = next(
2304
+ (index for index, item in enumerate(series) if item['is_partial']),
2305
+ len(series),
2306
+ )
2307
+ complete = series[:partial_index]
2308
+ color = color_map(topic_id % 10)
2309
+ if complete:
2310
+ axis.plot(
2311
+ [item['window_start'] for item in complete],
2312
+ [item['mean_probability'] for item in complete],
2313
+ color=color, linewidth=2.3, marker='o', markersize=4.5,
2314
+ label=label,
2315
+ )
2316
+ else:
2317
+ axis.plot([], [], color=color, linewidth=2.3, marker='o', label=label)
2318
+ if partial_index < len(series):
2319
+ partial = series[max(0, partial_index - 1):]
2320
+ first_partial = min(
2321
+ first_partial if first_partial is not None else partial[0]['window_start'],
2322
+ series[partial_index]['window_start'],
2323
+ )
2324
+ axis.plot(
2325
+ [item['window_start'] for item in partial],
2326
+ [item['mean_probability'] for item in partial],
2327
+ color=color, linewidth=2.0, marker='o', markersize=4,
2328
+ linestyle='--', alpha=0.72,
2329
+ )
2330
+
2331
+ starts = sorted(window_counts)
2332
+ count_axis.bar(
2333
+ starts,
2334
+ [window_counts[start] for start in starts],
2335
+ width=0.72,
2336
+ color=['#BBBBBB' if first_partial is not None and start >= first_partial else '#777777'
2337
+ for start in starts],
2338
+ edgecolor='white',
2339
+ linewidth=0.5,
2340
+ )
2341
+ if first_partial is not None:
2342
+ for plot_axis in (axis, count_axis):
2343
+ plot_axis.axvspan(
2344
+ first_partial - 0.5, max(starts) + 0.5,
2345
+ color='#E5E5E5', alpha=0.55, zorder=0,
2346
+ )
2347
+
2348
+ for plot_axis in (axis, count_axis):
2349
+ plot_axis.grid(axis='y', color='#D9D9D9', linewidth=0.8, alpha=0.75)
2350
+ plot_axis.spines[['top', 'right']].set_visible(False)
2351
+ bin_size = int(report['bin_size'])
2352
+ step_size = int(report['step_size'])
2353
+ annual = bin_size == 1 and step_size == 1
2354
+ axis.set_title(
2355
+ 'Annual topic prevalence' if annual else 'Topic prevalence over time',
2356
+ loc='left', fontsize=17, weight='bold', pad=18,
2357
+ )
2358
+ subtitle = (
2359
+ 'Mean LDA probability by publication year'
2360
+ if annual else
2361
+ f'Mean LDA probability in {bin_size}-year windows with a {step_size}-year step'
2362
+ )
2363
+ if first_partial is not None:
2364
+ subtitle += '; dashed lines are partial windows'
2365
+ axis.text(
2366
+ 0, 1.015, subtitle, transform=axis.transAxes,
2367
+ fontsize=10.5, color='#444444', va='bottom',
2368
+ )
2369
+ axis.set_ylabel('Mean topic probability')
2370
+ axis.yaxis.set_major_formatter(PercentFormatter(1.0, decimals=0))
2371
+ axis.set_ylim(0, min(1.0, max(0.4, math.ceil(maximum_probability * 20) / 20 + 0.05)))
2372
+ axis.legend(loc='upper left', bbox_to_anchor=(1.01, 1.0), frameon=False, fontsize=9.5)
2373
+ count_axis.set_ylabel('Papers')
2374
+ count_axis.set_xlabel('Publication year' if annual else 'Start year of time window')
2375
+ count_axis.yaxis.set_major_locator(MaxNLocator(integer=True, nbins=4))
2376
+ count_axis.set_xticks(starts)
2377
+ count_axis.tick_params(axis='x', rotation=45)
2378
+ count_axis.text(
2379
+ 1.0, -0.78,
2380
+ f'{report["papers_total"]} papers; observed publication years '
2381
+ f'{report["observed_start_year"]}–{report["observed_end_year"]}.',
2382
+ transform=count_axis.transAxes, ha='right', va='top',
2383
+ fontsize=9, color='#555555',
2384
+ )
2385
+ figure.subplots_adjust(left=0.08, right=0.72, top=0.88, bottom=0.18)
2386
+
2387
+ figure.savefig(
2388
+ destination,
2389
+ dpi=180 if destination.suffix.lower() == '.png' else None,
2390
+ bbox_inches='tight',
2391
+ )
2392
+ plt.close(figure)
2393
+ return str(destination)
2394
+
2395
+
2396
+ def aggregate_topic_trends(
2397
+ model_dir: str | PathLike[str],
2398
+ output_dir: str | PathLike[str],
2399
+ predictions_path: str | PathLike[str] | None = None,
2400
+ bin_size: int = 1,
2401
+ step_size: int = 1,
2402
+ start_year: int | None = None,
2403
+ end_year: int | None = None,
2404
+ include_partial: bool = True,
2405
+ overwrite: bool = False,
2406
+ plot: bool | str | PathLike[str] = False,
2407
+ ) -> dict[str, Any]:
2408
+ """Aggregate fixed-model topic probabilities into time windows.
2409
+
2410
+ Parameters
2411
+ ----------
2412
+ model_dir : str or os.PathLike[str]
2413
+ Topic-model artifact directory supplying configuration and names.
2414
+ output_dir : str or os.PathLike[str]
2415
+ Destination directory for trend artifacts.
2416
+ predictions_path : str, os.PathLike[str], or None, optional
2417
+ Long-form predictions; defaults to the model's training predictions.
2418
+ bin_size : int, default=1
2419
+ Width of each publication-year window.
2420
+ step_size : int, default=1
2421
+ Years between consecutive window starts.
2422
+ start_year : int or None, optional
2423
+ First window start; defaults to the earliest observed year.
2424
+ end_year : int or None, optional
2425
+ Final observed year included in the configured range.
2426
+ include_partial : bool, default=True
2427
+ Whether to include trailing windows extending past ``end_year``.
2428
+ overwrite : bool, default=False
2429
+ Whether known artifacts may be replaced in a nonempty directory.
2430
+ plot : bool, str, or os.PathLike[str], default=False
2431
+ Generate the default PNG when true, or write to the supplied filename.
2432
+
2433
+ Returns
2434
+ -------
2435
+ dict[str, Any]
2436
+ Artifact paths, window count, missing-date count, and optional plot path.
2437
+
2438
+ Raises
2439
+ ------
2440
+ FileNotFoundError
2441
+ If the prediction CSV is unavailable.
2442
+ OSError
2443
+ If model or trend artifacts cannot be accessed.
2444
+ ValueError
2445
+ If window settings or publication dates are unsuitable.
2446
+ """
2447
+ if bin_size < 1 or step_size < 1:
2448
+ raise ValueError('bin_size and step_size must be positive.')
2449
+ if step_size > bin_size:
2450
+ raise ValueError('step_size must not exceed bin_size.')
2451
+ _model, _vectorizer, config, names = load_topic_model(model_dir)
2452
+ predictions_path = Path(predictions_path or Path(model_dir) / PREDICTIONS_FILENAME)
2453
+ if not predictions_path.exists():
2454
+ raise FileNotFoundError(f'Missing topic predictions: {predictions_path}')
2455
+
2456
+ observed_years = []
2457
+ missing_dates = 0
2458
+ paper_count = 0
2459
+ for paper in _prediction_papers(predictions_path):
2460
+ paper_count += 1
2461
+ year = _publication_year(paper['publication_date'])
2462
+ if year is None:
2463
+ missing_dates += 1
2464
+ else:
2465
+ observed_years.append(year)
2466
+ if not observed_years:
2467
+ raise ValueError('Topic predictions contain no valid publication years.')
2468
+ observed_min = min(observed_years)
2469
+ observed_max = max(observed_years)
2470
+ resolved_start = observed_min if start_year is None else int(start_year)
2471
+ resolved_end = observed_max if end_year is None else int(end_year)
2472
+ if resolved_start > resolved_end:
2473
+ raise ValueError('start_year must not exceed end_year.')
2474
+
2475
+ windows = []
2476
+ for window_start in range(resolved_start, resolved_end + 1, step_size):
2477
+ window_end = window_start + bin_size - 1
2478
+ partial = window_end > resolved_end
2479
+ if partial and not include_partial:
2480
+ continue
2481
+ windows.append((window_start, window_end, partial))
2482
+ window_totals = {start: 0 for start, _, _ in windows}
2483
+ window_predicted = {start: 0 for start, _, _ in windows}
2484
+ aggregates = {
2485
+ (start, topic_id): {'probability_sum': 0.0, 'dominant_papers': 0}
2486
+ for start, _, _ in windows
2487
+ for topic_id in range(config['num_topics'])
2488
+ }
2489
+ for paper in _prediction_papers(predictions_path):
2490
+ year = _publication_year(paper['publication_date'])
2491
+ if year is None:
2492
+ continue
2493
+ matching = [window for window in windows if window[0] <= year <= window[1]]
2494
+ for window_start, _, _ in matching:
2495
+ window_totals[window_start] += 1
2496
+ if paper['status'] != 'predicted' or not paper['probabilities']:
2497
+ continue
2498
+ window_predicted[window_start] += 1
2499
+ for topic_id in range(config['num_topics']):
2500
+ aggregate = aggregates[(window_start, topic_id)]
2501
+ aggregate['probability_sum'] += paper['probabilities'].get(topic_id, 0.0)
2502
+ if paper['dominant_topic'] == topic_id:
2503
+ aggregate['dominant_papers'] += 1
2504
+
2505
+ output_path = _prepare_output_directory(output_dir, overwrite=overwrite)
2506
+ trend_path = output_path / TRENDS_CSV_FILENAME
2507
+ fields = [
2508
+ 'window_start', 'window_end', 'is_partial', 'topic_id', 'topic_name',
2509
+ 'papers_total', 'papers_predicted', 'mean_probability', 'expected_papers',
2510
+ 'dominant_papers', 'dominant_share',
2511
+ ]
2512
+ with trend_path.open('w', encoding='utf-8', newline='') as handle:
2513
+ writer = csv.DictWriter(handle, fieldnames=fields)
2514
+ writer.writeheader()
2515
+ for window_start, window_end, partial in windows:
2516
+ predicted = window_predicted[window_start]
2517
+ for topic_id in range(config['num_topics']):
2518
+ aggregate = aggregates[(window_start, topic_id)]
2519
+ probability_sum = aggregate['probability_sum']
2520
+ writer.writerow({
2521
+ 'window_start': window_start,
2522
+ 'window_end': window_end,
2523
+ 'is_partial': partial,
2524
+ 'topic_id': topic_id,
2525
+ 'topic_name': names[str(topic_id)],
2526
+ 'papers_total': window_totals[window_start],
2527
+ 'papers_predicted': predicted,
2528
+ 'mean_probability': f'{probability_sum / predicted:.12g}' if predicted else '',
2529
+ 'expected_papers': f'{probability_sum:.12g}' if predicted else '',
2530
+ 'dominant_papers': aggregate['dominant_papers'] if predicted else '',
2531
+ 'dominant_share': (
2532
+ f'{aggregate["dominant_papers"] / predicted:.12g}' if predicted else ''
2533
+ ),
2534
+ })
2535
+ report = {
2536
+ 'created_at': _utc_now(),
2537
+ 'model_id': config['model_id'],
2538
+ 'predictions_path': str(predictions_path),
2539
+ 'bin_size': bin_size,
2540
+ 'step_size': step_size,
2541
+ 'start_year': resolved_start,
2542
+ 'end_year': resolved_end,
2543
+ 'observed_start_year': observed_min,
2544
+ 'observed_end_year': observed_max,
2545
+ 'include_partial': include_partial,
2546
+ 'papers_total': paper_count,
2547
+ 'papers_missing_or_invalid_date': missing_dates,
2548
+ 'windows': len(windows),
2549
+ }
2550
+ report_path = output_path / TRENDS_REPORT_FILENAME
2551
+ _write_json(report_path, report)
2552
+ requested_plot_path = None
2553
+ if plot:
2554
+ requested_plot_path = None if plot is True else plot
2555
+ plot_path = (
2556
+ plot_topic_trends(trend_path, report_path, requested_plot_path)
2557
+ if plot else None
2558
+ )
2559
+ return {
2560
+ 'output_dir': str(output_path),
2561
+ 'trends_csv': str(trend_path),
2562
+ 'report_json': str(report_path),
2563
+ 'windows': len(windows),
2564
+ 'papers_missing_or_invalid_date': missing_dates,
2565
+ 'plot_path': plot_path,
2566
+ }
2567
+
2568
+
2569
+ def _topic_set_similarity(
2570
+ left_topics: Sequence[Mapping[str, Any]],
2571
+ right_topics: Sequence[Mapping[str, Any]],
2572
+ ) -> float:
2573
+ """Calculate symmetric best-match similarity between topic sets.
2574
+
2575
+ Parameters
2576
+ ----------
2577
+ left_topics : Sequence[Mapping[str, Any]]
2578
+ First topic collection containing ``top_terms`` lists.
2579
+ right_topics : Sequence[Mapping[str, Any]]
2580
+ Second topic collection containing ``top_terms`` lists.
2581
+
2582
+ Returns
2583
+ -------
2584
+ float
2585
+ Symmetric mean best-match Jaccard similarity from zero to one.
2586
+ """
2587
+ left_sets = [set(topic['top_terms']) for topic in left_topics]
2588
+ right_sets = [set(topic['top_terms']) for topic in right_topics]
2589
+
2590
+ def directional(source: Sequence[set[str]], targets: Sequence[set[str]]) -> float:
2591
+ """Calculate mean best-match similarity in one direction.
2592
+
2593
+ Parameters
2594
+ ----------
2595
+ source : Sequence[set[str]]
2596
+ Topic-term sets to score.
2597
+ targets : Sequence[set[str]]
2598
+ Candidate topic-term sets for each source topic.
2599
+
2600
+ Returns
2601
+ -------
2602
+ float
2603
+ Mean best-match Jaccard similarity, or zero for no source topics.
2604
+ """
2605
+ scores = []
2606
+ for source_terms in source:
2607
+ candidates = [
2608
+ len(source_terms & target_terms) / len(source_terms | target_terms)
2609
+ for target_terms in targets
2610
+ if source_terms or target_terms
2611
+ ]
2612
+ scores.append(max(candidates, default=0))
2613
+ return sum(scores) / len(scores) if scores else 0
2614
+
2615
+ return (directional(left_sets, right_sets) + directional(right_sets, left_sets)) / 2
2616
+
2617
+
2618
+ def _write_model_comparison(
2619
+ path: str | PathLike[str],
2620
+ rows: Iterable[Mapping[str, Any]],
2621
+ ) -> None:
2622
+ """Write quality metrics for a collection of comparison models.
2623
+
2624
+ Parameters
2625
+ ----------
2626
+ path : str or os.PathLike[str]
2627
+ Destination comparison CSV path.
2628
+ rows : Iterable[Mapping[str, Any]]
2629
+ Per-model configuration and quality metrics.
2630
+
2631
+ Raises
2632
+ ------
2633
+ OSError
2634
+ If the destination cannot be written.
2635
+ """
2636
+ fieldnames = [
2637
+ 'num_topics', 'random_state', 'model_dir', 'documents_used', 'vocabulary_size',
2638
+ 'perplexity', 'log_likelihood', 'topic_diversity', 'dominant_topic_balance',
2639
+ 'smallest_dominant_topic', 'largest_dominant_topic', 'mean_seed_stability',
2640
+ 'vectorization_seconds', 'fitting_seconds', 'cache_size_bytes', 'warnings',
2641
+ ]
2642
+ with Path(path).open('w', encoding='utf-8', newline='') as handle:
2643
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
2644
+ writer.writeheader()
2645
+ for row in rows:
2646
+ writer.writerow({
2647
+ **row,
2648
+ 'warnings': ' | '.join(row['warnings']),
2649
+ })
2650
+
2651
+
2652
+ def compare_topic_models(db_path: str | PathLike[str],
2653
+ output_dir: str | PathLike[str],
2654
+ topic_counts: Iterable[int] = (5, 10),
2655
+ random_states: Iterable[int] = (0, 1),
2656
+ text_fields: Iterable[str] = ('title', 'abstract'),
2657
+ min_df: int = 2,
2658
+ max_df: float = 0.95,
2659
+ max_features: int = 20000,
2660
+ learning_method: str = 'online',
2661
+ max_iter: int = 20,
2662
+ top_terms: int = 15,
2663
+ representative_papers: int = 5,
2664
+ stopwords_file: str | PathLike[str] | None = None,
2665
+ ngram_max: int = 2,
2666
+ overwrite: bool = False,
2667
+ streaming: bool = True,
2668
+ batch_size: int = DEFAULT_BATCH_SIZE,
2669
+ cache_dir: str | PathLike[str] | None = None,
2670
+ evaluation_sample_size: int = DEFAULT_EVALUATION_SAMPLE_SIZE) -> dict[str, Any]:
2671
+ """Train and compare topic counts and random seeds on one corpus.
2672
+
2673
+ Parameters
2674
+ ----------
2675
+ db_path : str or os.PathLike[str]
2676
+ Path to the source SQLite paper corpus.
2677
+ output_dir : str or os.PathLike[str]
2678
+ Directory for comparison models and reports.
2679
+ topic_counts : Iterable[int], default=(5, 10)
2680
+ Distinct topic counts to evaluate.
2681
+ random_states : Iterable[int], default=(0, 1)
2682
+ Distinct model seeds to evaluate.
2683
+ text_fields : Iterable[str], default=('title', 'abstract')
2684
+ Corpus fields combined into each modeling document.
2685
+ min_df : int, default=2
2686
+ Minimum number of documents in which a feature must occur.
2687
+ max_df : float, default=0.95
2688
+ Maximum fraction of documents in which a feature may occur.
2689
+ max_features : int, default=20000
2690
+ Maximum retained vocabulary size.
2691
+ learning_method : {'batch', 'online'}, default='online'
2692
+ Scikit-learn LDA learning strategy.
2693
+ max_iter : int, default=20
2694
+ Maximum LDA training iterations.
2695
+ top_terms : int, default=15
2696
+ Number of terms exported for each topic.
2697
+ representative_papers : int, default=5
2698
+ Number of high-probability papers exported per topic.
2699
+ stopwords_file : str, os.PathLike[str], or None, optional
2700
+ File containing domain-specific stopwords.
2701
+ ngram_max : {1, 2}, default=2
2702
+ Maximum feature n-gram size.
2703
+ overwrite : bool, default=False
2704
+ Whether nonempty comparison directories may be reused.
2705
+ streaming : bool, default=True
2706
+ Whether every model trains from one reusable disk-backed corpus cache.
2707
+ batch_size : int, default=128
2708
+ Maximum documents processed in each streaming batch.
2709
+ cache_dir : str, os.PathLike[str], or None, optional
2710
+ Parent directory for the temporary comparison cache.
2711
+ evaluation_sample_size : int, default=10000
2712
+ Maximum deterministic document sample used for streaming fit metrics.
2713
+
2714
+ Returns
2715
+ -------
2716
+ dict[str, Any]
2717
+ Comparison paths, model count, and per-model metrics.
2718
+
2719
+ Raises
2720
+ ------
2721
+ OSError
2722
+ If inputs or artifacts cannot be read or written.
2723
+ ValueError
2724
+ If the comparison grid or a training configuration is invalid.
2725
+ """
2726
+ counts = tuple(dict.fromkeys(int(value) for value in topic_counts))
2727
+ seeds = tuple(dict.fromkeys(int(value) for value in random_states))
2728
+ if not counts or any(value < 2 for value in counts):
2729
+ raise ValueError('topic_counts must contain values of at least 2.')
2730
+ if not seeds:
2731
+ raise ValueError('At least one random state is required.')
2732
+ if len(counts) * len(seeds) < 2:
2733
+ raise ValueError('Model comparison requires at least two topic-count and seed combinations.')
2734
+ if streaming and learning_method != 'online':
2735
+ raise ValueError('Streaming comparison requires learning_method="online"; use in-memory mode for batch LDA.')
2736
+
2737
+ fields = _validate_text_fields(text_fields)
2738
+ comparison_path = _prepare_output_directory(output_dir, overwrite)
2739
+ model_records = []
2740
+ summaries = []
2741
+ temporary = None
2742
+ try:
2743
+ if streaming:
2744
+ if cache_dir is not None:
2745
+ Path(cache_dir).mkdir(parents=True, exist_ok=True)
2746
+ temporary = tempfile.TemporaryDirectory(
2747
+ prefix='paperminertoolkit-topics-compare-', dir=cache_dir
2748
+ )
2749
+ prepared = _prepare_streaming_corpus(
2750
+ db_path, fields, load_domain_stopwords(stopwords_file), ngram_max,
2751
+ min_df, max_df, max_features, batch_size,
2752
+ evaluation_sample_size, temporary.name,
2753
+ )
2754
+ documents = None
2755
+ else:
2756
+ prepared = None
2757
+ documents = load_topic_documents(db_path, fields)
2758
+ for num_topics in counts:
2759
+ for random_state in seeds:
2760
+ model_dir = comparison_path / f'topics-{num_topics}_seed-{random_state}'
2761
+ summary = train_topic_model(
2762
+ db_path,
2763
+ model_dir,
2764
+ num_topics=num_topics,
2765
+ text_fields=fields,
2766
+ min_df=min_df,
2767
+ max_df=max_df,
2768
+ max_features=max_features,
2769
+ learning_method=learning_method,
2770
+ max_iter=max_iter,
2771
+ random_state=random_state,
2772
+ top_terms=top_terms,
2773
+ representative_papers=representative_papers,
2774
+ stopwords_file=stopwords_file,
2775
+ ngram_max=ngram_max,
2776
+ overwrite=overwrite,
2777
+ emit_warnings=False,
2778
+ documents=documents,
2779
+ streaming=streaming,
2780
+ batch_size=batch_size,
2781
+ cache_dir=cache_dir,
2782
+ evaluation_sample_size=evaluation_sample_size,
2783
+ _prepared_streaming=prepared,
2784
+ )
2785
+ report = summary['report']
2786
+ record = {
2787
+ 'num_topics': num_topics,
2788
+ 'random_state': random_state,
2789
+ 'model_dir': str(model_dir),
2790
+ 'documents_used': report['documents_used'],
2791
+ 'vocabulary_size': report['vocabulary_size'],
2792
+ 'perplexity': report['perplexity'],
2793
+ 'log_likelihood': report['log_likelihood'],
2794
+ 'topic_diversity': report['topic_diversity'],
2795
+ 'dominant_topic_balance': report['dominant_topic_balance'],
2796
+ 'smallest_dominant_topic': report['smallest_dominant_topic'],
2797
+ 'largest_dominant_topic': report['largest_dominant_topic'],
2798
+ 'mean_seed_stability': '',
2799
+ 'vectorization_seconds': report['vectorization_seconds'],
2800
+ 'fitting_seconds': report['fitting_seconds'],
2801
+ 'cache_size_bytes': report.get('cache_size_bytes', ''),
2802
+ 'warnings': report['warnings'],
2803
+ }
2804
+ model_records.append(record)
2805
+ summaries.append(summary)
2806
+ finally:
2807
+ if temporary is not None:
2808
+ temporary.cleanup()
2809
+
2810
+ for num_topics in counts:
2811
+ matching = [summary for summary in summaries if summary['config']['num_topics'] == num_topics]
2812
+ pair_scores = [
2813
+ _topic_set_similarity(left['topics'], right['topics'])
2814
+ for left, right in combinations(matching, 2)
2815
+ ]
2816
+ mean_stability = sum(pair_scores) / len(pair_scores) if pair_scores else ''
2817
+ for record in model_records:
2818
+ if record['num_topics'] == num_topics:
2819
+ record['mean_seed_stability'] = mean_stability
2820
+
2821
+ _write_model_comparison(comparison_path / COMPARISON_CSV_FILENAME, model_records)
2822
+ comparison_report = {
2823
+ 'created_at': _utc_now(),
2824
+ 'topic_counts': list(counts),
2825
+ 'random_states': list(seeds),
2826
+ 'streaming': streaming,
2827
+ 'batch_size': batch_size,
2828
+ 'models': model_records,
2829
+ }
2830
+ _write_json(comparison_path / COMPARISON_JSON_FILENAME, comparison_report)
2831
+ return {
2832
+ 'output_dir': str(comparison_path),
2833
+ 'models_trained': len(model_records),
2834
+ 'models': model_records,
2835
+ 'comparison_csv': str(comparison_path / COMPARISON_CSV_FILENAME),
2836
+ 'comparison_json': str(comparison_path / COMPARISON_JSON_FILENAME),
2837
+ }