#!/usr/bin/env python3
"""Experiment X2: does conditional entropy tell writing from non-writing?

    python3 pipeline/experiments/entropy-yardstick.py

Rao and colleagues (Science, 2009) argued the Indus signs are probably writing because their
conditional entropy (how predictable the next sign is from the one before) sits between rigid and
random sequences, where languages sit. Sproat (Computational Linguistics, 2010) answered that
non-linguistic sign systems can sit there too. This measures the same quantity, on open data:

  English     words of a public-domain English book (Project Gutenberg)
  shuffled    the same words in random order (same symbols, structure destroyed)
  DNA         codons (three-letter units) of the bacteriophage lambda genome (NCBI NC_001416)
  melody      the soprano line of Bach's chorales as pitch names (craigsapp/bach-370-chorales, Humdrum
              kern encodings): structured, rule-bound, and not language
  rigid       a sequence made by a fixed rule, so the next symbol is almost always certain

For each, H(next | previous) in bits over the N most frequent symbols, N = 20, 40, 60,
divided by log2(N) so sequences with different vocabularies sit on one scale (0 = rigid,
1 = random). Writes experiments/entropy-yardstick.json. Fixed seeds; rerun gives the same numbers.
"""
import collections, json, math, os, random, re, subprocess

HERE = os.path.dirname(os.path.abspath(__file__))
GUT = 'https://gutenberg.pglaf.org/1/3/4/1342/1342-0.txt'   # Pride and Prejudice
NCBI = ('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nuccore&id=NC_001416'
        '&rettype=fasta&retmode=text')

def get(url, name):
    p = os.path.join(HERE, '.cache-' + name)
    if not os.path.exists(p):
        open(p, 'wb').write(subprocess.run(['curl', '-sL', '--max-time', '120', url],
                                           capture_output=True).stdout)
    return open(p, encoding='utf-8', errors='ignore').read()

def cond_entropy(seq, n):
    top = {s for s, _ in collections.Counter(seq).most_common(n)}
    pairs = collections.Counter((a, b) for a, b in zip(seq, seq[1:]) if a in top and b in top)
    first = collections.Counter()
    for (a, _), c in pairs.items():
        first[a] += c
    total = sum(pairs.values())
    h = -sum(c / total * math.log2(c / first[a]) for (a, _), c in pairs.items())
    return h / math.log2(n)

text = get(GUT, 'pride.txt')
body = text.split('*** START')[1].split('*** END')[0]
words = re.findall(r"[a-z]+", body.lower())
fasta = get(NCBI, 'lambda.fasta')
dna = ''.join(l.strip() for l in fasta.splitlines() if not l.startswith('>'))
codons = [dna[i:i + 3] for i in range(0, len(dna) - 2, 3)]
CH = os.path.join(HERE, '.cache-chorales')
if not os.path.exists(CH):
    subprocess.run(['git', 'clone', '-q', '--depth', '1',
                    'https://github.com/craigsapp/bach-370-chorales', CH], check=True)
melody = []
for root, _, files in sorted(os.walk(CH)):
    for f in sorted(files):
        if not f.endswith('.krn'):
            continue
        for line in open(os.path.join(root, f), errors='ignore'):
            if line.startswith(('!', '*', '=')) or not line.strip():
                continue
            tok = line.rstrip('\n').split('\t')[-1]          # last spine: the soprano
            m = re.search(r'([a-gA-G]+[#-]*)', tok)
            if m and 'r' not in tok:
                melody.append(m.group(1))
rng = random.Random(1974)
shuffled = words[:]
rng.shuffle(shuffled)
rigid, s = [], 0
for _ in range(len(codons)):          # a cycle through 60 symbols, with one slip in fifty
    s = (s + 1) % 60 if rng.random() > 0.02 else rng.randrange(60)
    rigid.append(s)

assert len(words) > 100000 and len(dna) > 48000, (len(words), len(dna))
res = dict(sources=dict(english='Jane Austen, Pride and Prejudice, Project Gutenberg ebook 1342',
                        dna='Bacteriophage lambda, complete genome, NCBI NC_001416',
                        melody='J. S. Bach, 370 chorales, soprano line, Humdrum kern (github.com/craigsapp/bach-370-chorales)'),
           measure='H(next | previous) over the N most frequent symbols, divided by log2(N)',
           sizes=dict(english_words=len(words), dna_bases=len(dna), dna_codons=len(codons), melody_notes=len(melody), melody_pitches=len(set(melody))))
for n in (20, 40, 60):
    res[f'N={n}'] = {k: round(cond_entropy(v, n), 3) for k, v in
                     (('English', words), ('shuffled English', shuffled), ('DNA codons', codons), ('Bach melody', melody),
                      ('rigid rule', rigid)) if len(set(v)) >= n}  # a system with fewer than N symbols is not scored at N
json.dump(res, open(os.path.join(HERE, 'entropy-yardstick.json'), 'w'), indent=1)
print(json.dumps(res, indent=1))
