"""First Cell v2: conditional physical bookkeeping, not experimental prediction. No material constants, optical coefficients or quantum yields in this package are measurements of a First Cell apparatus. See README.md for validity limits. """ from __future__ import annotations import math from dataclasses import dataclass from scipy import stats import numpy as np VERSION = "firstcell-model-2.0.0" H, C, NA = 6.62607015e-34, 299792458.0, 6.02214076e23 def number(x, name, lower=0, strict=False): if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x): raise ValueError(f"{name}: finite number required") if x < lower or (strict and x == lower): raise ValueError(f"{name}: must be {'greater than' if strict else 'at least'} {lower}") return x def integer(x, name, minimum): number(x, name, minimum) if int(x) != x: raise ValueError(f"{name}: integer required") return int(x) def coefficient_from_decadic(A, path_mm, *, kind, scattering_mm_inv=None): """Convert absorption-only A, or extinction A under collimated assumptions. Extinction conversion requires a separately established scattering coefficient. This does NOT extract absorption/scattering from one ordinary spectrum. """ number(A, "A"); number(path_mm, "path", strict=True) a = A * math.log(10) / path_mm if kind == "absorption": return a if kind != "extinction" or scattering_mm_inv is None: raise ValueError("Extinction requires a separately established scattering coefficient") number(scattering_mm_inv, "scattering") if scattering_mm_inv > a + 1e-12: raise ValueError("Scattering exceeds the extinction coefficient") return max(0.0, a - scattering_mm_inv) def seed_from_beam(incident_mW, transmission, beam_area_mm2, cross_section_um2): """Uniform beam, small centered absorber: P_abs = local irradiance * C_abs. C_abs is an absorption cross-section, NOT a guessed geometric area. Scattered illumination and a Gaussian spatial profile are not modeled. """ number(incident_mW, "power"); number(transmission, "transmission") if transmission > 1: raise ValueError("Transmission must not exceed one") number(beam_area_mm2, "beam area", strict=True); number(cross_section_um2, "cross-section") ratio = cross_section_um2 * 1e-6 / beam_area_mm2 if ratio > 0.1: raise ValueError("Cross-section exceeds 10% of beam area: localized-absorber approximation rejected") return incident_mW * transmission * ratio def optical_ledger(incident_mW, absorption_mm_inv, scattering_mm_inv, path_mm, seed_position_fraction, seed_absorbed_mW): """First-pass power ledger with one discrete seed excluded from bath coefficients. Scattering is UNTRACKED after leaving the ballistic beam; it is not declared escaped energy. No multiple scattering, luminescence or window losses. Incident power means power just INSIDE the entry window. """ for x,n in [(incident_mW,"power"),(absorption_mm_inv,"absorption"), (scattering_mm_inv,"scattering"),(path_mm,"path")]: number(x,n) number(seed_position_fraction,"position") if seed_position_fraction > 1: raise ValueError("Position must be in [0,1]") ext = absorption_mm_inv + scattering_mm_inv tp = math.exp(-ext*path_mm*seed_position_fraction) ts = math.exp(-ext*path_mm*(1-seed_position_fraction)) available = incident_mW*tp if seed_absorbed_mW is None: return {"status":"incomplete", "seed_plane_ballistic_mW":available, "message":"Seed absorption unknown; full ledger unavailable"} number(seed_absorbed_mW,"seed absorption") if seed_absorbed_mW > available + 1e-12: raise ValueError("Seed absorption exceeds available ballistic power") after = max(0.0, available-seed_absorbed_mW) removed = incident_mW*(-math.expm1(-ext*path_mm*seed_position_fraction)) + after*(-math.expm1(-ext*path_mm*(1-seed_position_fraction))) bath = removed*absorption_mm_inv/ext if ext else 0.0 scatter = removed*scattering_mm_inv/ext if ext else 0.0 exit_power = after*ts return {"status":"scenario", "seed_plane_ballistic_mW":available, "bath_first_pass_absorbed_mW":bath,"seed_absorbed_mW":seed_absorbed_mW, "untracked_scattered_mW":scatter,"ballistic_exit_mW":exit_power, "closure_error_mW":incident_mW-bath-seed_absorbed_mW-scatter-exit_power} def thermal_sphere(seed_absorbed_mW, heat_fraction, radius_um, k_W_mK, ambient_C=25, phase_limit_C=100): """Steady isolated sphere in infinite constant-property conducting medium. Returns unknown for missing heat fraction/power. At phase limit, preserves a mathematical diagnostic but withholds a physical temperature prediction. The 10 K flag is a review heuristic, not a validated validity/safety threshold. """ number(radius_um,"radius",strict=True); number(k_W_mK,"conductivity",strict=True) number(ambient_C,"ambient",lower=-273.15,strict=True) number(phase_limit_C,"phase limit",lower=ambient_C,strict=True) if seed_absorbed_mW is None or heat_fraction is None: return {"status":"incomplete", "delta_T_K":None} number(seed_absorbed_mW,"seed power");number(heat_fraction,"heat fraction") if heat_fraction > 1: raise ValueError("Heat fraction must be in [0,1]") dt = seed_absorbed_mW*1e-3*heat_fraction/(4*math.pi*k_W_mK*radius_um*1e-6) status = "outside-model" if ambient_C+dt >= phase_limit_C else "review" if dt > 10 else "scenario" return {"status":status,"delta_T_K":None if status=="outside-model" else dt, "diagnostic_extrapolation_K":dt,"heat_power_mW":seed_absorbed_mW*heat_fraction} def thermal_interval(power_range, heat_fraction_range, radius_range, k_range): """Monotonic independent-input bounds, NOT a probabilistic confidence interval.""" for bounds,name in [(power_range,"power"),(heat_fraction_range,"heat fraction"), (radius_range,"radius"),(k_range,"conductivity")]: if len(bounds)!=2: raise ValueError("Two bounds required") for x in bounds: number(x,name,strict=name in ("radius","conductivity")) if bounds[0]>bounds[1]: raise ValueError("Reversed interval") if heat_fraction_range[1]>1: raise ValueError("Heat fraction exceeds one") lo=power_range[0]*1e-3*heat_fraction_range[0]/(4*math.pi*k_range[1]*radius_range[1]*1e-6) hi=power_range[1]*1e-3*heat_fraction_range[1]/(4*math.pi*k_range[0]*radius_range[0]*1e-6) return {"lower_K":lo,"upper_K":hi,"kind":"independent-input scenario bounds"} def adiabatic_bulk_rate(heat_power_mW,volume_mL,rho=997,cp=4181): for x,n in [(volume_mL,"volume"),(rho,"density"),(cp,"heat capacity")]: number(x,n,strict=True) number(heat_power_mW,"heat power") return heat_power_mW*1e-3/(volume_mL*1e-6*rho*cp)*3600 def chemistry_scenario(power_mW, wavelength_nm, phi, *, power_basis, yield_basis, volume_mL, duration_h, max_product_uM=None, loq_uM=None): """Linear photon accounting; no kinetics. Unknown phi is distinct from zero. Both basis fields must match: absorbed, incident, or effective. Users must verify that spectrum, reaction and yield definition fit the scenario. max_product is a user-supplied stoichiometric ceiling, not inferred chemistry. """ number(wavelength_nm,"wavelength",strict=True); number(volume_mL,"volume",strict=True) number(duration_h,"duration") if power_basis not in {"absorbed","incident","effective"} or power_basis!=yield_basis: raise ValueError("Photon power and quantum-yield denominator must match") if max_product_uM is not None: number(max_product_uM,"product ceiling") if loq_uM is not None: number(loq_uM,"LOQ",strict=True) if power_mW is None or phi is None: return {"status":"incomplete","rate_uM_h":None,"product_uM":None,"loq_time_h":None} number(power_mW,"photon-basis power");number(phi,"quantum yield") # Quantum yields >1 can occur for chain processes; do not impose a universal upper bound. photons_mol_s=power_mW*1e-3*wavelength_nm*1e-9/(H*C*NA) rate=phi*photons_mol_s*3600/(volume_mL*1e-3)*1e6 linear=rate*duration_h exceeded=max_product_uM is not None and linear>max_product_uM reachable=loq_uM is not None and rate>0 and (max_product_uM is None or loq_uM<=max_product_uM) return {"status":"ceiling-exceeded" if exceeded else "scenario", "rate_uM_h":rate, "linear_extrapolation_uM":linear,"product_uM":None if exceeded else linear, "loq_time_h":loq_uM/rate if reachable else None, "ceiling_time_h":max_product_uM/rate if max_product_uM is not None and rate>0 else None} @dataclass(frozen=True) class FactorialDesign: n_preparations: int measurements_per_preparation: int sd_preparation: float sd_measurement: float def __post_init__(self): integer(self.n_preparations,"preparations",2) integer(self.measurements_per_preparation,"measurements",1) number(self.sd_preparation,"preparation SD");number(self.sd_measurement,"measurement SD") if self.sd_preparation==self.sd_measurement==0: raise ValueError("Positive variance required") def power(self,effect,alpha=.05): number(effect,"absolute interaction magnitude") number(alpha,"alpha",strict=True) if alpha>=1:raise ValueError("alpha must be below one") variance=self.sd_preparation**2+self.sd_measurement**2/self.measurements_per_preparation se=2*math.sqrt(variance/self.n_preparations) df=4*(self.n_preparations-1) critical=stats.t.ppf(1-alpha/2,df) noncentral=effect/se return float(stats.nct.sf(critical,df,noncentral)+stats.nct.cdf(-critical,df,noncentral)) def required_preparations(effect,sd_preparation,sd_measurement,m=3,target=.8,alpha=.05,n_max=1000): number(effect,"effect",strict=True);number(target,"target",strict=True) if target>=1:raise ValueError("target must be below one") integer(n_max,"maximum n",2) for n in range(2,n_max+1): if FactorialDesign(n,m,sd_preparation,sd_measurement).power(effect,alpha)>=target:return n return None def simulate_power(design,effect,alpha=.05,repeats=20000,seed=20261022): """Simulation checks model arithmetic under its assumptions, not real validity.""" integer(repeats,"simulations",1); number(effect,"effect") rng=np.random.default_rng(seed);n=design.n_preparations;m=design.measurements_per_preparation df=4*(n-1);crit=stats.t.ppf(1-alpha/2,df);hits=0 for _ in range(repeats): preps=rng.normal(np.array([effect,0,0,0])[:,None],design.sd_preparation,(4,n)) observations=rng.normal(preps[:,:,None],design.sd_measurement,(4,n,m)) pm=observations.mean(2);cm=pm.mean(1) pooled=pm.var(1,ddof=1).mean();se=math.sqrt(4*pooled/n) hits+=abs((cm[0]-cm[1]-cm[2]+cm[3])/se)>crit p=hits/repeats return {"estimate":p,"simulation_se":math.sqrt(p*(1-p)/repeats),"simulations":repeats,"seed":seed}