# metre


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## Light and heavy syllables

Sanskrit verse is measured in syllables, and each syllable is either
light (laghu, written `l`) or heavy (guru, written `g`). A syllable is
heavy when its vowel is long (ā, ī, ū, ṝ, e, ai, o, au), when it ends in
an anusvāra (ṃ) or a visarga (ḥ), or when two or more consonants follow
its vowel, even across a word break. A syllable at the very end of the
text that ends in a consonant is also heavy. Every other syllable is
light. A metre (chandas) is a rule about the pattern of these weights,
usually stated for one pāda, a quarter of the verse. The anuṣṭubh or
śloka of the epics has eight syllables in each pāda, and the mandākrāntā
of the Meghadūta has seventeen in a fixed pattern.

Finding a metre takes three steps.
[`deva2iast`](https://vedicreader.github.io/ganapati/metre.html#deva2iast)
writes Devanagari in IAST and keeps the vowel length that the weights
depend on.
[`syllables`](https://vedicreader.github.io/ganapati/metre.html#syllables)
divides the text into syllables and marks each one heavy or light, and
[`scan`](https://vedicreader.github.io/ganapati/metre.html#scan) gives
the same result as a string of `g` and `l`.
[`detect_meter`](https://vedicreader.github.io/ganapati/metre.html#detect_meter)
then compares that string with the known metres.

[`deva2iast`](https://vedicreader.github.io/ganapati/metre.html#deva2iast)
is a separate transliteration from
[`fold_token`](https://vedicreader.github.io/ganapati/sanskrit.html#fold_token)
in `ganapati.sanskrit`, because
[`fold_token`](https://vedicreader.github.io/ganapati/sanskrit.html#fold_token)
drops vowel length on purpose so that a search matches either spelling.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L28"
target="_blank" style="float:right; font-size:smaller">source</a>

### deva2iast

``` python
def deva2iast(
    s:str
)->str:
```

*Transliterate Devanagari to IAST, keeping the vowel length that
scansion needs.*

``` python
from ganapati.metre import deva2iast
```

``` python
assert deva2iast('श्रीमाता') == 'śrīmātā'
assert deva2iast('देवी') == 'devī'
assert deva2iast('कर्म') == 'karma'      # the virāma kills the implicit vowel
assert deva2iast('गम्') == 'gam'
assert deva2iast('दे॒वी') == 'devī'      # the Vedic tone mark is stripped first
```

[`syllables`](https://vedicreader.github.io/ganapati/metre.html#syllables)
takes IAST or Devanagari and returns `(syllable, heavy)` pairs. It reads
an aspirated consonant such as `kh` or `th` as one consonant and the
diphthongs `ai` and `au` as one vowel, so `atha` has two syllables, `a`
and `tha`. A consonant that closes one syllable is not counted again at
the start of the next: in `kaṃsa` the ṃ belongs to `kaṃ`, which makes it
heavy. [`scan`](https://vedicreader.github.io/ganapati/metre.html#scan)
gives the pattern as a string, and
[`mora_weights`](https://vedicreader.github.io/ganapati/metre.html#mora_weights)
gives each syllable’s length in mātrās, the unit of duration: one for a
light syllable and two for a heavy one.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L100"
target="_blank" style="float:right; font-size:smaller">source</a>

### mora_weights

``` python
def mora_weights(
    text:str
)->fastcore.foundation.L:
```

*Return the syllables as `(syllable, mātrās)` pairs, 2 for a heavy
syllable and 1 for a light one.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L96"
target="_blank" style="float:right; font-size:smaller">source</a>

### scan

``` python
def scan(
    text:str
)->str:
```

*Return the weight pattern of a string, `g` for each heavy syllable and
`l` for each light one.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L74"
target="_blank" style="float:right; font-size:smaller">source</a>

### syllables

``` python
def syllables(
    text:str
)->fastcore.foundation.L:
```

*Divide a Sanskrit string in IAST or Devanagari into syllables, as
`(syllable, heavy)` pairs.*

``` python
import unicodedata
from ganapati.metre import syllables, scan
```

``` python
assert [s for s, _ in syllables('atha')] == ['a', 'tha']      # `th` is one consonant
assert [s for s, _ in syllables('kaṃsa')] == ['kaṃ', 'sa']    # the ṃ closes the first, not opens the second
assert scan('gam') == 'g'                                     # a final cluster makes it heavy
assert scan('rāma') == 'gl'                                   # long ā, then a bare short a
assert scan('īśā vāsyam idaṃ sarvaṃ') == 'gggllggg'
assert scan(unicodedata.normalize('NFD', 'īśā vāsyam idaṃ sarvaṃ')) == 'gggllggg'   # decomposed IAST keeps its long vowels
```

## The gaṇas

The handbooks of prosody describe a metre with gaṇas. A gaṇa is a named
group of three syllables, and each of the eight possible groups of
weights has a one-syllable name: ya is `lgg`, ma `ggg`, ta `ggl`, ra
`glg`, ja `lgl`, bha `gll`, na `lll` and sa `llg`. A leftover single
heavy or light syllable is ga or la. The indravajrā, for example, is ta
ta ja ga ga, which spells out `gglgglglgg`.

`GANAS` holds that table.
[`gana_pattern`](https://vedicreader.github.io/ganapati/metre.html#gana_pattern)
turns a recipe of gaṇa names into its pattern, and
[`ganas`](https://vedicreader.github.io/ganapati/metre.html#ganas) does
the reverse, reading a pattern three syllables at a time. `METERS` lists
twenty common metres by their gaṇa recipes, the way the handbooks state
them, and `VRTTA_EXTRA` adds eighty more as plain patterns. The recipe
of every verse is stored in the search metadata, which is what
`by_meter` in `ganapati.lemma` searches on.

A second family of metres counts duration instead of syllables. In the
āryā and its relatives a light syllable is one mātrā and a heavy
syllable two, and each half of the verse is built from groups of four
mātrās. The first half of an āryā has 30 mātrās and the second 27,
because its sixth group shrinks to a single light syllable.
[`detect_matra_meter`](https://vedicreader.github.io/ganapati/metre.html#detect_matra_meter)
finds these metres by fitting the weights into the groups, rather than
by matching a fixed pattern.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L195"
target="_blank" style="float:right; font-size:smaller">source</a>

### metrical_text

``` python
def metrical_text(
    s:str
)->str:
```

*Remove the citations, verse numbers, headings, gloss lines and
bracketed notes that are printed with a verse but not scanned.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L117"
target="_blank" style="float:right; font-size:smaller">source</a>

### gana_pattern

``` python
def gana_pattern(
    recipe:str
)->str:
```

*Spell out a gaṇa recipe as a `g`/`l` pattern: `ta ta ja ga ga` gives
`gglgglglgg`.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L110"
target="_blank" style="float:right; font-size:smaller">source</a>

### ganas

``` python
def ganas(
    pattern:str
)->fastcore.foundation.L:
```

*Name the gaṇas of a `g`/`l` pattern three syllables at a time, with a
leftover one or two syllables as `ga` or `la`.*

[`metrical_text`](https://vedicreader.github.io/ganapati/metre.html#metrical_text)
removes everything printed beside a verse that should not be scanned:
citations, verse numbers between daṇḍas, headings, `>` gloss lines, and
anything in square brackets, such as an audio timing or a page number.
[`detect_meter`](https://vedicreader.github.io/ganapati/metre.html#detect_meter)
calls it first, so you can pass a verse as the source prints it.

`Meter` is an enum of every metre ganapati can name. Each member has an
ASCII name for code and the IAST name as its value, so
`Meter.MANDAKRANTA == 'mandākrāntā'`. Besides the metres above, it holds
two other kinds. In an ardhasamavṛtta the odd and even pādas follow
different patterns, and `ARDHASAMA` holds two of them, the viyoginī and
the puṣpitāgrā. `MATRA_METERS` holds the five mātrā metres of the āryā
family, and
[`matras`](https://vedicreader.github.io/ganapati/metre.html#matras)
counts the mātrās in a string.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L232"
target="_blank" style="float:right; font-size:smaller">source</a>

### matras

``` python
def matras(
    text:str
)->int:
```

*Count the mātrās of a string: one for each light syllable and two for
each heavy one.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L261"
target="_blank" style="float:right; font-size:smaller">source</a>

### detect_matra_meter

``` python
def detect_matra_meter(
    text:str, weights:list=None
):
```

*Find the āryā-family metre of a verse as
`AttrDict(name, halves, ganas, matras)`, or None if none fits.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L289"
target="_blank" style="float:right; font-size:smaller">source</a>

### detect_meter

``` python
def detect_meter(
    text:str
):
```

*Find the metre of one whole verse, as
`AttrDict(name, variant, syllables, per_pada, ganas, scan, matras, halves)`.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L278"
target="_blank" style="float:right; font-size:smaller">source</a>

### detect_ardhasama

``` python
def detect_ardhasama(
    text:str, weights:list=None
):
```

*Find the ardhasamavṛtta of a verse, whose odd and even pādas differ, as
`AttrDict(name, padas, ganas)`, or None.*

[`detect_meter`](https://vedicreader.github.io/ganapati/metre.html#detect_meter)
names the metre of a whole verse. It returns an `AttrDict` with the
metre’s `name` (a `Meter`, or None if nothing fits), the number of
[`syllables`](https://vedicreader.github.io/ganapati/metre.html#syllables),
the syllables `per_pada`, the gaṇas of the first pāda in
[`ganas`](https://vedicreader.github.io/ganapati/metre.html#ganas), the
full [`scan`](https://vedicreader.github.io/ganapati/metre.html#scan),
the total
[`matras`](https://vedicreader.github.io/ganapati/metre.html#matras),
and, for an āryā-type metre, the mātrās of each half in `halves`. It
returns None only for text with no syllables at all.

It tries the metres in a fixed order: first those with one pattern for
all four pādas, then upajāti, then the anuṣṭubh, then the
ardhasamavṛttas, and the mātrā metres last, so that a verse in a
fixed-pattern metre is never relabelled as an āryā. Two rules from the
tradition apply throughout. The last syllable of a pāda may be heavy or
light, whatever the pattern says. And upajāti is a licence rather than a
metre: a verse whose pādas mix the indravajrā and the upendravajrā. The
anuṣṭubh has its own rules, which fix only the fifth to seventh
syllables of each pāda, and `variant` says which form its odd pādas
take, the regular pathyā or one of the vipulā forms.

The examples are the first verse of the Meghadūta in mandākrāntā and
Gītā 1.1 in anuṣṭubh.

``` python
# Meghadūta 1.1, four pādas of seventeen syllables
mand = ('kaścit kāntāvirahaguruṇā svādhikārātpramattaḥ '
        'śāpenāstaṃgamitamahimā varṣabhogyeṇa bhartuḥ '
        'yakṣaścakre janakatanayāsnānapuṇyodakeṣu '
        'snigdhacchāyātaruṣu vasatiṃ rāmagiryāśrameṣu')
m = detect_meter(mand)
assert m.name is Meter.MANDAKRANTA and m.per_pada == 17
assert m.ganas == 'ma bha na ta ta ga ga'

# Gītā 1.1: the anuṣṭubh, and which of its variants
a = detect_meter('dharmakṣetre kurukṣetre samavetā yuyutsavaḥ '
                 'māmakāḥ pāṇḍavāścaiva kimakurvata sañjaya')
assert a.name is Meter.ANUSTUBH and a.variant == 'pathyā' and a.per_pada == 8

assert Meter.VASANTATILAKA.value == 'vasantatilakā'
assert Meter.MANDAKRANTA == 'mandākrāntā'
```

## Partial verses

[`detect_meter`](https://vedicreader.github.io/ganapati/metre.html#detect_meter)
needs a whole verse. Some sources give you one line at a time with no
daṇḍa to show where a verse ends: forced alignment of a recording,
speech recognition, and TEI files that store each line as a record. Two
functions work on such input.
[`match_pada`](https://vedicreader.github.io/ganapati/metre.html#match_pada)
takes one pāda, as text or as a `g`/`l` pattern, and returns every metre
whose pāda it fits.
[`group_verses`](https://vedicreader.github.io/ganapati/metre.html#group_verses)
joins the lines one, two and four at a time, runs
[`detect_meter`](https://vedicreader.github.io/ganapati/metre.html#detect_meter)
on each grouping, and keeps the grouping in which the most verses get a
name. It returns the lines per verse in `size`, the share of verses that
got a name in `coverage`, and the joined `verses` with their `meters`.
The four lines of the Meghadūta’s first verse give a size of 4; a
Rāmāyaṇa aligned half a verse at a time would give 2.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L340"
target="_blank" style="float:right; font-size:smaller">source</a>

### group_verses

``` python
def group_verses(
    lines, # the lines of a source, or one string of them
    sizes:tuple=(1, 2, 4), # lines per verse to try, in order
):
```

*Find how many lines make a verse by trying each size in `sizes`,
returning `AttrDict(size, coverage, verses, meters)`.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L332"
target="_blank" style="float:right; font-size:smaller">source</a>

### match_pada

``` python
def match_pada(
    pada:str
)->fastcore.foundation.L:
```

*List the metres whose pāda matches one pāda of text or one `g`/`l`
pattern.*

``` python
# one pāda of the Meghadūta, which detect_meter can only call unmatched
padas = ['kaścit kāntāvirahaguruṇā svādhikārātpramattaḥ',
         'śāpenāstaṃgamitamahimā varṣabhogyeṇa bhartuḥ',
         'yakṣaścakre janakatanayāsnānapuṇyodakeṣu',
         'snigdhacchāyātaruṣu vasatiṃ rāmagiryāśrameṣu']
assert detect_meter(padas[0]).name is None              # an AttrDict, never None
assert Meter.MANDAKRANTA in match_pada(padas[0])
assert match_pada('gglggllglgg') == [Meter.INDRAVAJRA]  # a g/l pattern reads the same way

# the four lines with no daṇḍa anywhere: the grouping has to be guessed
g = group_verses(padas)
assert g.size == 4 and g.coverage == 1.0
assert g.meters[0].name is Meter.MANDAKRANTA
assert group_verses([]).coverage == 0.0
```

``` python
# Kumārasambhava 4.1, viyoginī: the odd pādas are 10 syllables, the even 11
K41 = ('अथ मोहपरायणा सती विवशा कामवधूर्विबोधिता ।\n'
       'विधिना प्रतिपादयिष्यता नववैधव्यमसह्यवेदनम् ॥')
m = detect_meter(K41)
assert m.name == Meter.VIYOGINI and m.syllables == 42 and m.per_pada is None

# and its closing verse, puṣpitāgrā: 12 + 13
K446 = ('अथ मदनवधूरुपप्लवान्तं व्यसनकृशा परिपालयां बभूव ।\n'
        'शशिन इव दिवातनस्य लेखा किरणपरिक्षयधूसरा प्रदोषम् ॥')
assert detect_meter(K446).name == Meter.PUSPITAGRA

# a samavṛtta is still named by the pāda table, not relabelled by the new one
assert detect_meter(' '.join(padas)).name == Meter.MANDAKRANTA
```

## Checking scansion against a recording

A recording aligned line by line gives an outside check on the scansion.
If each line’s duration comes from
[`line_times`](https://vedicreader.github.io/ganapati/text.html#line_times)
and its mātrās from
[`matras`](https://vedicreader.github.io/ganapati/metre.html#matras),
the milliseconds per mātrā should stay roughly constant through a
recitation. A line far from the median rate was scanned wrongly or
aligned wrongly.

[`mora_rate`](https://vedicreader.github.io/ganapati/metre.html#mora_rate)
gives the median milliseconds per mātrā over a chunk’s timed lines, or
None if the chunk has no timings.
[`timing_check`](https://vedicreader.github.io/ganapati/metre.html#timing_check)
lists the timed lines whose rate is more than `tol` (35% by default)
away from that median, and it needs at least three timed lines to say
anything.
[`guru_laghu_ratio`](https://vedicreader.github.io/ganapati/metre.html#guru_laghu_ratio)
estimates how much longer a heavy syllable lasts than a light one, with
a least-squares fit over many timed lines. The texts on prosody say 2:1.
Measured over aligned Vedic recitation, the ratio comes out between 1.3
and 2.7.

The example builds timed lines from the four Meghadūta pādas at exactly
100 ms per mātrā, then slows the last line down so that
[`timing_check`](https://vedicreader.github.io/ganapati/metre.html#timing_check)
flags it.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L377"
target="_blank" style="float:right; font-size:smaller">source</a>

### guru_laghu_ratio

``` python
def guru_laghu_ratio(
    texts
)->float:
```

*Estimate how many times longer a heavy syllable lasts than a light one,
by least squares over timed lines, or None if the lines cannot tell.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L370"
target="_blank" style="float:right; font-size:smaller">source</a>

### timing_check

``` python
def timing_check(
    text:str, tol:float=0.35
)->fastcore.foundation.L:
```

*List the timed lines whose milliseconds per mātrā are more than `tol`
away from the chunk’s median, where audio and scansion disagree.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L366"
target="_blank" style="float:right; font-size:smaller">source</a>

### mora_rate

``` python
def mora_rate(
    text:str
)->float:
```

*Return the median milliseconds per mātrā over a chunk’s timed lines, or
None if it has none.*

``` python
from ganapati.text import time_marker
```

``` python
def timed(ps, rate=100):
    'Each pāda with an audio span that honours its morae at `rate` ms per mora.'
    rs = rate if isinstance(rate, list) else [rate] * len(ps)
    out, t = [], 0
    for p, r in zip(ps, rs):
        d = matras(p) * r; out.append(f'{p} {time_marker(t, t + d)}'); t += d
    return '\n'.join(out)

assert mora_rate(timed(padas)) == 100
assert timing_check(timed(padas)) == []
assert 1.99 < guru_laghu_ratio(timed(padas)) < 2.01     # a guru is two laghus, measured
assert timing_check(timed(padas, [100, 100, 100, 180]))[0].start == 8000  # the line out of proportion
assert mora_rate('\n'.join(padas)) is None              # no timings, nothing to measure
```

## Metre as metadata

[`verse_meta`](https://vedicreader.github.io/ganapati/metre.html#verse_meta)
is how metre gets into a search index. It finds the verses in a chunk
with
[`verse_units`](https://vedicreader.github.io/ganapati/metre.html#verse_units),
runs
[`detect_meter`](https://vedicreader.github.io/ganapati/metre.html#detect_meter)
on each, and returns a flat dict of strings. `meter` and `variant` name
the metres found. `gana` holds the gaṇa recipes, joined with underscores
so that each is one search token, and
[`pada`](https://vedicreader.github.io/ganapati/vyakarana.html#pada) the
syllables per pāda. `matra` gives the mātrās of each half of an
āryā-type verse, and
[`mora_rate`](https://vedicreader.github.io/ganapati/metre.html#mora_rate)
and `timing` appear when the chunk has audio timings. Keys with nothing
to say are left out, so an empty chunk gives `{}`. litesearch stores
this dict in each chunk’s `metadata` column and indexes it for full-text
search beside the content, so no new column is needed.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L398"
target="_blank" style="float:right; font-size:smaller">source</a>

### verse_meta

``` python
def verse_meta(
    text:str
)->dict:
```

*Return the metre facets of one chunk as the flat dict litesearch stores
in its `metadata`.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L394"
target="_blank" style="float:right; font-size:smaller">source</a>

### verse_units

``` python
def verse_units(
    text:str
)->fastcore.foundation.L:
```

*Split one chunk into its verses, since a chunk may hold several and
each has its own metre.*

``` python
meta = verse_meta(mand)
assert meta['meter'] == Meter.MANDAKRANTA
assert meta['pada'] == '17'                        # 17 syllables per quarter
assert meta['gana'] == 'ma_bha_na_ta_ta_ga_ga'     # the recipe, searchable as one token
assert verse_meta('') == {}
```

[`meter_name`](https://vedicreader.github.io/ganapati/metre.html#meter_name)
is the short form for a single verse: the metre’s name as a string, or
`''` when the verse has no metre ganapati knows or cannot be scanned at
all. It never raises, so it is safe to call on every verse of a large
corpus.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/ganapati/blob/main/ganapati/metre.py#L417"
target="_blank" style="float:right; font-size:smaller">source</a>

### meter_name

``` python
def meter_name(
    text:str
)->str:
```

*Return the name of the metre one verse scans as, or `''`, without ever
raising an exception.*

``` python
assert meter_name(mand) == 'mandākrāntā' and meter_name(K41) == 'viyoginī'
assert meter_name(padas[0]) == ''             # one pāda: nothing to name
assert meter_name('') == '' and meter_name('धृतराष्ट्र उवाच') == ''
```
