# Quran pattern model A reproducible Python analysis of the Quran JSON already used by the Uthmanic visualization. It runs entirely locally with **Python 3.10 or newer, with no packages to install**. It does not change or upload anything to the website. ## Run From this folder: ```sh python quran_patterns.py analyze python quran_patterns.py find "فبأي آلاء ربكما تكذبان" python -m unittest discover -s tests -v ``` Open `results/report.html` for readable results. `results/analysis.json` records the input checksum, counting rules, leading results and the permutation test. CSV files contain the complete tables, in UTF-8 with a BOM for Arabic in Excel. The first command includes all three kinds of analysis: lexical repetition, numerical text measurements, and similarities between surahs. The default phrase search covers 2–5 consecutive words occurring at least three times. To change this: ```sh python quran_patterns.py analyze --min-n 2 --max-n 8 --min-count 4 --output results-longer ``` ## Mathematical model Represent each ayah as an ordered sequence of normalized word tokens: \[ A_{s,a}=(w_{s,a,1},\ldots,w_{s,a,L_{s,a}}). \] Here `s` is the surah, `a` the ayah, and `L` its word count. This is a model of the supplied text, not of every aspect of the Quran's meaning, pronunciation or manuscript structure. ### 1. Word-count matrix \[ C_{s,w}=\sum_{a,i}\mathbf{1}[w_{s,a,i}=w]. \] Rows represent surahs and columns represent exact normalized word forms. `surah_word_matrix.csv` stores the nonzero entries, so no large dense matrix is needed. Summing a column gives that word form's frequency across the corpus. `الله`, `والله`, `بالله` and `لله` are different word forms in this model. Their counts must not be described as a count of all forms of the same word or root. ### 2. Repeated phrases For a sequence `g` of `n` words: \[ F(g)=\sum_{s,a,i}\mathbf{1}[(w_{s,a,i},\ldots,w_{s,a,i+n-1})=g]. \] Only positions inside an ayah are eligible. Overlapping matches count separately. The output separately reports the number of occurrences, distinct ayahs, and distinct surahs. A reference such as `55:13@1` means surah 55, ayah 13, starting at word 1. All positions refer to the analyzed plain-text token sequence. `repeated_ayahs.csv` groups entire ayahs that have identical normalized word sequences. Nested phrases are retained; a five-word repetition will also contribute its shorter subsequences. These rows are not independent discoveries. ### 3. Vocabulary similarity Let `S` be the number of surahs and `df(w)` the number containing word `w`. The chosen, smoothed TF-IDF variant is: \[ W_{s,w}=(1+\ln C_{s,w})\left(1+\ln\frac{S+1}{df(w)+1}\right) \] for nonzero entries, and zero otherwise. Normalize each row to unit Euclidean length, then calculate: \[ \operatorname{similarity}(s,t)=\frac{W_s\cdot W_t}{\|W_s\|_2\|W_t\|_2}. \] The output includes all unordered surah pairs and the shared words contributing most to each score. This is **lexical similarity**, not a semantic equivalence or an interpretation of the surahs. Common function words remain included. Length normalization reduces direct length effects, but vocabulary size and other corpus differences can still affect results. The approach follows the vector-space model described in the [Stanford information retrieval textbook](https://nlp.stanford.edu/IR-book/html/htmledition/tf-idf-weighting-1.html); the exact smoothing and logarithms used here are defined above. ### 4. Numerical measurements and verse order For each ayah and surah, the tool measures word count, retained letter count and vocabulary size. It also exports final word frequencies. Final spelling is not a phonetic rhyme analysis. Type/token ratio and Shannon word entropy are descriptive measurements, not measures of spiritual or literary quality; type/token ratio is strongly length-dependent. For the order check, center each ayah's word count within its own surah, `z(s,a) = L(s,a) - mean(L(s,*))`. Define: \[ r_1=\frac{\sum_s\sum_{a=1}^{n_s-1}z_{s,a}z_{s,a+1}}{\sum_s\sum_{a=1}^{n_s}z_{s,a}^{2}}. \] Single-ayah groups are excluded. This pools a lag-one autocorrelation structure across surahs without ever joining two different surahs. The general autocorrelation construction is described by [NIST](https://www.itl.nist.gov/div898/handbook/eda/section3/eda35c.htm); the separate centering and pooling are explicit choices of this implementation. The null model shuffles the lengths independently **inside each surah**, preserving each surah's number of ayahs, mean and length distribution. Its exact expected statistic is: \[ E_0[r_1]=-\frac{\sum_s(\sum_a z_{s,a}^2)/n_s}{\sum_{s,a}z_{s,a}^2}. \] With `B` seeded shuffles, the two-sided Monte Carlo comparison is: \[ p=\frac{1+\#\{b:|r_b-E_0[r_1]|\geq|r_{obs}-E_0[r_1]|\}}{B+1}. \] Defaults are 999 shuffles and seed 20261110. Thus the smallest reported p-value is 0.001, never zero. A small result describes this chosen statistic relative to this chosen exchangeability model. It does not establish an explanation for the pattern. No significance test is assigned to the thousands of word/phrase/similarity rows. If many hypotheses or normalization choices are searched, independent confirmation and multiple-testing control are needed. ```sh python quran_patterns.py analyze --permutations 9999 --seed 20261110 --output results-more-shuffles ``` ## Counting rules and source The included `data/quran.json` was copied from the existing project at `quran-visualization/data/quran.json`. The input has 6,236 numbered ayahs across 114 surahs. The program validates references, uniqueness, nonempty Arabic text and consecutive numbering. These structural checks do not independently certify the original dataset's editorial accuracy. The analysis uses **`aya_text_emlaey`**, not the Uthmani display field. It does the following: 1. Apply Unicode NFC before removing combining marks. This keeps decomposed hamza letters from accidentally losing their hamza. 2. Ignore combining marks, tatweel and formatting controls. 3. Retain Arabic letters; punctuation and spaces delimit word tokens. 4. Preserve أ، إ، آ، ٱ، ا as distinct letters by default; preserve ة/ه, ى/ي and hamza forms. 5. Keep attached clitics attached. Do not stem, infer roots or remove stopwords. 6. Analyze only the supplied ayahs. Do not insert extra introductory basmalas, headings or verse numbers. See [Python's Unicode documentation](https://docs.python.org/3/library/unicodedata.html) for the normalization and character categories used. Letter totals count retained codepoints, not phonemes, diacritical marks or letters implied by recitation. Counts differ with orthography, segmentation and basmala policy; do not present these totals as universal counts under all conventions. For an explicitly different normalization, use `--fold-alef`. Keep the results in a separate folder to compare assumptions: ```sh python quran_patterns.py analyze --fold-alef --output results-folded ``` ## Root annotations The source has no scholarly morphological annotations. Root analysis is therefore reported as unavailable by default. The program does not reuse the visualization's approximate root heuristic as authoritative data. To use a trusted, manually checked or scholarly annotation file, supply CSV columns: ```text surah,ayah,word_index,token,root ``` Use one row per annotated word position, with a 1-based index matching this tool's tokenization. A blank `root` means no assigned root. Tokens must align exactly after the chosen normalization. Misaligned or duplicate positions are rejected. Annotation correctness and the conversion from an external morphology source still require linguistic review. Partial annotation coverage is reported explicitly; counts cover only supplied annotations. ```sh python quran_patterns.py analyze --root-annotations roots.csv --root-source "Name/version of verified annotation source" --output results-roots ``` ## Outputs | File | Contents | |---|---| | `report.html` | Readable offline report | | `analysis.json` | Rules, checksum, summary, leading patterns and shuffle comparison | | `word_frequencies.csv` | Every word form and its ayah references | | `letter_frequencies.csv` | Counts under the stated codepoint convention | | `phrases.csv` | Repeated n-grams, support counts and every word position | | `repeated_ayahs.csv` | Identical normalized complete ayahs | | `verse_endings.csv` | Final-word frequencies and references | | `ayahs.csv` | Per-ayah measurements and original plain text | | `surahs.csv` | Per-surah statistics | | `surah_word_matrix.csv` | Sparse word-count and TF-IDF matrix | | `surah_similarity.csv` | All surah pairs and shared-word contributions | The same data, tool version, Python/Unicode versions, parameters and seed reproduce the outputs. The program records these in `analysis.json`; it does not add a changing timestamp. Use `--allow-partial` only when intentionally analyzing a subset: it disables the full-corpus and consecutive-numbering requirement, but still rejects invalid/duplicate references.