"""Burrows' Delta / Cosine Delta on function words + char n-gram cosine, with leave-one-chunk-out validation, then Satoshi attribution.""" import json, re, collections, random, math, sys import numpy as np from textutil import words, strip_urls_code random.seed(42); np.random.seed(42) CHUNK = int(sys.argv[1]) if len(sys.argv) > 1 else 2000 CAP = 40000 FW = """a about above after again against all almost along already also although always am among an and another any anyone anything are around as at be because been before being below between both but by can cannot could did do does doing done down during each either else enough even ever every few for from further had has have having he her here hers herself him himself his how however i if in instead into is it its itself just least less like many may me might mine more most much must my myself neither never no nobody none nor not nothing now of off often on once one only onto or other others otherwise our ours ourselves out over own perhaps quite rather really same several shall she should since so some somebody someone something sometimes somewhat still such than that the their theirs them themselves then there therefore these they this those though through thus to together too toward towards under unless until up upon us very was we were what whatever when whenever where whereas wherever whether which while who whoever whole whom whose why will with within without would yet you your yours yourself yourselves i'm it's don't doesn't isn't can't won't i've i'd i'll that's there's you're we're they're let's didn't wasn't aren't wouldn't couldn't shouldn't""".split() FWSET = set(FW) NAMES = re.compile(r"\b(satoshi|nakamoto|hal|finney|james|donald|ian|grigg|iang|zooko|wilcox|len|sassaman|wei|dai|ray|dillinger|bear|nick|szabo|gavin|andresen|mike|hearn|peter|todd|greg|gregory|maxwell|gmaxwell|jeff|garzik|pieter|wuille|sipa|luke|dashjr|craig|wright|martti|malmi|sirius|laszlo|bob|robert|hettinga|perry|metzger|gutmann|lynn|wheeler|ben|laurie|steve|bellovin|ed|gerck|eric|rescorla|bill|stewart|travis|adam|digsig|paul|roux|dan|kaminsky|effugas|daira|hopwood|david|sarah)\b", re.I) def prep(t): t = strip_urls_code(t) lines = [l for l in t.split('\n') if l.strip() and sum(c.isalpha() or c.isspace() for c in l) / max(1, len(l)) > 0.75] # drop short trailing sign-off lines while lines and len(lines[-1].split()) <= 3: lines.pop() return '\n'.join(lines) PRIO = {'list': 0, 'private': 1, 'forum:bitcointalk.org': 2, 'forum:p2pfoundation.ning.com': 2, 'blog': 3, 'essay': 4, 'lesswrong:comment': 5, 'paper': 6, 'doc': 7} def prio(d): if d['source'] == 'lesswrong:comment': return 5 return PRIO.get(d['register'], PRIO.get(d['source'], 8)) docs = json.load(open('corpus_docs.json')) seen = set(); D = [] for d in docs: if d['register'] == 'commit': continue h = hash((d['author'], d['text'][:300])) if h in seen: continue seen.add(h); D.append(d) POOL = ['finney', 'donald', 'grigg', 'back', 'zooko', 'sassaman', 'dai', 'dillinger', 'szabo', 'andresen', 'hearn', 'todd', 'maxwell', 'garzik', 'wuille', 'dashjr', 'wright', 'leroux', 'malmi', 'hanyecz', 'hettinga', 'kaminsky', 'hopwood', 'other:Perry E. Metzger', 'other:Peter Gutmann', 'other:Anne & Lynn Wheeler', 'other:Ben Laurie', 'other:Steven M. Bellovin', 'other:Ed Gerck', 'other:Eric Rescorla', 'other:Bill Stewart', 'other:Travis H.', 'other:Florian Weimer'] def chunks_for(author, docs_): ds = sorted([d for d in docs_ if d['author'] == author], key=lambda d: (prio(d), d['ts'] or '')) toks_all = []; regs = collections.Counter() for d in ds: w = words(prep(d['text'])) if not w: continue take = w[:max(0, CAP - len(toks_all))] toks_all += take; regs[d['register'] if d['source'] != 'lesswrong:comment' else 'lw-comment'] += len(take) if len(toks_all) >= CAP: break ch = [toks_all[i:i + CHUNK] for i in range(0, len(toks_all) - CHUNK + 1, CHUNK)] return ch, regs, len(toks_all) data = {}; meta = {} for a in POOL + ['satoshi']: ch, regs, n = chunks_for(a, D) if len(ch) >= 2: data[a] = ch; meta[a] = dict(words=n, chunks=len(ch), registers=dict(regs)) # Satoshi chunks by register (not capped), for attribution sat_by_reg = {} for reg in ('forum', 'private', 'list', 'paper'): toks = [] for d in sorted([d for d in D if d['author'] == 'satoshi' and d['register'] == reg], key=lambda d: d['ts'] or ''): toks += words(prep(d['text'])) sat_by_reg[reg] = [toks[i:i + CHUNK] for i in range(0, len(toks) - CHUNK + 1, CHUNK)] or ([toks] if len(toks) > 1000 else []) def fw_vec(tok): c = collections.Counter(w.lower() for w in tok); n = len(tok) return np.array([c[w] / n for w in FW]) def char_profile(tok): s = ' '.join(tok); s = NAMES.sub(' ', s.lower()); c = collections.Counter() for k in (3, 4): for i in range(len(s) - k + 1): c[s[i:i + k]] += 1 return c authors = [a for a in data if a != 'satoshi'] allchunks = [(a, ch) for a in data for ch in data[a]] X = np.array([fw_vec(ch) for _, ch in allchunks]); mu = X.mean(0); sd = X.std(0) + 1e-9 keep = np.argsort(-X.mean(0))[:150] # 150 most frequent function words in the pooled corpus Z = ((X - mu) / sd)[:, keep] lab = [a for a, _ in allchunks] # char n-grams: top 3000 by pooled frequency, relative freq then z cp = [char_profile(ch) for _, ch in allchunks]; tot = collections.Counter() for c in cp: tot.update(c) vocab = [g for g, _ in tot.most_common(3000)]; vi = {g: i for i, g in enumerate(vocab)} def cvec(c): v = np.zeros(len(vocab)); n = sum(c.values()) for g, k in c.items(): if g in vi: v[vi[g]] = k / n return v def distort(tok): top = set(FW[i] for i in keep) return [w if w.lower() in top else '*' * len(w) for w in tok] dcp = [char_profile(distort(ch)) for _, ch in allchunks]; dtot = collections.Counter() for c in dcp: dtot.update(c) dvocab = [g for g, _ in dtot.most_common(3000)]; dvi = {g: i for i, g in enumerate(dvocab)} def dvec(c): v = np.zeros(len(dvocab)); n = sum(c.values()) for g, k in c.items(): if g in dvi: v[dvi[g]] = k / n return v DC = np.array([dvec(c) for c in dcp]); dmu = DC.mean(0); dsd = DC.std(0) + 1e-9; DZ = (DC - dmu) / dsd C = np.array([cvec(c) for c in cp]); cmu = C.mean(0); csd = C.std(0) + 1e-9; CZ = (C - cmu) / csd def delta(z, cen): return np.mean(np.abs(z - cen)) def cosd(z, cen): return 1 - np.dot(z, cen) / (np.linalg.norm(z) * np.linalg.norm(cen) + 1e-12) METHODS = {'burrows_delta_fw150': (Z, delta), 'cosine_delta_fw150': (Z, cosd), 'char34gram_cosine_z': (CZ, cosd), 'char34gram_topic_masked_cosine': (DZ, cosd)} def centroids(M, excl=None, include=None): cen = {} for a in data: if include is not None and a not in include: continue idx = [i for i, l in enumerate(lab) if l == a and i != excl] if idx: cen[a] = M[idx].mean(0) return cen res = {} cand = [a for a in data] # validation includes satoshi as a known author too for m, (M, f) in METHODS.items(): top1 = top3 = n = 0; per = collections.defaultdict(lambda: [0, 0]) for i, a in enumerate(lab): cen = centroids(M, excl=i) if a not in cen: continue r = sorted(cen, key=lambda b: f(M[i], cen[b])) n += 1; top1 += r[0] == a; top3 += a in r[:3]; per[a][0] += r[0] == a; per[a][1] += 1 res[m] = dict(top1=top1 / n, top3=top3 / n, n=n, per_author={a: f'{v[0]}/{v[1]}' for a, v in per.items()}) # Satoshi attribution: Satoshi excluded from the candidate set; profiles from all chunks of each candidate def vec_for(tok, M): if M is Z: return ((fw_vec(tok) - mu) / sd)[keep] if M is DZ: return (dvec(char_profile(distort(tok))) - dmu) / dsd return (cvec(char_profile(tok)) - cmu) / csd att = {} for m, (M, f) in METHODS.items(): cen = centroids(M, include=[a for a in data if a != 'satoshi']) att[m] = {} for reg, chs in sat_by_reg.items(): if not chs: continue ranks = collections.defaultdict(list); wins = collections.Counter() for tok in chs: v = vec_for(tok, M); ds = {b: f(v, cen[b]) for b in cen}; order = sorted(ds, key=ds.get) wins[order[0]] += 1 for k, b in enumerate(order): ranks[b].append(k + 1) mean_d = {b: float(np.mean([f(vec_for(tok, M), cen[b]) for tok in chs])) for b in cen} att[m][reg] = dict(chunks=len(chs), nearest_counts=dict(wins.most_common()), mean_rank={b: round(float(np.mean(r)), 2) for b, r in sorted(ranks.items(), key=lambda kv: np.mean(kv[1]))}, mean_distance={b: round(v, 4) for b, v in sorted(mean_d.items(), key=lambda kv: kv[1])}) # all Satoshi registers pooled # cross-register validation: profile from register A, test register B regchunks = {} for a in data: for reg in ('list', 'forum', 'private', 'blog', 'essay', 'paper'): toks = [] for d in sorted([d for d in D if d['author'] == a and d['register'] == reg and d['source'] != 'lesswrong:comment'], key=lambda d: d['ts'] or ''): toks += words(prep(d['text'])) if len(toks) > CAP: break ch = [toks[i:i + CHUNK] for i in range(0, len(toks) - CHUNK + 1, CHUNK)] if len(ch) >= 1: regchunks[(a, reg)] = ch xres = {} for m, (M, f) in METHODS.items(): tot = ok = 0; detail = [] for (a, rb), chs in regchunks.items(): for ra in ('list', 'forum', 'private', 'blog', 'essay', 'paper'): if ra == rb or (a, ra) not in regchunks or len(regchunks[(a, ra)]) < 2: continue cen = centroids(M, include=[b for b in data if b != a]); cen[a] = np.mean([vec_for(t, M) for t in regchunks[(a, ra)]], 0) hits = 0 for t in chs: v = vec_for(t, M); r = min(cen, key=lambda b: f(v, cen[b])); hits += r == a tot += len(chs); ok += hits; detail.append(f'{a}: {ra}->{rb} {hits}/{len(chs)}') xres[m] = dict(accuracy=ok / tot if tot else None, n=tot, detail=detail) print('CROSS-REGISTER', m, xres[m]['accuracy'], tot, detail) BTC = ['hearn', 'todd', 'maxwell', 'garzik', 'andresen', 'wuille', 'dashjr', 'malmi', 'hanyecz', 'back'] PRE = ['finney', 'donald', 'grigg', 'back', 'zooko', 'sassaman', 'dillinger', 'szabo', 'dai', 'wright', 'leroux', 'hettinga', 'kaminsky', 'hopwood'] + [a for a in data if a.startswith('other:')] sub = {} for m, (M, f) in METHODS.items(): sub[m] = {} for nm, pool in (('bitcoin_era_pool', BTC), ('pre_bitcoin_cypherpunk_pool', PRE)): cen = centroids(M, include=pool); sub[m][nm] = {} for reg, chs in sat_by_reg.items(): if not chs: continue wins = collections.Counter(min(cen, key=lambda b: f(vec_for(t, M), cen[b])) for t in chs) sub[m][nm][reg] = dict(wins.most_common()) out = dict(chunk_words=CHUNK, cap_words=CAP, n_function_words=len(keep), function_words_used=[FW[i] for i in keep], meta=meta, validation=res, cross_register_validation=xres, satoshi_attribution=att, satoshi_nearest_within_subpools=sub) json.dump(out, open(f'stylo_results_{CHUNK}.json', 'w'), indent=1) for m in res: print(m, 'top1=%.3f top3=%.3f n=%d' % (res[m]['top1'], res[m]['top3'], res[m]['n'])) for m in att: for reg in att[m]: print(m, reg, att[m][reg]['chunks'], 'nearest:', att[m][reg]['nearest_counts'], '| top5 mean rank:', list(att[m][reg]['mean_rank'].items())[:6]) for m in sub: for nm in sub[m]: print('SUBPOOL', m, nm, sub[m][nm]) print('satoshi self-attribution (LOO):', {m: res[m]['per_author'].get('satoshi') for m in res})