function fitPrunedKnotsDiscontinuous(iknots, { mu=2 } = {}) {
const n = iknots.length - 1;
const backptr = new Array(n + 1).fill(-1);
const min_cost = new Array(n + 1).fill(Infinity);
min_cost[0] = 0;
for(let i2=1; i2 < n+1; ++i2) {
for(let i1=0; i1 < i2; ++i1) {
const sfit = segmentFit(iknots[i1], iknots[i2]);
const ndata = breaks[iknots[i2]] - breaks[iknots[i1]];
let cost = sfit.chisq / ndata;
if(i1 > 0) cost += min_cost[i1] + mu / iknots.length;
if(cost < min_cost[i2]) {
min_cost[i2] = cost;
backptr[i2] = i1;
}
}
}
const pruned = [ ];
let j = n;
while(j != -1) {
pruned.push(iknots[j]);
j = backptr[j];
}
pruned.reverse();
const offset = index * arraySize;
let logw_lo, logw_hi = kwave[pruned[0]], chisq_sum = 0;
const fit = [ ];
for(let i = 0; i < pruned.length - 1; ++i) {
const sfit = segmentFit(pruned[i], pruned[i+1]);
logw_lo = logw_hi;
logw_hi = kwave[pruned[i+1]];
for(let k = breaks[pruned[i]]; k < breaks[pruned[i+1]]; ++k) {
const linear = sfit.linear(logwave[k]);
const chisq = ivar[offset + k] * (flux[offset + k] - linear) ** 2;
if(!Number.isFinite(chisq)) console.log(k, fullwave[k], i, sfit);
chisq_sum += chisq;
fit.push({ wlen:fullwave[k], linear, chisq });
}
}
return { pruned, fit, chisq_sum };
}