File size: 2,340 Bytes
ae853c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import random
import math
import colorsys


def _rgb_to_hsv(rgb):
    r, g, b = [c / 255.0 for c in rgb]
    return colorsys.rgb_to_hsv(r, g, b)


def inherit_numeric_trait(p1_alleles, p2_alleles, stab1, stab2):
    allele1 = random.choice(p1_alleles)
    allele2 = random.choice(p2_alleles)

    if not all(isinstance(a, (int, float)) for a in (allele1, allele2)):
        raise TypeError(f"Non-numeric alleles passed: {allele1}, {allele2}")

    offspring_alleles = (allele1, allele2)
    stability = (stab1 + stab2) / 2
    base = (allele1 + allele2) / 2
    noise_range = (1 - stability) * 2
    noise = random.uniform(-noise_range, noise_range)
    phenotype = max(0, base + noise)

    return offspring_alleles, phenotype, stability

def inherit_color_trait(p1_alleles, p2_alleles, stab1, stab2):
    allele1 = random.choice(p1_alleles)
    allele2 = random.choice(p2_alleles)

    offspring_alleles = (allele1, allele2)
    stability = (stab1 + stab2) / 2
    total_stab = stab1 + stab2 or 1
    w1 = stab1 / total_stab  # parent-1 weight

    h1, s1, v1 = _rgb_to_hsv(allele1)
    h2, s2, v2 = _rgb_to_hsv(allele2)

    # Blend hue on the colour wheel (vector mean = shortest arc) instead of
    # averaging RGB. Averaging RGB collapses opposite hues (e.g. orange + blue)
    # to gray/brown mud; a circular hue blend yields a new *vivid* hue instead.
    a1, a2 = h1 * 2 * math.pi, h2 * 2 * math.pi
    x = w1 * math.cos(a1) + (1 - w1) * math.cos(a2)
    y = w1 * math.sin(a1) + (1 - w1) * math.sin(a2)
    hue = (math.atan2(y, x) / (2 * math.pi)) % 1.0

    # Instability drifts the hue; saturation/value are kept high so offspring
    # read as a clear strain colour rather than washing out.
    hue = (hue + random.uniform(-1, 1) * (1 - stability) * 0.08) % 1.0
    sat = max(0.55, w1 * s1 + (1 - w1) * s2)
    val = max(0.70, w1 * v1 + (1 - w1) * v2)

    r, g, b = colorsys.hsv_to_rgb(hue, sat, val)
    expressed = (int(r * 255), int(g * 255), int(b * 255))

    return offspring_alleles, expressed, stability

def inherit_type(p1_alleles, p2_alleles, stab1, stab2):
    allele1 = random.choice(p1_alleles)
    allele2 = random.choice(p2_alleles)
    offspring_alleles = (allele1, allele2)
    stability = (stab1 + stab2) / 2
    selected = random.choice([allele1, allele2])
    return offspring_alleles, selected, stability