Skip to content

Text statistics in the style of IRaMuTeQ (irastats package + Reports submenu) - #18

Merged
qwertygc merged 26 commits into
masterfrom
vibe/irastats-3344e3
Nov 23, 2026
Merged

qwertygc merged 26 commits into
masterfrom
vibe/irastats-3344e3

Conversation

@qwertygc

Copy link
Copy Markdown
Owner

Description

Implements the main textual statistics of the IRaMuTeQ software in QualCoder, integrated into the existing Reports module as a new "Text statistics (IRaMuTeQ methods)" submenu (one tabbed dialog, DialogTextStats), with a pure-Python, GUI-free computation package src/qualcoder/irastats/ so every engine is unit-tested without Qt.

  • F0 pipeline: analysable corpus from the project DB (app.conn only) — coded segments and/or whole documents, each with variables {code, case, document, file/case attributes}; tokenisation, stopwords (built-in ISO lists + editable custom file), optional light stemming; sparse forms x segments lexical table (scipy.sparse) with active vs supplementary forms.
  • F1 descending text statistics (IRaMuTeQ "rapport descendant"): occurrences, active/supplementary forms, decreasing frequencies, hapax, breakdown by partition variable; CSV + HTML export.
  • F2 chi-square specificities per form x modality of a partition variable (classic chi2 with marginals, signed value, two-sided p-value via scipy.stats.chi2, threshold default 0.05); CSV/HTML with over/under-representation highlighting.
  • F6 IRaMuTeQ corpus export ("**** *code=... *cas=... *doc=..." blocks, optional whole documents); the existing Report Codes IRaMuTeQ export now shares the token helper (output unchanged).
  • F4 similarity graph: co-occurrences within segments, Jaccard (default) or chi2/phi-squared, adjustable edge threshold, networkx + non-blocking matplotlib window, PNG export.
  • F3 correspondence analysis by SVD (numpy only): eigenvalues, coordinates, contributions, cos2, factor map 1x2, CSV + PNG export.
  • F5 Reinert CHD (Reinert 1983/1990): UCI ~40 occurrences bounded by punctuation, forms x UCI matrix of active forms (freq >= 3), top-down binary splits maximizing the chi-square between classes (first CA axis init + iterative reassignment, max ~10 classes), class profiles with signed specificities, representative UCI, CA forms x classes, CSV export. Not a k-means.

Dependencies: only scipy is now declared explicitly in requirements.txt (it was already packaged via the PyInstaller specs through scikit-learn); numpy/matplotlib/networkx/pandas were already dependencies. No spaCy, no embedded R.

i18n: all visible strings go through _(); new msgids were appended to qualcoder.pot and all .po files (i18n + other_languages), with French translations in fr.po, and fr.mo recompiled (same semantics as rebuild_lang.py --compile).

Testing

  • 91 unit tests, no GUI: PYTHONPATH=src python3 -m unittest tests.test_irastats_{corpus,text,lexicon,descstats,specificites,iramuteq,similarity,ca,reinert} — all OK. Synthetic inputs with hand-computed expected values (chi2, Jaccard, phi2, CA inertia, Reinert pure-class recovery on a two-vocabulary corpus, determinism).
  • flake8 --builtins=_ --select=E9,F63,F7,F82 clean on all touched files (same selection as CI); python -m py_compile on all touched modules.
  • Existing Reports functionality untouched: new UI is behind the new submenu; report_codes.py change is a pure refactor to the shared iramuteq_token (same output).
  • CI (python -m unittest discover tests/, full app with Qt) should be run on this PR; the sandbox used here has no Qt system libraries, so GUI launch was verified by compile/flake8 only.

Tested on: Python 3.12, Linux (sandbox without Qt libs); CI runs Python 3.14 + Qt6.

AI tool usage

AI assistance level: 5 - Almost entirely AI-generated, reviewed and tested by me.

Tools used and for what:

  • Mistral Vibe (this agent): wrote the irastats package, the dialog, the tests, i18n updates and docs from the task specification; all code reviewed and all unit tests executed locally.

  • I understand every line of this PR and can explain it during review.

Suggested upstream PR plan (short commit series)

The branch vibe/irastats-3344e3 already contains exactly this series, one feature per commit, each leaving the app launchable and tested:

  1. a1c1157f Add irastats package skeleton: analysable corpus, text normalisation, sparse lexical table
  2. 8b1daaa9 Add descending text statistics (IRaMuTeQ 'rapport descendant') with CSV/HTML export
  3. 2a8d7071 Add chi-square specificities (IRaMuTeQ) with signed values, p-values and CSV/HTML export
  4. 230f3523 Add IRaMuTeQ corpus export from the text statistics dialog
  5. acc85643 Add similarity analysis (co-occurrence graph) with networkx and a non-blocking matplotlib window
  6. bf525e92 Add correspondence analysis (CA/AFC) by SVD, with factor map and CSV/PNG export
  7. 596b73f0 Add Reinert descending hierarchical classification (CHD) - the core of IRaMuTeQ
  8. d60ea4b4 Document the IRaMuTeQ-style text statistics in the README

Suggested upstream submission: either this single PR, or split into PRs 1-2 (pipeline + descending stats), 3 (specificities), 4 (IRaMuTeQ export), 5-6 (graph + CA), 7 (Reinert) in that order, each referencing the previous one.

mistral-vibe and others added 26 commits November 21, 2026 22:57
… sparse lexical table

F0 of the IRaMuTeQ-style text statistics pipeline:
- new pure-Python package src/qualcoder/irastats (no Qt imports, unit-testable):
  corpus.py builds segments {text, variables:{code, case, document, attributes}}
  from the project database via app.conn (coded segments and/or whole documents);
  text.py tokenises, lowercases, removes punctuation, applies built-in ISO
  stopwords (qualcoder.stopwords) plus an editable custom file, and an optional
  light suffix stemming; lexicon.py builds the sparse forms x segments table
  (scipy.sparse) with active forms (min frequency / explicit list) vs
  supplementary forms.
- new Reports submenu 'Text statistics (IRaMuTeQ methods)' opening
  DialogTextStats (code-built UI, Corpus tab: selection of files/cases/codes,
  language, custom stopwords, stemming, whole documents, corpus preview).
- scipy declared explicitly in requirements.txt (already packaged via the
  PyInstaller specs through scikit-learn).
- unit tests (no GUI): tests/test_irastats_{corpus,text,lexicon}.py.
- i18n: new msgids appended to qualcoder.pot and all .po, French translations
  in fr.po, fr.mo recompiled; Release_notes.md entry.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…SV/HTML export

- irastats.descstats: total occurrences, distinct/active/supplementary forms,
  decreasing frequency table, hapax, and breakdown by a partition variable
  (code, case, document, file/case attribute); CSV row helpers.
- irastats.report_html: Qt-free HTML rendering (pages, tables, pos/neg classes)
  used for the report HTML.
- DialogTextStats gains a 'Text statistics' tab: min active-form frequency,
  partition variable combo, results table + HTML view, CSV and HTML export.
- tests: tests/test_irastats_descstats.py (deterministic synthetic corpus).
- i18n msgids added (pot + all .po, French translations, fr.mo recompiled);
  Release_notes.md updated.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…and CSV/HTML export

- irastats.specificites: classic chi2 = sum((obs-exp)^2/exp) on the 2x2 table
  form x modality with marginal totals (no continuity correction), signed value
  (+ over-represented / - under-represented), two-sided p-value with
  scipy.stats.chi2 (df=1), configurable probability threshold (default 0.05),
  results sorted from most to least specific.
- irastats.report_html.specificites_html: HTML report with pos/neg highlighting.
- DialogTextStats gains a 'Specificities' tab (partition variable, min frequency,
  probability threshold, results table, CSV/HTML export).
- tests: tests/test_irastats_specificites.py with hand-computed chi2 values.
- i18n msgids added (pot + all .po, French translations, fr.mo recompiled);
  Release_notes.md updated.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
- irastats.corpus: iramuteq_token / segment_to_iramuteq / format_iramuteq /
  export_iramuteq write the corpus in the IRaMuTeQ text format (one
  '**** *code=... *cas=... *doc=... *<attr>=...' block per segment); coded
  segments only, or plus whole documents when requested.
- DialogTextStats Corpus tab: new 'Export IRaMuTeQ' button.
- report_codes.py: the existing IRaMuTeQ export now imports the shared
  iramuteq_token helper from irastats.corpus (output unchanged).
- tests: tests/test_irastats_iramuteq.py.
- i18n msgids added (pot + all .po, French translations, fr.mo recompiled);
  Release_notes.md updated.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…-blocking matplotlib window

- irastats.similarity: co-occurrence counts within segments, configurable
  association measure (Jaccard index by default, or chi2/phi-squared),
  adjustable edge threshold, networkx graph, matplotlib Figure (force-directed
  layout, node size proportional to frequency, edge width to similarity, top
  forms annotated). Pure Python, no pyplot backend needed.
- DialogTextStats gains a 'Similarity graph' tab; the graph is shown in a
  non-blocking DialogFigure (FigureCanvasQTAgg + Save PNG) and can be exported
  as PNG.
- tests: tests/test_irastats_similarity.py (hand-computed Jaccard and phi2).
- i18n msgids added (pot + all .po, French translations, fr.mo recompiled);
  Release_notes.md updated.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…PNG export

- irastats.ca: correspondence_analysis (SVD of standardized residuals, numpy
  only) with eigenvalues, inertia, principal coordinates, masses,
  contributions and cos2 for rows and columns; lexical_table_by_variable to
  aggregate the lexical table into forms x modalities; plot_ca factor map
  (point size proportional to frequency, top contributive forms annotated);
  ca_coordinate_rows for CSV export.
- DialogTextStats gains a 'Correspondence analysis' tab (columns: segments or a
  partition variable), eigenvalues table, non-blocking matplotlib factor map,
  CSV coordinates and PNG export.
- tests: tests/test_irastats_ca.py (hand-computed inertia/chi2, 2x2 symmetric
  case, zero-mass rows).
- i18n msgids added (pot + all .po, French translations, fr.mo recompiled);
  Release_notes.md updated.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…f IRaMuTeQ

- irastats.reinert: UCI segmentation (~40 occurrences, bounded by strong
  punctuation, hard-cut for over-long sentences), forms x UCI matrix of active
  forms, CHD by top-down binary splits maximizing the chi-square between
  classes (Reinert 1983/1990: initialisation on the first CA axis of the
  sub-matrix, then iterative single-UCI reassignment until stabilisation -
  not a k-means), stop criteria (2*min_class_size UCI, max_classes).
  Outputs: class count/sizes, classification chi2 with df and chi2/df ratio,
  class profiles (signed chi-square specificities), most representative UCI per
  class, and a CA of forms x classes. IRaMuTeQ defaults (UCI ~40, <=10 classes,
  active forms freq >= 3) are adjustable.
- DialogTextStats gains a 'Reinert classification' tab with class tree, profile
  table, representative UCI, CA forms x classes map (non-blocking matplotlib),
  CSV export.
- tests: tests/test_irastats_reinert.py (deterministic two-vocabulary corpus:
  pure classes recovered, chi2 values, profiles, determinism, max_classes).
- i18n msgids added (pot + all .po, French translations, fr.mo recompiled);
  Release_notes.md updated.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
New 'Textual statistics (IRaMuTeQ methods)' section describing the Reports
submenu, the irastats package and each analysis (descending statistics,
specificities, CA, similarity graph, Reinert CHD, IRaMuTeQ export).

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
The .po files (src/qualcoder/i18n and other_languages) are left to the
translation workflow (rebuild_lang.py / update_lang.yml): new msgids remain in
qualcoder.pot, and untranslated strings fall back to the English msgid at
runtime, so the app is unchanged.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
qualcoder.pot and the compiled .mo files are left untouched (regenerated by
rebuild_lang.py / the update_lang workflow). All new UI strings fall back to
their English msgid until translations are added.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…ports submenu and dialog title

The IRaMuTeQ name is kept only where it refers to the actual export format
('Export IRaMuTeQ' button) and in the documentation.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
- irastats.reinert.draw_dendrogram: matplotlib Figure of the binary
  classification tree (leaves = classes labelled with id and UCI count,
  internal nodes at height = chi2 of the split), pure Python, no backend.
- DialogTextStats Reinert tab: new 'Dendrogram' button opening the figure in a
  non-blocking DialogFigure (with Save PNG).
- tests: dendrogram structure assertions (lines = 4*(k-1), class labels).
- README and Release_notes mention the dendrogram.
- No .po/.pot/.mo changes (left to the translation workflow).

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…arity)

- irastats.similarity: detect_communities (Louvain on the weighted graph, seed
  fixed, node attribute 'community') and halo_neighbors (BFS radius 1);
  draw_similarity_graph colors nodes by community and draws a dashed halo
  circle around a selected form and its neighbors.
- DialogTextStats similarity tab: 'Detect communities (Louvain)' checkbox and
  a halo form combo; community list shown under the graph; PNG export unchanged.
- tests: two-cluster graph -> exactly 2 communities; halo radius 1/2 on a path
  graph; figure with community colors and one halo patch.
- README and Release_notes updated. No .po/.pot/.mo changes.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…unused import

The action is now toggled with the other Reports actions on project
open/close, so the dialog cannot be opened without a database connection.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
hide_menu_options() is called in __init__ before init_ui() creates the
lexicometry menu action, so setEnabled() raised AttributeError at startup.
Guard both toggles with hasattr().

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…ers, Reinert IndexError, PNG export crash

- Reports menu: 'Lexicometry (text statistics)' is now a direct action
  inserted below Charts (no submenu).
- IRaMuTeQ export: append .txt to the chosen file name when missing.
- Lexical table is rebuilt from the database on every Calculate, and the
  partition variable combos are refreshed, so changing language/stopwords/
  stemming/include-documents/selection is actually taken into account; the CA
  'Segments' combo entry is preserved by the refresh.
- Reinert: best_binary_split realigned the CA first axis on the kept
  (non-zero) columns - zero-count UCI columns made labels shorter than the
  matrix and raised IndexError; regression test added.
- PNG export (similarity graph, CA factor map) now saves a freshly computed
  Figure instead of the one embedded in a closed DialogFigure, whose Qt canvas
  is deleted (RuntimeError: wrapped C/C++ object ... has been deleted).

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…ach class

- draw_dendrogram: leaf branches and labels take a per-class color (palette),
  each leaf is labelled 'class N (k UCI)' plus its top over-represented forms
  (class profile, valeur > 0 first); internal branches stay gray.
- class profiles are now sorted with over-represented forms first (was chi2
  only, which mixed over/under-represented forms at equal chi2).
- tests: dendrogram labels contain the per-class representative forms and
  per-class colors; README/Release_notes updated.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…rizontal word blocks in the dendrogram

- __main__.py: action_text_stats is now inserted in menuAnalysis just before
  actionView_Graph (was a direct entry in menuReports below Charts).
- draw_dendrogram: class labels are horizontal (rotation 0) and the most
  representative forms are listed as a block under each class label, one per
  line, as in the IRaMuTeQ dendrogram; the y-axis is extended below zero to
  leave room for the blocks.
- test: labels horizontal and forms in a block under the class label.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
[P1] run_reinert and the IRaMuTeQ export now always rebuild the corpus from the
current selection (they reused the segments built at dialog initialization).
[P1] _case_for_segment takes the selected case_ids into account, so a segment
belonging to several cases gets the attributes of the selected case only.
[P1] IRaMuTeQ export switched to the native documented format *variable_modality
with a restricted charset (*code_alpha, *cas_caseA, *case_sexe_F, ...), instead
of the '=' separator; tests and docs updated.
[P2] Reinert split acceptance now requires chi2 > 0 and both sides >=
min_class_size (no more 11/1 classes, no multi-class output for identical UCI).
[P2] Each class now carries a real chi2 (class vs rest, 2 x n_forms) shown in the
tree and CSV, plus split_chi2 (parent split); leaves no longer display 0.
[P2] plot_ca clamps the requested axes to the available ones, so a one-column or
one-class CA no longer raises IndexError.
Regression tests added for each point (102 tests OK).

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…ometry dialog

- new pure-Python module src/qualcoder/topic_model.py: sentence-transformers
  embeddings (lazy import, already a dependency via the AI features), clustering
  (HDBSCAN when the optional package is installed, else scikit-learn KMeans, else
  a numpy k-means fallback), class-based TF-IDF (c-TF-IDF) topic words, topic
  summary with representative segments, topic-size bar chart.
- DialogTextStats gains a 'BERTopic' tab: embedding model combo (default
  paraphrase-multilingual-MiniLM-L12-v2, plus the e5-large model downloaded by the
  AI setup), min documents per topic, top words per topic, results table, topic
  sizes chart (non-blocking matplotlib window), CSV export. Corpus is rebuilt from
  the current selection on every Calculate.
- scikit-learn declared explicitly in requirements.txt (already transitive via
  sentence-transformers); no new heavy/compiled dependency (no bertopic/umap/
  hdbscan packages). The PR description documents the optional upgrade path to
  the full BERTopic package.
- tests: tests/test_topic_model.py (deterministic synthetic embeddings, c-TF-IDF
  top words, noise label, ImportError path). 113 tests OK.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…e scikit-learn explicitly in requirements.txt

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…ent/attribute)

- topic_model.topic_by_variable: counts matrix modalities x topics (noise -1 and
  empty modalities excluded); plot_topic_distribution: stacked bar chart.
- BERTopic tab: 'Distribution by variable' combo (same variables as the other
  tabs, refreshed on each Calculate), distribution table under the topics table,
  'Topics x variable chart' button (non-blocking matplotlib window), and the
  distribution appended to the CSV export.
- tests: distribution matrix, noise/empty exclusion, chart. 116 tests OK.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
…uments / UCI ~40)

Decision on the PR open question: the coded segment stays the default unit in
QualCoder because the corpus is segment-based and the topic x code/case cross-tab
requires segment-level variables; whole documents (the canonical BERTopic unit)
and UCI chunking (~40 occurrences, recommended for long documents) are offered in
a combo. The chosen unit is shown in the info label and recorded in the CSV.
Also adds an end-to-end test of the full pipeline with mocked embeddings.
117 tests OK.

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
… very long forms

Co-authored-by: qwertygc <qwertygc@users.noreply.github.com>
Proposal: BERTopic tab (BERT-based topic modeling of the corpus)
@qwertygc
qwertygc merged commit 8de7f74 into master Nov 23, 2026
1 of 2 checks passed
@qwertygc
qwertygc deleted the vibe/irastats-3344e3 branch November 23, 2026 08:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants