matter-embryogenesis / baseline_v1 /src /local_growth.py
PureOne's picture
Release Matter Embryogenesis v3.0.0: theory, code, data and audit
52fc221 verified
Raw
History Blame
7.34 kB
"""Coarse stochastic lattice demonstrator with finite-volume transport.
Not molecular dynamics, not a validated kTAM, and not proof of a finite chemical alphabet.
The same grammar is evaluated locally from inherited counters. Instruction copying is
ideal except in the explicitly labelled common-mode ablation. Lattice sites represent
porous computational modules. Maintained feed planes are an EXTERNAL apparatus resource.
"""
from dataclasses import dataclass, asdict
import numpy as np
from genome import evaluate, canonical
@dataclass
class Config:
n:int=16
dim:int=3
dt:float=0.1
steps:int=700
diffusivity:float=0.35 # lattice pitch^2 / abstract time
attachment:float=3.0
birth:float=0.015
repair:float=0.9
detection:float=0.96
repair_error:float=0.02
initial_error:float=0.12
transduction_error:float=0.015
common_mode:float=0.
dwell:float=4.
resource_cost:float=0.06
maintenance_cost:float=0.10
channel_spacing:int=5
hard_permeability:float=0.02
seed:int=0
def prior(a, axis, fill=0):
out=np.full_like(a,fill)
dst=[slice(None)]*a.ndim; src=dst.copy()
dst[axis]=slice(1,None); src[axis]=slice(None,-1)
out[tuple(dst)]=a[tuple(src)]
return out
def diffusion_step(c, permeability, D, dt):
"""Conservative no-flux faces. Harmonic conductance, positive CFL step."""
out=c.copy()
for ax in range(c.ndim):
a=[slice(None)]*c.ndim; b=a.copy(); a[ax]=slice(None,-1); b[ax]=slice(1,None)
a,b=tuple(a),tuple(b)
g=2*permeability[a]*permeability[b]/np.maximum(permeability[a]+permeability[b],1e-30)
flux=D*dt*g*(c[b]-c[a]); out[a]+=flux; out[b]-=flux
return out
def simulate(g,cfg):
if 2*cfg.dim*cfg.diffusivity*cfg.dt>1:
raise ValueError('Explicit diffusion CFL violated')
rng=np.random.default_rng(cfg.seed); shape=(cfg.n,)*cfg.dim
# 0 absent, 1 reversible, 2 hardened. Material 0 is sacrificial/void output.
state=np.zeros(shape,np.int8); mat=np.full(shape,-1,np.int8)
intent=np.zeros(shape,np.int8); age=np.zeros(shape); c=np.ones(shape)
coords=np.zeros(shape+(cfg.dim,),np.int32); time0=(0,)*cfg.dim
state[time0]=1; intent[time0]=int(evaluate(g,np.zeros(cfg.dim,dtype=int)))
mat[time0]=intent[time0]
reservoir=np.zeros(shape,bool)
for ax in range(cfg.dim):
sl=[slice(None)]*cfg.dim; sl[ax]=0; reservoir[tuple(sl)]=True
sl[ax]=-1; reservoir[tuple(sl)]=True
if cfg.channel_spacing:
# Fixed externally perfused planes, present at t=0, charged to apparatus.
sl=[slice(None)]*cfg.dim; sl[0]=slice(0,None,cfg.channel_spacing)
reservoir[tuple(sl)]=True
attach_count=1; repair_count=0; repair_attempts=0; fuel_proxy=0.
supply=0.; consumed=0.; waste=0.; trace=[]; post_transduction=0
for step in range(cfg.steps):
permeability=np.where(state==2,cfg.hard_permeability,1.)
c=diffusion_step(c,permeability,cfg.diffusivity,cfg.dt)
supply+=float(np.sum(1-c[reservoir])); c[reservoir]=1.
before=state.copy(); candidate=np.zeros(shape,bool)
inherited=np.zeros_like(coords)
for ax in range(cfg.dim):
available=(prior(before,ax)>0)&(before==0)&~candidate
pc=prior(coords,ax); pc[...,ax]+=1
inherited[available]=pc[available]; candidate|=available
# The seed's bound terminates growth even in a larger simulation vessel.
seed_bound=np.all(inherited < g.get('n',cfg.n),axis=-1)
take=candidate&seed_bound&(c>=cfg.resource_cost)&(rng.random(shape)<-np.expm1(-cfg.attachment*c*cfg.dt))
coords[take]=inherited[take]
if np.any(take):
intent[take]=evaluate(g,coords[take])
cm=rng.random(np.count_nonzero(take))<cfg.common_mode
# Corrupt both local specification and material: local checking cannot see it.
vals=intent[take]; vals[cm]=(vals[cm]+1)%3; intent[take]=vals
vals=intent[take].copy(); bad=rng.random(len(vals))<cfg.initial_error
vals[bad]=(vals[bad]+rng.integers(1,3,size=np.count_nonzero(bad)))%3
mat[take]=vals
state[take]=1; c[take]-=cfg.resource_cost
attach_count+=int(take.sum()); consumed+=float(take.sum()*cfg.resource_cost)
soft=state==1
damage=soft&(rng.random(shape)<-np.expm1(-cfg.birth*cfg.dt))
mat[damage]=(mat[damage]+rng.integers(1,3,size=damage.sum()))%3
# Syndrome compared against local specification, not analysis target.
wrong=soft&(mat!=intent)
fix=wrong&(c>=cfg.resource_cost)&(rng.random(shape)<-np.expm1(-cfg.repair*cfg.detection*c*cfg.dt))
repair_attempts+=int(fix.sum()); failed=fix&(rng.random(shape)<cfg.repair_error)
good=fix&~failed; mat[good]=intent[good]
repair_count+=int(good.sum()); c[fix]-=cfg.resource_cost
consumed+=float(fix.sum()*cfg.resource_cost); waste+=float(fix.sum()*cfg.resource_cost)
# Age is an access/developmental deadline; concentration also controls maturation.
age[soft]+=cfg.dt
lock=soft&(age>=cfg.dwell)&(c>=0.15)
state[lock]=2
defect=lock&(rng.random(shape)<cfg.transduction_error)
mat[defect]=(mat[defect]+rng.integers(1,3,size=defect.sum()))%3
post_transduction+=int(defect.sum())
metabolic=np.minimum(c,cfg.maintenance_cost*cfg.dt*(state==1))
c-=metabolic; consumed+=float(metabolic.sum())
fuel_proxy+=float((take.sum()+fix.sum()+lock.sum())*10.)
if step%10==0:
trace.append([step*cfg.dt,int((state>0).sum()),int((state==2).sum()),float(c.min()),repair_count])
if np.all(state==2): break
# Analysis-only target, constructed after dynamics finish.
analytic_coords=np.moveaxis(np.indices(shape),0,-1)
target=evaluate(g,analytic_coords); final=np.where(state==2,mat,-1)
target_occ=target>0; got_occ=final>0
intersection=np.logical_and(target_occ,got_occ).sum()
union=np.logical_or(target_occ,got_occ).sum()
errors=final!=target
result={'config':asdict(cfg),'genome':g,'program_bytes':len(canonical(g)),
'completed_fraction':float((state==2).mean()), 'material_fidelity':float((~errors).mean()),
'solid_material_fidelity':float(((final==target)&target_occ).sum()/max(1,target_occ.sum())),
'structural_iou':float(intersection/max(1,union)), 'defect_density':float(errors.mean()),
'growth_time':float((step+1)*cfg.dt),'repair_attempts':repair_attempts,'successful_repairs':repair_count,
'repair_overhead':float(repair_attempts/max(1,attach_count)), 'attachment_events':attach_count,
'transduction_defects':post_transduction,'feed_consumed':consumed,'feed_supplied':supply,
'waste_proxy':waste,'fuel_turnover_kBT_proxy':fuel_proxy,'min_concentration':float(c.min()),
'reservoir_site_fraction':float(reservoir.mean()),
'mass_balance_residual':float(np.prod(shape)+supply-consumed-c.sum()),
'temporary_counter_bits_per_site':int(cfg.dim*np.ceil(np.log2(cfg.n))),
'chemical_species_count':None,'implemented_output_labels':3,
'chemical_species_note':'Not compiled to chemistry; three labels are not three species.',
'trace':trace}
return result,{'target':target,'final':final,'state':state,'concentration':c,'counters':coords}