"""Derive 2,504-unrelated membership per sample from INFO/AC__unrel vs genotypes (derived, not a published list). stdin: CHROM POS AC_AFR AC_AFR_unrel AC_EUR AC_EUR_unrel AC_EAS AC_EAS_unrel [GT...] (biallelic SNVs). Constraint per (site, SP): AC_SP_unrel == sum over SP carriers of alt_count * [carrier unrelated]. Propagation: a constraint with exactly one carrier of unknown status fixes it (value must be 0 or its count).""" import sys, collections, json ped = [l.split() for l in open(sys.argv[1])][1:] samples = [l.strip() for l in open(sys.argv[2])] sp_of = {r[1]: r[6] for r in ped}; pop_of = {r[1]: r[5] for r in ped} SPS = ["AFR", "EUR", "EAS"] idx_sp = [sp_of[s] for s in samples] cons = []; bad = 0; sites = 0 for line in sys.stdin: p = line.rstrip("\n").split("\t"); sites += 1 gts = p[8:] car = collections.defaultdict(list) for i, g in enumerate(gts): n = g.count("1") if n: car[idx_sp[i]].append((i, n)) for k, sp in enumerate(SPS): tot, unrel = int(p[2+2*k]), int(p[3+2*k]); c = car.get(sp, []) if sum(n for _, n in c) != tot: bad += 1; continue if c: cons.append((unrel, c)) status = {} # i -> 1 unrel / 0 related evidence = collections.Counter(); conflicts = 0 changed = True; rounds = 0 while changed: changed = False; rounds += 1 for unrel, c in cons: known = sum(n for i, n in c if status.get(i) == 1) unk = [(i, n) for i, n in c if i not in status] rem = unrel - known if len(unk) == 1: i, n = unk[0] if rem == n: status[i] = 1; changed = True; evidence[i] += 1 elif rem == 0: status[i] = 0; changed = True; evidence[i] += 1 else: conflicts += 1 elif not unk and rem != 0: conflicts += 1 # final consistency check over all constraints with every carrier determined viol = sum(1 for unrel, c in cons if all(i in status for i, _ in c) and sum(n for i, n in c if status[i] == 1) != unrel) lab = {1: "unrel", 0: "related"} res = {s: lab.get(status.get(i), "undetermined") for i, s in enumerate(samples)} F = {r[1] for r in ped if r[2] == "0" and r[3] == "0"} cnt = collections.Counter((sp_of[s], v) for s, v in res.items()) pc = collections.Counter((pop_of[s], v, "founder" if s in F else "has_parent") for s, v in res.items() if pop_of[s] in ("YRI", "CEU", "CHB")) print(json.dumps({"sites": sites, "constraints": len(cons), "ac_inconsistent": bad, "rounds": rounds, "conflicts_during_propagation": conflicts, "violations_final": viol, "by_superpop": {f"{a}:{b}": v for (a, b), v in sorted(cnt.items())}, "by_pop_and_pedigree": {f"{a}:{b}:{c}": v for (a, b, c), v in sorted(pc.items())}}, indent=1)) with open(sys.argv[3], "w") as fh: fh.write("SampleID\tPopulation\tSuperpopulation\tstatus\tpedigree_founder\n") for s in samples: fh.write(f"{s}\t{pop_of[s]}\t{sp_of[s]}\t{res[s]}\t{int(s in F)}\n")