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