Follow the results back to native GX-TXT jobs at 0 and 100 rpm, the original GNU Octave scripts, the output tables and the checks still outstanding.

Native does not mean that model code disappears

A reusable scientific environment retains mathematical definitions with explicit inputs, units, parameters, versions and output ownership. Here native means a genuine Viewer or registered project admitted inputs, executed a calculation and published through GX-TXT. GNU Octave can be the backend of a real native Job. Conversely, importing a standalone batch’s CSV does not retroactively make its computation native.

The supplied definitions let a researcher select sources and variables, parameter values and Fixed masks, domains and plot variants through supported controls. The program need not be rewritten for every comparison. A new equation outside those definitions still requires a coherent scientific model resource. The original English comments in the consulted scripts remain unchanged.

Tool Actual role What it does not establish
Digitizer Figure centres, image/axis calibration and curve/point identity Author raw data or unacquired error bars
Fitter, SafeFormula and registered Model Calibrations, all-fixed evaluations, requested-coordinate responses and residuals Automatic mechanism selection; native models can contain reusable code
Dataset Expression Unit-aware algebra, p_max and fractions on actual pH rows Dynamic simulation or measured flux
Worksheet Cross-source bindings, conversion, inventories/ratios and row lineage Invented observations or undisclosed time alignment
Mathematics Explorer Published symbolic/numerical sensitivities, including nine initial-pH components Measured local reactor conditions
Generic reaction editor and Script/Job Fresh ODE integration and multiple canonical tables Automatic identity of states and assays
Curve Viewer Comparison, axes/styles, editable Graph/Workspace An overlay does not rerun a fit or ODE

Documented transitions, not a blanket native claim

The legacy standalone V6 reduced and V7 fast-limit batches remain historical reference material. A later genuine native reduced Job, script-20261118T093245Z-4091642-1794994365236654, computed the 23-case study afresh using registered project elec_reduced_competing_scenarios. This is numerical reproduction of the same reviewed formulation within its scope, not historical CSV import or physical validation. The complete fast-limit protocol is not established completed; its evaluated scalar projections do not complete that study.

Gate1 formal balances and Gate2 manufactured neutral transport were already registered native calculations. The latter is not measured beaker transport. A separate genuine Python Job serialized Gate1 tables to CSV without scientific recalculation; some Gate2 presentation copies were offline serialization of existing native HDF5 values. Serialization and website copies are not additional simulations. The historical provenance map retains these distinctions; later completed generic runs are updated here.

The operational, S2 and H_P/H_L branches are not all repetitions of one analysis: sources, free parameters or assumptions change. Six chlorine transfers are fixed predictions, not refits. The accepted registered ODE Model was used through Fitter, not the later generic editor. The generic scripts subsequently executed the same operational two-pool equations for0/100rpm with already accepted parameter packs; they did not create another calibration.

Two actual generic-network Jobs

Case Completed Job, exit0 Declared grid Canonical tables
0rpm script-20261120T043918Z-2293038-1795149558474630 61times,0–1200s 9
100rpm script-20261120T064007Z-2529515-1795156807585422 151times,0–3000s 9

The four files below are exact copies from the frozen source revisions of both completed Jobs, pinned by the execution map. network_entry.m is the actual entrypoint; reaction_network.m, network_numeric.m and network_publish.m form its directly called helper chain. Fixed/reduced/fast siblings admitted in the same project are not labelled executed by these Jobs. Parameters belong to saved model resources and receipts, not constants inserted into the listings for this article.

The ODE reuses public Numeric and declared ode45. Tolerances apply to molar amounts and extents rather than directly to concentrations. Actual returned times are retained. Finiteness, declared positivity and numerical inventories are engineering checks; a full elemental balance is not claimed for operational pools without identified composition/charge. Independent analytical verification checks existing native trajectories rather than replacing them.

Consult the original executed scripts

Each listing starts collapsed and identifies filename, role, execution version and origin. Downloads retain original bytes and English comments. These are not0.2.6 forcing sources or uninstalled optimization candidates.

The collection also contains exact registered sources for actually invoked Gates, reduced Runner and scalar Models, deduplicated by byte identity. Historical UNEXECUTED comments remain verbatim: later Job receipts establish execution without rewriting source comments. Failed-attempt sources remain separately labelled in the technical archive, not accepted scientific results. A function’s presence does not prove every branch or projection was called. Legacy outside source files are not replaced with prepared candidates or relabelled verified native scripts.

network_entry.m — Generic actual entrypoint

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Generic0.2.5

script-20261120T043918Z-2293038-1795149558474630 COMPLETED exit0; script-20261120T064007Z-2529515-1795156807585422 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 32dbca680c1882d36474477c7c410e3c3cba99d3c6a55b6226f4ebf6e44e5143

% Generic data-only network workflow. Actual Viewer Bridge admits native Jobs.
gxtxt_api_require('NUMERIC_API_v1@1');
gxtxt_api_require('DOCUMENT_SOURCE_API_v1@1');
gxtxt_api_require('DATASET_PUBLICATION_API_v2@2');
ctx=gxtxt_context();q=ctx.parameters;source_receipt=struct();
if strcmp(q.mode,'import')
  if !isfield(ctx.inputs,'network'),error('Network:Source','Bind a canonical network text Dataset');endif
  source_receipt=gxtxt_api_call('DOCUMENT_SOURCE_API_v1','read',{struct('dataset_id',ctx.inputs.network.dataset_id,'limit',262144)});
  if !source_receipt.complete,error('Network:Source','Truncated network JSON cannot be imported');endif
  q.network_json=source_receipt.source;
endif
if numel(q.network_json)>262144,error('Network:Size','Network JSON exceeds 256 KiB');endif
network=jsondecode(q.network_json,'makeValidName',false);model=reaction_network('validate',network);
record=struct('schema','gxtxt.reaction_network_execution.v1','module_version','0.2.5',...
  'mode',q.mode,'run_id',ctx.run_id,'script_sha256',ctx.script_sha256,...
  'network_sha256',hash('sha256',q.network_json),'network_json',q.network_json,...
  'source_receipt',source_receipt,'input_bindings',ctx.inputs,...
  'composition_status',model.composition_status,'scientific_status','User-defined network; no physical validation claimed');
if any(strcmp(q.mode,{'save_model','solve'}))
  if isempty(regexp(q.output_prefix,'^[A-Za-z][A-Za-z0-9_.-]{0,100}$','once')),error('Network:Prefix','A fresh bounded output prefix is required');endif
  description=gxtxt_api_call('DOCUMENT_SOURCE_API_v1','describe',{struct()});
  record.model_publication=gxtxt_api_call('DOCUMENT_SOURCE_API_v1','write',{struct('mode','new','dataset_id',[q.output_prefix '.network'],'text',[q.network_json sprintf('\n')],'expected_session',description.session)});
endif
if strcmp(q.mode,'solve')
  result=reaction_network('solve',network);
  if !result.valid_trajectory
    % Failed raw trajectory is a Job artifact, never an accepted canonical curve.
    save('-binary',fullfile(ctx.output_dir,'FAILED_RAW_NETWORK_TRAJECTORY.mat'),'result','network');
    if strcmp(result.numerical_domain_status,'FAILED_NONFINITE_COMPUTED_QUANTITIES')
      error('Network:NumericalDomain','Computed publication quantities are nonfinite (%s); raw failure retained only as Job artifact',strjoin(result.numerical_domain_failures,','));
    endif
    error('Network:Positivity','Accepted amount exceeds its declared negative tolerance; raw failure retained only as Job artifact');
  endif
  record.solver=struct('requested_method',result.solver.method,'actual_backend',result.solver.backend_method,'integration_protocol',result.solver.integration_protocol,'returned_solver_rows',numel(result.solver.time),'retained_rows',numel(result.time_s));
  record.solver.requested_time_s=result.requested_time_s;record.solver.actual_time_s=result.time_s;
  record.solver.state_timestamp_policy=result.solver.state_timestamp_policy;
  record.publications=network_publish(ctx,q.output_prefix,network,result);
  record.accepted_state_positivity=result.accepted_state_positivity;
  record.positivity_scope=result.positivity_scope;
  record.numerical_domain_status=result.numerical_domain_status;
endif
record.state='EXECUTED';
fid=fopen(fullfile(ctx.output_dir,'viewer_bridge_result.json'),'w');
if fid<0,error('Network:Receipt','Cannot create native Job receipt');endif
unwind_protect
  fprintf(fid,'%s\n',jsonencode(struct('schema','gxtxt.viewer_bridge_result.v1','module_id',ctx.module_id,'run_id',ctx.run_id,'action','run','result',record)));
unwind_protect_cleanup,fclose(fid);end_unwind_protect
reaction_network.m — Direct called helper in the actual generic entrypoint/ODE/publication source chain

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Generic0.2.5

script-20261120T043918Z-2293038-1795149558474630 COMPLETED exit0; script-20261120T064007Z-2529515-1795156807585422 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 b7ecdc0e3084fdf7cfe433a0fadff5888f5d146346a4749a9c99609b47f89aa6

function out=reaction_network(action,net,varargin)
% Data-driven homogeneous/boundary amount network; public Numeric owns maths.
% No ELEC constants, cases, equations or reaction identities are built in.
  if strcmp(action,'validate'),out=prepare(net);return;endif
  model=prepare(net);
  if strcmp(action,'rates'),out=rates(model,varargin{1},varargin{2});return;endif
  if !strcmp(action,'solve'),error('Network:Action','Unknown network action');endif
  grid=linspace(net.time.start_s,net.time.end_s,net.time.samples)';
  % Retain/check all provider-returned adaptive/refined rows on each two-point
  % span. dense_times merges grids and hides internal rows; never use it.
  ns=numel(model.n0);nr=numel(model.reactions);
  rhs=@(t,y) derivative(model,t,y,ns);
  state=zeros(numel(grid),ns+nr);state(1,:)=[model.n0;zeros(nr,1)]';
  retained_time=grid;accepted_time=grid(1);accepted_state=state(1,:);segments={};backends={};
  for interval=1:numel(grid)-1
    segment=network_numeric('foundation','ode','solve',rhs,[retained_time(interval);grid(interval+1)],state(interval,:)',net.solver);
    if !segment.success||segment.cancelled||segment.terminated_by_event||numel(segment.time)<2||any(!isfinite(segment.time))||any(diff(segment.time)<0)||segment.time(end)<=retained_time(interval)||any(segment.state_imaginary(:)!=0)
      error('Network:Integration','Public ODE segment did not complete the requested real endpoint');
    endif
    if rows(segment.state_real)!=numel(segment.time)||columns(segment.state_real)!=ns+nr||any(!isfinite(segment.state_real(:)))
      error('Network:Integration','Public ODE returned an invalid state trajectory');
    endif
    state(interval+1,:)=segment.state_real(end,:);
    % Public completion can return a terminal time differing by floating
    % representation. Carry/publish the ACTUAL time; never relabel its state.
    retained_time(interval+1)=segment.time(end);
    accepted_time=[accepted_time;segment.time(2:end)];
    accepted_state=[accepted_state;segment.state_real(2:end,:)];
    segments{end+1}=segment;backends{end+1}=segment.backend_method;
  endfor
  result=struct('method',net.solver.method,'backend_method',strjoin(unique(backends,'stable'),','),...
    'integration_protocol','ADJACENT_TWO_POINT_SPANS_WITH_FULL_RETURNED_STATE_CHECK',...
    'time',accepted_time,'state_real',accepted_state,'segments',{segments},'success',true,...
    'retained_time',retained_time,'requested_time',grid,'retained_state_real',state,...
    'state_timestamp_policy','ACTUAL_PROVIDER_TERMINAL_TIMES_CARRIED_FORWARD');
  amounts=state(:,1:ns);extents=state(:,ns+1:end);accepted_amounts=accepted_state(:,1:ns);
  rr=zeros(rows(amounts),nr);
  for k=1:rows(amounts),rr(k,:)=rates(model,retained_time(k),amounts(k,:)')';endfor
  exchange=extents(:,model.boundary)*(model.composition*model.S(:,model.boundary))';
  totals=amounts*model.composition';initial=model.composition*model.n0;
  out=struct('time_s',retained_time,'requested_time_s',grid,'amounts_mol',amounts,'concentrations_mol_m3',amounts/net.volume_m3,...
    'rates_mol_s',rr,'extents_mol',extents,'balance_totals_mol',totals,...
    'external_exchange_mol',exchange,'balance_residual_mol',totals-repmat(initial',rows(amounts),1)-exchange,...
    'kinematic_residual_mol',amounts-repmat(model.n0',rows(amounts),1)-extents*model.S',...
    'minimum_amount_mol',min([accepted_amounts;amounts]),'negative_amount_count',sum(accepted_amounts<0),...
    'accepted_minimum_amount_mol',min(accepted_amounts),'retained_minimum_amount_mol',min(amounts),...
    'retained_negative_amount_count',sum(amounts<0),...
    'composition_status',model.composition_status,'balance_labels',{model.balance_labels},...
    'species_ids',{model.species_ids},'reaction_ids',{model.reaction_ids},'solver',result,...
    'scientific_status','User-defined network; numerical execution is not physical validation');
  out.accepted_state_positivity='PASS_DECLARED_AMOUNT_TOLERANCES';
  out.positivity_scope='PROVIDER_RETURNED_STATES_AND_RETAINED_ENDPOINTS_NOT_CONTINUOUS_TIME_PROOF';
  out.numerical_domain_status='PASS_FINITE_COMPUTED_QUANTITIES';out.numerical_domain_failures={};
  fields={'time_s','requested_time_s','amounts_mol','concentrations_mol_m3','rates_mol_s','extents_mol',...
    'balance_totals_mol','external_exchange_mol','balance_residual_mol','kinematic_residual_mol',...
    'minimum_amount_mol','negative_amount_count','accepted_minimum_amount_mol','retained_minimum_amount_mol','retained_negative_amount_count'};
  for f=fields
    v=out.(f{1});
    if !isnumeric(v)||!isreal(v)||any(!isfinite(v(:))),out.numerical_domain_failures{end+1}=f{1};endif
  endfor
  out.valid_trajectory=isempty(out.numerical_domain_failures);
  if !out.valid_trajectory,out.numerical_domain_status='FAILED_NONFINITE_COMPUTED_QUANTITIES';endif
  for k=1:ns
    if !model.species{k}.signed_reservoir&&any([accepted_amounts(:,k);amounts(:,k)]<-model.species{k}.absolute_tolerance_mol)
      out.valid_trajectory=false;out.accepted_state_positivity='FAILED_AMOUNT_BELOW_DECLARED_TOLERANCE';
    endif
  endfor
endfunction

function m=prepare(n)
  required(n,{'schema','id','volume_m3','species','parameters','reactions','time','solver'});
  if !strcmp(n.schema,'gxtxt.reaction_network.v1'),error('Network:Schema','Unsupported network schema');endif
  identity(n.id);positive(n.volume_m3,'Constant volume m^3');
  required(n.time,{'start_s','end_s','samples'});required(n.solver,{'method','reltol','abstol','max_step'});
  finite_scalar(n.time.end_s,'End time');finite_scalar(n.time.samples,'Time samples');
  positive(n.solver.reltol,'Solver relative tolerance');positive(n.solver.abstol,'Solver absolute tolerance');positive(n.solver.max_step,'Maximum solver step');
  if !any(strcmp(n.solver.method,{'ode45','ode15s'})),error('Network:Solver','Choose public Numeric ode45 or ode15s');endif
  if !all(ismember(fieldnames(n.solver),{'method','reltol','abstol','max_step'})),error('Network:Solver','Unsupported solver setting');endif
  positive(n.time.end_s-n.time.start_s,'Time interval');finite_scalar(n.time.start_s,'Start time');
  if n.time.samples<2||n.time.samples>10001||n.time.samples!=fix(n.time.samples),error('Network:Size','Time samples must be an integer from 2 to 10001');endif
  species=items(n.species);parameters=items(n.parameters);rx=items(n.reactions);
  ns=numel(species);nr=numel(rx);
  if ns<1||ns>48||nr<1||nr>128||numel(parameters)>14||ns+numel(parameters)+2>64,error('Network:Size','Network exceeds 48 species, 128 reactions, 14 parameters or 64 expression symbols');endif
  ids={};n0=zeros(ns,1);elements={};element_known=false(1,ns);charge_known=false(1,ns);symbols=struct('t',n.time.start_s,'V',n.volume_m3);units=struct('t','s','V','m^3');
  for k=1:ns
    s=species{k};required(s,{'id','formula','elements','charge','initial_value','unit','signed_reservoir','absolute_tolerance_mol','initial_basis'});identity(s.id);
    positive(s.absolute_tolerance_mol,'Accepted-state absolute amount tolerance mol');
    if !ischar(s.formula)||numel(s.formula)>1024,error('Network:Formula','Formula label must be bounded text; explicit composition governs balance');endif
    if any(strcmp(s.id,[ids,{'t','V','pi','e'}])),error('Network:Identity','Species IDs must be unique and not reserved');endif
    ids{end+1}=s.id;finite_scalar(s.initial_value,'Initial amount');
    if !islogical(s.signed_reservoir)||!isscalar(s.signed_reservoir),error('Network:Reservoir','signed_reservoir must be a boolean');endif
    if s.initial_value<0&&!s.signed_reservoir,error('Network:Amount','Negative initial amount requires explicit signed bookkeeping reservoir');endif
    target='mol';if strcmp(s.initial_basis,'concentration'),target='mol/m^3';elseif !strcmp(s.initial_basis,'amount'),error('Network:Basis','Initial basis must be amount or concentration');endif
    conversion=network_numeric('expression_evaluate','a',struct('a',s.initial_value),struct('a',s.unit),struct('output_unit',target));
    n0(k)=conversion.values;if strcmp(s.initial_basis,'concentration'),n0(k)*=n.volume_m3;endif;
    computed_finite(n0(k),'Converted initial amount');symbols.(s.id)=n0(k);units.(s.id)='mol';
    if !isstruct(s.elements)||numel(s.elements)!=1,error('Network:Elements','Element composition must be an element-to-count object');endif
    for e=fieldnames(s.elements)'
      if isempty(regexp(e{1},'^[A-Z][a-z]?$','once')),error('Network:Elements','Element keys must be chemical element symbols');endif
      v=s.elements.(e{1});finite_scalar(v,'Element count');
      if v<0||v!=fix(v)||v>flintmax,error('Network:Elements','Element counts must be exact nonnegative integers within binary64 range');endif
      elements=union(elements,e);element_known(k)=element_known(k)||v>0;
    endfor
    if !isempty(s.charge),finite_scalar(s.charge,'Formal species charge');charge_known(k)=true;endif
  endfor
  pids={};
  for k=1:numel(parameters)
    p=parameters{k};required(p,{'id','value','unit'});identity(p.id);finite_scalar(p.value,'Parameter value');
    if any(strcmp(p.id,[ids,pids,{'t','V','pi','e'}])),error('Network:Identity','Parameter IDs must be unique and not reserved');endif
    % Parse/convert each declared unit through the public expression owner.
    network_numeric('expression_evaluate','a',struct('a',p.value),struct('a',p.unit));
    pids{end+1}=p.id;symbols.(p.id)=p.value;units.(p.id)=p.unit;
  endfor
  C=zeros(numel(elements)+1,ns);labels=[elements,{'formal_charge'}];
  for k=1:ns
    for j=1:numel(elements),if isfield(species{k}.elements,elements{j}),C(j,k)=species{k}.elements.(elements{j});endif,endfor
    if !isempty(species{k}.charge),C(end,k)=species{k}.charge;endif
  endfor
  computed_finite(n0/n.volume_m3,'Initial concentrations');
  computed_finite(C*n0,'Initial declared element/charge totals');
  S=zeros(ns,nr);rids={};boundary=false(1,nr);
  for j=1:nr
    r=rx{j};required(r,{'id','kind','stoichiometry','rate_type','rate_basis'});identity(r.id);
    if any(strcmp(r.id,rids)),error('Network:Identity','Reaction IDs must be unique');endif;rids{end+1}=r.id;
    if !any(strcmp(r.kind,{'homogeneous','boundary'})),error('Network:Boundary','Reaction kind must be homogeneous or boundary');endif
    boundary(j)=strcmp(r.kind,'boundary');
    if !any(strcmp(r.rate_basis,{'amount','concentration'})),error('Network:Basis','Rate basis must be amount or concentration');endif
    if !isstruct(r.stoichiometry)||numel(r.stoichiometry)!=1,error('Network:Stoichiometry','Stoichiometry must be an ID-to-number object');endif
    for q=fieldnames(r.stoichiometry)'
      k=find(strcmp(q{1},ids));if isempty(k),error('Network:Species','Unknown stoichiometric species');endif
      finite_scalar(r.stoichiometry.(q{1}),'Stoichiometric coefficient');S(k,j)=r.stoichiometry.(q{1});
    endfor
    if !any(S(:,j)),error('Network:Stoichiometry','A reaction requires nonzero stoichiometry');endif
    if strcmp(r.kind,'homogeneous')
      involved=find(S(:,j)!=0);
      verified_rows=[repmat(all(element_known(involved)),numel(elements),1);all(charge_known(involved))];
      verify_balance(C(verified_rows,:),S(:,j));
    endif
    if strcmp(r.rate_type,'mass_action')
      required(r,{'rate_constant','orders'});
      if !isstruct(r.orders)||numel(r.orders)!=1,error('Network:Order','Kinetic orders must be an ID-to-number object');endif
      if !any(strcmp(r.rate_constant,pids)),error('Network:Parameter','Mass-action constant must reference a declared parameter');endif
      expr=r.rate_constant;
      for q=fieldnames(r.orders)'
        if !any(strcmp(q{1},ids)),error('Network:Species','Unknown kinetic-order species');endif
        v=r.orders.(q{1});finite_scalar(v,'Kinetic order');if v<0,error('Network:Order','Mass-action kinetic orders must be nonnegative');endif
        expr=[expr '*' q{1} '^(' sprintf('%.17g',v) ')'];
      endfor
    elseif strcmp(r.rate_type,'expression')
      required(r,{'expression'});expr=r.expression;
    else error('Network:Rate','Rate type must be mass_action or expression');endif
    if !ischar(expr)||numel(expr)>8192,error('Network:Rate','Rate expression must be bounded text');endif
    u=units;target='mol/s';
    if strcmp(r.rate_basis,'concentration'),target='mol/m^3/s';for k=1:ns,u.(ids{k})='mol/m^3';endfor,endif
    % Shared public grammar/dimensional checker admits no code evaluation.
    network_numeric('expression_dimensions',expr,u,target);
    rx{j}.compiled_expression=expr;rx{j}.symbol_units=u;rx{j}.output_unit=target;
  endfor
  known=all(element_known)&&all(charge_known);
  status='CONSISTENT_DECLARED_COMPOSITION_TO_ARITHMETIC_PRECISION';if !known,status='UNVERIFIED_MISSING_COMPOSITION_OR_CHARGE';endif
  m=struct('network',n,'species', {species},'species_ids',{ids},'reaction_ids',{rids},'reactions',{rx},'n0',n0,'S',S,...
    'composition',C,'element_composition_known',element_known,'charge_known',charge_known,'composition_status',status,'balance_labels',{labels},'symbols',symbols,'units',units,'boundary',boundary);
  % Validate initial numeric rate domains separately from dimensions.
  rates(m,n.time.start_s,n0);
endfunction

function out=rates(m,t,n)
  symbols=m.symbols;symbols.t=t;out=zeros(numel(m.reactions),1);
  for j=1:numel(m.reactions)
    r=m.reactions{j};
    for k=1:numel(n)
      symbols.(m.species_ids{k})=n(k);
      if strcmp(r.rate_basis,'concentration'),symbols.(m.species_ids{k})/=m.network.volume_m3;endif
    endfor
    result=network_numeric('expression_evaluate',r.compiled_expression,symbols,r.symbol_units,struct('output_unit',r.output_unit));
    v=result.values;if !isscalar(v)||!isreal(v)||!isfinite(v)||v<0,error('Network:RateDomain','Directed channel rate must be one finite nonnegative real value; solver trial domain errors are not accepted-state positivity checks');endif
    if strcmp(r.rate_basis,'concentration'),v*=m.network.volume_m3;endif
    if !isfinite(v)||!isreal(v)||v<0,error('Network:RateDomain','Directed amount rate is not finite nonnegative after physical volume conversion');endif
    out(j)=v;
  endfor
endfunction
function out=derivative(m,t,y,ns),r=rates(m,t,y(1:ns));out=[m.S*r;r];endfunction
function out=items(v),if isempty(v),out={};elseif iscell(v),out=v(:)';elseif isstruct(v),out=num2cell(v);else error('Network:Schema','Expected an array of objects');endif,endfunction
function required(v,fields),if !isstruct(v)||!all(isfield(v,fields)),error('Network:Schema','Network object lacks required fields');endif,endfunction
function identity(s),if !ischar(s)||isempty(regexp(s,'^[A-Za-z][A-Za-z0-9_]{0,47}$','once')),error('Network:Identity','IDs must be bounded stable ASCII identifiers');endif,endfunction
function finite_scalar(v,label),if !isnumeric(v)||!isscalar(v)||!isreal(v)||!isfinite(v),error('Network:Domain','%s must be finite real scalar',label);endif,endfunction
function positive(v,label),finite_scalar(v,label);if v<=0,error('Network:Domain','%s must be positive',label);endif,endfunction
function computed_finite(v,label),if !isnumeric(v)||!isreal(v)||any(!isfinite(v(:))),error('Network:NumericalDomain','%s cannot be represented as finite real computed values',label);endif,endfunction

function verify_balance(C,s)
% Floating dot-product roundoff envelope, not a chemical acceptance tolerance.
  terms=C.*repmat(s',rows(C),1);scale=sum(abs(terms),2);residual=sum(terms,2);
  operations=2*numel(s);gamma=operations*eps/(1-operations*eps);bound=gamma*scale;
  if any(!isfinite(terms(:)))||any(!isfinite(scale))||any(!isfinite(residual))||any(!isfinite(bound))
    error('Network:Balance','Declared balance arithmetic is not finite');
  endif
  if any(((C!=0)&repmat(s'!=0,rows(C),1)&(terms==0))(:))
    error('Network:Balance','Declared balance product underflows binary64 representation');
  endif
  if any(abs(residual)>bound),error('Network:Balance','Known homogeneous channel is inconsistent with declared element/charge balance to arithmetic precision');endif
endfunction
network_numeric.m — Direct called helper in the actual generic entrypoint/ODE/publication source chain

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Generic0.2.5

script-20261120T043918Z-2293038-1795149558474630 COMPLETED exit0; script-20261120T064007Z-2529515-1795156807585422 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 78a85cc92e594b86fd81b1eba297da8a835c4a4633395582a4d52074b0942403

function out=network_numeric(varargin)
% Use the existing CORE-owned public Numeric resolver on the managed path.
% Project source paths and provider binding identity remain their owners.
  if exist('gxtxt_analysis_numeric_call','file')!=2
    error('Network:Numeric','The managed Script runtime must expose its existing CORE Numeric helper');
  endif
  out=gxtxt_analysis_numeric_call(varargin{:});
endfunction
network_publish.m — Direct called helper in the actual generic entrypoint/ODE/publication source chain

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Generic0.2.5

script-20261120T043918Z-2293038-1795149558474630 COMPLETED exit0; script-20261120T064007Z-2529515-1795156807585422 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 aa810da2270ea87f62c33340d625f7838a2ee2fa45b5354ee697a062362fa0c5

function receipts=network_publish(ctx,prefix,network,R)
% Public canonical Dataset ownership and standard Curve Viewer consumption.
  % Whole-bundle validation must finish BEFORE the first numeric writer exists.
  if !isfield(R,'valid_trajectory')||!R.valid_trajectory,error('Network:Publication','A failed trajectory cannot be published as numeric canonical data');endif
  fields={'time_s','requested_time_s','amounts_mol','concentrations_mol_m3','rates_mol_s','extents_mol',...
    'balance_totals_mol','external_exchange_mol','balance_residual_mol','kinematic_residual_mol',...
    'minimum_amount_mol','negative_amount_count','retained_negative_amount_count'};
  for f=fields
    v=R.(f{1});if !isnumeric(v)||!isreal(v)||any(!isfinite(v(:))),error('Network:NumericalDomain','Numeric publication refused: nonfinite or nonreal computed field %s',f{1});endif
  endfor
  def=struct('contract','table.generic','storage','auto','replace_owned',false,'producer_version','0.2.1',...
    'source_dataset_ids',{{[prefix '.network']}},'source','User-defined reaction network',...
    'provenance',['Native Job ' ctx.run_id '; source bundle ' ctx.script_sha256 '; requested solver ' R.solver.method '; actual backend ' R.solver.backend_method '; integration protocol ' R.solver.integration_protocol],...
    'notes',['dn/dt=S*r; amount basis mol; explicit constant volume; directed channels. ' R.scientific_status '. Composition: ' R.composition_status '. Positivity checks provider-returned states and retained endpoints; no continuous-time proof. Integration restarts on adjacent requested endpoints and retains every provider-returned row. Missing composition means partial declared-element totals only, never verified chemical conservation. Formal-charge ledger is mol of elementary-charge equivalents, not coulombs. Negative counts refer to returned solver rows; retained-grid counts are separate. No experimental uncertainty estimated; numerical negatives are never clipped.']);
  receipts={};
  specs={'amounts','amounts_mol','mol','species_ids';'concentrations','concentrations_mol_m3','mol/m^3','species_ids';...
    'rates','rates_mol_s','mol/s','reaction_ids';'extents','extents_mol','mol','reaction_ids';...
    'balance_totals','balance_totals_mol','mol','balance_labels';'external_exchange','external_exchange_mol','mol','balance_labels';...
    'balance_residual','balance_residual_mol','mol','balance_labels';'kinematic_residual','kinematic_residual_mol','mol','species_ids'};
  for i=1:rows(specs)
    labels=R.(specs{i,4});matrix=R.(specs{i,2});cols=struct('time_s',R.time_s,'requested_time_s',R.requested_time_s);units=struct('time_s','s','requested_time_s','s');
    for j=1:numel(labels),key=['v_' labels{j}];cols.(key)=matrix(:,j);units.(key)=specs{i,3};endfor
    def.dataset_id=[prefix '.' specs{i,1}];receipts{end+1}=publish(def,cols,units);
  endfor
  cols=struct();units=struct();
  for k=1:numel(R.species_ids)
    key=['minimum_' R.species_ids{k}];cols.(key)=R.minimum_amount_mol(k);units.(key)='mol';
    key=['negative_count_' R.species_ids{k}];cols.(key)=R.negative_amount_count(k);units.(key)='1';
    key=['retained_negative_count_' R.species_ids{k}];cols.(key)=R.retained_negative_amount_count(k);units.(key)='1';
  endfor
  def.dataset_id=[prefix '.diagnostics'];receipts{end+1}=publish(def,cols,units);
endfunction
function receipt=publish(def,cols,units)
  keys=fieldnames(cols);count=numel(cols.(keys{1}));writer=gxtxt_api_call('DATASET_PUBLICATION_API_v2','begin',{def});
  try
    gxtxt_api_call('DATASET_PUBLICATION_API_v2','declare_dimension',{writer,'row',count,struct('extendible',false)});
    for k=1:numel(keys)
      key=keys{k};value=cols.(key);
      schema=struct('dtype','float64','value_kind','number','rank',1,'dimension_ids',{{'row'}},'name',key,'unit',units.(key),'coordinate_role','data','axis_kind','explicit');
      schema=elec_reaction_time_schema(key,schema);
      if strcmp(key,'time_s'),schema.semantic_reason='Actual provider-returned state timestamp carried through declared segmented integration';endif
      if strcmp(key,'requested_time_s')
        schema=elec_reaction_time_schema('time_s',schema);
        schema.name='Requested endpoint [s]; actual state timestamp is time_s';
        schema.semantic_reason='Requested elapsed endpoint target; actual state timestamp is stored separately in time_s';
      endif
      gxtxt_api_call('DATASET_PUBLICATION_API_v2','declare_variable',{writer,key,schema});
      gxtxt_api_call('DATASET_PUBLICATION_API_v2','write_variable',{writer,key,value,count});
    endfor
    receipt=gxtxt_api_call('DATASET_PUBLICATION_API_v2','finalize',{writer});
  catch err
    try gxtxt_api_call('DATASET_PUBLICATION_API_v2','abort',{writer});catch,end_try_catch
    rethrow(err);
  end_try_catch
endfunction
elec_assay_chlorine_public_ode_model_011–a3bc58e40115864d.m — registered_source

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261118T175236Z-2032555-1795024356189422 COMPLETED exit0; script-20261118T175851Z-2051373-1795024731681928 COMPLETED exit0; script-20261118T180542Z-2079340-1795025142476552 COMPLETED exit0; script-20261118T181604Z-2120608-1795025764069564 COMPLETED exit0; script-20261119T071755Z-4173920-1795072675933183 COMPLETED exit0; script-20261119T114703Z-462161-1795088823383992 COMPLETED exit0; script-20261119T115607Z-478844-1795089367556973 COMPLETED exit0; script-20261119T120611Z-494366-1795089971876246 COMPLETED exit0; script-20261119T121435Z-506415-1795090475332791 COMPLETED exit0; script-20261119T122917Z-528961-1795091357129979 COMPLETED exit0; script-20261119T123943Z-542392-1795091983312698 COMPLETED exit0; script-20261119T124852Z-552817-1795092532720787 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 a3bc58e40115864d4e43dcd726b462ca93f2e26a84f69106ffcff06f9b3a5986

% Owned Model0.1.1; explicit clock-roundoff protocol elec.clock_roundoff.v1.
% Fitter responses approximate requested coordinates; actual clocks and bounded
% coordinate contributions remain in owned public_ode_callback_XXXXX.mat records.
% Public requirement/context initialization occurs BEFORE callback registration.
gxtxt_api_require('NUMERIC_API_v1@1');
global ELEC_ASSAY_ODE_CONTEXT;
initial_context=gxtxt_context();
ELEC_ASSAY_ODE_CONTEXT=struct('output_dir',initial_context.output_dir,'run_id',initial_context.run_id,'script_sha256',initial_context.script_sha256,'calls',0);

function response=elec_assay_chlorine_public_ode_N(parameters,predictors)
  [response,unused]=coupled_public_ode(parameters,predictors);
endfunction

function response=elec_assay_chlorine_public_ode_B(parameters,predictors)
  [unused,response]=coupled_public_ode(parameters,predictors);
endfunction

function [Nmass,Bout]=coupled_public_ode(parameters,predictors)
  % w=int(B dt), units mol*s/m^3; exact transformation, public ODE only.
  if !isnumeric(parameters)||!isreal(parameters)||numel(parameters)!=10||any(!isfinite(parameters(:)))
    error('ELEC:Parameters','Ten finite real parameters in declared order required');
  endif
  p=parameters(:);h=p(1);f=p(2);km=p(3);nu=p(4);C0=p(5);MN=p(6);I=p(7);V=p(8);F=p(9);reference_s=p(10);
  if h<0||h>1||f<0||f>1||km<0||km>10||nu<=0||C0<0||MN<=0||I<0||V<=0||F<=0||reference_s<=0
    error('ELEC:Domain','Require h,f in [0,1], loss in [0,10]/min, positive nu,M_N,V,F,reference_s and nonnegative N0,I');
  endif
  if !isnumeric(predictors)||!isreal(predictors)||columns(predictors)!=1||numel(predictors)>2048||any(!isfinite(predictors(:)))||any(predictors(:)<0)||any(predictors(:)>60)
    error('ELEC:Predictors','At most 2048 finite elapsed-minute query values in 0..60 required');
  endif
  t=60*predictors(:);[query,unused,mapping]=unique(t);
  A0=C0/MN;P=f*I/(2*F*V);kappa=km/60;
  if C0==0,kA=0;else,kA=h/(reference_s*A0);endif
  if !all(isfinite([A0,P,kappa,kA])),error('ELEC:Finite','Finite derived source/rate scales required');endif
  opts=struct('method','ode45','reltol',1e-10,'abstol',1e-10,'max_step',2);
  record=struct('schema','elec.assay_public_ode_callback.v1','parameters',p,'predictor_min',predictors(:),'requested_time_s',query,'solver',opts,'w_unit','mol*s/m^3','positivity_amount_tolerance_mol',1e-12,'clock_protocol','elec.clock_roundoff.v1','segments',{{}},'scientific_scope','Conditional operational assay pool, first-order effective oxidant loss, no N fate or physical validation');
  nquery=C0*ones(size(query));bquery=zeros(size(query));actual_query=zeros(size(query));clock_query=cell(size(query));w=0;now=0;segments={};
  try
    for j=1:numel(query)
      target=query(j);
      if target==0,clock_query{j}=clock_roundoff_diagnostic(0,0,C0,kA,P,kappa,nu,A0);continue;endif
      clock_require_forward(target,now);
      rhs=@(tt,ww) exposure_rhs(tt,ww,P,kappa,nu,kA,A0);
      s=network_numeric('foundation','ode','solve',rhs,[now;target],w,opts);
      segment=struct('provider',s);segments{end+1}=segment;record.segments=segments;
      if !s.success||s.cancelled||s.terminated_by_event||!strcmp(s.backend_method,'ode45')||numel(s.time)<2||columns(s.state_real)!=1||rows(s.state_real)!=numel(s.time)||any(!isfinite([s.time(:);s.state_real(:)]))||any(s.state_imaginary(:)!=0)||any(diff(s.time)<0)
        error('ELEC:ODE','Public ODE must complete a finite real ode45 segment');
      endif
      clock_require_continuity(s,now,w);
      % Never overwrite provider clocks. This bounds only coordinate displacement.
      clock=clock_roundoff_diagnostic(target,s.time(end),C0,kA,P,kappa,nu,A0);
      segments{end}.clock=clock;record.segments=segments;
      if !clock.accepted,error('ELEC:ODETime','Clock discrepancy exceeds finite four-ULP or induced-N bound');endif
      actual_query(j)=s.time(end);clock_query{j}=clock;
      physical=physical_rows(s.time,s.state_real(:,1),P,kappa,nu,kA,A0,C0,MN,V,I,F,opts);
      segments{end}.physical=physical;record.segments=segments;
      w=s.state_real(end,1);now=s.time(end);nquery(j)=physical.N_mg_L(end);bquery(j)=physical.B_mol_m3(end);
    endfor
    Nmass=nquery(mapping);Bout=bquery(mapping);
    if any(!isfinite([Nmass;Bout])),error('ELEC:Finite','Finite Model response required');endif
    record.response_requested_time_s=t;record.query_mapping=mapping;record.query_actual_time_s=actual_query;record.query_clock_diagnostics=clock_query;record.response_actual_time_s=actual_query(mapping);record.response_clock_diagnostics=clock_query(mapping);record.N_mg_L=Nmass;record.B_mol_m3=Bout;record.state='COMPLETED_CALLBACK';store_callback_record(record);
  catch e
    record.segments=segments;record.state='FAILED_CALLBACK';record.error=struct('identifier',e.identifier,'message',e.message);
    try
      store_callback_record(record);
    catch artifact_error
      fprintf(2,'Secondary callback-artifact failure: %s\n',artifact_error.message);
    end_try_catch
    rethrow(e);
  end_try_catch
endfunction

function clock_require_forward(target,previous_actual)
  if !isreal([target,previous_actual])||any(!isfinite([target,previous_actual]))||target<=previous_actual
    error('ELEC:ODETimeOrder','Next requested endpoint is not later than finite actual continuation time');
  endif
endfunction

function clock_require_continuity(s,previous_actual,previous_state)
  if s.time(1)!=previous_actual||s.state_real(1,1)!=previous_state||s.time(end)<=previous_actual
    error('ELEC:ODEContinuity','Raw provider initial clock/state continuity and forward endpoint required');
  endif
endfunction

function d=clock_roundoff_diagnostic(requested,actual,C0,kA,P,kappa,nu,A0)
  % Positive binary64 bit patterns are monotone; distance counts adjacent values.
  v=[requested,actual,C0,kA,P,kappa,nu,A0];
  if !isreal(v)||any(!isfinite(v))||any(v<0)||nu<=0
    error('ELEC:ClockFinite','Finite nonnegative clock-bound inputs and positive nu required');
  endif
  if (requested==0||actual==0)&&!(requested==0&&actual==0)
    error('ELEC:ClockDomain','Only an exact zero/zero clock pair is allowed at zero');
  endif
  requested_bits=typecast(double(requested),'uint64');actual_bits=typecast(double(actual),'uint64');
  if requested_bits>=actual_bits,steps=requested_bits-actual_bits;else steps=actual_bits-requested_bits;endif
  delta=actual-requested;T=max(requested,actual);
  delta_magnitude_bound=clock_up_nonnegative(abs(delta));
  kP=clock_product_up(kA,P);kPT=clock_product_up(kP,T);e_clock=clock_product_up(kPT,delta_magnitude_bound);Nlimit=1e-12*C0;EN=clock_product_up(C0,e_clock);
  if C0==0
    if kA!=0,error('ELEC:ClockZero','Zero initial N requires exact zero reaction coefficient');endif
    Naccepted=true;
  else
    Naccepted=e_clock<=1e-12;
  endif
  reaction=clock_product_up(nu,kA);reactionA=clock_product_up(reaction,A0);loss=clock_sum_up(reactionA,kappa);
  lossT=clock_product_up(loss,T);Bfactor=clock_sum_up(1,lossT);BP=clock_product_up(P,Bfactor);EB=clock_product_up(BP,delta_magnitude_bound);
  computed=[delta,delta_magnitude_bound,T,kP,kPT,e_clock,EN,Nlimit,reaction,reactionA,loss,lossT,Bfactor,BP,EB];
  if any(!isfinite(computed))
    error('ELEC:ClockFinite','Nonfinite intermediate clock-bound diagnostic');
  endif
  d=struct('protocol','elec.clock_roundoff.v1','requested_time_s',requested,'actual_time_s',actual,'delta_time_s',delta,'absolute_delta_time_bound_s',delta_magnitude_bound,'requested_binary64_bits',requested_bits,'actual_binary64_bits',actual_bits,'adjacent_binary64_steps',steps,'binary64_step_limit',uint64(4),'normalized_N_coordinate_error_bound',e_clock,'normalized_N_coordinate_error_limit',1e-12,'N_coordinate_error_bound_mg_L',EN,'N_coordinate_error_limit_mg_L',Nlimit,'B_coordinate_error_bound_mol_m3',EB,'accepted',steps<=uint64(4)&&Naccepted,'scope','Exact-solution coordinate displacement bound only; not solver truncation error or physical uncertainty. Actual provider clock/state unchanged.');
endfunction

function result=clock_up_nonnegative(value)
  if !isreal(value)||!isscalar(value)||!isfinite(value)||value<0
    error('ELEC:ClockFinite','Finite nonnegative scalar bound required');
  endif
  if value==0,result=0;return;endif
  result=typecast(typecast(double(value),'uint64')+uint64(1),'double');
  if !isfinite(result),error('ELEC:ClockFinite','Outward bound overflows binary64');endif
endfunction

function result=clock_product_up(a,b)
  if any(!isfinite([a,b]))||any([a,b]<0),error('ELEC:ClockFinite','Finite nonnegative bound factors required');endif
  if a==0||b==0,result=0;return;endif
  value=a*b;
  if !isfinite(value),error('ELEC:ClockFinite','Bound product overflows binary64');endif
  if value==0,result=typecast(uint64(1),'double');else result=clock_up_nonnegative(value);endif
endfunction

function result=clock_sum_up(a,b)
  if any(!isfinite([a,b]))||any([a,b]<0),error('ELEC:ClockFinite','Finite nonnegative bound summands required');endif
  if a==0&&b==0,result=0;return;endif
  result=clock_up_nonnegative(a+b);
endfunction

function value=exposure_rhs(t,w,P,kappa,nu,kA,A0)
  % Smooth mathematical extension at solver trial states; no rate clipping.
  value=P*t-kappa*w+nu*A0*expm1(-kA*w);
  if !isreal(value)||!isscalar(value)||!isfinite(value),error('ELEC:RHS','Finite real exposure derivative required');endif
endfunction

function r=physical_rows(t,w,P,kappa,nu,kA,A0,C0,MN,V,I,F,opts)
  t=t(:);w=w(:);A=A0*exp(-kA*w);deltaA=-A0*expm1(-kA*w);
  terms=[P*t,-kappa*w,-nu*deltaA];B=sum(terms,2);
  roundoff_scale=16*eps*sum(abs(terms),2);
  local_solver_B_scale=(kappa+nu*kA*A).*(opts.abstol+opts.reltol*abs(w));
  % Local solver scale is diagnostic, NOT a global error or acceptance bound.
  amount_tolerance=1e-12;concentration_tolerance=amount_tolerance/V;
  positivity_limit=concentration_tolerance+roundoff_scale;
  if any(!isfinite([A;B;deltaA;roundoff_scale;local_solver_B_scale]))||any(w < -opts.abstol)||any(A < -concentration_tolerance)||any(A>A0+concentration_tolerance)||any(B < -positivity_limit)
    error('ELEC:Positivity','Returned physical state outside explicit amount tolerance; no clipping or solver-error relabelling');
  endif
  ICRR=2*F*V*kappa*B;current_tolerance=2*F*kappa*amount_tolerance+64*eps*max(I,realmin);
  if any(!isfinite(ICRR))||any(ICRR < -current_tolerance)||any(ICRR>f_source_current(P,V,F)+current_tolerance)
    error('ELEC:Current','Returned reduction current exceeds the conditional source-current comparison bound');
  endif
  r=struct('actual_time_s',t,'w_mol_s_m3',w,'A_mol_m3',A,'N_mg_L',MN*A,'B_mol_m3',B,'removed_N_pool_mol_m3',deltaA,'CER_extent_mol_m3',P*t,'loss_extent_mol_m3',kappa*w,'oxidant_balance_residual_mol_m3',B+nu*deltaA+kappa*w-P*t,'B_roundoff_scale_mol_m3',roundoff_scale,'B_local_solver_scale_mol_m3',local_solver_B_scale,'B_positivity_limit_mol_m3',positivity_limit,'I_CRR_A',ICRR,'I_HER_A',I-ICRR,'current_tolerance_A',current_tolerance,'state_check_scope','Every provider-returned row; no continuous-time positivity proof. Allowed numerical negatives retained, not clipped.');
endfunction

function current=f_source_current(P,V,F),current=2*F*V*P;endfunction

function store_callback_record(record)
  global ELEC_ASSAY_ODE_CONTEXT;
  if !isstruct(ELEC_ASSAY_ODE_CONTEXT)||!isfield(ELEC_ASSAY_ODE_CONTEXT,'output_dir')||isempty(ELEC_ASSAY_ODE_CONTEXT.output_dir)
    error('ELEC:Context','Native owned output context must be initialized before callback registration');
  endif
  ELEC_ASSAY_ODE_CONTEXT.calls+=1;index=ELEC_ASSAY_ODE_CONTEXT.calls;
  record.run_id=ELEC_ASSAY_ODE_CONTEXT.run_id;record.script_sha256=ELEC_ASSAY_ODE_CONTEXT.script_sha256;record.callback_index=index;
  path=fullfile(ELEC_ASSAY_ODE_CONTEXT.output_dir,sprintf('public_ode_callback_%05d.mat',index));
  if exist(path,'file'),error('ELEC:Artifact','Refuse existing callback artifact');endif
  save('-mat7-binary',path,'record');
endfunction

% BEGIN EXACT OWNED GENERIC 0.2.1 PUBLIC NUMERIC BINDING HELPER
function out=network_numeric(varargin)
% Resolve only the advertised public Octave binding; never source runtime code.
  persistent entry fn;
  if isempty(entry)
    context=canonicalize_file_name(which('gxtxt_context'));
    if isempty(context),error('Network:Numeric','Native Script context binding is unavailable');endif
    root=fileparts(fileparts(fileparts(fileparts(context))));
    owner=canonicalize_file_name(fullfile(root,'plugins','modules','math.numeric'));
    descriptor=gxtxt_ini_read(fullfile(owner,'module.ini'));
    if !strcmp(gxtxt_ini_get(descriptor,'meta.id',''),'math.numeric')||!strcmp(gxtxt_ini_get(descriptor,'public_api.NUMERIC_API_v1.api_version',''),'1')
      error('Network:Numeric','Public Numeric provider identity is unavailable');
    endif
    fn=gxtxt_ini_get(descriptor,'public_api.NUMERIC_API_v1.octave_function','');
    entry=canonicalize_file_name(fullfile(owner,gxtxt_ini_get(descriptor,'public_api.NUMERIC_API_v1.octave_entrypoint','')));
    if isempty(entry)||isempty(regexp(fn,'^[A-Za-z][A-Za-z0-9_]*$','once'))||!strncmp(entry,[owner filesep],numel(owner)+1)
      error('Network:Numeric','Public Numeric entrypoint is invalid');
    endif
    addpath(fileparts(entry));
  endif
  if !strcmp(canonicalize_file_name(which(fn)),entry),error('Network:Numeric','Public Numeric binding is shadowed');endif
  out=feval(fn,varargin{:});
endfunction
elec_assay_chlorine_public_ode_model–bff324667dc585dc.m — registered_source

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261118T171040Z-1885714-1795021840020015 COMPLETED exit0; script-20261118T171850Z-1910964-1795022330401613 COMPLETED exit0; script-20261118T172456Z-1928011-1795022696668613 COMPLETED exit0; script-20261118T173121Z-1948046-1795023081106788 FAILED exit1; script-20261118T181245Z-2107917-1795025565175113 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 bff324667dc585dce543560be6fb19437fa8286b379a3426e388543b7bc44ecd

% Public requirement/context initialization occurs BEFORE callback registration.
gxtxt_api_require('NUMERIC_API_v1@1');
global ELEC_ASSAY_ODE_CONTEXT;
initial_context=gxtxt_context();
ELEC_ASSAY_ODE_CONTEXT=struct('output_dir',initial_context.output_dir,'run_id',initial_context.run_id,'script_sha256',initial_context.script_sha256,'calls',0);

function response=elec_assay_chlorine_public_ode_N(parameters,predictors)
  [response,unused]=coupled_public_ode(parameters,predictors);
endfunction

function response=elec_assay_chlorine_public_ode_B(parameters,predictors)
  [unused,response]=coupled_public_ode(parameters,predictors);
endfunction

function [Nmass,Bout]=coupled_public_ode(parameters,predictors)
  % w=int(B dt), units mol*s/m^3; exact transformation, public ODE only.
  if !isnumeric(parameters)||!isreal(parameters)||numel(parameters)!=10||any(!isfinite(parameters(:)))
    error('ELEC:Parameters','Ten finite real parameters in declared order required');
  endif
  p=parameters(:);h=p(1);f=p(2);km=p(3);nu=p(4);C0=p(5);MN=p(6);I=p(7);V=p(8);F=p(9);reference_s=p(10);
  if h<0||h>1||f<0||f>1||km<0||km>10||nu<=0||C0<0||MN<=0||I<0||V<=0||F<=0||reference_s<=0
    error('ELEC:Domain','Require h,f in [0,1], loss in [0,10]/min, positive nu,M_N,V,F,reference_s and nonnegative N0,I');
  endif
  if !isnumeric(predictors)||!isreal(predictors)||columns(predictors)!=1||numel(predictors)>2048||any(!isfinite(predictors(:)))||any(predictors(:)<0)||any(predictors(:)>60)
    error('ELEC:Predictors','At most 2048 finite elapsed-minute query values in 0..60 required');
  endif
  t=60*predictors(:);[query,unused,mapping]=unique(t);
  A0=C0/MN;P=f*I/(2*F*V);kappa=km/60;
  if C0==0,kA=0;else,kA=h/(reference_s*A0);endif
  if !all(isfinite([A0,P,kappa,kA])),error('ELEC:Finite','Finite derived source/rate scales required');endif
  opts=struct('method','ode45','reltol',1e-10,'abstol',1e-10,'max_step',2);
  record=struct('schema','elec.assay_public_ode_callback.v1','parameters',p,'predictor_min',predictors(:),'requested_time_s',query,'solver',opts,'w_unit','mol*s/m^3','positivity_amount_tolerance_mol',1e-12,'segments',{{}},'scientific_scope','Conditional operational assay pool, first-order effective oxidant loss, no N fate or physical validation');
  nquery=C0*ones(size(query));bquery=zeros(size(query));w=0;now=0;segments={};
  try
    for j=1:numel(query)
      target=query(j);
      if target==0,continue;endif
      rhs=@(tt,ww) exposure_rhs(tt,ww,P,kappa,nu,kA,A0);
      s=network_numeric('foundation','ode','solve',rhs,[now;target],w,opts);
      segment=struct('provider',s);segments{end+1}=segment;record.segments=segments;
      if !s.success||s.cancelled||s.terminated_by_event||!strcmp(s.backend_method,'ode45')||numel(s.time)<2||columns(s.state_real)!=1||rows(s.state_real)!=numel(s.time)||any(!isfinite([s.time(:);s.state_real(:)]))||any(s.state_imaginary(:)!=0)||any(diff(s.time)<0)
        error('ELEC:ODE','Public ODE must complete a finite real ode45 segment');
      endif
      % The Fitter coordinate must be the actual retained endpoint, not relabelled.
      if s.time(end)!=target,error('ELEC:ODETime','Provider endpoint differs from requested Model coordinate; no relabelling');endif
      physical=physical_rows(s.time,s.state_real(:,1),P,kappa,nu,kA,A0,C0,MN,V,I,F,opts);
      segments{end}.physical=physical;record.segments=segments;
      w=s.state_real(end,1);now=s.time(end);nquery(j)=physical.N_mg_L(end);bquery(j)=physical.B_mol_m3(end);
    endfor
    Nmass=nquery(mapping);Bout=bquery(mapping);
    if any(!isfinite([Nmass;Bout])),error('ELEC:Finite','Finite Model response required');endif
    record.N_mg_L=Nmass;record.B_mol_m3=Bout;record.state='COMPLETED_CALLBACK';store_callback_record(record);
  catch e
    record.segments=segments;record.state='FAILED_CALLBACK';record.error=struct('identifier',e.identifier,'message',e.message);
    try
      store_callback_record(record);
    catch artifact_error
      fprintf(2,'Secondary callback-artifact failure: %s\n',artifact_error.message);
    end_try_catch
    rethrow(e);
  end_try_catch
endfunction

function value=exposure_rhs(t,w,P,kappa,nu,kA,A0)
  % Smooth mathematical extension at solver trial states; no rate clipping.
  value=P*t-kappa*w+nu*A0*expm1(-kA*w);
  if !isreal(value)||!isscalar(value)||!isfinite(value),error('ELEC:RHS','Finite real exposure derivative required');endif
endfunction

function r=physical_rows(t,w,P,kappa,nu,kA,A0,C0,MN,V,I,F,opts)
  t=t(:);w=w(:);A=A0*exp(-kA*w);deltaA=-A0*expm1(-kA*w);
  terms=[P*t,-kappa*w,-nu*deltaA];B=sum(terms,2);
  roundoff_scale=16*eps*sum(abs(terms),2);
  local_solver_B_scale=(kappa+nu*kA*A).*(opts.abstol+opts.reltol*abs(w));
  % Local solver scale is diagnostic, NOT a global error or acceptance bound.
  amount_tolerance=1e-12;concentration_tolerance=amount_tolerance/V;
  positivity_limit=concentration_tolerance+roundoff_scale;
  if any(!isfinite([A;B;deltaA;roundoff_scale;local_solver_B_scale]))||any(w < -opts.abstol)||any(A < -concentration_tolerance)||any(A>A0+concentration_tolerance)||any(B < -positivity_limit)
    error('ELEC:Positivity','Returned physical state outside explicit amount tolerance; no clipping or solver-error relabelling');
  endif
  ICRR=2*F*V*kappa*B;current_tolerance=2*F*kappa*amount_tolerance+64*eps*max(I,realmin);
  if any(!isfinite(ICRR))||any(ICRR < -current_tolerance)||any(ICRR>f_source_current(P,V,F)+current_tolerance)
    error('ELEC:Current','Returned reduction current exceeds the conditional source-current comparison bound');
  endif
  r=struct('actual_time_s',t,'w_mol_s_m3',w,'A_mol_m3',A,'N_mg_L',MN*A,'B_mol_m3',B,'removed_N_pool_mol_m3',deltaA,'CER_extent_mol_m3',P*t,'loss_extent_mol_m3',kappa*w,'oxidant_balance_residual_mol_m3',B+nu*deltaA+kappa*w-P*t,'B_roundoff_scale_mol_m3',roundoff_scale,'B_local_solver_scale_mol_m3',local_solver_B_scale,'B_positivity_limit_mol_m3',positivity_limit,'I_CRR_A',ICRR,'I_HER_A',I-ICRR,'current_tolerance_A',current_tolerance,'state_check_scope','Every provider-returned row; no continuous-time positivity proof. Allowed numerical negatives retained, not clipped.');
endfunction

function current=f_source_current(P,V,F),current=2*F*V*P;endfunction

function store_callback_record(record)
  global ELEC_ASSAY_ODE_CONTEXT;
  if !isstruct(ELEC_ASSAY_ODE_CONTEXT)||!isfield(ELEC_ASSAY_ODE_CONTEXT,'output_dir')||isempty(ELEC_ASSAY_ODE_CONTEXT.output_dir)
    error('ELEC:Context','Native owned output context must be initialized before callback registration');
  endif
  ELEC_ASSAY_ODE_CONTEXT.calls+=1;index=ELEC_ASSAY_ODE_CONTEXT.calls;
  record.run_id=ELEC_ASSAY_ODE_CONTEXT.run_id;record.script_sha256=ELEC_ASSAY_ODE_CONTEXT.script_sha256;record.callback_index=index;
  path=fullfile(ELEC_ASSAY_ODE_CONTEXT.output_dir,sprintf('public_ode_callback_%05d.mat',index));
  if exist(path,'file'),error('ELEC:Artifact','Refuse existing callback artifact');endif
  save('-mat7-binary',path,'record');
endfunction

% BEGIN EXACT OWNED GENERIC 0.2.1 PUBLIC NUMERIC BINDING HELPER
function out=network_numeric(varargin)
% Resolve only the advertised public Octave binding; never source runtime code.
  persistent entry fn;
  if isempty(entry)
    context=canonicalize_file_name(which('gxtxt_context'));
    if isempty(context),error('Network:Numeric','Native Script context binding is unavailable');endif
    root=fileparts(fileparts(fileparts(fileparts(context))));
    owner=canonicalize_file_name(fullfile(root,'plugins','modules','math.numeric'));
    descriptor=gxtxt_ini_read(fullfile(owner,'module.ini'));
    if !strcmp(gxtxt_ini_get(descriptor,'meta.id',''),'math.numeric')||!strcmp(gxtxt_ini_get(descriptor,'public_api.NUMERIC_API_v1.api_version',''),'1')
      error('Network:Numeric','Public Numeric provider identity is unavailable');
    endif
    fn=gxtxt_ini_get(descriptor,'public_api.NUMERIC_API_v1.octave_function','');
    entry=canonicalize_file_name(fullfile(owner,gxtxt_ini_get(descriptor,'public_api.NUMERIC_API_v1.octave_entrypoint','')));
    if isempty(entry)||isempty(regexp(fn,'^[A-Za-z][A-Za-z0-9_]*$','once'))||!strncmp(entry,[owner filesep],numel(owner)+1)
      error('Network:Numeric','Public Numeric entrypoint is invalid');
    endif
    addpath(fileparts(entry));
  endif
  if !strcmp(canonicalize_file_name(which(fn)),entry),error('Network:Numeric','Public Numeric binding is shadowed');endif
  out=feval(fn,varargin{:});
endfunction
elec_assay_chlorine_noloss_model–378ed2a4d6944f01.m — registered_source

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261118T160756Z-1650017-1795018076725365 COMPLETED exit0; script-20261118T161141Z-1667460-1795018301512618 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 378ed2a4d6944f01aa52c91fffcfb68e14b1049525da28936ac99f256726a0e6

1; % Inert definitions; actual science executes in a native registered Model Job.

function response=elec_assay_chlorine_noloss_N(parameters,predictors)
  [response,unused]=coupled_noloss_closed_form(parameters,predictors);
endfunction

function response=elec_assay_chlorine_noloss_B(parameters,predictors)
  [unused,response]=coupled_noloss_closed_form(parameters,predictors);
endfunction

function [Nmass,B]=coupled_noloss_closed_form(parameters,predictors)
  % Exact coupled no-loss branch; existing base erfcx/erfc, no numerical solver.
  % Parameter h sets lambda=h/reference_s=k_A*A0; h=0 is exact no reaction.
  if !isnumeric(parameters)||!isreal(parameters)||numel(parameters)!=9||any(!isfinite(parameters(:)))
    error('ELEC:Parameters','Nine finite real parameters in declared order required');
  endif
  p=parameters(:);h=p(1);f=p(2);nu=p(3);C0=p(4);MN=p(5);I=p(6);V=p(7);F=p(8);reference_s=p(9);
  if h<0||h>1||f<0||f>1||nu<=0||C0<0||MN<=0||I<0||V<=0||F<=0||reference_s<=0
    error('ELEC:Domain','Require h,f in [0,1], nu,M_N,V,F,reference_s positive and N0,I nonnegative');
  endif
  if !isnumeric(predictors)||!isreal(predictors)||columns(predictors)!=1||any(!isfinite(predictors(:)))||any(predictors(:)<0)||any(predictors(:)>60)
    error('ELEC:Predictors','One finite elapsed-minute column in 0..60 required');
  endif
  t=60*predictors(:);A0=C0/MN;P=f*I/(2*F*V);Nmass=C0*ones(size(t));B=P*t;
  if any(!isfinite([A0;P;B])),error('ELEC:Finite','Finite nominal stock and source required');endif
  if C0==0,Nmass=zeros(size(t));return;endif
  if h==0||P==0,return;endif
  lambda=h/reference_s;kA=lambda/A0;a=nu*lambda;b=kA*P/2;
  if !all(isfinite([lambda,kA,a,b]))||lambda<=0||b<=0
    error('ELEC:ComputedDomain','Finite positive derived rate scales required; no underflow substitution');
  endif
  root_b=sqrt(b);z=a/(2*root_b);q=sqrt(pi)*z;
  % Domain bound makes subtraction conditioning explicit; never floor d.
  if !isfinite(z)||z<=0||z>32,error('ELEC:Conditioning','Declared numerical domain requires 0<z<=32');endif
  d=1-q*erfcx(z);
  if !isfinite(d)||d<=0,error('ELEC:Conditioning','Positive finite Mills remainder required; no flooring');endif
  for j=1:numel(t)
    if t(j)==0,continue;endif
    v=z-root_b*t(j);g=a*t(j)-b*t(j)*t(j);
    if !all(isfinite([v,g])),error('ELEC:Finite','Finite transformed time coordinates required');endif
    if v>=0
      e=erfcx(v);
      if !isfinite(e)||e<=0,error('ELEC:SpecialFunction','Positive finite erfcx required');endif
      log_e=log(e);
    else
      % erfc(v) is in (1,2); avoid overflow of erfcx for negative v.
      log_e=v*v+log(erfc(v));
    endif
    l1=log(d)-g;l2=log(q)+log_e;m=max(l1,l2);
    logden=m+log(exp(l1-m)+exp(l2-m));
    if !isfinite(logden),error('ELEC:Finite','Finite log denominator required');endif
    Nmass(j)=exp(log(C0)-logden);
  endfor
  A=Nmass/MN;B=P*t-nu*(A0-A);
  stock_tolerance=128*eps*(P*t+nu*A0);
  if any(!isfinite([Nmass;B]))||any(Nmass<0)||any(Nmass>C0+128*eps*C0)||any(B < -stock_tolerance)
    error('ELEC:Balance','Finite nonnegative N and oxidant required to numerical stock tolerance; no clipping');
  endif
  % Preserve actual values, including any allowed floating negative B.
endfunction
elec_chlorine_transport_model–97d95d60ee602159.m — registered_source

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261118T153414Z-1557672-1795016054192090 COMPLETED exit0; script-20261118T154059Z-1574287-1795016459880389 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 97d95d60ee6021593d81c94b37492c3d9ea599e96451c2fcb5a346e14c909a99

1; % Inert Script Library definitions; no top-level scientific calculation.

function response=elec_chlorine_transport(parameters,predictors)
  % Exact no-N solution. No custom solver, Bridge, IO or external output.
  if !isnumeric(parameters)||!isreal(parameters)||numel(parameters)!=6||any(!isfinite(parameters(:)))
    error('ELEC:Parameters','Six finite real parameters in declared order required');
  endif
  p=parameters(:);f=p(1);k=p(2);I=p(3);V=p(4);F=p(5);M=p(6);
  if f<0||f>1||k<0||I<0||V<=0||F<=0||M<=0
    error('ELEC:Domain','Require 0<=f<=1, k>=0, I>=0 and positive V,F,M');
  endif
  if !isnumeric(predictors)||!isreal(predictors)||columns(predictors)!=1||any(!isfinite(predictors(:)))||any(predictors(:)<0)||any(predictors(:)>60)
    error('ELEC:Predictors','Finite N-by-1 elapsed minutes in 0..60 required');
  endif
  t=predictors(:);pmax=M*I*60/(2*F*V);response=zeros(size(t));
  if !isfinite(pmax),error('ELEC:Finite','Finite current-equivalent production ceiling required');endif
  if k==0
    response=f*pmax*t;
  else
    response=f*pmax*(-expm1(-k*t))/k;
  endif
  ceiling=f*pmax*t;
  if any(!isfinite([response;ceiling]))||any(response<0)||any(response>ceiling+64*eps*max(ceiling,realmin))
    error('ELEC:Balance','Finite nonnegative response below its current-source ceiling required');
  endif
endfunction
elec_fast_checkpoint_model–8bb61aa56d1576d2.m — registered_source

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261118T115546Z-719262-1795002946560971 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 8bb61aa56d1576d2060fd0209f7e33cdd1aa78b1d66ef48ef2436255674b67e1

1; % Script-local callable definitions only; no top-level production.

function response=elec_fast_n_concentration(parameters,predictors)
  response=elec_fast_projection(parameters,predictors,'n_concentration');
endfunction

function response=elec_fast_n_fraction(parameters,predictors)
  response=elec_fast_projection(parameters,predictors,'n_fraction');
endfunction

function response=elec_fast_oxidant_amount(parameters,predictors)
  response=elec_fast_projection(parameters,predictors,'oxidant_amount');
endfunction

function response=elec_fast_projection(parameters,predictors,quantity)
  % Pure, per-execution cached projection of the unchanged complete kernel.
  % No nested Bridge calls, external results, file access or interpolation.
  persistent cached_key cached_result;
  if !isnumeric(parameters)||!isreal(parameters)||numel(parameters)!=7||any(!isfinite(parameters(:)))
    error('ELEC:ModelParameters','Seven finite real parameters in declared order are required');
  endif
  parameters=parameters(:);case_index=parameters(7);
  if case_index!=fix(case_index)||case_index<1||case_index>6
    error('ELEC:ModelCase','Case index must be an integer from1 through6');
  endif
  if !isnumeric(predictors)||!isreal(predictors)||columns(predictors)!=1||any(!isfinite(predictors(:)))
    error('ELEC:ModelPredictors','Predictors must be a finite real N-by-1 column in seconds');
  endif
  allowed=(0:60:300)';
  if !all(ismember(predictors,allowed))
    error('ELEC:ModelGrid','Only exact declared checkpoints0:60:300 seconds are supported; no interpolation or extrapolation');
  endif
  key=parameters(1:6);
  if isempty(cached_result)||!isequal(cached_key,key)
    p=struct('volume_m3',key(1),'current_A',key(2),'initial_N_g_m3',key(3),'background_NaCl_mol_m3',key(4),'F_C_mol',key(5),'M_N_g_mol',key(6),'specification_sha256','98f2d76191b8b6eab76b434012fcd83cd245c4ca866e6a2f682708d42588ae71');
    result=fast_evaluate(p);
    if !result.passed,error('ELEC:ModelChecks','Unchanged kernel checks/coverage did not pass; no prediction accepted');endif
    cached_result=result;cached_key=key;
  endif
  cp=cached_result.checkpoints(cached_result.checkpoints(:,1)==case_index & cached_result.checkpoints(:,2)==3,:);
  if !isequal(cp(:,3),allowed),error('ELEC:ModelCoverage','Exact finest-level checkpoint grid is required');endif
  [present,index]=ismember(predictors,cp(:,3));
  if !all(present),error('ELEC:ModelGrid','No source checkpoint for query');endif
  switch quantity
    case 'n_concentration',response=cp(index,4)*key(6)/key(1);
    case 'n_fraction',response=cp(index,4)/(key(3)*key(1)/key(6));
    case 'oxidant_amount',response=cp(index,5);
    otherwise,error('ELEC:ModelQuantity','Unsupported scalar projection');
  endswitch
  response=response(:);
  if any(!isfinite(response)),error('ELEC:ModelFinite','Finite response is required');endif
endfunction

% BEGIN EXACT UNCHANGED REVIEWED KERNEL
function R=fast_evaluate(p)
  % SOURCE ONLY: illustrative reduced kinetics, no assay or physical pH model.
  spec='98f2d76191b8b6eab76b434012fcd83cd245c4ca866e6a2f682708d42588ae71';
  if !strcmp(p.specification_sha256,spec),error('Reduced:Spec','Exact reviewed specification04 required');endif
  positive={'volume_m3','F_C_mol','M_N_g_mol'};
  nonnegative={'current_A','initial_N_g_m3','background_NaCl_mol_m3'};
  for k=1:numel(positive),input_guard(p,positive{k},true);endfor
  for k=1:numel(nonnegative),input_guard(p,nonnegative{k},false);endfor
  % Normalization and stored controls require nominal positive N inventory.
  if p.initial_N_g_m3<=0,error('Reduced:Input','initial_N_g_m3 must be >0; chlorine-only controls are generated explicitly');endif
  R.species={'formal_NH3','formal_HOCl_equivalent','chloride','exported_Cl2','stipulated_N2','signed_acid','water_reservoir_delta','O2_cumulative','H2_cumulative','electron_reservoir_delta','Na_spectator'};
  R.reactions={'CER','OER','CRR','HER','formal_N2_endpoint','formal_Cl2_export'};
  R.elements={'N','Cl','H','O','Na','formal_charge'};
  E=[1 0 0 0 2 0 0 0 0 0 0;0 1 1 2 0 0 0 0 0 0 0;3 1 0 0 0 1 2 0 2 0 0;0 1 0 0 0 0 1 2 0 0 0;0 0 0 0 0 0 0 0 0 0 1;0 0 -1 0 0 1 0 0 0 -1 1];
  nu=[0 0 0 0 -2 0;1 0 -1 0 -3 -1;-1 0 1 0 3 -1;0 0 0 0 0 1;0 0 0 0 1 0;1 4 -1 -2 3 -1;-1 -2 1 0 3 1;0 1 0 0 0 0;0 0 0 1 0 0;2 4 -2 -2 0 0;0 0 0 0 0 0];
  R.element_matrix=E;R.reaction_matrix=nu;
  C=struct('name',{},'actual',{},'limit',{},'unit',{},'comparison',{},'pass',{});
  C=check(C,'integer_element_charge_nullspace',max(abs((E*nu)(:))),0,'1');
  Nnom=p.initial_N_g_m3*p.volume_m3/p.M_N_g_mol;Na=p.background_NaCl_mol_m3*p.volume_m3;
  if !all(isfinite([Nnom,Na]))||Nnom<=0,error('Reduced:Input','Derived N/Na amounts invalid: %s mol',jsonencode([Nnom,Na]));endif
  base=struct('label','L_m0_common_P_pH7p5','family','common','m',0,'pH_ext',7.5,'fCER',.6,'fCRR',.15,'tau',600,'HB',.1*p.volume_m3,'HL',p.volume_m3,'I',p.current_A,'N0',Nnom,'Na0',Na,'B0',0,'reference_kind','none');
  cases={};
  for tau=[60,6]
    for scenario=1:3
      a=base;a.tau=tau;
      if scenario==1,a.label=sprintf('L_m0_tau%d',tau);a.family='common';
      elseif scenario==2,a.label=sprintf('L_m4_tau%d',tau);a.family='loss';a.m=4;a.fCRR=.15+.45*4/5;
      else,a.label=sprintf('P_pH11_tau%d',tau);a.family='imposed_selectivity';a.pH_ext=11;a.fCER=.6+.4*(1/(1+10^(11-7.5))-.5);endif
      cases{end+1}=a;
    endfor
  endfor
  if numel(cases)!=6,error('Fast:Plan','Fixed6case plan violated');endif
  R.cases=cases;R.state_headers=[{'case_index','level','step','time_s','dt_s'},R.species,strcat('extent_',R.reactions),strcat('rate_used_',R.reactions),{'I_CER_A','I_OER_A','I_CRR_A','I_HER_A','Q_C','Q_CER_C','Q_OER_C','Q_CRR_C','Q_HER_C','tiny_negative_flag','dt_limiter_code'}];
  R.checkpoint_headers=[{'case_index','level','time_s'},R.species,strcat('extent_',R.reactions),{'Q_C'}];
  R.balance_headers={'case_index','level','step','time_s','N_residual','N_limit','Cl_residual','Cl_limit','oxidant_residual','oxidant_limit','acid_Cl_residual','acid_Cl_limit','Na_residual','Na_limit','formal_charge','formal_charge_limit','anode_Q_residual','Q_limit','cathode_Q_residual','N_ceiling_excess','N_ceiling_limit','min_stock','stock_lower_bound','element_scaled_max','kappa_residual','kappa_limit'};
  R.summary_headers={'case_index','level','dt_max_s','accepted_steps','final_N_atoms_mol','final_oxidant_mol','t50_s','t50_reached','t90_s','t90_reached','implicit_time_residual_max','stationary_error_max'};
  states={};balances={};checkpoints={};summary=[];sampled=cell(6,3);totalsteps=0;implicit=zeros(6,3);
  for ci=1:6
    a=cases{ci};
    if any(!isfinite([a.fCER,a.fCRR,a.tau,a.HB,a.HL,a.I,a.N0,a.Na0,a.B0]))||any([a.fCER,a.fCRR]<0)||any([a.fCER,a.fCRR]>1)||min([a.tau,a.HB,a.HL])<=0||min([a.I,a.N0,a.Na0,a.B0])<0,error('Reduced:Case','Invalid fixed case %s',a.label);endif
    y0=[a.N0;a.B0;a.Na0+a.N0;0;0;a.N0;0;0;0;0;a.Na0];
    for level=1:3
      dtmax=[.2,.1,.05](level);t=0;y=y0;x=zeros(6,1);step=0;next_time=60;
      ss=zeros(20001,numel(R.state_headers));bb=zeros(20001,numel(R.balance_headers));cp=zeros(6,numel(R.checkpoint_headers));ns=1;nc=1;
      rates=rate(a,y,p.F_C_mol);ss(1,:)=state_row(ci,level,0,t,0,y,x,rates,a.I,p.F_C_mol);
      bb(1,:)=balance_row(ci,level,0,t,y,y0,x,a,E,nu,p.F_C_mol);cp(1,:)=[ci,level,0,y',x',0];
      imax=0;smax=0;t50=0;t90=0;hit50=false;hit90=false;
      while t<300
        rates=rate(a,y,p.F_C_mol);dt=min(dtmax,next_time-t);limiter=1;if next_time-t<dtmax,limiter=2;endif
        sinks=[2*rates(5),rates(3)+3*rates(5),rates(1)];stock=[y(1),y(2),y(3)];
        for q=1:3,if sinks(q)>0,bound=.5*stock(q)/sinks(q);if bound<dt,dt=bound;limiter=q+2;endif;endif;endfor
        if !isfinite(dt)||dt<=0||t+dt<=t,error('Reduced:Step','Invalid dt at case%d level%d step%d: %s',ci,level,step,jsonencode(struct('dt_s',dt,'stocks_mol',stock,'sinks_mol_s',sinks)));endif
        yn=y+nu*(dt*rates);xn=x+dt*rates;tn=t+dt;
        if any(!isfinite([yn;xn]))||min(yn([1:5,8:9,11]))<0,error('Reduced:Stock','No clipping; case%d level%d step%d actual=%s mol lower_bound=0 (amount tolerance1e-14mol; any negative retained here and stops evaluation)',ci,level,step+1,jsonencode(yn'));endif
        if !hit50&&a.N0>0&&yn(1)<=.5*a.N0,t50=t+dt*(y(1)-.5*a.N0)/(y(1)-yn(1));hit50=true;endif
        if !hit90&&a.N0>0&&yn(1)<=.1*a.N0,t90=t+dt*(y(1)-.1*a.N0)/(y(1)-yn(1));hit90=true;endif
        t=tn;y=yn;x=xn;step+=1;totalsteps+=1;
        if step>20000||totalsteps>500000,error('Reduced:Budget','Fixed step budget exceeded case%d level%d count%d total%d',ci,level,step,totalsteps);endif
        ns+=1;ss(ns,:)=state_row(ci,level,step,t,dt,y,x,rates,a.I,p.F_C_mol,limiter);
        bb(ns,:)=balance_row(ci,level,step,t,y,y0,x,a,E,nu,p.F_C_mol);
        if strcmp(a.reference_kind,'zero_oxidant'),smax=max(smax,max(abs(y-y0)));endif
        if t==next_time
          nc+=1;cp(nc,:)=[ci,level,t,y',x',a.I*t];
          if any(strcmp(a.reference_kind,{'kappa_zero','kappa_positive'}))
            lrN=log1p((y(1)-a.N0)/a.N0);
            if strcmp(a.reference_kind,'kappa_zero')
              rhs=-lrN+(2*a.HB/3)*(1/y(1)-1/a.N0);
            else
              kappa=a.B0-1.5*a.N0;lrB=log1p((y(2)-a.B0)/a.B0);rhs=-lrN-(a.HB/kappa)*(lrN-lrB);
            endif
            residual=abs(a.tau*rhs-t)/300;
            if !isfinite(residual),error('Reduced:Reference','Nonfinite declared current-off reference case%d level%d',ci,level);endif
            imax=max(imax,residual);
          endif
          next_time=min(300,next_time+60);
        endif
      endwhile
      if nc!=6,error('Reduced:Checkpoint','Exact6checkpoint schedule required');endif
      states{end+1}=ss(1:ns,:);balances{end+1}=bb(1:ns,:);checkpoints{end+1}=cp;
      % Retain all actual/limit pairs per step; summary checks aggregate normalized ratios.
      diag=bb(1:ns,:);ratios=[abs(diag(:,5))./diag(:,6),abs(diag(:,7))./diag(:,8),abs(diag(:,9))./diag(:,10),abs(diag(:,11))./diag(:,12),abs(diag(:,13))./diag(:,14),abs(diag(:,15))./diag(:,16),abs(diag(:,17))./diag(:,18),abs(diag(:,19))./diag(:,18),max(0,diag(:,20))./diag(:,21),diag(:,24),abs(diag(:,25))./diag(:,26)];
      labels={'N','Cl','oxidant','acid_Cl','Na','formal_charge','anode_Q','cathode_Q','N_ceiling','all_elements','kappa'};
      for z=1:numel(labels),C=check(C,sprintf('%s_level%d_%s_all_steps',a.label,level,labels{z}),max(ratios(:,z)),1,'1');endfor
      C=check(C,sprintf('%s_level%d_instant_anode',a.label,level),max(abs(ss(1:ns,29)+ss(1:ns,30)-a.I)),1e-12+1e-10*a.I,'A');
      C=check(C,sprintf('%s_level%d_instant_cathode',a.label,level),max(abs(ss(1:ns,31)+ss(1:ns,32)-a.I)),1e-12+1e-10*a.I,'A');
      C=check(C,sprintf('%s_level%d_initial_state',a.label,level),max(abs(ss(1,6:16)'-y0)),0,'mol');
      C=check(C,sprintf('%s_level%d_nonnegative_stocks',a.label,level),max(0,-min(diag(:,22))),1e-14,'mol');
      if a.N0==0,C=check(C,sprintf('%s_level%d_zero_N',a.label,level),max(abs([ss(1:ns,6);ss(1:ns,10)])),0,'mol');endif
      if strcmp(a.reference_kind,'zero_oxidant'),C=check(C,sprintf('%s_level%d_stationary',a.label,level),smax,0,'mol');endif
      if level==3&&any(strcmp(a.reference_kind,{'kappa_zero','kappa_positive'})),C=check(C,[a.label '_fine_implicit_time'],imax,.01,'1');endif
      summary(end+1,:)=[ci,level,dtmax,step,y(1),y(2),t50,double(hit50),t90,double(hit90),imax,smax];implicit(ci,level)=imax;
      Bscale=max([a.B0+a.I*300/(2*p.F_C_mol),Nnom,a.HB]);
      sampled{ci,level}=[cp(:,4)/Nnom,cp(:,5)/Bscale,cp(:,19)/Nnom,cp(:,15)/Bscale,cp(:,17)/Bscale,cp(:,16)/Bscale,cp(:,18)/Bscale];
    endfor
  endfor
  R.states=vertcat(states{:});R.balances=vertcat(balances{:});R.checkpoints=vertcat(checkpoints{:});R.summary=summary;
  R.refinement_headers={'case_index','E21','E10','order','order_assessed','stationary_exempt','error_floor','order_lower','order_upper','difference_limit'};
  conv=[];convlabels={};assessed=0;required=0;
  for ci=1:6
    e21=max(abs(sampled{ci,1}(:)-sampled{ci,2}(:)));e10=max(abs(sampled{ci,2}(:)-sampled{ci,3}(:)));order=0;available=false;exempt=strcmp(cases{ci}.reference_kind,'zero_oxidant');
    C=check(C,[cases{ci}.label '_fine_difference'],e10,.01,'1');
    if exempt,status='EXACT_STATIONARY_EXEMPT';else
      required+=1;
      if e21>1e-9&&e10>1e-9
        order=log2(e21/e10);available=true;assessed+=1;status='ASSESSED';C=check(C,[cases{ci}.label '_order_lower'],.7-order,0,'1');C=check(C,[cases{ci}.label '_order_upper'],order-1.3,0,'1');
      else status='NOT_ASSESSED_ERROR_FLOOR';endif
    endif
    conv(end+1,:)=[ci,e21,e10,order,double(available),double(exempt),1e-9,.7,1.3,.01];convlabels{end+1,1}=status;
  endfor
  ph=[6;7;7.5;8.4;9;11];aa=1./(1+10.^(9.3-ph));bb=1./(1+10.^(ph-7.5));g=aa.*bb;
  C=check(C,'dimensionless_prefactor_derivative_at_mean_pKa',abs(log(10)*g(4)*(bb(4)-aa(4))),1e-14,'1');
  C=check(C,'dimensionless_prefactor_declared_grid_maximum',max(g)-g(4),1e-14,'1');
  R.refinement=conv;R.refinement_labels=convlabels;R.checks=C;R.arithmetic_checks_passed=all([C.pass]);R.convergence_rows_assessed=assessed;R.convergence_rows_total=required;R.convergence_verified=assessed==required;
  R.passed=R.arithmetic_checks_passed&&R.convergence_verified;
  if !R.arithmetic_checks_passed,R.validation_status='FAILED_CHECK';elseif !R.convergence_verified,R.validation_status='PARTIAL_ERROR_FLOOR';else R.validation_status='VERIFIED_NUMERICS_ILLUSTRATIVE_ONLY';endif
  R.prefactor=[ph,aa,bb,g];
  R.prefactor_headers={'external_pH_label','alpha_NH3','alpha_HOCl','dimensionless_formation_prefactor'};
  R.total_steps=totalsteps;R.implicit_residual_by_level=implicit;
endfunction
function r=rate(a,y,F)
  cer=a.fCER*a.I/(2*F)*y(3)/(y(3)+a.HL);crr=a.fCRR*a.I/(2*F)*y(2)/(y(2)+a.HB);n2=y(1)/(2*a.tau)*y(2)/(y(2)+a.HB);
  r=[cer;(a.I-2*F*cer)/(4*F);crr;(a.I-2*F*crr)/(2*F);n2;0];
  if any(!isfinite(r))||any(r<0),error('Reduced:Rate','Invalid rate vector actual=%s mol/s lower0',jsonencode(r'));endif
endfunction
function row=state_row(ci,level,step,t,dt,y,x,r,I,F,limiter)
  if nargin<11,limiter=0;endif
  row=[ci,level,step,t,dt,y',x',r',2*F*r(1),4*F*r(2),2*F*r(3),2*F*r(4),I*t,2*F*x(1),4*F*x(2),2*F*x(3),2*F*x(4),double(any(y([1:5,8:9,11])<0)),limiter];
  if any(!isfinite(row)),error('Reduced:Finite','Entire state row must be finite');endif
endfunction
function row=balance_row(ci,level,step,t,y,y0,x,a,E,nu,F)
  atol=1e-14;rtol=1e-10;Q=a.I*t;
  nr=y(1)+2*x(5)-a.N0;nl=atol+rtol*(a.N0+2*x(5));cl=y(3)+y(2)+2*x(6)-(y0(3)+a.B0);cll=atol+rtol*(y0(3)+a.B0+x(1)+x(3)+3*x(5)+2*x(6));
  ox=y(2)+x(6)+3*x(5)+x(3)-(a.B0+x(1));ol=atol+rtol*(a.B0+x(1)+x(3)+3*x(5)+x(6));acid=y(6)-y(3)-(y0(6)-y0(3));al=atol+rtol*(abs(y0(6))+abs(y0(3))+sum(abs(y-y0)));
  nar=y(11)-a.Na0;nal=atol+rtol*a.Na0;z=y(6)-y(3)+y(11)-y(10);ql=1e-9+rtol*abs(Q);
  % Gross integrated species transfers count both consumed and produced
  % stoichiometric contributions, without cancellation of net stock changes.
  scale=atol+rtol*(abs(E)*abs(y0)+abs(E)*abs(nu)*x);element_residual=E*(y-y0);
  if any(!isfinite(scale))||any(scale<=0)||any(!isfinite(element_residual)),error('Reduced:ElementFinite','Finite positive elemental limits and finite residuals required; actual_scale=%s mol actual_residual=%s mol',mat2str(scale'),mat2str(element_residual'));endif
  elem=max(abs(element_residual)./scale);
  cap=min(a.N0,2*a.B0/3+Q/(3*F));capl=atol+rtol*(a.N0+a.B0+Q/(3*F));kr=0;kl=atol+rtol*(a.B0+1.5*a.N0);
  if a.I==0,kr=(y(2)-1.5*y(1))-(a.B0-1.5*a.N0);endif
  row=[ci,level,step,t,nr,nl,cl,cll,ox,ol,acid,al,nar,nal,z,al,2*F*x(1)+4*F*x(2)-Q,ql,2*F*x(3)+2*F*x(4)-Q,2*x(5)-cap,capl,min(y([1:5,8:9,11])),-atol,elem,kr,kl];
  if any(!isfinite(row))||any([nl,cll,ol,al,nal,ql,capl,kl]<=0),error('Reduced:Finite','Balance actuals and finite positive bounds required');endif
endfunction
function C=check(C,name,actual,limit,unit)
  pass=isnumeric(actual)&&isscalar(actual)&&isfinite(actual)&&isnumeric(limit)&&isscalar(limit)&&isfinite(limit)&&actual<=limit;
  C(end+1)=struct('name',name,'actual',full(actual),'limit',full(limit),'unit',unit,'comparison','le','pass',pass);
endfunction
function input_guard(p,name,positive)
  if !isfield(p,name)||!isnumeric(p.(name))||!isscalar(p.(name))||!isreal(p.(name))||!isfinite(p.(name)),error('Reduced:Input','Finite real scalar required: %s',name);endif
  if (positive&&p.(name)<=0)||(!positive&&p.(name)<0),error('Reduced:Input','Invalid %s actual=%s bound0 positive=%d',name,jsonencode(p.(name)),positive);endif
endfunction
elec_reduced_checkpoint_model–cb7961b4e124362d.m — registered_source

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261118T114821Z-670675-1795002501706446 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 cb7961b4e124362d34f6bc29017462758ac04d4a3b3a726846cf59883ab464b6

1; % Script-local callable definitions only; no top-level production.

function response=elec_reduced_n_concentration(parameters,predictors)
  response=elec_reduced_projection(parameters,predictors,'n_concentration');
endfunction

function response=elec_reduced_n_fraction(parameters,predictors)
  response=elec_reduced_projection(parameters,predictors,'n_fraction');
endfunction

function response=elec_reduced_oxidant_amount(parameters,predictors)
  response=elec_reduced_projection(parameters,predictors,'oxidant_amount');
endfunction

function response=elec_reduced_projection(parameters,predictors,quantity)
  % Pure, per-execution cached projection of the unchanged complete kernel.
  % No nested Bridge calls, external results, file access or interpolation.
  persistent cached_key cached_result;
  if !isnumeric(parameters)||!isreal(parameters)||numel(parameters)!=7||any(!isfinite(parameters(:)))
    error('ELEC:ModelParameters','Seven finite real parameters in declared order are required');
  endif
  parameters=parameters(:);case_index=parameters(7);
  if case_index!=fix(case_index)||case_index<1||case_index>23
    error('ELEC:ModelCase','Case index must be an integer from1 through23');
  endif
  if !isnumeric(predictors)||!isreal(predictors)||columns(predictors)!=1||any(!isfinite(predictors(:)))
    error('ELEC:ModelPredictors','Predictors must be a finite real N-by-1 column in seconds');
  endif
  allowed=(0:60:1200)';
  if !all(ismember(predictors,allowed))
    error('ELEC:ModelGrid','Only exact declared checkpoints0:60:1200 seconds are supported; no interpolation or extrapolation');
  endif
  key=parameters(1:6);
  if isempty(cached_result)||!isequal(cached_key,key)
    p=struct('volume_m3',key(1),'current_A',key(2),'initial_N_g_m3',key(3),'background_NaCl_mol_m3',key(4),'F_C_mol',key(5),'M_N_g_mol',key(6),'specification_sha256','2961766955c2b471fcc2c58b48a4f65730ef9fa89a999b630e626534810b89f4');
    result=reduced_evaluate(p);
    if !result.passed,error('ELEC:ModelChecks','Unchanged kernel checks/coverage did not pass; no prediction accepted');endif
    cached_result=result;cached_key=key;
  endif
  cp=cached_result.checkpoints(cached_result.checkpoints(:,1)==case_index & cached_result.checkpoints(:,2)==3,:);
  if !isequal(cp(:,3),allowed),error('ELEC:ModelCoverage','Exact finest-level checkpoint grid is required');endif
  [present,index]=ismember(predictors,cp(:,3));
  if !all(present),error('ELEC:ModelGrid','No source checkpoint for query');endif
  switch quantity
    case 'n_concentration',response=cp(index,4)*key(6)/key(1);
    case 'n_fraction',response=cp(index,4)/(key(3)*key(1)/key(6));
    case 'oxidant_amount',response=cp(index,5);
    otherwise,error('ELEC:ModelQuantity','Unsupported scalar projection');
  endswitch
  response=response(:);
  if any(!isfinite(response)),error('ELEC:ModelFinite','Finite response is required');endif
endfunction

% BEGIN EXACT UNCHANGED REVIEWED KERNEL
function R=reduced_evaluate(p)
  % SOURCE ONLY: illustrative reduced kinetics, no assay or physical pH model.
  spec='2961766955c2b471fcc2c58b48a4f65730ef9fa89a999b630e626534810b89f4';
  if !strcmp(p.specification_sha256,spec),error('Reduced:Spec','Exact reviewed specification04 required');endif
  positive={'volume_m3','F_C_mol','M_N_g_mol'};
  nonnegative={'current_A','initial_N_g_m3','background_NaCl_mol_m3'};
  for k=1:numel(positive),input_guard(p,positive{k},true);endfor
  for k=1:numel(nonnegative),input_guard(p,nonnegative{k},false);endfor
  % Normalization and stored controls require nominal positive N inventory.
  if p.initial_N_g_m3<=0,error('Reduced:Input','initial_N_g_m3 must be >0; chlorine-only controls are generated explicitly');endif
  R.species={'formal_NH3','formal_HOCl_equivalent','chloride','exported_Cl2','stipulated_N2','signed_acid','water_reservoir_delta','O2_cumulative','H2_cumulative','electron_reservoir_delta','Na_spectator'};
  R.reactions={'CER','OER','CRR','HER','formal_N2_endpoint','formal_Cl2_export'};
  R.elements={'N','Cl','H','O','Na','formal_charge'};
  E=[1 0 0 0 2 0 0 0 0 0 0;0 1 1 2 0 0 0 0 0 0 0;3 1 0 0 0 1 2 0 2 0 0;0 1 0 0 0 0 1 2 0 0 0;0 0 0 0 0 0 0 0 0 0 1;0 0 -1 0 0 1 0 0 0 -1 1];
  nu=[0 0 0 0 -2 0;1 0 -1 0 -3 -1;-1 0 1 0 3 -1;0 0 0 0 0 1;0 0 0 0 1 0;1 4 -1 -2 3 -1;-1 -2 1 0 3 1;0 1 0 0 0 0;0 0 0 1 0 0;2 4 -2 -2 0 0;0 0 0 0 0 0];
  R.element_matrix=E;R.reaction_matrix=nu;
  C=struct('name',{},'actual',{},'limit',{},'unit',{},'comparison',{},'pass',{});
  C=check(C,'integer_element_charge_nullspace',max(abs((E*nu)(:))),0,'1');
  Nnom=p.initial_N_g_m3*p.volume_m3/p.M_N_g_mol;Na=p.background_NaCl_mol_m3*p.volume_m3;
  if !all(isfinite([Nnom,Na]))||Nnom<=0,error('Reduced:Input','Derived N/Na amounts invalid: %s mol',jsonencode([Nnom,Na]));endif
  base=struct('label','L_m0_common_P_pH7p5','family','common','m',0,'pH_ext',7.5,'fCER',.6,'fCRR',.15,'tau',600,'HB',.1*p.volume_m3,'HL',p.volume_m3,'I',p.current_A,'N0',Nnom,'Na0',Na,'B0',0,'reference_kind','none');
  cases={base};
  for m=[1,2,4],a=base;a.label=sprintf('L_m%d',m);a.family='loss';a.m=m;a.fCRR=.15+.45*m/(1+m);cases{end+1}=a;endfor
  for ph=[6,7,8.4,9,11],a=base;a.label=['P_pH' strrep(num2str(ph),'.','p')];a.family='imposed_selectivity';a.pH_ext=ph;a.fCER=.6+.4*(1/(1+10^(ph-7.5))-.5);cases{end+1}=a;endfor
  for scale=[.5,2],a=base;a.label=['sensitivity_tau_' strrep(num2str(scale),'.','p')];a.family='sensitivity';a.tau=600*scale;cases{end+1}=a;endfor
  for scale=[.5,2],a=base;a.label=['sensitivity_HB_' strrep(num2str(scale),'.','p')];a.family='sensitivity';a.HB=base.HB*scale;cases{end+1}=a;endfor
  for scale=[.5,1.5],a=cases{3};a.label=['sensitivity_loss_contrast_' strrep(num2str(scale),'.','p')];a.family='sensitivity';a.fCRR=.15+.45*scale*2/3;cases{end+1}=a;endfor
  for scale=[.5,1.5],a=cases{8};a.label=['sensitivity_selectivity_contrast_' strrep(num2str(scale),'.','p')];a.family='sensitivity';a.fCER=.6+.4*scale*(1/(1+10^(9-7.5))-.5);cases{end+1}=a;endfor
  for index=[1,4,9],a=cases{index};a.label=['chlorine_only_' a.label];a.family='chlorine_only';a.N0=0;cases{end+1}=a;endfor
  for kind={'zero_oxidant','kappa_zero','kappa_positive'}
    a=base;a.label=['current_off_' kind{1}];a.family='current_off';a.reference_kind=kind{1};a.I=0;a.fCER=0;a.fCRR=0;
    if strcmp(kind{1},'kappa_zero'),a.B0=1.5*Nnom;elseif strcmp(kind{1},'kappa_positive'),a.B0=3*Nnom;endif
    cases{end+1}=a;
  endfor
  if numel(cases)!=23,error('Reduced:Plan','Fixed23case plan violated');endif
  R.cases=cases;R.state_headers=[{'case_index','level','step','time_s','dt_s'},R.species,strcat('extent_',R.reactions),strcat('rate_used_',R.reactions),{'I_CER_A','I_OER_A','I_CRR_A','I_HER_A','Q_C','Q_CER_C','Q_OER_C','Q_CRR_C','Q_HER_C','tiny_negative_flag','dt_limiter_code'}];
  R.checkpoint_headers=[{'case_index','level','time_s'},R.species,strcat('extent_',R.reactions),{'Q_C'}];
  R.balance_headers={'case_index','level','step','time_s','N_residual','N_limit','Cl_residual','Cl_limit','oxidant_residual','oxidant_limit','acid_Cl_residual','acid_Cl_limit','Na_residual','Na_limit','formal_charge','formal_charge_limit','anode_Q_residual','Q_limit','cathode_Q_residual','N_ceiling_excess','N_ceiling_limit','min_stock','stock_lower_bound','element_scaled_max','kappa_residual','kappa_limit'};
  R.summary_headers={'case_index','level','dt_max_s','accepted_steps','final_N_atoms_mol','final_oxidant_mol','t50_s','t50_reached','t90_s','t90_reached','implicit_time_residual_max','stationary_error_max'};
  states={};balances={};checkpoints={};summary=[];sampled=cell(23,3);totalsteps=0;implicit=zeros(23,3);
  for ci=1:23
    a=cases{ci};
    if any(!isfinite([a.fCER,a.fCRR,a.tau,a.HB,a.HL,a.I,a.N0,a.Na0,a.B0]))||any([a.fCER,a.fCRR]<0)||any([a.fCER,a.fCRR]>1)||min([a.tau,a.HB,a.HL])<=0||min([a.I,a.N0,a.Na0,a.B0])<0,error('Reduced:Case','Invalid fixed case %s',a.label);endif
    y0=[a.N0;a.B0;a.Na0+a.N0;0;0;a.N0;0;0;0;0;a.Na0];
    for level=1:3
      dtmax=[2,1,.5](level);t=0;y=y0;x=zeros(6,1);step=0;next_time=60;
      ss=zeros(20001,numel(R.state_headers));bb=zeros(20001,numel(R.balance_headers));cp=zeros(21,numel(R.checkpoint_headers));ns=1;nc=1;
      rates=rate(a,y,p.F_C_mol);ss(1,:)=state_row(ci,level,0,t,0,y,x,rates,a.I,p.F_C_mol);
      bb(1,:)=balance_row(ci,level,0,t,y,y0,x,a,E,nu,p.F_C_mol);cp(1,:)=[ci,level,0,y',x',0];
      imax=0;smax=0;t50=0;t90=0;hit50=false;hit90=false;
      while t<1200
        rates=rate(a,y,p.F_C_mol);dt=min(dtmax,next_time-t);limiter=1;if next_time-t<dtmax,limiter=2;endif
        sinks=[2*rates(5),rates(3)+3*rates(5),rates(1)];stock=[y(1),y(2),y(3)];
        for q=1:3,if sinks(q)>0,bound=.5*stock(q)/sinks(q);if bound<dt,dt=bound;limiter=q+2;endif;endif;endfor
        if !isfinite(dt)||dt<=0||t+dt<=t,error('Reduced:Step','Invalid dt at case%d level%d step%d: %s',ci,level,step,jsonencode(struct('dt_s',dt,'stocks_mol',stock,'sinks_mol_s',sinks)));endif
        yn=y+nu*(dt*rates);xn=x+dt*rates;tn=t+dt;
        if any(!isfinite([yn;xn]))||min(yn([1:5,8:9,11]))<0,error('Reduced:Stock','No clipping; case%d level%d step%d actual=%s mol lower_bound=0 (amount tolerance1e-14mol; any negative retained here and stops evaluation)',ci,level,step+1,jsonencode(yn'));endif
        if !hit50&&a.N0>0&&yn(1)<=.5*a.N0,t50=t+dt*(y(1)-.5*a.N0)/(y(1)-yn(1));hit50=true;endif
        if !hit90&&a.N0>0&&yn(1)<=.1*a.N0,t90=t+dt*(y(1)-.1*a.N0)/(y(1)-yn(1));hit90=true;endif
        t=tn;y=yn;x=xn;step+=1;totalsteps+=1;
        if step>20000||totalsteps>500000,error('Reduced:Budget','Fixed step budget exceeded case%d level%d count%d total%d',ci,level,step,totalsteps);endif
        ns+=1;ss(ns,:)=state_row(ci,level,step,t,dt,y,x,rates,a.I,p.F_C_mol,limiter);
        bb(ns,:)=balance_row(ci,level,step,t,y,y0,x,a,E,nu,p.F_C_mol);
        if strcmp(a.reference_kind,'zero_oxidant'),smax=max(smax,max(abs(y-y0)));endif
        if t==next_time
          nc+=1;cp(nc,:)=[ci,level,t,y',x',a.I*t];
          if any(strcmp(a.reference_kind,{'kappa_zero','kappa_positive'}))
            lrN=log1p((y(1)-a.N0)/a.N0);
            if strcmp(a.reference_kind,'kappa_zero')
              rhs=-lrN+(2*a.HB/3)*(1/y(1)-1/a.N0);
            else
              kappa=a.B0-1.5*a.N0;lrB=log1p((y(2)-a.B0)/a.B0);rhs=-lrN-(a.HB/kappa)*(lrN-lrB);
            endif
            residual=abs(a.tau*rhs-t)/1200;
            if !isfinite(residual),error('Reduced:Reference','Nonfinite declared current-off reference case%d level%d',ci,level);endif
            imax=max(imax,residual);
          endif
          next_time=min(1200,next_time+60);
        endif
      endwhile
      if nc!=21,error('Reduced:Checkpoint','Exact21checkpoint schedule required');endif
      states{end+1}=ss(1:ns,:);balances{end+1}=bb(1:ns,:);checkpoints{end+1}=cp;
      % Retain all actual/limit pairs per step; summary checks aggregate normalized ratios.
      diag=bb(1:ns,:);ratios=[abs(diag(:,5))./diag(:,6),abs(diag(:,7))./diag(:,8),abs(diag(:,9))./diag(:,10),abs(diag(:,11))./diag(:,12),abs(diag(:,13))./diag(:,14),abs(diag(:,15))./diag(:,16),abs(diag(:,17))./diag(:,18),abs(diag(:,19))./diag(:,18),max(0,diag(:,20))./diag(:,21),diag(:,24),abs(diag(:,25))./diag(:,26)];
      labels={'N','Cl','oxidant','acid_Cl','Na','formal_charge','anode_Q','cathode_Q','N_ceiling','all_elements','kappa'};
      for z=1:numel(labels),C=check(C,sprintf('%s_level%d_%s_all_steps',a.label,level,labels{z}),max(ratios(:,z)),1,'1');endfor
      C=check(C,sprintf('%s_level%d_instant_anode',a.label,level),max(abs(ss(1:ns,29)+ss(1:ns,30)-a.I)),1e-12+1e-10*a.I,'A');
      C=check(C,sprintf('%s_level%d_instant_cathode',a.label,level),max(abs(ss(1:ns,31)+ss(1:ns,32)-a.I)),1e-12+1e-10*a.I,'A');
      C=check(C,sprintf('%s_level%d_initial_state',a.label,level),max(abs(ss(1,6:16)'-y0)),0,'mol');
      C=check(C,sprintf('%s_level%d_nonnegative_stocks',a.label,level),max(0,-min(diag(:,22))),1e-14,'mol');
      if a.N0==0,C=check(C,sprintf('%s_level%d_zero_N',a.label,level),max(abs([ss(1:ns,6);ss(1:ns,10)])),0,'mol');endif
      if strcmp(a.reference_kind,'zero_oxidant'),C=check(C,sprintf('%s_level%d_stationary',a.label,level),smax,0,'mol');endif
      if level==3&&any(strcmp(a.reference_kind,{'kappa_zero','kappa_positive'})),C=check(C,[a.label '_fine_implicit_time'],imax,.01,'1');endif
      summary(end+1,:)=[ci,level,dtmax,step,y(1),y(2),t50,double(hit50),t90,double(hit90),imax,smax];implicit(ci,level)=imax;
      Bscale=max([a.B0+a.I*1200/(2*p.F_C_mol),Nnom,a.HB]);
      sampled{ci,level}=[cp(:,4)/Nnom,cp(:,5)/Bscale,cp(:,19)/Nnom,cp(:,15)/Bscale,cp(:,17)/Bscale,cp(:,16)/Bscale,cp(:,18)/Bscale];
    endfor
  endfor
  R.states=vertcat(states{:});R.balances=vertcat(balances{:});R.checkpoints=vertcat(checkpoints{:});R.summary=summary;
  R.refinement_headers={'case_index','E21','E10','order','order_assessed','stationary_exempt','error_floor','order_lower','order_upper','difference_limit'};
  conv=[];convlabels={};assessed=0;required=0;
  for ci=1:23
    e21=max(abs(sampled{ci,1}(:)-sampled{ci,2}(:)));e10=max(abs(sampled{ci,2}(:)-sampled{ci,3}(:)));order=0;available=false;exempt=strcmp(cases{ci}.reference_kind,'zero_oxidant');
    C=check(C,[cases{ci}.label '_fine_difference'],e10,.01,'1');
    if exempt,status='EXACT_STATIONARY_EXEMPT';else
      required+=1;
      if e21>1e-9&&e10>1e-9
        order=log2(e21/e10);available=true;assessed+=1;status='ASSESSED';C=check(C,[cases{ci}.label '_order_lower'],.7-order,0,'1');C=check(C,[cases{ci}.label '_order_upper'],order-1.3,0,'1');
      else status='NOT_ASSESSED_ERROR_FLOOR';endif
    endif
    conv(end+1,:)=[ci,e21,e10,order,double(available),double(exempt),1e-9,.7,1.3,.01];convlabels{end+1,1}=status;
  endfor
  ph=[6;7;7.5;8.4;9;11];aa=1./(1+10.^(9.3-ph));bb=1./(1+10.^(ph-7.5));g=aa.*bb;
  C=check(C,'dimensionless_prefactor_derivative_at_mean_pKa',abs(log(10)*g(4)*(bb(4)-aa(4))),1e-14,'1');
  C=check(C,'dimensionless_prefactor_declared_grid_maximum',max(g)-g(4),1e-14,'1');
  R.refinement=conv;R.refinement_labels=convlabels;R.checks=C;R.arithmetic_checks_passed=all([C.pass]);R.convergence_rows_assessed=assessed;R.convergence_rows_total=required;R.convergence_verified=assessed==required;
  R.passed=R.arithmetic_checks_passed&&R.convergence_verified;
  if !R.arithmetic_checks_passed,R.validation_status='FAILED_CHECK';elseif !R.convergence_verified,R.validation_status='PARTIAL_ERROR_FLOOR';else R.validation_status='VERIFIED_NUMERICS_ILLUSTRATIVE_ONLY';endif
  R.prefactor=[ph,aa,bb,g];
  R.prefactor_headers={'external_pH_label','alpha_NH3','alpha_HOCl','dimensionless_formation_prefactor'};
  R.total_steps=totalsteps;R.implicit_residual_by_level=implicit;
endfunction
function r=rate(a,y,F)
  cer=a.fCER*a.I/(2*F)*y(3)/(y(3)+a.HL);crr=a.fCRR*a.I/(2*F)*y(2)/(y(2)+a.HB);n2=y(1)/(2*a.tau)*y(2)/(y(2)+a.HB);
  r=[cer;(a.I-2*F*cer)/(4*F);crr;(a.I-2*F*crr)/(2*F);n2;0];
  if any(!isfinite(r))||any(r<0),error('Reduced:Rate','Invalid rate vector actual=%s mol/s lower0',jsonencode(r'));endif
endfunction
function row=state_row(ci,level,step,t,dt,y,x,r,I,F,limiter)
  if nargin<11,limiter=0;endif
  row=[ci,level,step,t,dt,y',x',r',2*F*r(1),4*F*r(2),2*F*r(3),2*F*r(4),I*t,2*F*x(1),4*F*x(2),2*F*x(3),2*F*x(4),double(any(y([1:5,8:9,11])<0)),limiter];
  if any(!isfinite(row)),error('Reduced:Finite','Entire state row must be finite');endif
endfunction
function row=balance_row(ci,level,step,t,y,y0,x,a,E,nu,F)
  atol=1e-14;rtol=1e-10;Q=a.I*t;
  nr=y(1)+2*x(5)-a.N0;nl=atol+rtol*(a.N0+2*x(5));cl=y(3)+y(2)+2*x(6)-(y0(3)+a.B0);cll=atol+rtol*(y0(3)+a.B0+x(1)+x(3)+3*x(5)+2*x(6));
  ox=y(2)+x(6)+3*x(5)+x(3)-(a.B0+x(1));ol=atol+rtol*(a.B0+x(1)+x(3)+3*x(5)+x(6));acid=y(6)-y(3)-(y0(6)-y0(3));al=atol+rtol*(abs(y0(6))+abs(y0(3))+sum(abs(y-y0)));
  nar=y(11)-a.Na0;nal=atol+rtol*a.Na0;z=y(6)-y(3)+y(11)-y(10);ql=1e-9+rtol*abs(Q);
  % Gross integrated species transfers count both consumed and produced
  % stoichiometric contributions, without cancellation of net stock changes.
  scale=atol+rtol*(abs(E)*abs(y0)+abs(E)*abs(nu)*x);element_residual=E*(y-y0);
  if any(!isfinite(scale))||any(scale<=0)||any(!isfinite(element_residual)),error('Reduced:ElementFinite','Finite positive elemental limits and finite residuals required; actual_scale=%s mol actual_residual=%s mol',mat2str(scale'),mat2str(element_residual'));endif
  elem=max(abs(element_residual)./scale);
  cap=min(a.N0,2*a.B0/3+Q/(3*F));capl=atol+rtol*(a.N0+a.B0+Q/(3*F));kr=0;kl=atol+rtol*(a.B0+1.5*a.N0);
  if a.I==0,kr=(y(2)-1.5*y(1))-(a.B0-1.5*a.N0);endif
  row=[ci,level,step,t,nr,nl,cl,cll,ox,ol,acid,al,nar,nal,z,al,2*F*x(1)+4*F*x(2)-Q,ql,2*F*x(3)+2*F*x(4)-Q,2*x(5)-cap,capl,min(y([1:5,8:9,11])),-atol,elem,kr,kl];
  if any(!isfinite(row))||any([nl,cll,ol,al,nal,ql,capl,kl]<=0),error('Reduced:Finite','Balance actuals and finite positive bounds required');endif
endfunction
function C=check(C,name,actual,limit,unit)
  pass=isnumeric(actual)&&isscalar(actual)&&isfinite(actual)&&isnumeric(limit)&&isscalar(limit)&&isfinite(limit)&&actual<=limit;
  C(end+1)=struct('name',name,'actual',full(actual),'limit',full(limit),'unit',unit,'comparison','le','pass',pass);
endfunction
function input_guard(p,name,positive)
  if !isfield(p,name)||!isnumeric(p.(name))||!isscalar(p.(name))||!isreal(p.(name))||!isfinite(p.(name)),error('Reduced:Input','Finite real scalar required: %s',name);endif
  if (positive&&p.(name)<=0)||(!positive&&p.(name)<0),error('Reduced:Input','Invalid %s actual=%s bound0 positive=%d',name,jsonencode(p.(name)),positive);endif
endfunction
elec_reduced_competing_scenarios__reduced_evaluate–b5901a87d083922b.m — Direct named helper referenced by entrypoint

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261118T093245Z-4091642-1794994365236654 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 b5901a87d083922b4cf192687986d19cdd81a60de70cb9cbc3d399b07601561c

function R=reduced_evaluate(p)
  % SOURCE ONLY: illustrative reduced kinetics, no assay or physical pH model.
  spec='2961766955c2b471fcc2c58b48a4f65730ef9fa89a999b630e626534810b89f4';
  if !strcmp(p.specification_sha256,spec),error('Reduced:Spec','Exact reviewed specification04 required');endif
  positive={'volume_m3','F_C_mol','M_N_g_mol'};
  nonnegative={'current_A','initial_N_g_m3','background_NaCl_mol_m3'};
  for k=1:numel(positive),input_guard(p,positive{k},true);endfor
  for k=1:numel(nonnegative),input_guard(p,nonnegative{k},false);endfor
  % Normalization and stored controls require nominal positive N inventory.
  if p.initial_N_g_m3<=0,error('Reduced:Input','initial_N_g_m3 must be >0; chlorine-only controls are generated explicitly');endif
  R.species={'formal_NH3','formal_HOCl_equivalent','chloride','exported_Cl2','stipulated_N2','signed_acid','water_reservoir_delta','O2_cumulative','H2_cumulative','electron_reservoir_delta','Na_spectator'};
  R.reactions={'CER','OER','CRR','HER','formal_N2_endpoint','formal_Cl2_export'};
  R.elements={'N','Cl','H','O','Na','formal_charge'};
  E=[1 0 0 0 2 0 0 0 0 0 0;0 1 1 2 0 0 0 0 0 0 0;3 1 0 0 0 1 2 0 2 0 0;0 1 0 0 0 0 1 2 0 0 0;0 0 0 0 0 0 0 0 0 0 1;0 0 -1 0 0 1 0 0 0 -1 1];
  nu=[0 0 0 0 -2 0;1 0 -1 0 -3 -1;-1 0 1 0 3 -1;0 0 0 0 0 1;0 0 0 0 1 0;1 4 -1 -2 3 -1;-1 -2 1 0 3 1;0 1 0 0 0 0;0 0 0 1 0 0;2 4 -2 -2 0 0;0 0 0 0 0 0];
  R.element_matrix=E;R.reaction_matrix=nu;
  C=struct('name',{},'actual',{},'limit',{},'unit',{},'comparison',{},'pass',{});
  C=check(C,'integer_element_charge_nullspace',max(abs((E*nu)(:))),0,'1');
  Nnom=p.initial_N_g_m3*p.volume_m3/p.M_N_g_mol;Na=p.background_NaCl_mol_m3*p.volume_m3;
  if !all(isfinite([Nnom,Na]))||Nnom<=0,error('Reduced:Input','Derived N/Na amounts invalid: %s mol',jsonencode([Nnom,Na]));endif
  base=struct('label','L_m0_common_P_pH7p5','family','common','m',0,'pH_ext',7.5,'fCER',.6,'fCRR',.15,'tau',600,'HB',.1*p.volume_m3,'HL',p.volume_m3,'I',p.current_A,'N0',Nnom,'Na0',Na,'B0',0,'reference_kind','none');
  cases={base};
  for m=[1,2,4],a=base;a.label=sprintf('L_m%d',m);a.family='loss';a.m=m;a.fCRR=.15+.45*m/(1+m);cases{end+1}=a;endfor
  for ph=[6,7,8.4,9,11],a=base;a.label=['P_pH' strrep(num2str(ph),'.','p')];a.family='imposed_selectivity';a.pH_ext=ph;a.fCER=.6+.4*(1/(1+10^(ph-7.5))-.5);cases{end+1}=a;endfor
  for scale=[.5,2],a=base;a.label=['sensitivity_tau_' strrep(num2str(scale),'.','p')];a.family='sensitivity';a.tau=600*scale;cases{end+1}=a;endfor
  for scale=[.5,2],a=base;a.label=['sensitivity_HB_' strrep(num2str(scale),'.','p')];a.family='sensitivity';a.HB=base.HB*scale;cases{end+1}=a;endfor
  for scale=[.5,1.5],a=cases{3};a.label=['sensitivity_loss_contrast_' strrep(num2str(scale),'.','p')];a.family='sensitivity';a.fCRR=.15+.45*scale*2/3;cases{end+1}=a;endfor
  for scale=[.5,1.5],a=cases{8};a.label=['sensitivity_selectivity_contrast_' strrep(num2str(scale),'.','p')];a.family='sensitivity';a.fCER=.6+.4*scale*(1/(1+10^(9-7.5))-.5);cases{end+1}=a;endfor
  for index=[1,4,9],a=cases{index};a.label=['chlorine_only_' a.label];a.family='chlorine_only';a.N0=0;cases{end+1}=a;endfor
  for kind={'zero_oxidant','kappa_zero','kappa_positive'}
    a=base;a.label=['current_off_' kind{1}];a.family='current_off';a.reference_kind=kind{1};a.I=0;a.fCER=0;a.fCRR=0;
    if strcmp(kind{1},'kappa_zero'),a.B0=1.5*Nnom;elseif strcmp(kind{1},'kappa_positive'),a.B0=3*Nnom;endif
    cases{end+1}=a;
  endfor
  if numel(cases)!=23,error('Reduced:Plan','Fixed23case plan violated');endif
  R.cases=cases;R.state_headers=[{'case_index','level','step','time_s','dt_s'},R.species,strcat('extent_',R.reactions),strcat('rate_used_',R.reactions),{'I_CER_A','I_OER_A','I_CRR_A','I_HER_A','Q_C','Q_CER_C','Q_OER_C','Q_CRR_C','Q_HER_C','tiny_negative_flag','dt_limiter_code'}];
  R.checkpoint_headers=[{'case_index','level','time_s'},R.species,strcat('extent_',R.reactions),{'Q_C'}];
  R.balance_headers={'case_index','level','step','time_s','N_residual','N_limit','Cl_residual','Cl_limit','oxidant_residual','oxidant_limit','acid_Cl_residual','acid_Cl_limit','Na_residual','Na_limit','formal_charge','formal_charge_limit','anode_Q_residual','Q_limit','cathode_Q_residual','N_ceiling_excess','N_ceiling_limit','min_stock','stock_lower_bound','element_scaled_max','kappa_residual','kappa_limit'};
  R.summary_headers={'case_index','level','dt_max_s','accepted_steps','final_N_atoms_mol','final_oxidant_mol','t50_s','t50_reached','t90_s','t90_reached','implicit_time_residual_max','stationary_error_max'};
  states={};balances={};checkpoints={};summary=[];sampled=cell(23,3);totalsteps=0;implicit=zeros(23,3);
  for ci=1:23
    a=cases{ci};
    if any(!isfinite([a.fCER,a.fCRR,a.tau,a.HB,a.HL,a.I,a.N0,a.Na0,a.B0]))||any([a.fCER,a.fCRR]<0)||any([a.fCER,a.fCRR]>1)||min([a.tau,a.HB,a.HL])<=0||min([a.I,a.N0,a.Na0,a.B0])<0,error('Reduced:Case','Invalid fixed case %s',a.label);endif
    y0=[a.N0;a.B0;a.Na0+a.N0;0;0;a.N0;0;0;0;0;a.Na0];
    for level=1:3
      dtmax=[2,1,.5](level);t=0;y=y0;x=zeros(6,1);step=0;next_time=60;
      ss=zeros(20001,numel(R.state_headers));bb=zeros(20001,numel(R.balance_headers));cp=zeros(21,numel(R.checkpoint_headers));ns=1;nc=1;
      rates=rate(a,y,p.F_C_mol);ss(1,:)=state_row(ci,level,0,t,0,y,x,rates,a.I,p.F_C_mol);
      bb(1,:)=balance_row(ci,level,0,t,y,y0,x,a,E,nu,p.F_C_mol);cp(1,:)=[ci,level,0,y',x',0];
      imax=0;smax=0;t50=0;t90=0;hit50=false;hit90=false;
      while t<1200
        rates=rate(a,y,p.F_C_mol);dt=min(dtmax,next_time-t);limiter=1;if next_time-t<dtmax,limiter=2;endif
        sinks=[2*rates(5),rates(3)+3*rates(5),rates(1)];stock=[y(1),y(2),y(3)];
        for q=1:3,if sinks(q)>0,bound=.5*stock(q)/sinks(q);if bound<dt,dt=bound;limiter=q+2;endif;endif;endfor
        if !isfinite(dt)||dt<=0||t+dt<=t,error('Reduced:Step','Invalid dt at case%d level%d step%d: %s',ci,level,step,jsonencode(struct('dt_s',dt,'stocks_mol',stock,'sinks_mol_s',sinks)));endif
        yn=y+nu*(dt*rates);xn=x+dt*rates;tn=t+dt;
        if any(!isfinite([yn;xn]))||min(yn([1:5,8:9,11]))<0,error('Reduced:Stock','No clipping; case%d level%d step%d actual=%s mol lower_bound=0 (amount tolerance1e-14mol; any negative retained here and stops evaluation)',ci,level,step+1,jsonencode(yn'));endif
        if !hit50&&a.N0>0&&yn(1)<=.5*a.N0,t50=t+dt*(y(1)-.5*a.N0)/(y(1)-yn(1));hit50=true;endif
        if !hit90&&a.N0>0&&yn(1)<=.1*a.N0,t90=t+dt*(y(1)-.1*a.N0)/(y(1)-yn(1));hit90=true;endif
        t=tn;y=yn;x=xn;step+=1;totalsteps+=1;
        if step>20000||totalsteps>500000,error('Reduced:Budget','Fixed step budget exceeded case%d level%d count%d total%d',ci,level,step,totalsteps);endif
        ns+=1;ss(ns,:)=state_row(ci,level,step,t,dt,y,x,rates,a.I,p.F_C_mol,limiter);
        bb(ns,:)=balance_row(ci,level,step,t,y,y0,x,a,E,nu,p.F_C_mol);
        if strcmp(a.reference_kind,'zero_oxidant'),smax=max(smax,max(abs(y-y0)));endif
        if t==next_time
          nc+=1;cp(nc,:)=[ci,level,t,y',x',a.I*t];
          if any(strcmp(a.reference_kind,{'kappa_zero','kappa_positive'}))
            lrN=log1p((y(1)-a.N0)/a.N0);
            if strcmp(a.reference_kind,'kappa_zero')
              rhs=-lrN+(2*a.HB/3)*(1/y(1)-1/a.N0);
            else
              kappa=a.B0-1.5*a.N0;lrB=log1p((y(2)-a.B0)/a.B0);rhs=-lrN-(a.HB/kappa)*(lrN-lrB);
            endif
            residual=abs(a.tau*rhs-t)/1200;
            if !isfinite(residual),error('Reduced:Reference','Nonfinite declared current-off reference case%d level%d',ci,level);endif
            imax=max(imax,residual);
          endif
          next_time=min(1200,next_time+60);
        endif
      endwhile
      if nc!=21,error('Reduced:Checkpoint','Exact21checkpoint schedule required');endif
      states{end+1}=ss(1:ns,:);balances{end+1}=bb(1:ns,:);checkpoints{end+1}=cp;
      % Retain all actual/limit pairs per step; summary checks aggregate normalized ratios.
      diag=bb(1:ns,:);ratios=[abs(diag(:,5))./diag(:,6),abs(diag(:,7))./diag(:,8),abs(diag(:,9))./diag(:,10),abs(diag(:,11))./diag(:,12),abs(diag(:,13))./diag(:,14),abs(diag(:,15))./diag(:,16),abs(diag(:,17))./diag(:,18),abs(diag(:,19))./diag(:,18),max(0,diag(:,20))./diag(:,21),diag(:,24),abs(diag(:,25))./diag(:,26)];
      labels={'N','Cl','oxidant','acid_Cl','Na','formal_charge','anode_Q','cathode_Q','N_ceiling','all_elements','kappa'};
      for z=1:numel(labels),C=check(C,sprintf('%s_level%d_%s_all_steps',a.label,level,labels{z}),max(ratios(:,z)),1,'1');endfor
      C=check(C,sprintf('%s_level%d_instant_anode',a.label,level),max(abs(ss(1:ns,29)+ss(1:ns,30)-a.I)),1e-12+1e-10*a.I,'A');
      C=check(C,sprintf('%s_level%d_instant_cathode',a.label,level),max(abs(ss(1:ns,31)+ss(1:ns,32)-a.I)),1e-12+1e-10*a.I,'A');
      C=check(C,sprintf('%s_level%d_initial_state',a.label,level),max(abs(ss(1,6:16)'-y0)),0,'mol');
      C=check(C,sprintf('%s_level%d_nonnegative_stocks',a.label,level),max(0,-min(diag(:,22))),1e-14,'mol');
      if a.N0==0,C=check(C,sprintf('%s_level%d_zero_N',a.label,level),max(abs([ss(1:ns,6);ss(1:ns,10)])),0,'mol');endif
      if strcmp(a.reference_kind,'zero_oxidant'),C=check(C,sprintf('%s_level%d_stationary',a.label,level),smax,0,'mol');endif
      if level==3&&any(strcmp(a.reference_kind,{'kappa_zero','kappa_positive'})),C=check(C,[a.label '_fine_implicit_time'],imax,.01,'1');endif
      summary(end+1,:)=[ci,level,dtmax,step,y(1),y(2),t50,double(hit50),t90,double(hit90),imax,smax];implicit(ci,level)=imax;
      Bscale=max([a.B0+a.I*1200/(2*p.F_C_mol),Nnom,a.HB]);
      sampled{ci,level}=[cp(:,4)/Nnom,cp(:,5)/Bscale,cp(:,19)/Nnom,cp(:,15)/Bscale,cp(:,17)/Bscale,cp(:,16)/Bscale,cp(:,18)/Bscale];
    endfor
  endfor
  R.states=vertcat(states{:});R.balances=vertcat(balances{:});R.checkpoints=vertcat(checkpoints{:});R.summary=summary;
  R.refinement_headers={'case_index','E21','E10','order','order_assessed','stationary_exempt','error_floor','order_lower','order_upper','difference_limit'};
  conv=[];convlabels={};assessed=0;required=0;
  for ci=1:23
    e21=max(abs(sampled{ci,1}(:)-sampled{ci,2}(:)));e10=max(abs(sampled{ci,2}(:)-sampled{ci,3}(:)));order=0;available=false;exempt=strcmp(cases{ci}.reference_kind,'zero_oxidant');
    C=check(C,[cases{ci}.label '_fine_difference'],e10,.01,'1');
    if exempt,status='EXACT_STATIONARY_EXEMPT';else
      required+=1;
      if e21>1e-9&&e10>1e-9
        order=log2(e21/e10);available=true;assessed+=1;status='ASSESSED';C=check(C,[cases{ci}.label '_order_lower'],.7-order,0,'1');C=check(C,[cases{ci}.label '_order_upper'],order-1.3,0,'1');
      else status='NOT_ASSESSED_ERROR_FLOOR';endif
    endif
    conv(end+1,:)=[ci,e21,e10,order,double(available),double(exempt),1e-9,.7,1.3,.01];convlabels{end+1,1}=status;
  endfor
  ph=[6;7;7.5;8.4;9;11];aa=1./(1+10.^(9.3-ph));bb=1./(1+10.^(ph-7.5));g=aa.*bb;
  C=check(C,'dimensionless_prefactor_derivative_at_mean_pKa',abs(log(10)*g(4)*(bb(4)-aa(4))),1e-14,'1');
  C=check(C,'dimensionless_prefactor_declared_grid_maximum',max(g)-g(4),1e-14,'1');
  R.refinement=conv;R.refinement_labels=convlabels;R.checks=C;R.arithmetic_checks_passed=all([C.pass]);R.convergence_rows_assessed=assessed;R.convergence_rows_total=required;R.convergence_verified=assessed==required;
  R.passed=R.arithmetic_checks_passed&&R.convergence_verified;
  if !R.arithmetic_checks_passed,R.validation_status='FAILED_CHECK';elseif !R.convergence_verified,R.validation_status='PARTIAL_ERROR_FLOOR';else R.validation_status='VERIFIED_NUMERICS_ILLUSTRATIVE_ONLY';endif
  R.prefactor=[ph,aa,bb,g];
  R.prefactor_headers={'external_pH_label','alpha_NH3','alpha_HOCl','dimensionless_formation_prefactor'};
  R.total_steps=totalsteps;R.implicit_residual_by_level=implicit;
endfunction
function r=rate(a,y,F)
  cer=a.fCER*a.I/(2*F)*y(3)/(y(3)+a.HL);crr=a.fCRR*a.I/(2*F)*y(2)/(y(2)+a.HB);n2=y(1)/(2*a.tau)*y(2)/(y(2)+a.HB);
  r=[cer;(a.I-2*F*cer)/(4*F);crr;(a.I-2*F*crr)/(2*F);n2;0];
  if any(!isfinite(r))||any(r<0),error('Reduced:Rate','Invalid rate vector actual=%s mol/s lower0',jsonencode(r'));endif
endfunction
function row=state_row(ci,level,step,t,dt,y,x,r,I,F,limiter)
  if nargin<11,limiter=0;endif
  row=[ci,level,step,t,dt,y',x',r',2*F*r(1),4*F*r(2),2*F*r(3),2*F*r(4),I*t,2*F*x(1),4*F*x(2),2*F*x(3),2*F*x(4),double(any(y([1:5,8:9,11])<0)),limiter];
  if any(!isfinite(row)),error('Reduced:Finite','Entire state row must be finite');endif
endfunction
function row=balance_row(ci,level,step,t,y,y0,x,a,E,nu,F)
  atol=1e-14;rtol=1e-10;Q=a.I*t;
  nr=y(1)+2*x(5)-a.N0;nl=atol+rtol*(a.N0+2*x(5));cl=y(3)+y(2)+2*x(6)-(y0(3)+a.B0);cll=atol+rtol*(y0(3)+a.B0+x(1)+x(3)+3*x(5)+2*x(6));
  ox=y(2)+x(6)+3*x(5)+x(3)-(a.B0+x(1));ol=atol+rtol*(a.B0+x(1)+x(3)+3*x(5)+x(6));acid=y(6)-y(3)-(y0(6)-y0(3));al=atol+rtol*(abs(y0(6))+abs(y0(3))+sum(abs(y-y0)));
  nar=y(11)-a.Na0;nal=atol+rtol*a.Na0;z=y(6)-y(3)+y(11)-y(10);ql=1e-9+rtol*abs(Q);
  % Gross integrated species transfers count both consumed and produced
  % stoichiometric contributions, without cancellation of net stock changes.
  scale=atol+rtol*(abs(E)*abs(y0)+abs(E)*abs(nu)*x);element_residual=E*(y-y0);
  if any(!isfinite(scale))||any(scale<=0)||any(!isfinite(element_residual)),error('Reduced:ElementFinite','Finite positive elemental limits and finite residuals required; actual_scale=%s mol actual_residual=%s mol',mat2str(scale'),mat2str(element_residual'));endif
  elem=max(abs(element_residual)./scale);
  cap=min(a.N0,2*a.B0/3+Q/(3*F));capl=atol+rtol*(a.N0+a.B0+Q/(3*F));kr=0;kl=atol+rtol*(a.B0+1.5*a.N0);
  if a.I==0,kr=(y(2)-1.5*y(1))-(a.B0-1.5*a.N0);endif
  row=[ci,level,step,t,nr,nl,cl,cll,ox,ol,acid,al,nar,nal,z,al,2*F*x(1)+4*F*x(2)-Q,ql,2*F*x(3)+2*F*x(4)-Q,2*x(5)-cap,capl,min(y([1:5,8:9,11])),-atol,elem,kr,kl];
  if any(!isfinite(row))||any([nl,cll,ol,al,nal,ql,capl,kl]<=0),error('Reduced:Finite','Balance actuals and finite positive bounds required');endif
endfunction
function C=check(C,name,actual,limit,unit)
  pass=isnumeric(actual)&&isscalar(actual)&&isfinite(actual)&&isnumeric(limit)&&isscalar(limit)&&isfinite(limit)&&actual<=limit;
  C(end+1)=struct('name',name,'actual',full(actual),'limit',full(limit),'unit',unit,'comparison','le','pass',pass);
endfunction
function input_guard(p,name,positive)
  if !isfield(p,name)||!isnumeric(p.(name))||!isscalar(p.(name))||!isreal(p.(name))||!isfinite(p.(name)),error('Reduced:Input','Finite real scalar required: %s',name);endif
  if (positive&&p.(name)<=0)||(!positive&&p.(name)<0),error('Reduced:Input','Invalid %s actual=%s bound0 positive=%d',name,jsonencode(p.(name)),positive);endif
endfunction
elec_reduced_competing_scenarios__reduced_publish–b4aff1557ad8aab4.m — Direct named helper referenced by entrypoint

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261118T093245Z-4091642-1794994365236654 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 b4aff1557ad8aab4a6c99f1ea6ecbc90a953d72b710d2d20c4d6458e017fd874

function receipts=reduced_publish(ctx,p,R)
  % Public create-only tables; no direct canonical storage/registry access.
  if isempty(regexp(p.output_prefix,'^[A-Za-z][A-Za-z0-9_.-]{0,100}$','once')),error('Reduced:ID','New bounded output prefix required');endif
  def=struct('contract','table.generic','storage','auto','replace_owned',false,'producer_version','1.0.3', ...
    'source_dataset_ids',{{p.source_dataset_id}},'source','Illustrative conservative reduced model', ...
    'provenance',['Actual run ' ctx.run_id '; Project SHA ' ctx.script_sha256 '; reviewed spec ' p.specification_sha256], ...
    'notes','Formal NH3/HOCl-equivalent bookkeeping with NH4Cl counterion and Na spectator; no free-H+/physical pH or TNT830/DPD observation model. No RPM fit. Prescribed pH is a scenario label. N2/O2/H2/export are cumulative stipulated product ledgers. Stripping is explicitly zero. Units mol for chemical amounts retain distinct elemental/oxidant/product bases in variable names; they must not be pooled as one observable.');
  receipts={};
  keys=fieldnames(p);values=cell(numel(keys),1);refs=values;status=values;units=values;
  nominal=struct('volume_m3',.0002,'current_A',.12,'initial_N_g_m3',10,'background_NaCl_mol_m3',84,'F_C_mol',96485.33212,'M_N_g_mol',14.0067);
  for k=1:numel(keys)
    key=keys{k};values{k}=jsonencode(p.(key));refs{k}='';status{k}='execution_or_source_label';units{k}='1';
    if isfield(nominal,key)
      refs{k}=jsonencode(nominal.(key));
      if any(strcmp(key,{'F_C_mol','M_N_g_mol'})),status{k}='adopted_physical_constant';else status{k}='source_reported_nominal';endif
      if !isequal(p.(key),nominal.(key)),status{k}=['explicit_override_of_' status{k}];endif
    endif
    switch key
      case 'volume_m3',units{k}='m^3';case 'current_A',units{k}='A';case 'initial_N_g_m3',units{k}='g/m^3';case 'background_NaCl_mol_m3',units{k}='mol/m^3';case 'F_C_mol',units{k}='A*s/mol';case 'M_N_g_mol',units{k}='g/mol';
    endswitch
  endfor
  cols=struct('parameter',{keys},'actual_literal',{values},'nominal_reference_literal',{refs},'unit_label',{units},'status',{status});
  receipts=commit(receipts,[p.output_prefix '.inputs'],cols,struct(),def);
  c=R.cases;n=numel(c);cols=struct('case_index',(1:n)');
  text={'label','family','reference_kind'};num={'m','pH_ext','fCER','fCRR','tau','HB','HL','I','N0','Na0','B0'};
  for k=1:numel(text),v=cell(n,1);for j=1:n,v{j}=c{j}.(text{k});endfor;cols.(text{k})=v;endfor
  um=struct('tau','s','HB','mol','HL','mol','I','A','N0','mol','Na0','mol','B0','mol');
  for k=1:numel(num),v=zeros(n,1);for j=1:n,v(j)=c{j}.(num{k});endfor;cols.(num{k})=v;endfor
  cols.parameter_status=repmat({'illustrative_programmed_scenario_not_fitted'},n,1);
  receipts=commit(receipts,[p.output_prefix '.cases'],cols,um,def);
  descriptions={'states','state_headers';'balances','balance_headers';'checkpoints','checkpoint_headers';'summary','summary_headers';'refinement','refinement_headers';'prefactor','prefactor_headers'};
  for d=1:size(descriptions,1)
    key=descriptions{d,1};headers=R.(descriptions{d,2});matrix=R.(key);
    if size(matrix,2)!=numel(headers),error('Reduced:Shape','Header mismatch %s',key);endif
    cols=struct();um=struct();
    for k=1:numel(headers),cols.(headers{k})=matrix(:,k);um.(headers{k})=unit_for(key,headers{k});endfor
    % V9 publication-only unit conversions from this Job's computed states.
    % 1 g/m^3 equals 1 mg/L. This is formal remaining N, not an assay model.
    if any(strcmp(key,{'states','checkpoints'}))
      cols.time_min=cols.time_s/60;um.time_min='min';
      cols.formal_N_mgN_L=cols.formal_NH3*p.M_N_g_mol/p.volume_m3;um.formal_N_mgN_L='mg/L';
      nominal_N=p.initial_N_g_m3*p.volume_m3/p.M_N_g_mol;
      cols.formal_N_fraction_nominal=cols.formal_NH3/nominal_N;um.formal_N_fraction_nominal='1';
      labels=cell(size(matrix,1),1);
      for row=1:size(matrix,1)
        index=cols.case_index(row);
        if index!=fix(index)||index<1||index>numel(R.cases),error('Reduced:Case','Invalid publication case index');endif
        labels{row}=R.cases{index}.label;
      endfor
      cols.case_label=labels;
      cols.observation_scope=repmat({'illustrative_formal_N_not_validated_TNT830_assay'},size(matrix,1),1);
    endif
    if strcmp(key,'refinement'),cols.order_status=R.refinement_labels;endif
    receipts=commit(receipts,[p.output_prefix '.' key],cols,um,def);
  endfor
  species={};reactions={};v=[];
  for j=1:numel(R.species),for k=1:numel(R.reactions),species{end+1,1}=R.species{j};reactions{end+1,1}=R.reactions{k};v(end+1,1)=R.reaction_matrix(j,k);endfor;endfor
  receipts=commit(receipts,[p.output_prefix '.stoichiometry'],struct('species',{species},'reaction',{reactions},'integer_coefficient',v),struct(),def);
  species={};elements={};v=[];
  for j=1:numel(R.species),for k=1:numel(R.elements),species{end+1,1}=R.species{j};elements{end+1,1}=R.elements{k};v(end+1,1)=R.element_matrix(k,j);endfor;endfor
  receipts=commit(receipts,[p.output_prefix '.elements'],struct('species',{species},'element_or_formal_charge',{elements},'integer_coefficient',v),struct(),def);
  C=R.checks;cols=struct('check_name',{{C.name}'},'actual',[C.actual]','limit',[C.limit]','unit_label',{{C.unit}'},'comparison',{{C.comparison}'},'passed',double([C.pass]'));
  receipts=commit(receipts,[p.output_prefix '.checks'],cols,struct(),def);
endfunction
function unit=unit_for(table,key)
  unit='1';
  if strcmp(table,'states')
    if any(strcmp(key,{'time_s','dt_s'})),unit='s';elseif strncmp(key,'rate_used_',10),unit='mol/s';elseif strncmp(key,'I_',2),unit='A';elseif strncmp(key,'Q_',2),unit='A*s';elseif !any(strcmp(key,{'case_index','level','step','tiny_negative_flag','dt_limiter_code'})),unit='mol';endif
  elseif strcmp(table,'checkpoints')
    if strcmp(key,'time_s'),unit='s';elseif strcmp(key,'Q_C'),unit='A*s';elseif !any(strcmp(key,{'case_index','level'})),unit='mol';endif
  elseif strcmp(table,'balances')
    if strcmp(key,'time_s'),unit='s';elseif any(strcmp(key,{'anode_Q_residual','Q_limit','cathode_Q_residual'})),unit='A*s';elseif !any(strcmp(key,{'case_index','level','step','element_scaled_max'})),unit='mol';endif
  elseif strcmp(table,'summary')
    if any(strcmp(key,{'dt_max_s','t50_s','t90_s'})),unit='s';elseif any(strcmp(key,{'final_N_atoms_mol','final_oxidant_mol','stationary_error_max'})),unit='mol';endif
  endif
endfunction
function receipts=commit(receipts,id,cols,units,def)
  def.dataset_id=id;keys=fieldnames(cols);count=numel(cols.(keys{1}));writer=gxtxt_api_call('DATASET_PUBLICATION_API_v2','begin',{def});
  try
    gxtxt_api_call('DATASET_PUBLICATION_API_v2','declare_dimension',{writer,'row',count,struct('extendible',false)});
    for k=1:numel(keys)
      key=keys{k};v=cols.(key);unit='1';if isfield(units,key),unit=units.(key);endif
      if numel(v)!=count,error('Reduced:Shape','Column mismatch %s',key);endif
      if iscell(v),dtype='string';kind='text';else
        v=full(v);if !isreal(v)||any(!isfinite(v(:))),error('Reduced:Finite','Finite real dense publication column required: %s',key);endif
        dtype='float64';kind='number';
      endif
      schema=struct('dtype',dtype,'value_kind',kind,'rank',1,'dimension_ids',{{'row'}},'name',key,'unit',unit,'coordinate_role','data','axis_kind','explicit');
      gxtxt_api_call('DATASET_PUBLICATION_API_v2','declare_variable',{writer,key,schema});
      gxtxt_api_call('DATASET_PUBLICATION_API_v2','write_variable',{writer,key,v,count});
    endfor
    receipt=gxtxt_api_call('DATASET_PUBLICATION_API_v2','finalize',{writer});receipts{end+1}=receipt;fprintf('CANONICAL_RECEIPT %s\n',jsonencode(receipt));
  catch err
    try gxtxt_api_call('DATASET_PUBLICATION_API_v2','abort',{writer});catch,end_try_catch
    rethrow(err);
  end_try_catch
endfunction
elec_reduced_competing_scenarios__reduced_run–49100713bcc10a52.m — Actual invoked project entrypoint

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261118T093245Z-4091642-1794994365236654 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 49100713bcc10a5298d09cdc6c4b94d5f4af008dd984bee10c24d20ec046857a

% Reduced source1.0.3: source-only, same primary ELEC-01, no physical validation.
gxtxt_api_require('DATASET_PUBLICATION_API_v2@2');
gxtxt_api_require('DATASET_FILE_PUBLICATION_API_v1@1');
gxtxt_api_require('UNIT_REGISTRY_API_v1@1');
gxtxt_parameter_declare('volume_m3','double','default',.0002,'min',0,'description','Source-reported nominal beaker volume; override labelled explicitly');
gxtxt_parameter_declare('current_A','double','default',.12,'min',0,'description','Source-reported nominal current; current-off controls override this');
gxtxt_parameter_declare('initial_N_g_m3','double','default',10,'min',0,'description','Source-reported nominal NH4Cl nitrogen; must be positive, N0=0 controls explicit');
gxtxt_parameter_declare('background_NaCl_mol_m3','double','default',84,'min',0,'description','Background NaCl only; NH4Cl adds chloride');
gxtxt_parameter_declare('F_C_mol','double','default',96485.33212,'min',0,'description','Adopted Faraday constant');
gxtxt_parameter_declare('M_N_g_mol','double','default',14.0067,'min',0,'description','Adopted nitrogen molar mass');
gxtxt_parameter_declare('output_prefix','string','default','elec_reduced_v1_01','description','NEW create-only canonical prefix');
gxtxt_parameter_declare('source_dataset_id','string','default','ref-001_atrashkevich_2025_hal_accepted','description','Actual HAL paper context binding');
gxtxt_parameter_declare('specification_sha256','string','default','2961766955c2b471fcc2c58b48a4f65730ef9fa89a999b630e626534810b89f4','description','Reviewed exact reduced specification04');
ctx=gxtxt_context();p=ctx.parameters;
if !all(isfield(ctx,{'output_dir','run_id','script_sha256','inputs'})),error('Reduced:Context','Actual registered native context required');endif
try
  todo={ctx.inputs};bound={};
  while !isempty(todo)
    value=todo{end};todo(end)=[];
    if isstruct(value)
      for j=1:numel(value)
        if isfield(value(j),'dataset_id')&&ischar(value(j).dataset_id),bound{end+1}=value(j).dataset_id;endif
        names=fieldnames(value(j));for k=1:numel(names),v=value(j).(names{k});if isstruct(v)||iscell(v),todo{end+1}=v;endif;endfor
      endfor
    elseif iscell(value),todo=[todo,value(:)'];endif
  endwhile
  if !any(strcmp(bound,p.source_dataset_id)),error('Reduced:Binding','Actual bound HAL PDF required');endif
  cv=gxtxt_api_call('UNIT_REGISTRY_API_v1','convert',{1,'mm','m'});
  if !isscalar(cv)||!isfinite(cv)||abs(cv-.001)>1e-13,error('Reduced:Unit','Native mm-to-m conversion failed');endif
  R=reduced_evaluate(p);
  % Preserve complete fresh numerical evidence before scientific checks can fail.
  diagnostics_path=fullfile(ctx.output_dir,'reduced_diagnostics.mat');
  save('-mat7-binary',diagnostics_path,'R');
  report=struct('schema','elec.reduced.illustrative.v1','source_version','1.0.3','run_id',ctx.run_id,'project_sha256',ctx.script_sha256,'module_id',ctx.module_id, ...
    'parameters',p,'input_bindings',ctx.inputs,'runtime',struct('octave_version',version(),'architecture',computer(),'OMP_NUM_THREADS',getenv('OMP_NUM_THREADS'),'OPENBLAS_NUM_THREADS',getenv('OPENBLAS_NUM_THREADS')), ...
    'expected_experiment_id','experiment-20261117T171059Z-846242-1794935459579080-1','validation_status',R.validation_status, ...
    'arithmetic_checks_passed',R.arithmetic_checks_passed,'convergence_verified',R.convergence_verified,'convergence_rows_assessed',R.convergence_rows_assessed,'convergence_rows_total',R.convergence_rows_total, ...
    'required_checks_passed',R.passed,'diagnostics_artifact','reduced_diagnostics.mat','diagnostics_format','MATLAB-v7 binary via Octave -mat7-binary', ...
    'complete_evaluation_returned',true,'completed_case_levels',size(R.summary,1),'retained_state_rows',size(R.states,1),'retained_balance_rows',size(R.balances,1),'retained_checkpoint_rows',size(R.checkpoints,1), ...
    'elemental_scale_convention','initial absolute elemental amounts plus abs(E)*abs(nu)*cumulative_extents; both consumed and produced species contributions', ...
    'total_steps',R.total_steps,'cases',{R.cases},'checks',R.checks,'implicit_residual_by_level',R.implicit_residual_by_level, ...
    'scope','Shared illustrative production/loss alternatives only; no RPM fit, no physical pH, no assay/N2 validation; zero stripping explicit');
  reportpath=fullfile(ctx.output_dir,'reduced_report.json');fid=fopen(reportpath,'w');if fid<0,error('Reduced:Output','Cannot write owned diagnostic');endif
  unwind_protect
    fprintf(fid,'%s\n',jsonencode(report));
  unwind_protect_cleanup
    fclose(fid);
  end_unwind_protect
  if !R.passed,error('Reduced:Checks','Required checks/coverage incomplete; owned report retained, no PASS publication');endif
  receipts=reduced_publish(ctx,p,R);
  request=struct('dataset_id',[p.output_prefix '.report'],'contract','document.text','format','json','source_file',reportpath,'storage_kind','text','media_type','application/json','producer_version','1.0.3','source_dataset_ids',{{p.source_dataset_id}},'source','Illustrative reduced native Project','provenance',['Actual run ' ctx.run_id '; Project SHA ' ctx.script_sha256],'notes','Numerical verification only; no mechanistic/assay/physical validation.');
  receipt=gxtxt_api_call('DATASET_FILE_PUBLICATION_API_v1','publish',{request});fprintf('CANONICAL_RECEIPT %s\n',jsonencode(receipt));
  fid=fopen(fullfile(ctx.output_dir,'reduced_publication_receipts.json'),'w');if fid<0,error('Reduced:Output','Cannot write owned diagnostic');endif
  unwind_protect
    fprintf(fid,'%s\n',jsonencode(struct('tables',{receipts},'report',receipt)));
  unwind_protect_cleanup
    fclose(fid);
  end_unwind_protect
catch err
  failure=struct('schema','elec.reduced.failure.v1','run_id',ctx.run_id,'project_sha256',ctx.script_sha256,'parameters',p,'complete_evaluation_returned',exist('R','var')==1,'diagnostics_artifact_if_written','reduced_diagnostics.mat','early_guard_scope','If evaluator did not return, no complete69integration evidence is claimed; retained guard message/stack only', ...
    'identifier',err.identifier,'message',err.message,'stack',err.stack);
  fid=fopen(fullfile(ctx.output_dir,'reduced_failure.json'),'w');
  if fid>=0
    unwind_protect
      fprintf(fid,'%s\n',jsonencode(failure));
    unwind_protect_cleanup
      fclose(fid);
    end_unwind_protect
  endif
  rethrow(err);
end_try_catch
elec_gate2_neutral_diffusion_corrected__gate2_evaluate–e6abade0c9b2c81a.m — Direct named helper referenced by entrypoint

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261117T214559Z-1706497-1794951959732939 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 e6abade0c9b2c81ad4a0e9a8ea0b1d639f60901cc2d1da849f79c4f3eabcc8b7

function R=gate2_evaluate(p)
  % Unexecuted Gate2 v1.0.2: fixed manufactured neutral diffusion problems.
  for name={'length_m','diffusivity_m2_s','concentration_mol_m3','epsilon'}
    key=name{1};if !isfield(p,key)||!isnumeric(p.(key))||!isscalar(p.(key))||!isfinite(p.(key))||p.(key)<=0
      error('Gate2:Input','%s must be finite and positive',key);
    endif
  endfor
  if p.epsilon>=1,error('Gate2:Input','epsilon must be below one');endif
  L=p.length_m;D=p.diffusivity_m2_s;cref=p.concentration_mol_m3;epsilon=p.epsilon;
  T=0.1*L^2/D;mass_scale=cref*L;flux_scale=D*cref/L;
  if !all(isfinite([T,mass_scale,flux_scale]))||any([T,mass_scale,flux_scale]<=0)
    error('Gate2:Scale','Derived T and fixed physical scales must be finite positive');
  endif
  plans={};
  for N=[20,40,80]
    plans{end+1}=struct('label',sprintf('closed_N%d_steps80',N),'N',N,'steps',80,'kind','closed','control',false);
    plans{end+1}=struct('label',sprintf('open_N%d_steps80',N),'N',N,'steps',80,'kind','open','control',false);
  endfor
  for steps=[20,40]
    plans{end+1}=struct('label',sprintf('closed_N40_steps%d',steps),'N',40,'steps',steps,'kind','closed','control',false);
  endfor
  plans{end+1}=struct('label','unequal_Dirichlet_steady_control','N',40,'steps',1,'kind','steady','control',true);
  plans{end+1}=struct('label','equal_Dirichlet_constant_control','N',40,'steps',1,'kind','constant','control',true);
  R.plan=plans;R.inputs=p;R.final_time_s=T;
  R.fields=[];R.fluxes=[];R.budgets=[];R.operator=[];R.forcing=[];R.summary=[];R.convergence=[];
  R.checks=struct('name',{},'actual',{},'limit',{},'unit',{},'comparison',{},'pass',{});
  for run=1:numel(plans)
    plan=plans{run};N=plan.N;h=L/N;dt=T/plan.steps;r=D/h^2;
    x=((1:N)'-0.5)*h;k=pi/L;S=sin(k*h/2)/(k*h/2);
    if !all(isfinite([h,dt,r,S]))||any([h,dt,r]<=0),error('Gate2:Scale','Invalid mesh/time/operator scale');endif
    A=spdiags([r*ones(N,1),-2*r*ones(N,1),r*ones(N,1)],[-1,0,1],N,N);
    forcing=zeros(N,1);cl=cref;cr=2*cref;
    if strcmp(plan.kind,'closed')
      A(1,1)=-r;A(N,N)=-r;steady=cref*ones(N,1);
      v=cos(pi*((1:N)'-0.5)/N);amp=cref*epsilon*S;
    else
      if strcmp(plan.kind,'constant'),cr=cref;endif
      A(1,1)=-3*r;A(N,N)=-3*r;
      forcing(1)=2*r*cl;forcing(N)=2*r*cr;
      steady=cl+(cr-cl)*x/L;v=sin(pi*((1:N)'-0.5)/N);
      amp=0.25*cref*S;if plan.control,amp=0;endif
    endif
    lambda=4*D/h^2*sin(pi/(2*N))^2;
    normalizers=[r*cref,cref/dt,h*r,lambda,D*k^2];
    if !all(isfinite(normalizers))||any(normalizers<=0),error('Gate2:Scale','Nonfinite or underflowed normalization/reference rate');endif
    B=speye(N)-dt*A;
    if !all(isfinite(nonzeros(B)))||!all(isfinite(forcing)),error('Gate2:Finite','Nonfinite actual system');endif
    expected=A*steady+forcing;
    R.checks=check(R.checks,[plan.label '_steady_operator'],max(abs(expected))/(r*cref),1e-10,'1','le');
    R.checks=check(R.checks,[plan.label '_actual_operator_mode'],max(abs(A*v+lambda*v))/r,1e-10,'1','le');
    if strcmp(plan.kind,'closed')
      R.checks=check(R.checks,[plan.label '_constant_row_sums'],max(abs(A*ones(N,1)))/r,1e-10,'1','le');
      R.checks=check(R.checks,[plan.label '_weighted_column_sums'],max(abs(h*sum(A,1)))/(h*r),1e-10,'1','le');
    endif
    % Explicit independent stencil/forcing contract checks for actual matrix.
    expectedA=zeros(N);expectedf=zeros(N,1);
    for i=1:N
      if i>1,expectedA(i,i-1)=r;endif
      if i<N,expectedA(i,i+1)=r;endif
      expectedA(i,i)=-2*r;
    endfor
    if strcmp(plan.kind,'closed'),expectedA(1,1)=-r;expectedA(N,N)=-r;
    else expectedA(1,1)=-3*r;expectedA(N,N)=-3*r;expectedf(1)=2*r*cl;expectedf(N)=2*r*cr;endif
    R.checks=check(R.checks,[plan.label '_stencil_entries'],max(abs(full(A)(:)-expectedA(:)))/r,1e-10,'1','le');
    R.checks=check(R.checks,[plan.label '_forcing_entries'],max(abs(forcing-expectedf))/(r*cref),1e-10,'1','le');
    [ii,jj,vv]=find(A);R.operator=[R.operator;[run*ones(numel(vv),1),ii,jj,vv]];
    R.forcing=[R.forcing;[run*ones(N,1),(1:N)',x,forcing,steady,v]];
    C=steady+amp*v;initial_mass=h*sum(C);cumulative=0;
    for step=0:plan.steps
      t=step*dt;
      if step>0
        old=C;C=B\(old+dt*forcing);
        residual=(C-old)/dt-A*C-forcing;
        R.checks=check(R.checks,sprintf('%s_step%d_equation',plan.label,step),max(abs(residual))/(cref/dt),1e-10,'1','le');
      endif
      J=zeros(N+1,1);J(2:N)=-D*diff(C)/h;
      if !strcmp(plan.kind,'closed'),J(1)=-D*(C(1)-cl)/(h/2);J(end)=-D*(cr-C(end))/(h/2);endif
      if step>0,cumulative+=dt*(J(1)-J(end));endif
      continuum=steady+amp*v*exp(-D*k^2*t);
      semidiscrete=steady+amp*v*exp(-lambda*t);
      discrete=steady+amp*v*(1+dt*lambda)^(-step);
      mass=h*sum(C);budget=mass-initial_mass-cumulative;
      if strcmp(plan.kind,'closed'),continuum_mass=cref*L;
      else continuum_mass=L*(cl+cr)/2+2*(amp/S)*exp(-D*k^2*t)/k;endif
      exact_initial_mass=L*(cl+cr)/2+2*(amp/S)/k;
      if strcmp(plan.kind,'closed'),exact_initial_mass=cref*L;endif
      continuum_transfer=continuum_mass-exact_initial_mass;
      econt=norms(C-continuum,h,L,cref);esemi=norms(C-semidiscrete,h,L,cref);
      eBE=norms(C-discrete,h,L,cref);espace=norms(semidiscrete-continuum,h,L,cref);
      if step==0
        R.checks=check(R.checks,[plan.label '_exact_initial_inventory'],abs(mass-exact_initial_mass)/mass_scale,1e-10,'1','le');
      else
        local_budget=mass-h*sum(old)-dt*(J(1)-J(end));
        R.checks=check(R.checks,sprintf('%s_step%d_local_budget',plan.label,step),abs(local_budget)/mass_scale,1e-10,'1','le');
      endif
      R.checks=check(R.checks,sprintf('%s_step%d_budget',plan.label,step),abs(budget)/mass_scale,1e-10,'1','le');
      R.checks=check(R.checks,sprintf('%s_step%d_BE_mode',plan.label,step),eBE(1),1e-10,'1','le');
      R.checks=check(R.checks,sprintf('%s_step%d_nonnegative',plan.label,step),min(C)/cref,-1e-12,'1','ge');
      if strcmp(plan.kind,'closed')
        R.checks=check(R.checks,sprintf('%s_step%d_closed_inventory',plan.label,step),abs(mass-cref*L)/mass_scale,1e-10,'1','le');
      endif
      if plan.control
        exact_flux=D*(cl-cr)/L;
        R.checks=check(R.checks,sprintf('%s_step%d_steady_flux',plan.label,step),max(abs(J-exact_flux))/flux_scale,1e-10,'1','le');
        R.checks=check(R.checks,sprintf('%s_step%d_preservation',plan.label,step),max(abs(C-steady))/cref,1e-10,'1','le');
      endif
      R.fields=[R.fields;[run*ones(N,1),step*ones(N,1),t*ones(N,1),(1:N)',x,C,continuum,semidiscrete,discrete,C-continuum,C-semidiscrete,C-discrete,double(C<0)]];
      R.fluxes=[R.fluxes;[run*ones(N+1,1),step*ones(N+1,1),t*ones(N+1,1),(0:N)',(0:N)'*h,J]];
      R.budgets=[R.budgets;[run,step,t,dt,mass,initial_mass,cumulative,budget,J(1),J(end),continuum_mass,continuum_transfer,min(C),econt,esemi,eBE,espace]];
    endfor
    R.summary=[R.summary;[run,N,plan.steps,h,dt,T,lambda,econt,esemi,eBE,espace]];
  endfor
  % Fixed closed studies: auxiliary80-step cases at runs1/3/5; time runs7/8/3.
  groups={struct('name','spatial_semidiscrete','runs',[1,3,5],'columns',[14,15],'lo',1.8,'hi',2.2), ...
          struct('name','temporal_samegrid_BE','runs',[7,8,3],'columns',[10,11],'lo',0.8,'hi',1.2)};
  R.arithmetic_checks_passed=all([R.checks.pass]);
  R.convergence_labels={};R.convergence_studies={};R.convergence_norms={};
  for group=1:2
    g=groups{group};
    for normidx=1:2
      for pair=1:2
        coarse=R.summary(g.runs(pair),g.columns(normidx));fine=R.summary(g.runs(pair+1),g.columns(normidx));
        eligible=(coarse>1e-11&&fine>1e-11);rate=0;
        if eligible
          rate=log(coarse/fine)/log(2);
          R.checks=check(R.checks,sprintf('%s_norm%d_pair%d_lower',g.name,normidx,pair),rate,g.lo,'1','ge');
          R.checks=check(R.checks,sprintf('%s_norm%d_pair%d_upper',g.name,normidx,pair),rate,g.hi,'1','le');
        endif
        R.convergence=[R.convergence;[group,normidx,g.runs(pair),g.runs(pair+1),coarse,fine,rate,double(eligible),1e-11,g.lo,g.hi]];
        R.convergence_studies{end+1,1}=g.name;
        if normidx==1,R.convergence_norms{end+1,1}='normalized_Linf';else R.convergence_norms{end+1,1}='normalized_cell_weighted_L2';endif
        if eligible,R.convergence_labels{end+1,1}='rate_assessed';else R.convergence_labels{end+1,1}='error_floor_limited_rate_unavailable';endif
      endfor
    endfor
  endfor
  for name={'fields','fluxes','budgets','operator','forcing','summary','convergence'}
    key=name{1};if !all(isfinite(R.(key)(:))),error('Gate2:Finite','Nonfinite output in %s',key);endif
  endfor
  R.passed=all([R.checks.pass]);
  R.convergence_rows_assessed=sum(R.convergence(:,8));R.convergence_rows_total=size(R.convergence,1);
  R.convergence_verified=R.passed&&R.convergence_rows_assessed==R.convergence_rows_total;
  R.validation_status='FAIL';
  if R.passed&&R.convergence_verified,R.validation_status='PASS_MANUFACTURED_BENCHMARK_ONLY';
  elseif R.passed,R.validation_status='PARTIAL_ERROR_FLOOR';endif
endfunction
function e=norms(delta,h,L,cref)
  e=[max(abs(delta))/cref,sqrt(sum(h*delta.^2)/L)/cref];
endfunction
function C=check(C,name,actual,limit,unit,comparison)
  % Store scalar facts densely; sparse FV reductions are not binary wire arrays.
  if !isnumeric(actual)||!isscalar(actual)||!isreal(actual)||!isnumeric(limit)||!isscalar(limit)||!isreal(limit)
    error('Gate2:CheckShape','Checks require real numeric scalar actual/limit');
  endif
  actual=full(actual);limit=full(limit);
  finite=isfinite(actual)&&isfinite(limit);
  if strcmp(comparison,'le'),passed=finite&&actual<=limit;else passed=finite&&actual>=limit;endif
  C(end+1)=struct('name',name,'actual',actual,'limit',limit,'unit',unit,'comparison',comparison,'pass',logical(passed));
endfunction
elec_gate2_neutral_diffusion_corrected__gate2_publish–2a78f4d63a09ccaf.m — Direct named helper referenced by entrypoint

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261117T214559Z-1706497-1794951959732939 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 2a78f4d63a09ccafada6a6feb07acaa79ac7861d04ecb53137a5048847963405

function receipts=gate2_publish(ctx,p,R)
  % Unexecuted current-context public publisher; commits are independent.
  if isempty(regexp(p.output_prefix,'^[A-Za-z][A-Za-z0-9_.-]{0,100}$','once')),error('Gate2:ID','New simple prefix required');endif
  definition=struct('contract','table.generic','storage','auto','replace_owned',false, ...
    'producer_version','1.0.2','source_dataset_ids',{{p.source_dataset_id}}, ...
    'source','Gate2 manufactured neutral diffusion', ...
    'provenance',['Registered run ' ctx.run_id '; source ' ctx.script_sha256 '; spec ' p.specification_sha256], ...
    'notes','Manufactured neutral tracer mathematics only; HAL source is context, not provenance for L/D/c_ref. No physical beaker/RPM/assay validation. Analytical continuum, analytical semidiscrete, analytical fully discrete modal references and actual BE fields remain separately labelled. Same primary ELEC-01.');
  definition.notes=[definition.notes ' Validation coverage: ' R.validation_status '. Unavailable convergence order is NOT VERIFIED.'];
  receipts={};
  names=fieldnames(p);values=cell(numel(names),1);statuses=cell(numel(names),1);units=cell(numel(names),1);
  for k=1:numel(names)
    key=names{k};values{k}=jsonencode(p.(key));units{k}='1';statuses{k}='execution_or_source_label';
    if any(strcmp(key,{'length_m','diffusivity_m2_s','concentration_mol_m3','epsilon'})),statuses{k}='manufactured_not_measured';endif
    switch key
      case 'length_m',units{k}='m';case 'diffusivity_m2_s',units{k}='m^2/s';case 'concentration_mol_m3',units{k}='mol/m^3';
    endswitch
  endfor
  columns=struct('parameter',{names},'literal',{values},'unit_label',{units},'status',{statuses});
  receipts{end+1}=table_publish([p.output_prefix '.inputs'],columns,struct(),definition);log_receipt(receipts{end});
  labels=cell(numel(R.plan),1);kinds=labels;Ns=[];steps=[];
  for k=1:numel(R.plan),labels{k}=R.plan{k}.label;kinds{k}=R.plan{k}.kind;Ns(k,1)=R.plan{k}.N;steps(k,1)=R.plan{k}.steps;endfor
  columns=struct('run_index',(1:numel(R.plan))','label',{labels},'case_kind',{kinds},'cells',Ns,'BE_steps',steps);
  receipts{end+1}=table_publish([p.output_prefix '.plan'],columns,struct(),definition);log_receipt(receipts{end});
  descriptions={ ...
    'fields',{'run_index','step','time_s','cell','x_m','actual_BE','analytical_continuum_cell_average','analytical_semidiscrete','analytical_fully_discrete_mode','actual_minus_continuum','actual_minus_semidiscrete','actual_minus_discrete_mode','tiny_negative_flag'}, ...
      {'1','1','s','1','m','mol/m^3','mol/m^3','mol/m^3','mol/m^3','mol/m^3','mol/m^3','mol/m^3','1'}; ...
    'fluxes',{'run_index','step','time_s','face','x_m','actual_newtime_flux'}, ...
      {'1','1','s','1','m','mol/m^2/s'}; ...
    'budgets',{'run_index','step','time_s','dt_s','actual_inventory_per_area','initial_inventory_per_area','cumulative_actual_boundary_transfer','budget_residual','left_flux','right_flux','analytical_continuum_inventory','analytical_continuum_transfer','actual_min_concentration','actual_continuum_Linf','actual_continuum_L2','actual_semidiscrete_Linf','actual_semidiscrete_L2','actual_discrete_Linf','actual_discrete_L2','semidiscrete_continuum_Linf','semidiscrete_continuum_L2'}, ...
      {'1','1','s','s','mol/m^2','mol/m^2','mol/m^2','mol/m^2','mol/m^2/s','mol/m^2/s','mol/m^2','mol/m^2','mol/m^3','1','1','1','1','1','1','1','1'}; ...
    'operator',{'run_index','row','column','actual_coefficient'}, {'1','1','1','1/s'}; ...
    'forcing',{'run_index','cell','x_m','actual_forcing','exact_steady_cell_average','dimensionless_mode'}, {'1','1','m','mol/m^3/s','mol/m^3','1'}; ...
    'summary',{'run_index','cells','BE_steps','h_m','dt_s','final_time_s','lambda_h','actual_continuum_Linf','actual_continuum_L2','actual_semidiscrete_Linf','actual_semidiscrete_L2','actual_discrete_Linf','actual_discrete_L2','semidiscrete_continuum_Linf','semidiscrete_continuum_L2'}, ...
      {'1','1','1','m','s','s','1/s','1','1','1','1','1','1','1','1'}; ...
    'convergence',{'study_index','norm_index','coarse_run','fine_run','coarse_error','fine_error','order_value','order_available','error_floor','order_lower','order_upper'}, repmat({'1'},1,11)};
  for d=1:size(descriptions,1)
    key=descriptions{d,1};headers=descriptions{d,2};declared_units=descriptions{d,3};matrix=R.(key);
    if size(matrix,2)!=numel(headers)||numel(headers)!=numel(declared_units),error('Gate2:Shape','Header mismatch %s',key);endif
    columns=struct();unitmap=struct();
    for k=1:numel(headers),columns.(headers{k})=matrix(:,k);unitmap.(headers{k})=declared_units{k};endfor
    if strcmp(key,'convergence')
      columns.order_status=R.convergence_labels;columns.study_name=R.convergence_studies;columns.norm_name=R.convergence_norms;
    endif
    receipts{end+1}=table_publish([p.output_prefix '.' key],columns,unitmap,definition);log_receipt(receipts{end});
  endfor
  C=R.checks;columns=struct('check_name',{{C.name}'},'actual',[C.actual]','limit',[C.limit]', ...
    'unit_label',{{C.unit}'},'comparison',{{C.comparison}'},'passed',double([C.pass]'));
  receipts{end+1}=table_publish([p.output_prefix '.checks'],columns,struct(),definition);log_receipt(receipts{end});
endfunction
function result=table_publish(id,columns,unitmap,definition)
  keys=fieldnames(columns);count=numel(columns.(keys{1}));definition.dataset_id=id;
  writer=gxtxt_api_call('DATASET_PUBLICATION_API_v2','begin',{definition});
  try
    gxtxt_api_call('DATASET_PUBLICATION_API_v2','declare_dimension',{writer,'row',count,struct('extendible',false)});
    for k=1:numel(keys)
      key=keys{k};value=columns.(key);
      % Serialization boundary only: preserve values/shape, no sparse fwrite.
      if isnumeric(value)||islogical(value),value=full(value);endif
      if numel(value)!=count,error('Gate2:Shape','Column mismatch');endif
      unit='1';if isfield(unitmap,key),unit=unitmap.(key);endif
      if iscell(value),dtype='string';kind='text';else dtype='float64';kind='number';endif
      schema=struct('dtype',dtype,'value_kind',kind,'rank',1,'dimension_ids',{{'row'}},'name',key,'unit',unit,'coordinate_role','data','axis_kind','explicit');
      gxtxt_api_call('DATASET_PUBLICATION_API_v2','declare_variable',{writer,key,schema});
      gxtxt_api_call('DATASET_PUBLICATION_API_v2','write_variable',{writer,key,value,count});
    endfor
    result=gxtxt_api_call('DATASET_PUBLICATION_API_v2','finalize',{writer});
  catch err
    try gxtxt_api_call('DATASET_PUBLICATION_API_v2','abort',{writer});catch,end_try_catch
    rethrow(err);
  end_try_catch
endfunction
function log_receipt(receipt)
  fprintf('CANONICAL_RECEIPT %s\n',jsonencode(receipt));
endfunction
elec_gate2_neutral_diffusion_corrected__gate2_run–3d172540cb53b587.m — Actual invoked project entrypoint

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261117T214559Z-1706497-1794951959732939 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 3d172540cb53b58722694f2414adb82989061142ddba6a17c14cb40a512ed36b

% Gate2 source1.0.2; UNEXECUTED, existing primary ELEC-01 only.
gxtxt_api_require('DATASET_PUBLICATION_API_v2@2');
gxtxt_api_require('DATASET_FILE_PUBLICATION_API_v1@1');
gxtxt_api_require('UNIT_REGISTRY_API_v1@1');
gxtxt_parameter_declare('length_m','double','default',0.0001,'min',0,'description','Manufactured slab L, not identified beaker film thickness');
gxtxt_parameter_declare('diffusivity_m2_s','double','default',0.000000001,'min',0,'description','Manufactured neutral tracer D, not sourced electrolyte diffusivity');
gxtxt_parameter_declare('concentration_mol_m3','double','default',1,'min',0,'description','Manufactured neutral tracer reference concentration');
gxtxt_parameter_declare('epsilon','double','default',0.25,'min',0,'max',1,'description','Manufactured closed-mode relative amplitude; strict0<epsilon<1');
gxtxt_parameter_declare('output_prefix','string','default','elec_gate2_v1_02','description','Choose NEW create-only canonical output prefix');
gxtxt_parameter_declare('source_dataset_id','string','default','ref-001_atrashkevich_2025_hal_accepted','description','Actual context PDF binding, not source for manufactured parameters');
gxtxt_parameter_declare('specification_sha256','string','default','aa6b2f4b0a3ffde78db2ccaba9da97f98b369aa474cabfdb030be4770649b1f3','description','Reviewed spec02 hash; reference-category and fixed-schedule contract');
ctx=gxtxt_context();p=ctx.parameters;
if !isfield(ctx,'output_dir')||!isfield(ctx,'run_id')||!isfield(ctx,'script_sha256'),error('Gate2:Context','Registered native context required');endif
try
  bound={};todo={ctx.inputs};
  while !isempty(todo)
    value=todo{end};todo(end)=[];
    if isstruct(value)
      for j=1:numel(value)
        if isfield(value(j),'dataset_id')&&ischar(value(j).dataset_id),bound{end+1}=value(j).dataset_id;endif
        keys=fieldnames(value(j));for k=1:numel(keys),child=value(j).(keys{k});if isstruct(child)||iscell(child),todo{end+1}=child;endif;endfor
      endfor
    elseif iscell(value),todo=[todo,value(:)'];endif
  endwhile
  if !any(strcmp(bound,p.source_dataset_id)),error('Gate2:Binding','Bind actual context PDF as Runner input');endif
  converted=gxtxt_api_call('UNIT_REGISTRY_API_v1','convert',{1,'mm','m'});
  if !isscalar(converted)||!isfinite(converted)||abs(converted-0.001)>1e-13,error('Gate2:Unit','Native unit conversion failed');endif
  R=gate2_evaluate(p);
  report=struct('schema','elec.neutral_diffusion.gate2.v1','source_version','1.0.2', ...
    'run_id',ctx.run_id,'project_sha256',ctx.script_sha256,'module_id',ctx.module_id,'parameters',p,'input_bindings',ctx.inputs, ...
    'runtime',struct('octave_version',version(),'architecture',computer(),'OMP_NUM_THREADS',getenv('OMP_NUM_THREADS'),'OPENBLAS_NUM_THREADS',getenv('OPENBLAS_NUM_THREADS')), ...
    'expected_experiment_id','experiment-20261117T171059Z-846242-1794935459579080-1', ...
    'scope','Manufactured neutral transport only; analytic references distinct from actual native BE solve; no physical beaker/RPM/assay validation', ...
    'plan',{R.plan},'checks',R.checks,'required_checks_passed',R.passed, ...
    'arithmetic_checks_passed',R.arithmetic_checks_passed,'convergence_rows_assessed',R.convergence_rows_assessed, ...
    'convergence_rows_total',R.convergence_rows_total,'convergence_verified',R.convergence_verified, ...
    'validation_status',R.validation_status,'final_time_s',R.final_time_s);
  path=fullfile(ctx.output_dir,'gate2_report.json');fid=fopen(path,'w');if fid<0,error('Gate2:Output','Cannot write owned report');endif
  unwind_protect
    fprintf(fid,'%s\n',jsonencode(report));
  unwind_protect_cleanup
    fclose(fid);
  end_unwind_protect
  if !R.passed,error('Gate2:Checks','Required check failed; owned report retained, no PASS publication');endif
  receipts=gate2_publish(ctx,p,R);
  request=struct('dataset_id',[p.output_prefix '.report'],'contract','document.text','format','json','source_file',path,'storage_kind','text','media_type','application/json','producer_version','1.0.2','source_dataset_ids',{{p.source_dataset_id}},'source','Gate2 native registered Project','provenance',['Actual run ' ctx.run_id '; project SHA ' ctx.script_sha256],'notes','Manufactured neutral diffusion benchmark only. No physical validation.');
  receipt=gxtxt_api_call('DATASET_FILE_PUBLICATION_API_v1','publish',{request});
  fprintf('CANONICAL_RECEIPT %s\n',jsonencode(receipt));
  path=fullfile(ctx.output_dir,'gate2_publication_receipts.json');fid=fopen(path,'w');if fid<0,error('Gate2:Output','Cannot write receipt ledger');endif
  unwind_protect
    fprintf(fid,'%s\n',jsonencode(struct('tables',{receipts},'report',receipt)));
  unwind_protect_cleanup
    fclose(fid);
  end_unwind_protect
catch err
  failure=struct('schema','elec.gate2.failure.v1','run_id',ctx.run_id,'project_sha256',ctx.script_sha256,'parameters',p,'identifier',err.identifier,'message',err.message,'stack',err.stack);
  fid=fopen(fullfile(ctx.output_dir,'gate2_failure.json'),'w');
  if fid>=0
    unwind_protect
      fprintf(fid,'%s\n',jsonencode(failure));
    unwind_protect_cleanup
      fclose(fid);
    end_unwind_protect
  endif
  rethrow(err);
end_try_catch
elec_gate1_bookkeeping__gate1_evaluate–e04e8acc9e8ea480.m — Direct named helper referenced by entrypoint

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261117T203042Z-1446901-1794947442736238 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 e04e8acc9e8ea48039e1e49d8e4ab8e244ba8c9621e1668e3fc2e30c8d62ef6b

function R = gate1_evaluate(p)
  % Gate1 v1.0.2: reviewed analytic/manufactured bookkeeping, never assay physics.
  positive = {'duration_s','volume_m3','area_m2','F_C_mol','M_N_g_mol','M_Cl2_g_mol'};
  nonnegative = {'current_A','background_NaCl_mol_m3','initial_N_g_m3','stored_HOCl_mol'};
  fractions = {'mixed_CER_fraction','mixed_CRR_fraction','mixed_N2_fraction','mixed_strip_fraction','stored_N2_fraction'};
  for k=1:numel(positive)
    must_scalar(p,positive{k}); if p.(positive{k})<=0,fail_guard(positive{k},p.(positive{k}),0,input_unit(positive{k}),'gt');endif
  endfor
  for k=1:numel(nonnegative)
    must_scalar(p,nonnegative{k}); if p.(nonnegative{k})<0,fail_guard(nonnegative{k},p.(nonnegative{k}),0,input_unit(nonnegative{k}),'ge');endif
  endfor
  for k=1:numel(fractions)
    must_scalar(p,fractions{k}); if p.(fractions{k})<0||p.(fractions{k})>1,fail_guard(fractions{k},p.(fractions{k}),[0,1],'1','within');endif
  endfor
  R.species={'formal_NH3','neutral_HOCl','chloride','escaped_Cl2','stipulated_N2','signed_acid','water_reservoir_delta','O2_cumulative','H2_cumulative','electron_reservoir_delta','Na_spectator'};
  R.reactions={'hydrolyzed_CER','OER','CRR','HER','formal_N2_endpoint','formal_Cl2_stripping'};
  R.elements={'N','Cl','H','O','Na','formal_charge'};
  % Columns follow species above; charge includes electron and fixed Na+.
  B=[1 0 0 0 2 0 0 0 0 0 0;
     0 1 1 2 0 0 0 0 0 0 0;
     3 1 0 0 0 1 2 0 2 0 0;
     0 1 0 0 0 0 1 2 0 0 0;
     0 0 0 0 0 0 0 0 0 0 1;
     0 0 -1 0 0 1 0 0 0 -1 1];
  % Integer columns are six formal reactions, including water/electron reservoirs.
  nu=[0 0 0 0 -2 0;
      1 0 -1 0 -3 -1;
     -1 0 1 0 3 -1;
      0 0 0 0 0 1;
      0 0 0 0 1 0;
      1 4 -1 -2 3 -1;
     -1 -2 1 0 3 1;
      0 1 0 0 0 0;
      0 0 0 1 0 0;
      2 4 -2 -2 0 0;
      0 0 0 0 0 0];
  R.element_matrix=B; R.reaction_matrix=nu;
  C=struct('name',{},'actual',{},'limit',{},'unit',{},'comparison',{},'pass',{});
  C=add_check(C,'integer_element_charge_nullspace',max(abs((B*nu)(:))),0,'1','le');
  F=p.F_C_mol; N0=p.initial_N_g_m3*p.volume_m3/p.M_N_g_mol;
  Na0=p.background_NaCl_mol_m3*p.volume_m3;
  L0=Na0+N0; A0=N0;
  if !all(isfinite([N0,Na0,L0,A0])),fail_guard('derived_initial_amounts',[N0,Na0,L0,A0],'finite','mol','type');endif
  % NH4Cl source formally translated to NH3 + H+ + Cl-.
  R.initial=struct('N0_mol_atoms',N0,'Na0_mol',Na0,'background_Cl_mol',Na0,'L0_total_chloride_mol',L0,'A0_formal_acid_mol',A0);
  % A/B/C are current-on manufactured extents; D/E explicitly override I=0.
  S={struct('name','A_all_CER_HER','I',p.current_A,'B0',0,'fcer',1,'fcrr',0,'alpha',0,'beta',0,'stored',false),
     struct('name','B_all_OER_HER','I',p.current_A,'B0',0,'fcer',0,'fcrr',0,'alpha',0,'beta',0,'stored',false),
     struct('name','C_illustrative_mixed','I',p.current_A,'B0',0,'fcer',p.mixed_CER_fraction,'fcrr',p.mixed_CRR_fraction,'alpha',p.mixed_N2_fraction,'beta',p.mixed_strip_fraction,'stored',false),
     struct('name','D_current_off_stored_HOCl','I',0,'B0',p.stored_HOCl_mol,'fcer',0,'fcrr',0,'alpha',p.stored_N2_fraction,'beta',0,'stored',true),
     struct('name','E_current_off_no_oxidant','I',0,'B0',0,'fcer',0,'fcrr',0,'alpha',p.stored_N2_fraction,'beta',0,'stored',true)};
  sampled=[0 .25 .5 .75 1]; rows=[]; names={};
  headers={'scenario_index','fractional_time','time_s','current_A','Q_C','initial_HOCl_mol'};
  headers=[headers,R.species,{'x_CER_mol','x_OER_mol','x_CRR_mol','x_HER_mol','x_N2_mol','x_strip_mol','Q_CER_C','Q_OER_C','Q_CRR_C','Q_HER_C','N_converted_atoms_mol','gross_Cl2eq_charge_ceiling_mol','N_charge_storage_ceiling_atoms_mol','geometric_current_density_A_m2','N_residual_mol','Cl_residual_mol','oxidant_residual_mol','acid_Cl_residual_mol','global_formal_charge_mol','formal_N_g_m3','gross_Cl2eq_charge_ceiling_g_m3','N_charge_storage_ceiling_g_m3','tiny_negative_stock_flag'}];
  amount_atol=1e-14; charge_atol=1e-9; rtol=1e-10;
  for i=1:numel(S)
    a=S{i};
    y0=[N0;a.B0;L0;0;0;A0;0;0;0;0;Na0];
    for j=1:numel(sampled)
      s=sampled(j); t=p.duration_s*s; Q=a.I*t;
      xcer=a.fcer*Q/(2*F); xoer=(1-a.fcer)*Q/(4*F);
      xcrr=a.fcrr*Q/(2*F); xher=(1-a.fcrr)*Q/(2*F);
      if !all(isfinite([t,Q,xcer,xoer,xcrr,xher])),fail_guard('derived_schedule_nonfinite',[t,Q,xcer,xoer,xcrr,xher],'finite','mixed_s_A*s_mol','type');endif
      tag=sprintf('%s_sample_%d_',a.name,j);
      % Prospective sequential path checks, not a posteriori stock clipping.
      if xcer>L0,fail_guard([tag 'CER_initial_chloride'],xcer,L0,'mol','le');endif
      if xcrr>a.B0+xcer,fail_guard([tag 'CRR_available_HOCl'],xcrr,a.B0+xcer,'mol','le');endif
      l_electrode=L0-xcer+xcrr;
      if l_electrode<0,fail_guard([tag 'electrode_chloride'],l_electrode,0,'mol','ge');endif
      available=a.B0+xcer-xcrr;
      if available<0,fail_guard([tag 'available_oxidant'],available,0,'mol','ge');endif
      fraction=a.alpha;if a.stored,fraction=s*a.alpha;endif
      % Algebraic limiting-substrate residuals avoid subtracting equal floating
      % products at alpha=1. This is not clipping a computed negative stock.
      N_capacity=1.5*N0;
      if available<=N_capacity
        xn=fraction*available/3;
        b_before_strip=(1-fraction)*available;
      else
        xn=fraction*N0/2;
        b_before_strip=(available-N_capacity)+(1-fraction)*N_capacity;
      endif
      l_before_strip=l_electrode+3*xn;
      if b_before_strip<0,fail_guard([tag 'post_N_oxidant'],b_before_strip,0,'mol','ge');endif
      if l_before_strip<0,fail_guard([tag 'post_N_chloride'],l_before_strip,0,'mol','ge');endif
      xs=a.beta*b_before_strip;
      if xs>l_before_strip,fail_guard([tag 'stripping_chloride'],xs,l_before_strip,'mol','le');endif
      extent=[xcer;xoer;xcrr;xher;xn;xs]; y=y0+nu*extent;
      qcer=2*F*xcer; qoer=4*F*xoer; qcrr=2*F*xcrr; qher=2*F*xher;
      Nres=y(1)+2*y(5)-N0; Clres=y(3)+y(2)+2*y(4)-(L0+a.B0);
      Eres=y(2)+y(4)+3*y(5)+xcrr-(a.B0+xcer);
      acidres=y(6)-y(3)-(A0-L0); z=y(6)-y(3)+y(11);
      Nlimit=amount_atol+rtol*max([N0,2*xn,abs(y(1))]);
      Cllimit=amount_atol+rtol*max([L0+a.B0,abs(y(3))+abs(y(2))+2*abs(y(4))]);
      Elimit=amount_atol+rtol*max([a.B0+xcer,xcrr+3*xn+xs,abs(y(2))]);
      acidlimit=amount_atol+rtol*max([abs(A0-L0),abs(y(6))+abs(y(3))]);
      Nalimit=amount_atol+rtol*abs(Na0);
      charge_limit=charge_atol+rtol*abs(Q);
      C=add_check(C,[tag 'N_balance'],abs(Nres),Nlimit,'mol','le');
      C=add_check(C,[tag 'Cl_balance'],abs(Clres),Cllimit,'mol','le');
      C=add_check(C,[tag 'oxidant_source_minus_sink'],abs(Eres),Elimit,'mol','le');
      C=add_check(C,[tag 'formal_acid_minus_Cl'],abs(acidres),acidlimit,'mol','le');
      C=add_check(C,[tag 'fixed_Na_spectator'],abs(y(11)-Na0),Nalimit,'mol','le');
      C=add_check(C,[tag 'global_formal_charge'],abs(z),acidlimit,'mol','le');
      delta=nu*extent;
      for element=1:size(B,1)
        element_scale=sum(abs(B(element,:)).*(abs(y0)+abs(delta))');
        C=add_check(C,[tag R.elements{element} '_reservoir_delta'],abs(B(element,:)*(y-y0)),amount_atol+rtol*element_scale,'mol','le');
      endfor
      C=add_check(C,[tag 'anode_current_integral'],abs(qcer+qoer-Q),charge_limit,'A*s','le');
      C=add_check(C,[tag 'cathode_current_integral'],abs(qcrr+qher-Q),charge_limit,'A*s','le');
      C=add_check(C,[tag 'net_electron_flow'],abs(y(10)),amount_atol+rtol*max([2*xcer+4*xoer,2*xcrr+2*xher]),'mol','le');
      C=add_check(C,[tag 'nonnegative_nonreservoir_stocks'],min(y([1:5,8:9,11])), -amount_atol,'mol','ge');
      converted=2*y(5); ceiling=2*a.B0/3+Q/(3*F);
      C=add_check(C,[tag 'N_initial_substrate_ceiling'],converted-N0,Nlimit,'mol','le');
      C=add_check(C,[tag 'N_charge_storage_ceiling'],converted-ceiling,amount_atol+rtol*max([converted,ceiling]),'mol','le');
      if j==1
        C=add_check(C,[tag 'initial_state_preserved'],max(abs(y-y0)),0,'mol','le');
      endif
      if i==1
        C=add_check(C,[tag 'all_CER_gross_Cl2eq_ceiling'],abs(y(2)-Q/(2*F)),Elimit,'mol','le');
      endif
      if i==2
        C=add_check(C,[tag 'zero_chlorine_production'],abs(y(2)+y(4)),0,'mol','le');
      endif
      if i==5
        C=add_check(C,[tag 'no_oxidant_no_conversion'],abs(converted),0,'mol','le');
      endif
      if i==4&&j==numel(sampled)
        C=add_check(C,[tag 'current_off_zero_charge'],abs(Q),0,'A*s','le');
        % Strictly positive formal conversion is a counterexample, not a rate law.
        C=add_check(C,[tag 'stored_oxidant_conversion_positive'],converted,0,'mol','gt');
      endif
      row=[i,s,t,a.I,Q,a.B0,y',extent',qcer,qoer,qcrr,qher,converted,Q/(2*F),ceiling,a.I/p.area_m2,Nres,Clres,Eres,acidres,z,y(1)*p.M_N_g_mol/p.volume_m3,(Q/(2*F))*p.M_Cl2_g_mol/p.volume_m3,ceiling*p.M_N_g_mol/p.volume_m3,double(any(y([1:5,8:9,11])<0))];
      if !all(isfinite(row)),fail_guard([tag 'derived_output_row'],row,'finite','mixed_see_state_units','type');endif
      if numel(row)!=numel(headers),error('Gate1:Shape','State column mismatch');endif
      rows(end+1,:)=row; names{end+1,1}=a.name;
    endfor
  endfor
  R.state_names=headers; R.state_values=rows; R.scenario_names=names; R.checks=C;
  R.tolerances=struct('relative',rtol,'amount_atol_mol',amount_atol,'charge_atol_C',charge_atol);
  R.passed=all([C.pass]);
endfunction

function must_scalar(p,name)
  if !isfield(p,name)
    fail_guard(name,'MISSING','finite_numeric_scalar',input_unit(name),'type');
  endif
  if !isnumeric(p.(name))||!isscalar(p.(name))||!isfinite(p.(name))
    fail_guard(name,p.(name),'finite_numeric_scalar',input_unit(name),'type');
  endif
endfunction

function C=add_check(C,name,actual,limit,unit,comparison)
  switch comparison
    case 'le', passed=isfinite(actual)&&isfinite(limit)&&actual<=limit;
    case 'ge', passed=isfinite(actual)&&isfinite(limit)&&actual>=limit;
    case 'gt', passed=isfinite(actual)&&isfinite(limit)&&actual>limit;
    otherwise, error('Gate1:Check','Unknown comparison');
  endswitch
  C(end+1)=struct('name',name,'actual',actual,'limit',limit,'unit',unit,'comparison',comparison,'pass',logical(passed));
endfunction

function fail_guard(name,actual,bound,unit,relation)
  diagnostic=struct('guard',name,'actual',actual,'bound',bound,'unit',unit,'required_relation',relation);
  error('Gate1:Guard','GATE1_DIAGNOSTIC:%s',jsonencode(diagnostic));
endfunction

function unit=input_unit(name)
  switch name
    case 'current_A',unit='A';case 'duration_s',unit='s';
    case 'volume_m3',unit='m^3';case 'area_m2',unit='m^2';
    case 'F_C_mol',unit='A*s/mol';case {'M_N_g_mol','M_Cl2_g_mol'},unit='g/mol';
    case 'background_NaCl_mol_m3',unit='mol/m^3';case 'initial_N_g_m3',unit='g/m^3';
    case 'stored_HOCl_mol',unit='mol';otherwise,unit='1';
  endswitch
endfunction
elec_gate1_bookkeeping__gate1_publish–a0e79d5c59456bc6.m — Direct named helper referenced by entrypoint

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261117T203042Z-1446901-1794947442736238 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 a0e79d5c59456bc6e43bd69ef5ae5ec782a3fd0a47d31fb23e27a0ad3541175d

function receipts = gate1_publish(ctx,p,R)
  % Current-context public publication only. Tables commit independently.
  prefix=p.output_prefix;
  if isempty(regexp(prefix,'^[A-Za-z][A-Za-z0-9_.-]{0,100}$','once'))
    error('Gate1:ID','Choose a simple new public output prefix');
  endif
  notes=['Analytical/manufactured Gate1 bookkeeping, not experimental or assay validation. ' ...
    'Formal NH4Cl translation includes N0 additional Cl and A0 signed acid; fixed Na spectator. ' ...
    'HOCl counts one Cl atom/one Cl2-equivalent; gas Cl2 counts two Cl atoms/one equivalent. ' ...
    'O2/H2/escaped Cl2 are cumulative product/export ledgers. No physical pH. ' ...
    'V5: existing primary ELEC-01 experiment-20261117T171059Z-846242-1794935459579080-1.'];
  provenance=sprintf('Gate1 v1.0.2; registered run %s; source SHA %s; nominal inputs %s; declared paper SHA %s',ctx.run_id,ctx.script_sha256,p.source_dataset_id,p.declared_paper_sha256);
  definition=struct('contract','table.generic','storage','auto','replace_owned',false, ...
    'producer_version','1.0.2','source_dataset_ids',{{p.source_dataset_id}}, ...
    'source','ELEC Gate1 registered Octave benchmark','provenance',provenance,'notes',notes);
  receipts={};
  % Input literals retain exact typed Registry values in the Job/preset; this table labels them.
  keys=fieldnames(p); n=numel(keys); literals=cell(n,1); units=cell(n,1); status=cell(n,1);
  nominal={'current_A','duration_s','volume_m3','area_m2','background_NaCl_mol_m3','initial_N_g_m3'};
  reported=struct('current_A',0.12,'duration_s',3600,'volume_m3',0.0002,'area_m2',0.0006,'background_NaCl_mol_m3',84,'initial_N_g_m3',10);
  reference=cell(n,1);
  constants={'F_C_mol','M_N_g_mol','M_Cl2_g_mol'};
  for k=1:n
    key=keys{k};literals{k}=jsonencode(p.(key));units{k}='1';reference{k}='not_applicable';
    if any(strcmp(key,nominal))
      reference{k}=jsonencode(reported.(key));
      if isequal(p.(key),reported.(key)),status{k}='source_reported_nominal';else status{k}='user_override_of_reported_nominal';endif
    elseif any(strcmp(key,constants)),status{k}='declared_constant_convention';
    elseif strncmp(key,'mixed_',6)||strncmp(key,'stored_',7),status{k}='illustrative';
    else status{k}='execution_or_source_label';endif
    switch key
      case 'current_A',units{k}='A';case 'duration_s',units{k}='s';
      case 'volume_m3',units{k}='m^3';case 'area_m2',units{k}='m^2';
      case 'background_NaCl_mol_m3',units{k}='mol/m^3';
      case 'initial_N_g_m3',units{k}='g/m^3';case 'stored_HOCl_mol',units{k}='mol';
      case 'F_C_mol',units{k}='A*s/mol';case {'M_N_g_mol','M_Cl2_g_mol'},units{k}='g/mol';
    endswitch
  endfor
  columns=struct('parameter',{keys},'value_literal',{literals},'unit_label',{units},'source_status',{status},'reported_reference_literal',{reference});
  receipts{end+1}=publish_table([prefix '.inputs'],columns,struct(),definition);
  fprintf('CANONICAL_RECEIPT %s\n',jsonencode(receipts{end}));
  species={};reactions={};coefficient=[];elements=[];
  for a=1:numel(R.reactions)
    for b=1:numel(R.species)
      species{end+1,1}=R.species{b};reactions{end+1,1}=R.reactions{a};
      coefficient(end+1,1)=R.reaction_matrix(b,a);elements(end+1,:)=R.element_matrix(:,b)';
    endfor
  endfor
  columns=struct('species',{species},'reaction',{reactions},'coefficient',coefficient);
  for k=1:numel(R.elements),columns.(['per_species_' R.elements{k}])=elements(:,k);endfor
  receipts{end+1}=publish_table([prefix '.stoichiometry'],columns,struct(),definition);
  fprintf('CANONICAL_RECEIPT %s\n',jsonencode(receipts{end}));
  columns=struct('scenario_name',{R.scenario_names});unitmap=struct();
  for k=1:numel(R.state_names)
    key=R.state_names{k};columns.(key)=R.state_values(:,k);
    if any(strcmp(key,{'scenario_index','fractional_time','tiny_negative_stock_flag'})),unitmap.(key)='1';
    elseif strcmp(key,'time_s'),unitmap.(key)='s';
    elseif strcmp(key,'current_A'),unitmap.(key)='A';
    elseif strcmp(key,'geometric_current_density_A_m2'),unitmap.(key)='A/m^2';
    elseif !isempty(regexp(key,'_g_m3$','once')),unitmap.(key)='g/m^3';
    elseif strcmp(key,'Q_C')||strncmp(key,'Q_',2),unitmap.(key)='A*s';
    else unitmap.(key)='mol';endif
  endfor
  receipts{end+1}=publish_table([prefix '.states'],columns,unitmap,definition);
  fprintf('CANONICAL_RECEIPT %s\n',jsonencode(receipts{end}));
  C=R.checks;
  columns=struct('check_name',{{C.name}'},'actual',[C.actual]','limit',[C.limit]', ...
    'quantity_unit',{{C.unit}'},'comparison',{{C.comparison}'},'passed',double([C.pass]'));
  % actual/limit have per-row quantities; explicit quantity_unit is authoritative.
  receipts{end+1}=publish_table([prefix '.checks'],columns,struct(),definition);
  fprintf('CANONICAL_RECEIPT %s\n',jsonencode(receipts{end}));
endfunction

function receipt=publish_table(id,columns,unitmap,definition)
  keys=fieldnames(columns); n=numel(columns.(keys{1}));definition.dataset_id=id;
  writer=gxtxt_api_call('DATASET_PUBLICATION_API_v2','begin',{definition});
  try
    gxtxt_api_call('DATASET_PUBLICATION_API_v2','declare_dimension',{writer,'row',n,struct('extendible',false)});
    for k=1:numel(keys)
      key=keys{k};value=columns.(key);
      if numel(value)!=n,error('Gate1:Shape','Output column lengths differ');endif
      unit='1';if isfield(unitmap,key),unit=unitmap.(key);endif
      if iscell(value),dtype='string';kind='text';else dtype='float64';kind='number';endif
      schema=struct('dtype',dtype,'value_kind',kind,'rank',1,'dimension_ids',{{'row'}}, ...
        'name',key,'unit',unit,'coordinate_role','data','axis_kind','explicit');
      gxtxt_api_call('DATASET_PUBLICATION_API_v2','declare_variable',{writer,key,schema});
      gxtxt_api_call('DATASET_PUBLICATION_API_v2','write_variable',{writer,key,value,n});
    endfor
    receipt=gxtxt_api_call('DATASET_PUBLICATION_API_v2','finalize',{writer});
  catch err
    try gxtxt_api_call('DATASET_PUBLICATION_API_v2','abort',{writer});catch,end_try_catch
    rethrow(err);
  end_try_catch
endfunction
elec_gate1_bookkeeping__gate1_run–af6e44ddd88880e1.m — Actual invoked project entrypoint

EXECUTED_SOURCE_CHAIN_COMPLETED_NATIVE_USE · Exact retained registered-source revision

script-20261117T203042Z-1446901-1794947442736238 COMPLETED exit0

Frozen source: historical comments unchanged; not every contained function is necessarily called.

Download exact original file · SHA256 af6e44ddd88880e1b8e9c1dfb14b251b18e9a0e96f928d907d940d70a70ae086

% Gate1 v1.0.2 — intended registered Octave Project entrypoint, NOT EXECUTED.
% V5: run only in existing primary ELEC-01 after independent implementation review.
gxtxt_api_require('DATASET_PUBLICATION_API_v2@2');
gxtxt_api_require('DATASET_FILE_PUBLICATION_API_v1@1');
gxtxt_api_require('UNIT_REGISTRY_API_v1@1');
gxtxt_parameter_declare('current_A','double','default',0.12,'min',0,'description','Reported nominal open-cell current A; not measured current history');
gxtxt_parameter_declare('duration_s','double','default',3600,'min',0,'description','Declared observation duration s; evaluator requires positive');
gxtxt_parameter_declare('volume_m3','double','default',0.0002,'min',0,'description','Reported nominal solution volume m^3');
gxtxt_parameter_declare('area_m2','double','default',0.0006,'min',0,'description','Projected geometric area only; not electrochemically active area');
gxtxt_parameter_declare('background_NaCl_mol_m3','double','default',84,'min',0,'description','Reported background NaCl concentration; NH4Cl adds N0 further chloride');
gxtxt_parameter_declare('initial_N_g_m3','double','default',10,'min',0,'description','Reported nominal nitrogen mass concentration g N/m^3; numeric mg N/L equivalent');
gxtxt_parameter_declare('F_C_mol','double','default',96485.33212,'min',0,'description','Declared rounded Faraday constant A*s/mol, not fitted');
gxtxt_parameter_declare('M_N_g_mol','double','default',14.0067,'min',0,'description','Declared nitrogen atomic molar-mass convention g/mol');
gxtxt_parameter_declare('M_Cl2_g_mol','double','default',70.906,'min',0,'description','Declared Cl2 molecular molar-mass convention g/mol');
gxtxt_parameter_declare('stored_HOCl_mol','double','default',0.00001,'min',0,'description','Illustrative neutral external HOCl initial store in current-off case, not NaOCl dose');
gxtxt_parameter_declare('mixed_CER_fraction','double','default',0.6,'min',0,'max',1,'description','Illustrative current fraction, not measured CER efficiency');
gxtxt_parameter_declare('mixed_CRR_fraction','double','default',0.25,'min',0,'max',1,'description','Illustrative cathodic current fraction; availability checked');
gxtxt_parameter_declare('mixed_N2_fraction','double','default',0.25,'min',0,'max',1,'description','Illustrative fraction of substrate-limited formal N2 extent');
gxtxt_parameter_declare('mixed_strip_fraction','double','default',0.1,'min',0,'max',1,'description','Illustrative fraction of post-N oxidant formally stripped');
gxtxt_parameter_declare('stored_N2_fraction','double','default',0.5,'min',0,'max',1,'description','Illustrative current-off schedule fraction; zero disables the required positive counterexample');
gxtxt_parameter_declare('output_prefix','string','default','elec_gate1_v1_01','description','Choose a NEW canonical output prefix; existing IDs never replaced');
gxtxt_parameter_declare('source_dataset_id','string','default','ref-001_atrashkevich_2025_hal_accepted','description','Actual same-Session authentic source PDF ID; bind as a Runner input too');
gxtxt_parameter_declare('declared_paper_sha256','string','default','29d3a64cd947d50967a4316623f3684d0fe099422df343d2df98fe0abd788260','description','Declared reviewed HAL PDF SHA; independent input/archive readback remains required');
gxtxt_parameter_declare('source_note_ref','string','default','Atrashkevich2025 DOI10.1016/j.watres.2025.123732 HAL physical PDF7 NH4Cl/background NaCl; nominal conditions only','description','Reviewed source locator; not automatic extraction');
ctx=gxtxt_context();p=ctx.parameters;
if !isfield(ctx,'output_dir')||!isfield(ctx,'run_id')||!isfield(ctx,'script_sha256')
  error('Gate1:Context','A registered supervised GX-TXT Script context is required');
endif
try
% Public context input aliases are logical Dataset bindings, not storage paths.
bound={};todo={ctx.inputs};
while !isempty(todo)
  value=todo{end};todo(end)=[];
  if isstruct(value)
    for j=1:numel(value)
      if isfield(value(j),'dataset_id')&&ischar(value(j).dataset_id),bound{end+1}=value(j).dataset_id;endif
      fields=fieldnames(value(j));
      for k=1:numel(fields)
        child=value(j).(fields{k});if isstruct(child)||iscell(child),todo{end+1}=child;endif
      endfor
    endfor
  elseif iscell(value)
    todo=[todo,value(:)'];
  endif
endwhile
if !any(strcmp(bound,p.source_dataset_id))
  error('Gate1:InputBinding','Bind the actual same-Session source PDF as a Runner input before execution');
endif
% The operator verifies the stable experiment ID in the normal Runner GUI.
% A parameter label is not an attestation of the active Session identity.
R=gate1_evaluate(p);
unit_cases={{1,'min','s',60},{1,'cm^3','m^3',0.000001},{1,'mg','g',0.001}};
for k=1:numel(unit_cases)
  a=unit_cases{k};observed=gxtxt_api_call('UNIT_REGISTRY_API_v1','convert',{a{1},a{2},a{3}});
  residual=abs(observed-a{4});limit=1e-14+1e-10*abs(a{4});
  R.checks(end+1)=struct('name',['CORE_unit_conversion_' a{2} '_to_' a{3}], ...
    'actual',residual,'limit',limit,'unit',a{3},'comparison','le','pass',logical(isfinite(residual)&&residual<=limit));
endfor
R.passed=all([R.checks.pass]);
report=struct('schema','elec.gate1.bookkeeping.v1','source_version','1.0.2', ...
  'status','FAIL','run_id',ctx.run_id,'registered_script_sha256',ctx.script_sha256, ...
  'module_id',ctx.module_id,'parameters',p,'input_bindings',ctx.inputs, ...
  'runtime',struct('octave_version',version(),'architecture',computer(), ...
    'OMP_NUM_THREADS',getenv('OMP_NUM_THREADS'),'OPENBLAS_NUM_THREADS',getenv('OPENBLAS_NUM_THREADS')), ...
  'expected_experiment_id','experiment-20261117T171059Z-846242-1794935459579080-1', ...
  'scope','Analytical/manufactured bookkeeping; no physical pH, assay, kinetic or mechanism validation', ...
  'initial_composition',R.initial,'tolerances',R.tolerances,'checks',R.checks);
if R.passed,report.status='PASS_DECLARED_BOOKKEEPING_ONLY';endif
report_path=fullfile(ctx.output_dir,'gate1_report.json');
fid=fopen(report_path,'w');if fid<0,error('Gate1:Output','Cannot write owned report');endif
unwind_protect
  fprintf(fid,'%s\n',jsonencode(report));
unwind_protect_cleanup
  fclose(fid);
end_unwind_protect
fprintf('Gate1 checks: %d; passed: %d.\n',numel(R.checks),sum([R.checks.pass]));
if !R.passed,error('Gate1:Verification','Required check failed; owned diagnostic report retained, no PASS publication');endif
receipts=gate1_publish(ctx,p,R);
request=struct('dataset_id',[p.output_prefix '.report'],'contract','document.text','format','json', ...
  'source_file',report_path,'storage_kind','text','media_type','application/json','producer_version','1.0.2', ...
  'source_dataset_ids',{{p.source_dataset_id}},'source','ELEC Gate1 native registered Script', ...
  'provenance',['Registered run ' ctx.run_id '; source SHA ' ctx.script_sha256], ...
  'notes','Formal bookkeeping verification only; input statuses and limitations retained; no physical validation.');
report_receipt=gxtxt_api_call('DATASET_FILE_PUBLICATION_API_v1','publish',{request});
publication_path=fullfile(ctx.output_dir,'gate1_publication_receipts.json');
fid=fopen(publication_path,'w');if fid<0,error('Gate1:Output','Cannot write publication receipts');endif
unwind_protect
  fprintf(fid,'%s\n',jsonencode(struct('tables',{receipts},'report',report_receipt)));
unwind_protect_cleanup
  fclose(fid);
end_unwind_protect
fprintf('Gate1 native canonical publication completed; inspect original receipts.\n');

catch err
  failure=struct('schema','elec.gate1.failure.v1','status','FAILED_BEFORE_OR_DURING_PUBLICATION', ...
    'run_id',ctx.run_id,'source_sha256',ctx.script_sha256,'parameters',p, ...
    'identifier',err.identifier,'message',err.message,'stack',err.stack);
  token=regexp(err.message,'GATE1_DIAGNOSTIC:(\{.*\})','tokens','once');
  if !isempty(token),failure.guard=jsondecode(token{1});endif
  failure_path=fullfile(ctx.output_dir,'gate1_failure.json');
  fid=fopen(failure_path,'w');
  if fid>=0
    unwind_protect
      fprintf(fid,'%s\n',jsonencode(failure));
    unwind_protect_cleanup
      fclose(fid);
    end_unwind_protect
  else
    fprintf(2,'Unable to retain owned failure report: %s\n',failure_path);
  endif
  rethrow(err);
end_try_catch

Reproducing the work without conflating versions

Datasets and figures have native identities and consultable reference files. A Workspace is an editable configuration with source selections; a published Graph is a presentation result. Save, reopen and Portable have separate evidence: completed Job alone does not prove all lifecycle steps. No common grid or relabelled pH-as-time is introduced to simplify import.

The documented generic executions used private0.2.5. Version0.2.6 is installed, but no scientific forcing use is qualified here. Worksheet2.1.8 is a later private version; Numeric1.65.3 remains an uninstalled proposal. Private corrections are separately supplied for the owner’s review and do not constitute a public framework release.

P013 is the owner-committed reproduction target for MAIN to verify; it is not released or verified at this freeze. Running a listing standalone would not by itself constitute native reproduction. Reproduction on P013 requires the actual verified release, the same model/input/unit contracts and normal admission/Job workflow, followed by comparison to retained output records. This offline WordPress project documents completed work and its limits; it neither changes the website nor mutates the scientific Session.

Actual verified native delivery closure

The final official Portable export is completed and verified:4533Session files plus one package header, with CRC and exact manifest membership checks. That complete archive contains privately retained paper PDFs and belongs to the private scientific delivery, not the public WordPress assets. Graphs p0037/p0038 are published,saved and independently reopened in distinct Workspaces with final receipts. No new generic-network or fraction graph was published: their canonical outputs remain consultable as data without an invented figure. Successful archive custody does not turn unexecuted candidates into results.

Practical GX-TXT walkthrough: from source to result

Five illustrated chapters teach the principal routes actually used. Specific model definitions, scripts and the Job map complete coverage of the delivered results; this is neither a new execution nor a claim of already verified P013 reproduction.

  1. 1. Session, PDFs and source figure
  2. 2. Digitization: four panels, four calibrations
  3. 3. Fitting, expressions, worksheets and sensitivity
  4. 4. Graphs, units and editable Workspaces
  5. 5. Reaction network, Jobs and reproduction

Procedure coverage · 26 MAIN/P013 NOT_RUN cases · MAIN handoff.

ELEC project and full diary · Next: ELEC 07

#Convection #Electrochemistry #Electrolysis #Mass Transport

Other steps of this project