"""Hypothetical independent parallel transport paths; not a pinhole flow solver."""
from pathlib import Path
import math,csv,json
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
OUT=Path(__file__).resolve().parent

def paths(f,r):
    if not 0<=f<=1 or r<1:raise ValueError('Fraction0..1 and flux ratio>=1 required')
    intact=1-f;degraded=r*f;total=intact+degraded
    return dict(degraded_area_fraction=f,degraded_flux_ratio=r,intact_normalized_flow=intact,degraded_normalized_flow=degraded,total_flow_relative_to_all_intact=total,degraded_share_of_total=degraded/total)
rows=[paths(float(f),r) for r in [10,100,1000] for f in np.linspace(0,.01,101)]
with (OUT/'parallel-paths.csv').open('w',newline='',encoding='utf-8') as f:
    w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
# Independent discrete area partition:10,000 equal cells, each contributes its assigned flux.
maxerror=0
for row in rows:
    n=10000;bad=round(row['degraded_area_fraction']*n)
    discrete=math.fsum([row['degraded_flux_ratio']]*bad+[1.]*(n-bad))/n
    maxerror=max(maxerror,abs(discrete-row['total_flow_relative_to_all_intact']))
    assert math.isclose(discrete,row['total_flow_relative_to_all_intact'],abs_tol=1e-12)
    assert math.isclose(row['intact_normalized_flow']+row['degraded_normalized_flow'],row['total_flow_relative_to_all_intact'])
for r in [1,10,100,1000]:
    assert paths(0,r)['total_flow_relative_to_all_intact']==1
    assert paths(1,r)['total_flow_relative_to_all_intact']==r
    assert math.isclose(paths(1/(r+1),r)['degraded_share_of_total'],.5)
    assert paths(.25,1)['total_flow_relative_to_all_intact']==1
meta={'title':'When a small weak region dominates a barrier','kind':'Hypothetical analytical two-path illustration; no material measurements','scope':'Independent parallel patches under the same fixed driving conditions, each with a prescribed uniform flux per area','formulas':{'total_flow':'Q=A[(1-f)*j_intact+f*j_degraded]','ratio':'r=j_degraded/j_intact','normalized_total':'Q/(A*j_intact)=1-f+r*f','degraded_share':'r*f/(1-f+r*f)','equal_contribution_fraction':'f=1/(r+1)'},'parameters':{'degraded_area_fraction_range':[0,.01],'fraction_points':101,'hypothetical_flux_ratios':[10,100,1000]},'rows':len(rows),'example':paths(.001,1000),'validation':{'independent_10000cell_sum_max_difference':maxerror,'component_additivity':True,'zero_and_full_fraction_limits':True,'equal_flux_ratio_no_change':True,'equal_contribution_fraction':True},'limitations':['Ratios10,100,1000 are chosen teaching inputs, not tested coating properties or measured defect leakage factors.','This is an area-weighted parallel-patch budget; it does not derive flux through a real hole from radius or thickness.','Fixed driving conditions, steady independent paths, no lateral diffusion, access resistance, edge effects, substrate limitation, sorption or depletion.','A real crack or pinhole may have different transport laws, geometry and interactions; area fraction alone need not predict leakage.','No adhesion, abrasion lifetime, skin compatibility, microbial reduction, disinfection, road traction or dust-removal efficacy is inferred.','All-intact normalization presumes positive intact flux; an exactly impermeable reference cannot define this ratio.'],'sources':[{'title':'NIST, Potential Stable Low-Permeation Rate Standard Based on Micro-machined Silicon','url':'https://tsapps.nist.gov/publication/get_pdf.cfm?pub_id=916339','scope':'Controlled aperture permeation context, not validation of an arbitrary coating flux ratio.'}]}
(OUT/'study.json').write_text(json.dumps(meta,indent=2)+'\n',encoding='utf-8')
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'axes.spines.top':False,'axes.spines.right':False})
fig,ax=plt.subplots(1,2,figsize=(11,4.7),constrained_layout=True)
for r,c in zip([10,100,1000],['#393f94','#087f8c','#b42e8d']):
    rr=[x for x in rows if x['degraded_flux_ratio']==r];xx=[100*x['degraded_area_fraction'] for x in rr]
    ax[0].plot(xx,[x['total_flow_relative_to_all_intact'] for x in rr],lw=2,color=c,label=f'Local flux ratio r = {r}')
    ax[1].plot(xx,[100*x['degraded_share_of_total'] for x in rr],lw=2,color=c,label=f'r = {r}')
ax[0].set(title='A  |  Total flow can rise sharply',xlabel='Degraded area (% of surface)',ylabel='Total flow / all-intact reference')
ax[1].set(title='B  |  A small region can carry most flow',xlabel='Degraded area (% of surface)',ylabel='Flow through degraded region (% of total)',ylim=(0,100));ax[1].axhline(50,ls=':',color='#777')
for a in ax:a.legend(fontsize=8);a.grid(alpha=.2)
fig.suptitle('Barrier continuity matters — a hypothetical parallel-path model',fontsize=14,weight='bold')
fig.supxlabel('Prescribed local flux ratios, identical driving conditions. These curves do not predict real pinhole leakage or protective efficacy.',fontsize=9)
for ext in ['png','svg','pdf']:fig.savefig(OUT/f'parallel-paths.{ext}',dpi=180)
print(json.dumps({'rows':len(rows),'example':meta['example'],'validation':meta['validation']}))
