"""Reference experiments; synthetic inputs, not tests of AppInitDev Android apps.""" import argparse, csv, json, math, platform, sys, time, io, hashlib, os, sqlite3 from pathlib import Path from decimal import Decimal, localcontext import numpy as np from PIL import Image, ImageFilter, features from scipy import optimize, interpolate, integrate, signal, ndimage from skimage.metrics import structural_similarity from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305 from cryptography.exceptions import InvalidTag import importlib.metadata as md def patterns(): y,x=np.mgrid[:128,:128]; rng=np.random.default_rng(42) return {'gradiente':np.stack([x*2,y*2,(x+y)%256],-1).astype('uint8'), 'cuadricula':np.stack([((x//8+y//8)%2)*255,x*2,y*2],-1).astype('uint8'), 'ruido':rng.integers(0,256,(128,128,3),dtype=np.uint8), 'formas':np.stack([((x-64)**2+(y-64)**2<32**2)*255,(x>y)*255,(y>80)*255],-1).astype('uint8')} def image_metrics(a,b): mse=np.mean((a.astype(float)-b.astype(float))**2) return dict(psnr_db=None if mse==0 else round(10*math.log10(255**2/mse),6),ssim=round(float(structural_similarity(a,b,channel_axis=2,data_range=255)),6),identical=bool(mse==0)) def e001(): rows=[]; skipped=[] for n,a in patterns().items(): for fmt in ['PNG','JPEG','WEBP','AVIF','HEIF','JXL']: if fmt not in Image.SAVE: Image.init() if fmt not in Image.SAVE: skipped.append(fmt);continue for q in ([None] if fmt=='PNG' else [40,70,90]): f=io.BytesIO(); Image.fromarray(a).save(f,format=fmt,**({} if q is None else {'quality':q})); b=np.array(Image.open(f).convert('RGB')); rows.append(dict(pattern=n,format=fmt,quality=q,bytes=len(f.getvalue()),**image_metrics(a,b))) assert all(r['identical'] for r in rows if r['format']=='PNG') return rows,{'omitted_formats':sorted(set(skipped)), 'interpretation':'PNG reconstruyó todos los patrones exactamente. Los formatos con pérdida se comparan por tamaño y fidelidad, no por equivalencia de su parámetro quality. PSNR vacío significa MSE cero, no dato perdido.'} def e004(): rows=[];rng=np.random.default_rng(42) for n,a in patterns().items(): for sd in [5,15,30]: b=np.clip(a.astype(float)+rng.normal(0,sd,a.shape),0,255).astype('uint8') for method,c in [('ruidosa',b),('mediana',ndimage.median_filter(b,size=(3,3,1))),('gaussiano',ndimage.gaussian_filter(b.astype(float),sigma=(1,1,0)).astype('uint8'))]: rows.append(dict(pattern=n,sigma=sd,method=method,**image_metrics(a,c))) return rows,{'interpretation':'Piloto de filtros clásicos; no se ejecutó un modelo IA. Compare cada filtro contra su propia imagen ruidosa; el ruido y la textura cambian el resultado.'} def e009(): rows=[] for n,a in patterns().items(): low=Image.fromarray(a).resize((32,32),Image.Resampling.LANCZOS) for k in ['NEAREST','BILINEAR','BICUBIC','LANCZOS']: b=np.array(low.resize((128,128),getattr(Image.Resampling,k))); rows.append(dict(pattern=n,method=k,**image_metrics(a,b))) return rows,{'interpretation':'Comparación clásica 4x; no se ejecutó IA. Las imágenes aleatorias pierden información de alta frecuencia imposible de recuperar exactamente.'} def linear(x): return x/12.92 if x<=.04045 else ((x+.055)/1.055)**2.4 def e016(): rows=[] for k in range(101): t=k/100; encoded=1.055*t**(1/2.4)-.055 if t>.0031308 else 12.92*t # For neutral black-white, Oklab L is cube root of relative luminance. o=t**3; oe=1.055*o**(1/2.4)-.055 if o>.0031308 else 12.92*o rows.append(dict(t=t,srgb_encoded=t,srgb_luminance=linear(t),linear_encoded=encoded,linear_luminance=t,oklab_neutral_encoded=oe,oklab_luminance=o)) assert abs(rows[50]['linear_luminance']-.5)<1e-12 return rows,{'interpretation':'En el punto medio sRGB codificado produce luminancia relativa ~0.214, lineal 0.5 y Oklab neutro 0.125. Solo se estudia el eje negro-blanco; no hay pruebas perceptuales.'} def e018(): rows=[] for r in range(0,256,17): for g in range(0,256,17): for b in range(0,256,17): L=sum(c*linear(v/255) for c,v in zip([.2126,.7152,.0722],[r,g,b])); black=(L+.05)/.05; white=1.05/(L+.05); rows.append(dict(r=r,g=g,b=b,black=black,white=white,best=max(black,white),text='negro' if black>=white else 'blanco')) assert all(r['best']>=4.5 for r in rows) return rows,{'interpretation':'La selección del mayor contraste entre negro y blanco alcanza al menos 4.5:1 en esta cuadrícula; no equivale a una auditoría WCAG completa.'} def e019(): rows=[] for name,f,df,exact,br,x0,x1 in [('x²−2',lambda x:x*x-2,lambda x:2*x,math.sqrt(2),(1,2),1.,2.),('cos(x)−x',lambda x:math.cos(x)-x,lambda x:-math.sin(x)-1,.7390851332151607,(0,1),.5,1.),('x³−8',lambda x:x**3-8,lambda x:3*x*x,2.,(1,3),1.5,3.)]: for method,kwargs in [('bisect',{'bracket':br}),('newton',{'x0':x0,'fprime':df}),('secant',{'x0':x0,'x1':x1})]: s=optimize.root_scalar(f,method=method,xtol=1e-12,rtol=1e-12,maxiter=100,**kwargs);rows.append(dict(function=name,method=method,root=s.root,iterations=s.iterations,calls=s.function_calls,absolute_error=abs(s.root-exact),residual=abs(f(s.root)),converged=bool(s.converged))) assert all(r['converged'] and r['residual']<1e-9 for r in rows) return rows,{'interpretation':'Los tres métodos convergieron en los casos elegidos. Compare iteraciones y llamadas por función: Newton necesita derivadas y no garantiza convergencia global.'} def e020(): rows=[] with localcontext() as ctx: ctx.prec=60 for n in range(17): x=10**n; ref=(Decimal(x)+1).sqrt()-Decimal(x).sqrt() for name,v in [('directa',math.sqrt(x+1)-math.sqrt(x)),('racionalizada',1/(math.sqrt(x+1)+math.sqrt(x)))]:rows.append(dict(x=x,method=name,value=v,relative_error=float(abs(Decimal(v)-ref)/ref))) return rows,{'interpretation':'La forma racionalizada evita cancelar raíces cercanas. La referencia Decimal usa 60 cifras; no prueba estabilidad de todas las expresiones.'} def e021(): rows=[]; f=lambda x:1/(1+25*x*x);g=np.linspace(-1,1,2001) for n in [5,9,13,17,21]: for typ,x in [('equidistantes',np.linspace(-1,1,n)),('Chebyshev',np.sort(np.cos(np.pi*np.arange(n)/(n-1))))]: for m,p in [('baricentrica',interpolate.BarycentricInterpolator(x,f(x))),('spline',interpolate.CubicSpline(x,f(x)))]: e=p(g)-f(g);rows.append(dict(nodes=n,grid=typ,method=m,rmse=float(np.sqrt(np.mean(e**2))),max_error=float(max(abs(e))))) return rows,{'interpretation':'El caso de Runge muestra la dependencia del error respecto de nodos y método; no se extrapola a cualquier función.'} def e022(): rows=[] for name,f,end,exact in [('sin',np.sin,np.pi,2),('exp',np.exp,1,math.e-1)]: for n in [10,20,40,80]: x=np.linspace(0,end,n+1) for method,fn in [('trapecio',integrate.trapezoid),('Simpson',integrate.simpson)]: val=float(fn(f(x),x=x));rows.append(dict(function=name,intervals=n,method=method,estimate=val,error=abs(val-exact))) return rows,{'interpretation':'Para los integrandos suaves probados, el error disminuye al refinar la malla; Simpson se beneficia de suavidad y número par de intervalos.'} def e023(): rows=[] for n in range(1,16): h=10.**(-n) for method,v in [('adelante',(math.sin(1+h)-math.sin(1))/h),('central',(math.sin(1+h)-math.sin(1-h))/(2*h))]:rows.append(dict(h=h,method=method,value=v,error=abs(v-math.cos(1)))) return rows,{'interpretation':'Reducir h no mejora indefinidamente: la cancelación amplifica redondeo. El mínimo depende de función, método y precisión.'} def e029(): rows=[] for n in [10,100,1000,10000,100000]: ref=Decimal(n)/10 for method,v in [('sum',sum([.1]*n)),('fsum',math.fsum([.1]*n)),('Decimal',sum([Decimal('0.1')]*n))]: rows.append(dict(n=n,method=method,value=str(v),error=float(abs(Decimal(v)-ref)))) return rows,{'interpretation':'math.fsum reduce error de suma; Decimal representa exactamente 0.1 con el contexto usado. Python y plataforma afectan resultados.'} def e032(): rows=[];fs=48000;t=np.arange(fs)/fs for n in [2,4,8]: sos=signal.butter(n,1000,fs=fs,output='sos') for f in [200,1000,5000]: x=np.sin(2*np.pi*f*t);y=signal.sosfilt(sos,x);ratio=np.linalg.norm(y[fs//2:])/np.linalg.norm(x[fs//2:]);rows.append(dict(order=n,freq_hz=f,gain_db=float(20*np.log10(ratio)))) return rows,{'interpretation':'Los filtros Butterworth atenúan frecuencias por encima del corte y la pendiente aumenta con el orden. Se descartó la primera mitad para reducir transitorios.'} def e033(): rows=[];fs=48000 for n in [1024,4096,16384]: for f in [1000,1023.5]: x=np.sin(2*np.pi*f*np.arange(n)/fs) for method,w in [('rectangular',np.ones(n)),('Hann',np.hanning(n))]: p=abs(np.fft.rfft(x*w))**2; k=int(np.argmax(p)); outside=np.sum(p)-np.sum(p[max(0,k-1):k+2]);rows.append(dict(n=n,freq_hz=f,window=method,peak_hz=k*fs/n,error_hz=abs(k*fs/n-f),outside_fraction=float(outside/np.sum(p)))) return rows,{'interpretation':'Ventana y duración modifican resolución y fuga espectral; el máximo de un bin no es un estimador de frecuencia de precisión ilimitada.'} def e047(): rows=[] for n,a in patterns().items(): for rad in [0,1,2,4,8]: b=np.array(Image.fromarray(a).convert('L').filter(ImageFilter.GaussianBlur(rad))).astype(float); rows.append(dict(pattern=n,radius=rad,laplacian_variance=float(np.var(ndimage.laplace(b))))) return rows,{'interpretation':'La varianza del Laplaciano disminuye generalmente con el desenfoque, pero depende fuertemente del contenido de cada patrón; no se propone umbral universal.'} def e049(): rows=[] for name,cls in [('AES-GCM-256',AESGCM),('ChaCha20-Poly1305',ChaCha20Poly1305)]: a=cls(cls.generate_key(bit_length=256) if cls is AESGCM else cls.generate_key()); counter=0 for size in [1024,65536,1048576]: data=bytes([37])*size for rep in range(12): counter+=1; nonce=counter.to_bytes(12,'big');t=time.perf_counter_ns();c=a.encrypt(nonce,data,None); dt=time.perf_counter_ns()-t; assert a.decrypt(nonce,c,None)==data try:a.decrypt(nonce,c[:-1]+bytes([c[-1]^1]),None);raise AssertionError('accepted tampered tag') except InvalidTag: pass rows.append(dict(algorithm=name,bytes=size,repeat=rep,encrypt_ns=dt,mib_s=size/(2**20)/(dt/1e9),roundtrip=True,tamper_rejected=True)) return rows,{'interpretation':'Todos los round-trips y rechazos de etiquetas alteradas se comprobaron. Tiempos locales variables; ninguna medida prueba seguridad de Encrypted.'} def e050(): rows=[]; im=Image.fromarray(patterns()['gradiente']); ex=Image.Exif();ex[270]='Synthetic test marker' for name,opts in [('preservar',{'exif':ex}),('omitir',{})]: f=io.BytesIO();im.save(f,format='JPEG',**opts); r=Image.open(f);rows.append(dict(mode=name,bytes=len(f.getvalue()),exif_fields=len(r.getexif()),marker_present=270 in r.getexif(),width=r.width,height=r.height)) assert rows[0]['marker_present'] and not rows[1]['marker_present'] return rows,{'interpretation':'La exportación controlada omitió el marcador EXIF de prueba. No se verificaron otros contenedores de metadatos ni información visual.'} def e053(): rows=[];db=sqlite3.connect(':memory:');db.execute('create table files(id integer primary key,category integer,name text)');db.executemany('insert into files values(?,?,?)',((i,i%100,f"file-{i}") for i in range(100000)));q='select count(*) from files where category=?' for m in ['sin indice','con indice']: if m=='con indice':db.execute('create index ix on files(category)') plan=str(db.execute('explain query plan '+q,(7,)).fetchall()) for i in range(30): t=time.perf_counter_ns(); count=db.execute(q,(i,)).fetchone()[0];dt=time.perf_counter_ns()-t;assert count==1000;rows.append(dict(method=m,repeat=i,count=count,ns=dt,plan=plan)) db.close();return rows,{'interpretation':'La consulta devolvió 1000 filas en ambos escenarios; EXPLAIN permite verificar uso de índice. Base en memoria, no incluye costes de escritura ni disco móvil.'} def e054(): data=[b'a'*8,b'b'*8,b'a'*8,b'c'*9,b'b'*8,b'd'*9];rows=[] for i,a in enumerate(data): for j,b in enumerate(data[i+1:],i+1): rows.append(dict(i=i,j=j,same_size=len(a)==len(b),same_sha256=hashlib.sha256(a).digest()==hashlib.sha256(b).digest(),exact=a==b)) assert all(r['same_sha256']==r['exact'] for r in rows) return rows,{'interpretation':'El tamaño solo produce falsos candidatos en este conjunto. SHA-256 coincide con la igualdad exacta observada; esto no demuestra imposibilidad matemática de colisiones.'} def e067(): weights={'H':Decimal('1.008'),'C':Decimal('12.011'),'N':Decimal('14.007'),'O':Decimal('15.999'),'Na':Decimal('22.990'),'Cl':Decimal('35.45'),'Ca':Decimal('40.078')};rows=[] for formula,counts,ref in [('H2O',{'H':2,'O':1},'18.015'),('CO2',{'C':1,'O':2},'44.009'),('NaCl',{'Na':1,'Cl':1},'58.440'),('Ca(OH)2',{'Ca':1,'O':2,'H':2},'74.092'),('C6H12O6',{'C':6,'H':12,'O':6},'180.156'),('NH3',{'N':1,'H':3},'17.031')]: v=sum(weights[k]*n for k,n in counts.items());assert v==Decimal(ref);rows.append(dict(formula=formula,counts=str(counts),g_mol=str(v),reference=str(ref),error=0)) return rows,{'interpretation':'Se verifican sumas estequiométricas manualmente especificadas usando pesos redondeados. No se implementó parser de fórmulas, ni se verificó ElementalHub; los valores reales tienen incertidumbre.'} def e075(): rng=np.random.default_rng(42);t=np.arange(180);y=30+.12*t+6*np.sin(2*np.pi*t/7)+rng.normal(0,2,len(t)); rows=[] for i in range(60,len(y)): X=np.column_stack([np.ones(i),t[:i],np.sin(2*np.pi*t[:i]/7),np.cos(2*np.pi*t[:i]/7)]);b=np.linalg.lstsq(X,y[:i],rcond=None)[0];pred=np.array([1,i,np.sin(2*np.pi*i/7),np.cos(2*np.pi*i/7)])@b for m,v in [('ultimo',y[i-1]),('media7',y[i-7:i].mean()),('regresion estacional',pred)]:rows.append(dict(day=i,method=m,actual=float(y[i]),pred=float(v),abs_error=float(abs(y[i]-v)))) return rows,{'interpretation':'La regresión conoce la periodicidad usada para generar la simulación, lo que favorece ese modelo; no representa ventas reales ni garantiza generalización.'} def e089(): rows=[] for h in [1.5,1.7,1.8,2.]: for b in [18.4,18.5,24.9,25,29.9,30,40]: hd=Decimal(str(h));bd=Decimal(str(b));weight=bd*hd**2;v=weight/hd**2;category='bajo' if v