Spaces:
Sleeping

PhiGrowth / simcore.py
DazukaD's picture
Update simcore.py
61bea31 verified
Raw History Blame Contribute Delete
7.72 kB
# simcore.py v3
import math
import random
# ============================================
# PARÁMETROS DEL MODELO (ajustables)
# ============================================
CELL_RADIUS_1 = 12
CELL_RADIUS_2 = 16
# Distancia de división: aleatoria entre 4 y 6 diámetros (v3)
DIVISION_DISTANCE_MIN = 4.0
DIVISION_DISTANCE_MAX = 6.0
# Resolución y separación angular para evitar apelotonamientos
STEP_DEG = 5 # resolución de candidatos angulares
MIN_SEPARATION_DEG = 20 # separación mínima entre hijos del mismo padre (grados)
# Lista global de células
cells = []
# Índice de paso (para display / Fibonacci)
step_index = 0
# ============================================
# CLASE CELL
# ============================================
class Cell:
def __init__(self, x, y, t=1, parent=None):
self.x = x
self.y = y
self.t = t # 1 o 2 (nunca 3 visible)
self.parent = parent
# Para animación (interpolación desde start -> final)
self.start_x = x
self.start_y = y
self.final_x = x
self.final_y = y
self.anim_progress = 1.0 # 1.0 = en posición final
# ============================================
# FIBONACCI (para display)
# ============================================
def fibonacci_n(n):
if n <= 1:
return 1
a, b = 1, 1
for _ in range(n - 1):
a, b = b, a + b
return b
# ============================================
# UTILIDADES ANGULARES
# ============================================
def _deg_between(a, b):
"""Diferencia angular mínima entre dos ángulos en grados."""
diff = abs(a - b) % 360
return min(diff, 360 - diff)
def _existing_child_angles(parent):
"""Devuelve lista de ángulos (grados) de hijos ya posicionados respecto al parent."""
angles = []
for c in cells:
if c.parent is parent:
dx = c.final_x - parent.x
dy = c.final_y - parent.y
if dx == 0 and dy == 0:
continue
ang = math.degrees(math.atan2(dy, dx))
angles.append(ang)
return angles
def _choose_angle_nonoverlapping(parent, reserved_angles=None,
ang_min=30, ang_max=150,
step_deg=STEP_DEG, min_sep=MIN_SEPARATION_DEG):
"""
Elige un ángulo entre ang_min y ang_max:
- genera candidatos cada step_deg grados
- filtra los que estén a menos de min_sep de ángulos ya usados (existentes + reserved)
- si quedan candidatos, elige uno aleatorio
- si no quedan, elige el candidato que maximiza la mínima separación (fallback)
"""
if reserved_angles is None:
reserved_angles = []
used = _existing_child_angles(parent) + list(reserved_angles)
# generar candidatos
candidates = [ang_min + i * step_deg for i in range(int((ang_max - ang_min) / step_deg) + 1)]
# filtrar por separación mínima
good = []
for ang in candidates:
ok = True
for ua in used:
if _deg_between(ang, ua) < min_sep:
ok = False
break
if ok:
good.append(ang)
if good:
return random.choice(good)
# fallback: elegir candidato que maximiza la mínima separación
best_ang = None
best_minsep = -1
for ang in candidates:
minsep = min((_deg_between(ang, ua) for ua in used), default=360)
if minsep > best_minsep:
best_minsep = minsep
best_ang = ang
return best_ang if best_ang is not None else random.uniform(ang_min, ang_max)
# ============================================
# DIVISIÓN CELULAR (lógica solicitada)
# ============================================
def divide_cell(parent, reserved_angles=None):
"""
Crea una hija móvil con t=1:
- parent queda con t=2 (estática)
- la hija aparece a distancia aleatoria entre DIVISION_DISTANCE_MIN y DIVISION_DISTANCE_MAX diámetros
- ángulo entre 30° y 150°, evitando solapamientos
- reserved_angles: lista (mutable) donde se añadirá el ángulo elegido
"""
parent.t = 2
# Distancia aleatoria entre min y max (usando diámetro = 2 * CELL_RADIUS_2)
diameter = CELL_RADIUS_2 * 2
mult = random.uniform(DIVISION_DISTANCE_MIN, DIVISION_DISTANCE_MAX)
d = mult * diameter
chosen_angle = _choose_angle_nonoverlapping(parent,
reserved_angles=reserved_angles,
ang_min=30, ang_max=150,
step_deg=STEP_DEG, min_sep=MIN_SEPARATION_DEG)
angle_rad = math.radians(chosen_angle)
new_x = parent.x + d * math.cos(angle_rad)
new_y = parent.y + d * math.sin(angle_rad)
daughter = Cell(new_x, new_y, t=1, parent=parent)
daughter.start_x = parent.x
daughter.start_y = parent.y
daughter.final_x = new_x
daughter.final_y = new_y
daughter.anim_progress = 0.0
# reservar el ángulo para este padre en este paso
if reserved_angles is not None:
reserved_angles.append(chosen_angle)
return daughter
# ============================================
# ANIMACIÓN
# ============================================
def update_animation(animation_steps=10):
"""
Avanza la animación de todas las células.
animation_steps: número de frames para completar la interpolación (por llamada a update_animation).
"""
if animation_steps <= 0:
animation_steps = 1
delta = 1.0 / animation_steps
for c in cells:
if c.anim_progress < 1.0:
c.anim_progress += delta
if c.anim_progress > 1.0:
c.anim_progress = 1.0
# ============================================
# SIMULACIÓN (REGLAS POR PASO)
# ============================================
def step_simulation():
"""
Reglas por paso:
- En cada paso, todas las células incrementan su temporizador t en +1.
- Si una célula alcanza t == 3, DIVIDE inmediatamente:
* La célula original queda con t = 2 (estática).
* Se crea una nueva célula con t = 1 que se desplaza (según divide_cell).
- Nunca se muestra t == 3 (se divide en el mismo paso).
- step_index incrementa en 1 por cada llamada.
"""
global step_index
if not cells:
return
# Hacemos una copia de la lista para iterar sin problemas al añadir nuevas células
snapshot = list(cells)
# Primero incrementamos t para todas las células del snapshot
to_divide = []
for c in snapshot:
c.t += 1
# Si alcanza 3, marcar para dividir (no dejamos que muestre 3)
if c.t >= 3:
# Forzamos que la madre quede en 2 antes de dividir
c.t = 2
to_divide.append(c)
# Ahora procesamos las divisiones (cada madre genera una hija móvil)
# Reservas por parent para evitar ángulos repetidos en el mismo paso
angle_reservations = {}
for parent in to_divide:
reserved = angle_reservations.setdefault(parent, [])
daughter = divide_cell(parent, reserved_angles=reserved)
cells.append(daughter)
step_index += 1
# ============================================
# RESET
# ============================================
def reset_simulation(x0=0.0, y0=-400.0):
"""
Reinicia la simulación:
- Una célula inicial en (x0, y0) con t = 1
- Por defecto la inicial se sitúa más abajo (y0 = -620)
- step_index a 0
"""
global cells, step_index
cells = []
step_index = 0
c0 = Cell(x0, y0, t=1, parent=None)
c0.anim_progress = 1.0
cells.append(c0)