@JohnHenckel/

Population and genetics

Nodejs

measure the degree of mixture of genetics over time

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
popsize = 10000;
pop = [];
pop_next = [];
overlap = 0;
gid = popsize;

// Initial population
for (let i = 0; i < popsize; ++i) {
    pop.push({id:i,f:[],anc:[i]});
}

// Generations...
for (g = 0; g < 50; ++g) {

    let m = 0;
    overlap = 0;

    // Births
    while (pop.length > 1) {
        let i = pick_person();
        make_children(i, pick_spouse(i));
        ++m;
    }

    pop = pop_next;
    pop_next = [];

    // Statistics
    console.log(g+','+pop[0].anc.length+','+overlap/m);
    //console.log('====',pop[0]);
    if (overlap == m) break;

    // Deaths
    while (pop.length > popsize) {
        pop.splice(pick_person(), 1);
    }
}
console.log('=============== THE END');
//console.log(pop);



function rand(x) {
    return Math.floor(Math.random() * x);
}

function pick_person() { 
    return rand(pop.length); 
}

function pick_spouse(i) {
    let j = i;
    for (let k=0; k<100; ++k) {
        j = pick_person();
        //if (j!=i && (k>90 || !close_relation(i,j))) return j;
        if (j!=i) return j;
    }
    return j;
}

function close_relation(i,j) {
    let n=4; // test 2=first cousin or closer
    for (let k=1; k<=n; ++k) {
        if (pop[i].f.length<k || pop[j].f.length<k || 
            pop[i].f[pop[i].f.length-k] == pop[j].f[pop[j].f.length-k]) {
            return true;
        }
    }
    return false;
}

function make_children(i,j) {
    // Collect stats
    let newanc = merge(pop[i].anc,pop[j].anc);
    let c = pop[i].anc.length + pop[j].anc.length;
    overlap += (c - newanc.length) / newanc.length;
    let f = pop[i].f.slice();
    f.push(pop[i].id);

    // Make some children
    let n = rand(5);  
    for (let k = 0; k < n; ++k) {
        pop_next.push({
            id: gid++, f:f, anc: newanc
        });
    }
    // Kill the parents
    pop.splice(i, 1);
    pop.splice(j>i?j-1:j, 1);
}

function merge(a, b) {
    let i=0;
    let j=0;
    let c = [];
    for (;;) {
        if (i == a.length) {
            if (j == b.length) return c;
            c.push(b[j++]);
        } else if (j == b.length || a[i] < b[j]) {
            c.push(a[i++]);
        } else {
            if (a[i] == b[j]) ++i;   // skip duplicates
            c.push(b[j++]);
        }
    }
}

function merge2(a, b) {
    var hash = {}, i;
    for (i=0; i<a.length; i++) {
        hash[a[i]]=true;
    } 
    for (i=0; i<b.length; i++) {
        hash[b[i]]=true;
    } 
    return Object.keys(hash);
}