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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
let lastReport = null;

const resultBox = document.getElementById("result");
const statusBox = document.getElementById("status");
const analyzeButton = document.getElementById("analyze");
const downloadButton = document.getElementById("download");

function mean(a) {
  return a.reduce((s,x)=>s+x,0)/a.length;
}

function solve3(A,b) {
  const M = A.map((r,i)=>[...r,b[i]]);

  for (let i=0;i<3;i++) {
    let pivot=i;

    for (let j=i+1;j<3;j++) {
      if (Math.abs(M[j][i]) > Math.abs(M[pivot][i])) pivot=j;
    }

    [M[i],M[pivot]]=[M[pivot],M[i]];

    if (Math.abs(M[i][i]) < 1e-15) return null;

    const d=M[i][i];
    for (let k=i;k<4;k++) M[i][k]/=d;

    for (let j=0;j<3;j++) {
      if (j===i) continue;
      const f=M[j][i];

      for (let k=i;k<4;k++) {
        M[j][k]-=f*M[i][k];
      }
    }
  }

  return [M[0][3],M[1][3],M[2][3]];
}

function quadFit(x,y) {
  let s0=x.length,s1=0,s2=0,s3=0,s4=0;
  let t0=0,t1=0,t2=0;

  for(let i=0;i<x.length;i++) {
    const X=x[i], Y=y[i], X2=X*X;

    s1+=X; s2+=X2; s3+=X2*X; s4+=X2*X2;
    t0+=Y; t1+=X*Y; t2+=X2*Y;
  }

  return solve3(
    [[s4,s3,s2],[s3,s2,s1],[s2,s1,s0]],
    [t2,t1,t0]
  );
}

function linearRegression(x,y) {
  const mx=mean(x), my=mean(y);

  let sxx=0,sxy=0,syy=0;

  for(let i=0;i<x.length;i++) {
    const dx=x[i]-mx;
    const dy=y[i]-my;

    sxx+=dx*dx;
    sxy+=dx*dy;
    syy+=dy*dy;
  }

  if (sxx===0) return null;

  const slope=sxy/sxx;
  const intercept=my-slope*mx;

  let rss=0;

  for(let i=0;i<x.length;i++) {
    const e=y[i]-(intercept+slope*x[i]);
    rss+=e*e;
  }

  const r2=syy===0 ? NaN : 1-rss/syy;

  return {slope,intercept,r2,rss};
}

function r2(y,yhat) {
  const m=mean(y);

  let rss=0,tss=0;

  for(let i=0;i<y.length;i++) {
    rss+=(y[i]-yhat[i])**2;
    tss+=(y[i]-m)**2;
  }

  return tss===0 ? NaN : 1-rss/tss;
}

function aic(y,yhat,k) {
  let rss=0;

  for(let i=0;i<y.length;i++) {
    rss+=(y[i]-yhat[i])**2;
  }

  rss=Math.max(rss,Number.MIN_VALUE);

  return y.length*Math.log(rss/y.length)+2*k;
}

function parseCSV(text,pcol,xcol) {
  const lines=text.trim().split(/\r?\n/);

  const headers=lines[0]
    .split(",")
    .map(x=>x.replace(/^"|"$/g,"").trim());

  const pi=headers.indexOf(pcol);
  const xi=headers.indexOf(xcol);

  if(pi<0 || xi<0) {
    throw new Error(
      `Columns not found. Available: ${headers.join(", ")}`
    );
  }

  const pts=[];

  for(let i=1;i<lines.length;i++) {
    const v=lines[i].split(",");

    let p=Number((v[pi]||"").replace(/^"|"$/g,""));
    let x=Number((v[xi]||"").replace(/^"|"$/g,""));

    if(Number.isFinite(p) && Number.isFinite(x)) {
      pts.push({p,x});
    }
  }

  return pts;
}

function candidateCenters(pts) {
  const centers=[];

  for(let i=2;i<pts.length-2;i++) {
    const dx1=pts[i].x-pts[i-1].x;
    const dx2=pts[i+1].x-pts[i].x;

    if(dx1===0 || dx2===0) continue;

    const s1=(pts[i].p-pts[i-1].p)/dx1;
    const s2=(pts[i+1].p-pts[i].p)/dx2;

    if(
      Number.isFinite(s1) &&
      Number.isFinite(s2) &&
      (
        s1===0 ||
        s2===0 ||
        Math.sign(s1)!==Math.sign(s2)
      )
    ) {
      centers.push(i);
    }
  }

  return centers;
}

function consecutiveSteps(pts,pc,xc,left,threshold) {
  let branch=pts.filter(q => left ? q.x<xc : q.x>xc);

  branch.sort(
    (a,b)=>Math.abs(a.x-xc)-Math.abs(b.x-xc)
  );

  let count=0;

  for(let i=0;i<branch.length-1;i++) {
    const rel =
      Math.abs(branch[i+1].p-branch[i].p) /
      Math.max(Math.abs(pc),Number.EPSILON);

    if(rel<threshold) count++;
    else break;
  }

  return count;
}

async function analyze() {
  try {
    analyzeButton.disabled=true;
    statusBox.textContent="Reading data…";
    resultBox.textContent="Working…";

    await new Promise(r=>setTimeout(r,50));

    const file=document.getElementById("file").files[0];

    if(!file) throw new Error("Choose a CSV file.");

    const pcol=document.getElementById("pcol").value.trim();
    const xcol=document.getElementById("xcol").value.trim();
    const resolution=Number(document.getElementById("resolution").value);
    const required=Number(document.getElementById("steps").value);

    const text=await file.text();

    let pts=parseCSV(text,pcol,xcol);

    if(pts.length<9) throw new Error("Not enough numeric points.");

    statusBox.textContent=`Loaded ${pts.length.toLocaleString()} numeric points.`;

    await new Promise(r=>setTimeout(r,50));

    pts.sort((a,b)=>a.x-b.x);

    const centers=candidateCenters(pts);

    statusBox.textContent=
      `Loaded ${pts.length.toLocaleString()} points. ` +
      `Testing ${centers.length} turning-point candidates…`;

    await new Promise(r=>setTimeout(r,50));

    if(centers.length===0) {
      lastReport={
        n_points:pts.length,
        candidate_centers:0,
        verdict:"NO_TURNING_POINT_CANDIDATE"
      };

      resultBox.textContent=JSON.stringify(lastReport,null,2);
      return;
    }

    let best=null;

    for(const center of centers) {
      for(const win of [9,15,21,31]) {
        const h=Math.floor(win/2);

        if(center-h<0 || center+h>=pts.length) continue;

        const slice=pts.slice(center-h,center+h+1);
        const xs=slice.map(q=>q.x);
        const ps=slice.map(q=>q.p);

        const x0=mean(xs);
        const u=xs.map(v=>v-x0);

        const q=quadFit(u,ps);

        if(!q) continue;

        const [a,b,c]=q;

        if(Math.abs(a)<1e-15) continue;

        const uv=-b/(2*a);
        const xc=x0+uv;

        if(xc<Math.min(...xs) || xc>Math.max(...xs)) continue;

        const pc=a*uv*uv+b*uv+c;

        const qhat=u.map(v=>a*v*v+b*v+c);

        const lin=linearRegression(u,ps);

        if(!lin) continue;

        const lhat=u.map(v=>lin.intercept+lin.slope*v);

        const candidate={
          pc,
          xc,
          window:win,
          quadratic_r2:r2(ps,qhat),
          delta_aic_linear_minus_quadratic:
            aic(ps,lhat,2)-aic(ps,qhat,3)
        };

        if(
          !best ||
          candidate.delta_aic_linear_minus_quadratic >
          best.delta_aic_linear_minus_quadratic
        ) {
          best=candidate;
        }
      }
    }

    if(!best) {
      lastReport={
        n_points:pts.length,
        candidate_centers:centers.length,
        verdict:"NO_VALID_LOCAL_QUADRATIC_CANDIDATE"
      };

      resultBox.textContent=JSON.stringify(lastReport,null,2);
      return;
    }

    const pc=best.pc;
    const xc=best.xc;

    const scaling=[];

    for(const left of [true,false]) {
      let branch=pts.filter(q => left ? q.x<xc : q.x>xc);

      branch.sort(
        (a,b)=>Math.abs(a.x-xc)-Math.abs(b.x-xc)
      );

      branch=branch.slice(0,12);

      for(const q of branch) {
        const dp=Math.abs(q.p-pc);
        const dx=Math.abs(q.x-xc);

        if(dp>0 && dx>0) {
          scaling.push({
            lp:Math.log(dp),
            lx:Math.log(dx)
          });
        }
      }
    }

    let beta=null;
    let scalingR2=null;

    if(scaling.length>=4) {
      const reg=linearRegression(
        scaling.map(q=>q.lp),
        scaling.map(q=>q.lx)
      );

      if(reg) {
        beta=reg.slope;
        scalingR2=reg.r2;
      }
    }

    const leftSteps =
      consecutiveSteps(pts,pc,xc,true,resolution);

    const rightSteps =
      consecutiveSteps(pts,pc,xc,false,resolution);

    const gate =
      leftSteps>=required &&
      rightSteps>=required;

    let verdict;

    if(
      best.delta_aic_linear_minus_quadratic<=0 ||
      best.quadratic_r2<0.9
    ) {
      verdict="WEAK_OR_NO_FOLD_EVIDENCE";
    } else if(beta===null) {
      verdict="FOLD_CANDIDATE_SCALING_INCONCLUSIVE";
    } else if(gate) {
      verdict="FOLD_CANDIDATE_PRIMARY_RESOLUTION_PASS";
    } else {
      verdict="FOLD_CANDIDATE_RESOLUTION_FAIL";
    }

    lastReport={
      n_points:pts.length,
      candidate_centers:centers.length,
      pc,
      xc,
      quadratic_window:best.window,
      quadratic_r2:best.quadratic_r2,
      delta_aic_linear_minus_quadratic:
        best.delta_aic_linear_minus_quadratic,
      beta,
      scaling_r2:scalingR2,
      consecutive_steps_left:leftSteps,
      consecutive_steps_right:rightSteps,
      resolution_threshold:resolution,
      required_consecutive_steps_per_branch:required,
      resolution_gate_pass:gate,
      verdict,
      warning:
        "Numerical screening only. A detected turning point is not proof of a physical fold."
    };

    resultBox.textContent=JSON.stringify(lastReport,null,2);

    statusBox.textContent=
      `Done. ${pts.length.toLocaleString()} points analyzed.`;

  } catch(err) {
    resultBox.textContent="ERROR: "+err.message;
    statusBox.textContent="Analysis failed.";
    console.error(err);
  } finally {
    analyzeButton.disabled=false;
  }
}

function downloadJSON() {
  if(!lastReport) {
    alert("Run an analysis first.");
    return;
  }

  const blob=new Blob(
    [JSON.stringify(lastReport,null,2)],
    {type:"application/json"}
  );

  const url=URL.createObjectURL(blob);
  const a=document.createElement("a");

  a.href=url;
  a.download="foldcheck_result.json";
  a.click();

  URL.revokeObjectURL(url);
}

analyzeButton.addEventListener("click",analyze);
downloadButton.addEventListener("click",downloadJSON);