javascript-lp-solver 1.0.0 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -54,6 +54,22 @@ var solver = (function () {
54
54
  this.heap = new Array(initialCapacity);
55
55
  this.size = 0;
56
56
  this.seqCounter = 0;
57
+ this.pool = new Array(64);
58
+ this.poolSize = 0;
59
+ }
60
+ allocEntry(branch, seq) {
61
+ if (this.poolSize > 0) {
62
+ const entry = this.pool[--this.poolSize];
63
+ entry.branch = branch;
64
+ entry.seq = seq;
65
+ return entry;
66
+ }
67
+ return { branch, seq };
68
+ }
69
+ freeEntry(entry) {
70
+ if (this.poolSize < 256) {
71
+ this.pool[this.poolSize++] = entry;
72
+ }
57
73
  }
58
74
  get length() {
59
75
  return this.size;
@@ -81,7 +97,7 @@ var solver = (function () {
81
97
  if (idx >= heap.length) {
82
98
  heap.length = heap.length * 2;
83
99
  }
84
- const entry = { branch, seq: this.seqCounter++ };
100
+ const entry = this.allocEntry(branch, this.seqCounter++);
85
101
  // Bubble up
86
102
  while (idx > 0) {
87
103
  const parentIdx = (idx - 1) >> 1;
@@ -99,8 +115,11 @@ var solver = (function () {
99
115
  return undefined;
100
116
  }
101
117
  const heap = this.heap;
102
- const result = heap[0].branch;
118
+ const poppedEntry = heap[0];
119
+ const result = poppedEntry.branch;
103
120
  this.size--;
121
+ // Return entry to pool
122
+ this.freeEntry(poppedEntry);
104
123
  if (this.size === 0) {
105
124
  return result;
106
125
  }
@@ -143,15 +162,16 @@ var solver = (function () {
143
162
  tableau.addCutConstraints(branchingCuts);
144
163
  tableau.simplex();
145
164
  if ((_a = tableau.model) === null || _a === void 0 ? void 0 : _a.useMIRCuts) {
146
- let fractionalVolumeImproved = true;
147
- while (fractionalVolumeImproved) {
148
- const fractionalVolumeBefore = tableau.computeFractionalVolume(true);
165
+ // Optimization: reuse previous "after" as next "before" to avoid redundant computation
166
+ let fractionalVolume = tableau.computeFractionalVolume(true);
167
+ while (fractionalVolume > 0) {
149
168
  tableau.applyMIRCuts();
150
169
  tableau.simplex();
151
170
  const fractionalVolumeAfter = tableau.computeFractionalVolume(true);
152
- if (fractionalVolumeAfter >= 0.9 * fractionalVolumeBefore) {
153
- fractionalVolumeImproved = false;
171
+ if (fractionalVolumeAfter >= 0.9 * fractionalVolume) {
172
+ break;
154
173
  }
174
+ fractionalVolume = fractionalVolumeAfter;
155
175
  }
156
176
  }
157
177
  };
@@ -168,7 +188,10 @@ var solver = (function () {
168
188
  let bestEvaluation = Infinity;
169
189
  let bestBranch = null;
170
190
  const bestOptionalObjectivesEvaluations = [];
171
- for (let oInit = 0; oInit < tableau.optionalObjectives.length; oInit += 1) {
191
+ // Cache optionalObjectives reference to avoid repeated property lookups in hot loop
192
+ const optionalObjectives = tableau.optionalObjectives;
193
+ const nOptionalObjectives = optionalObjectives.length;
194
+ for (let oInit = 0; oInit < nOptionalObjectives; oInit += 1) {
172
195
  bestOptionalObjectivesEvaluations.push(Infinity);
173
196
  }
174
197
  const branch = createBranch$2(-Infinity, []);
@@ -187,7 +210,7 @@ var solver = (function () {
187
210
  }
188
211
  }
189
212
  const activeBranch = branches.pop();
190
- if (activeBranch.relaxedEvaluation > bestEvaluation) {
213
+ if (activeBranch.relaxedEvaluation >= bestEvaluation) {
191
214
  continue;
192
215
  }
193
216
  const cuts = activeBranch.cuts;
@@ -202,13 +225,13 @@ var solver = (function () {
202
225
  }
203
226
  if (evaluation === bestEvaluation) {
204
227
  let isCurrentEvaluationWorse = true;
205
- for (let o = 0; o < tableau.optionalObjectives.length; o += 1) {
206
- if (tableau.optionalObjectives[o].reducedCosts[0] >
207
- bestOptionalObjectivesEvaluations[o]) {
228
+ for (let o = 0; o < nOptionalObjectives; o += 1) {
229
+ const currentCost = optionalObjectives[o].reducedCosts[0];
230
+ const bestCost = bestOptionalObjectivesEvaluations[o];
231
+ if (currentCost > bestCost) {
208
232
  break;
209
233
  }
210
- else if (tableau.optionalObjectives[o].reducedCosts[0] <
211
- bestOptionalObjectivesEvaluations[o]) {
234
+ else if (currentCost < bestCost) {
212
235
  isCurrentEvaluationWorse = false;
213
236
  break;
214
237
  }
@@ -225,9 +248,9 @@ var solver = (function () {
225
248
  }
226
249
  bestBranch = activeBranch;
227
250
  bestEvaluation = evaluation;
228
- for (let oCopy = 0; oCopy < tableau.optionalObjectives.length; oCopy += 1) {
251
+ for (let oCopy = 0; oCopy < nOptionalObjectives; oCopy += 1) {
229
252
  bestOptionalObjectivesEvaluations[oCopy] =
230
- tableau.optionalObjectives[oCopy].reducedCosts[0];
253
+ optionalObjectives[oCopy].reducedCosts[0];
231
254
  }
232
255
  if ((_e = tableau.model) === null || _e === void 0 ? void 0 : _e.keep_solutions) {
233
256
  const nowSolution = tableau.model.tableau.getSolution();
@@ -245,6 +268,7 @@ var solver = (function () {
245
268
  }
246
269
  const variable = tableau.getMostFractionalVar();
247
270
  const varIndex = variable.index;
271
+ const varValue = variable.value;
248
272
  const cutsHigh = [];
249
273
  const cutsLow = [];
250
274
  const nCuts = cuts.length;
@@ -263,11 +287,9 @@ var solver = (function () {
263
287
  cutsLow.push(cut);
264
288
  }
265
289
  }
266
- const min = Math.ceil(variable.value);
267
- const max = Math.floor(variable.value);
268
- const cutHigh = createCut$2("min", varIndex, min);
290
+ const cutHigh = createCut$2("min", varIndex, Math.ceil(varValue));
269
291
  cutsHigh.push(cutHigh);
270
- const cutLow = createCut$2("max", varIndex, max);
292
+ const cutLow = createCut$2("max", varIndex, Math.floor(varValue));
271
293
  cutsLow.push(cutLow);
272
294
  branches.push(createBranch$2(evaluation, cutsHigh));
273
295
  branches.push(createBranch$2(evaluation, cutsLow));
@@ -281,6 +303,50 @@ var solver = (function () {
281
303
  return { applyCuts, branchAndCut };
282
304
  }
283
305
 
306
+ /**
307
+ * Optimized cycle detector using hash-based O(1) lookup.
308
+ * The original checkForCycles was O(n²) - comparing every pair against all others.
309
+ * This version uses a Map to track where each (leaving,entering) pair occurred,
310
+ * making duplicate detection O(1) average case.
311
+ */
312
+ class CycleDetector {
313
+ constructor() {
314
+ this.pairs = [];
315
+ this.positions = new Map();
316
+ }
317
+ add(leaving, entering) {
318
+ const key = `${leaving}_${entering}`;
319
+ const pos = this.pairs.length;
320
+ this.pairs.push([leaving, entering]);
321
+ const prevPositions = this.positions.get(key);
322
+ if (prevPositions === undefined) {
323
+ this.positions.set(key, [pos]);
324
+ return [];
325
+ }
326
+ // Check if any previous occurrence starts a repeating cycle
327
+ for (const startPos of prevPositions) {
328
+ const cycleLength = pos - startPos;
329
+ // Need at least cycleLength more elements to verify
330
+ if (cycleLength > this.pairs.length - pos) {
331
+ continue;
332
+ }
333
+ let cycleFound = true;
334
+ for (let i = 1; i < cycleLength && startPos + cycleLength + i < this.pairs.length; i++) {
335
+ const p1 = this.pairs[startPos + i];
336
+ const p2 = this.pairs[startPos + cycleLength + i];
337
+ if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
338
+ cycleFound = false;
339
+ break;
340
+ }
341
+ }
342
+ if (cycleFound) {
343
+ return [startPos, cycleLength];
344
+ }
345
+ }
346
+ prevPositions.push(pos);
347
+ return [];
348
+ }
349
+ }
284
350
  function simplex() {
285
351
  this.bounded = true;
286
352
  this.phase1();
@@ -289,21 +355,125 @@ var solver = (function () {
289
355
  }
290
356
  return this;
291
357
  }
358
+ /**
359
+ * Dual simplex algorithm for warm-starting after adding constraints.
360
+ *
361
+ * Use when: The current solution is dual feasible (reduced costs valid) but
362
+ * may be primal infeasible (some RHS values negative). This is common after
363
+ * adding bound constraints in branch-and-cut.
364
+ *
365
+ * Algorithm:
366
+ * 1. Find a basic variable with negative value (leaving variable)
367
+ * 2. Find entering variable using dual ratio test
368
+ * 3. Pivot to restore primal feasibility
369
+ * 4. Repeat until all basic variables are non-negative
370
+ *
371
+ * @returns Number of iterations, or -1 if dual infeasible
372
+ */
373
+ function dualSimplex() {
374
+ const matrix = this.matrix;
375
+ const width = this.width;
376
+ const rhsColumn = this.rhsColumn;
377
+ const lastColumn = width - 1;
378
+ const lastRow = this.height - 1;
379
+ const precision = this.precision;
380
+ const negPrecision = -precision;
381
+ let iterations = 0;
382
+ const maxIterations = 10000; // Safety limit
383
+ while (iterations < maxIterations) {
384
+ // Step 1: Find leaving variable (row with most negative RHS)
385
+ let leavingRow = 0;
386
+ let minRHS = negPrecision;
387
+ for (let r = 1; r <= lastRow; r++) {
388
+ const rhsValue = matrix[r * width + rhsColumn];
389
+ if (rhsValue < minRHS) {
390
+ minRHS = rhsValue;
391
+ leavingRow = r;
392
+ }
393
+ }
394
+ // If no negative RHS, we're primal feasible - done!
395
+ if (leavingRow === 0) {
396
+ this.feasible = true;
397
+ this.setEvaluation();
398
+ return iterations;
399
+ }
400
+ // Step 2: Find entering variable using dual ratio test
401
+ // For each non-basic variable j with a_ij < 0 (negative coefficient in leaving row),
402
+ // compute ratio = reduced_cost[j] / |a_ij|
403
+ // Choose the one with minimum ratio (to maintain dual feasibility)
404
+ let enteringColumn = 0;
405
+ let minRatio = Infinity;
406
+ const leavingRowOffset = leavingRow * width;
407
+ for (let c = 1; c <= lastColumn; c++) {
408
+ const coefficient = matrix[leavingRowOffset + c];
409
+ // Only consider columns with negative coefficient in leaving row
410
+ if (coefficient < negPrecision) {
411
+ // Reduced cost is in row 0 (cost row)
412
+ const reducedCost = matrix[c];
413
+ // For minimization, reduced costs should be >= 0 for optimality
414
+ // Ratio test: reducedCost / |coefficient|
415
+ if (reducedCost >= negPrecision) {
416
+ const ratio = reducedCost / -coefficient;
417
+ if (ratio < minRatio) {
418
+ minRatio = ratio;
419
+ enteringColumn = c;
420
+ }
421
+ }
422
+ }
423
+ }
424
+ // If no entering column found, the problem is dual infeasible (primal unbounded)
425
+ if (enteringColumn === 0) {
426
+ this.feasible = false;
427
+ return -1;
428
+ }
429
+ // Step 3: Pivot
430
+ this.pivot(leavingRow, enteringColumn);
431
+ iterations++;
432
+ }
433
+ // Hit iteration limit - something went wrong
434
+ this.feasible = false;
435
+ return iterations;
436
+ }
292
437
  function phase1() {
293
438
  const debugCheckForCycles = this.model.checkForCycles;
294
- const varIndexesCycle = [];
439
+ const cycleDetector = debugCheckForCycles ? new CycleDetector() : null;
295
440
  const matrix = this.matrix;
296
441
  const width = this.width;
297
442
  const rhsColumn = this.rhsColumn;
298
443
  const lastColumn = this.width - 1;
299
444
  const lastRow = this.height - 1;
300
- let unrestricted;
445
+ const precision = this.precision;
446
+ const negPrecision = -precision;
447
+ // Cache arrays for faster access in hot loops
448
+ const unrestrictedVars = this.unrestrictedVars;
449
+ const varIndexByRow = this.varIndexByRow;
450
+ const varIndexByCol = this.varIndexByCol;
451
+ // Anti-cycling: on degenerate problems, the max-quotient pivot rule
452
+ // can oscillate, corrupting the matrix. We detect stalling early
453
+ // (after SAVE_THRESHOLD iterations without RHS improvement) and save
454
+ // the matrix state. If still stuck after maxQuotientLimit iterations,
455
+ // we restore the clean matrix and switch to Bland's rule. The lazy
456
+ // save avoids the copy cost on the vast majority of phase1 calls
457
+ // that converge quickly.
458
+ const SAVE_THRESHOLD = 10;
459
+ const maxQuotientLimit = Math.max(lastRow, lastColumn);
301
460
  let iterations = 0;
461
+ let useBland = false;
462
+ let initialRHS = -Infinity;
463
+ let savedMatrix = null;
464
+ let savedVarIndexByRow = null;
465
+ let savedVarIndexByCol = null;
466
+ let savedRowByVarIndex = null;
467
+ let savedColByVarIndex = null;
302
468
  while (true) {
469
+ // Find leaving row (most negative RHS among restricted basic vars).
470
+ // Unrestricted variables can validly have negative values, so rows
471
+ // where the basic variable is unrestricted are not infeasible.
303
472
  let leavingRowIndex = 0;
304
- let rhsValue = -this.precision;
473
+ let rhsValue = negPrecision;
305
474
  for (let r = 1; r <= lastRow; r++) {
306
- unrestricted = this.unrestrictedVars[this.varIndexByRow[r]] === true;
475
+ if (unrestrictedVars[varIndexByRow[r]] === true)
476
+ continue;
307
477
  const value = matrix[r * width + rhsColumn];
308
478
  if (value < rhsValue) {
309
479
  rhsValue = value;
@@ -314,18 +484,95 @@ var solver = (function () {
314
484
  this.feasible = true;
315
485
  return iterations;
316
486
  }
487
+ // Detect non-convergence and apply anti-cycling.
488
+ if (!useBland && iterations > 0 && rhsValue <= initialRHS) {
489
+ if (iterations >= SAVE_THRESHOLD && savedMatrix === null) {
490
+ // Stalling detected: save matrix for potential rollback
491
+ savedMatrix = matrix.slice();
492
+ savedVarIndexByRow = varIndexByRow.slice();
493
+ savedVarIndexByCol = varIndexByCol.slice();
494
+ savedRowByVarIndex = this.rowByVarIndex.slice();
495
+ savedColByVarIndex = this.colByVarIndex.slice();
496
+ }
497
+ if (iterations >= maxQuotientLimit) {
498
+ // Still stuck after generous budget: restore and switch
499
+ useBland = true;
500
+ if (savedMatrix) {
501
+ matrix.set(savedMatrix);
502
+ for (let i = 0; i < savedVarIndexByRow.length; i++) {
503
+ varIndexByRow[i] = savedVarIndexByRow[i];
504
+ }
505
+ for (let i = 0; i < savedVarIndexByCol.length; i++) {
506
+ varIndexByCol[i] = savedVarIndexByCol[i];
507
+ }
508
+ for (let i = 0; i < savedRowByVarIndex.length; i++) {
509
+ this.rowByVarIndex[i] = savedRowByVarIndex[i];
510
+ }
511
+ for (let i = 0; i < savedColByVarIndex.length; i++) {
512
+ this.colByVarIndex[i] = savedColByVarIndex[i];
513
+ }
514
+ iterations = 0;
515
+ continue;
516
+ }
517
+ }
518
+ }
519
+ if (iterations === 0) {
520
+ initialRHS = rhsValue;
521
+ }
522
+ // Find entering column.
523
+ // Prefer columns with negative coefficient in leaving row (these directly
524
+ // fix the infeasibility by making RHS positive after pivot).
525
+ // Only fall back to unrestricted variables with positive coefficient when
526
+ // no negative coefficient column exists - this "swaps" the infeasibility
527
+ // to an unrestricted variable (which is allowed to be negative).
317
528
  let enteringColumn = 0;
318
- let maxQuotient = -Infinity;
319
- const costRowOffset = 0; // row 0
320
529
  const leavingRowOffset = leavingRowIndex * width;
321
- for (let c = 1; c <= lastColumn; c++) {
322
- const coefficient = matrix[leavingRowOffset + c];
323
- unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
324
- if (unrestricted || coefficient < -this.precision) {
325
- const quotient = -matrix[costRowOffset + c] / coefficient;
326
- if (maxQuotient < quotient) {
327
- maxQuotient = quotient;
530
+ if (useBland) {
531
+ // Bland's rule: pick the first eligible column (smallest index).
532
+ // First pass: negative coefficients only (directly fix infeasibility)
533
+ for (let c = 1; c <= lastColumn; c++) {
534
+ const coefficient = matrix[leavingRowOffset + c];
535
+ if (coefficient < negPrecision) {
328
536
  enteringColumn = c;
537
+ break;
538
+ }
539
+ }
540
+ // Fallback: unrestricted with non-zero coefficient (swap infeasibility)
541
+ if (enteringColumn === 0) {
542
+ for (let c = 1; c <= lastColumn; c++) {
543
+ const coefficient = matrix[leavingRowOffset + c];
544
+ if (unrestrictedVars[varIndexByCol[c]] === true &&
545
+ (coefficient < negPrecision || coefficient > precision)) {
546
+ enteringColumn = c;
547
+ break;
548
+ }
549
+ }
550
+ }
551
+ }
552
+ else {
553
+ // Max-quotient rule: faster in practice but can oscillate on
554
+ // degenerate problems.
555
+ // First pass: negative coefficients only
556
+ let maxQuotient = -Infinity;
557
+ for (let c = 1; c <= lastColumn; c++) {
558
+ const coefficient = matrix[leavingRowOffset + c];
559
+ if (coefficient < negPrecision) {
560
+ const quotient = -matrix[c] / coefficient;
561
+ if (maxQuotient < quotient) {
562
+ maxQuotient = quotient;
563
+ enteringColumn = c;
564
+ }
565
+ }
566
+ }
567
+ // Fallback: unrestricted with non-zero coefficient
568
+ if (enteringColumn === 0) {
569
+ for (let c = 1; c <= lastColumn; c++) {
570
+ const coefficient = matrix[leavingRowOffset + c];
571
+ if (unrestrictedVars[varIndexByCol[c]] === true &&
572
+ (coefficient < negPrecision || coefficient > precision)) {
573
+ enteringColumn = c;
574
+ break;
575
+ }
329
576
  }
330
577
  }
331
578
  }
@@ -333,12 +580,8 @@ var solver = (function () {
333
580
  this.feasible = false;
334
581
  return iterations;
335
582
  }
336
- if (debugCheckForCycles) {
337
- varIndexesCycle.push([
338
- this.varIndexByRow[leavingRowIndex],
339
- this.varIndexByCol[enteringColumn],
340
- ]);
341
- const cycleData = this.checkForCycles(varIndexesCycle);
583
+ if (cycleDetector) {
584
+ const cycleData = cycleDetector.add(varIndexByRow[leavingRowIndex], varIndexByCol[enteringColumn]);
342
585
  if (cycleData.length > 0) {
343
586
  this.model.messages.push("Cycle in phase 1");
344
587
  this.model.messages.push("Start :" + cycleData[0]);
@@ -353,18 +596,38 @@ var solver = (function () {
353
596
  }
354
597
  function phase2() {
355
598
  const debugCheckForCycles = this.model.checkForCycles;
356
- const varIndexesCycle = [];
599
+ const cycleDetector = debugCheckForCycles ? new CycleDetector() : null;
357
600
  const matrix = this.matrix;
358
601
  const width = this.width;
359
602
  const rhsColumn = this.rhsColumn;
360
603
  const lastColumn = this.width - 1;
361
604
  const lastRow = this.height - 1;
362
605
  const precision = this.precision;
606
+ const negPrecision = -precision;
363
607
  const nOptionalObjectives = this.optionalObjectives.length;
364
608
  let optionalCostsColumns = null;
609
+ // Cache arrays for faster access in hot loops
610
+ const unrestrictedVars = this.unrestrictedVars;
611
+ const varIndexByCol = this.varIndexByCol;
612
+ const varIndexByRow = this.varIndexByRow;
613
+ // Note: costRowIndex is always 0, so we access matrix[c] directly
365
614
  let iterations = 0;
366
615
  let reducedCost;
367
616
  let unrestricted;
617
+ // Anti-cycling for phase 2: if the objective stalls (no meaningful
618
+ // improvement over several hundred iterations), the simplex is
619
+ // cycling through degenerate vertices. Switch to Bland's rule which
620
+ // guarantees termination in exact arithmetic. In floating-point,
621
+ // even Bland's can cycle indefinitely, so we also impose a limit:
622
+ // if Bland's runs for lastRow iterations without improving the
623
+ // objective, we accept the current solution as optimal.
624
+ const PHASE2_WINDOW = 100;
625
+ const PHASE2_STALE_LIMIT = 5; // consecutive stale windows before switching
626
+ let useBland = false;
627
+ let windowStartObj = matrix[rhsColumn];
628
+ let staleWindows = 0;
629
+ let blandStartIter = 0;
630
+ let blandStartObj = 0;
368
631
  // Partial pricing setup
369
632
  // Batch size: use configured value or auto-compute (sqrt of columns, min 50, max 500)
370
633
  const nColumns = lastColumn;
@@ -374,14 +637,68 @@ var solver = (function () {
374
637
  // For small problems, just scan everything (no benefit from partial pricing)
375
638
  const usePartialPricing = nColumns > batchSize * 2;
376
639
  while (true) {
377
- const costRowOffset = this.costRowIndex * width;
378
640
  if (nOptionalObjectives > 0) {
379
641
  optionalCostsColumns = [];
380
642
  }
643
+ // Detect degenerate cycling: check every WINDOW iterations
644
+ // whether the objective has made meaningful progress.
645
+ if (!useBland && iterations > 0 && iterations % PHASE2_WINDOW === 0) {
646
+ const currentObj = matrix[rhsColumn];
647
+ const delta = Math.abs(currentObj - windowStartObj);
648
+ const scale = Math.max(1, Math.abs(windowStartObj));
649
+ if (delta / scale < 1e-10) {
650
+ staleWindows++;
651
+ if (staleWindows >= PHASE2_STALE_LIMIT) {
652
+ useBland = true;
653
+ blandStartIter = iterations;
654
+ blandStartObj = currentObj;
655
+ }
656
+ }
657
+ else {
658
+ staleWindows = 0;
659
+ }
660
+ windowStartObj = currentObj;
661
+ }
662
+ // Bland's termination: in floating-point arithmetic, Bland's rule
663
+ // can cycle through degenerate bases indefinitely. If it hasn't
664
+ // improved the objective after lastRow pivots, accept the current
665
+ // solution (reduced costs are within floating-point noise of zero).
666
+ if (useBland && iterations - blandStartIter > lastRow) {
667
+ const currentObj = matrix[rhsColumn];
668
+ const delta = Math.abs(currentObj - blandStartObj);
669
+ const scale = Math.max(1, Math.abs(blandStartObj));
670
+ if (delta / scale < 1e-10) {
671
+ this.setEvaluation();
672
+ this.simplexIters += 1;
673
+ return iterations;
674
+ }
675
+ // Objective did improve; reset the counter
676
+ blandStartIter = iterations;
677
+ blandStartObj = currentObj;
678
+ }
381
679
  let enteringColumn = 0;
382
680
  let enteringValue = precision;
383
681
  let isReducedCostNegative = false;
384
- if (usePartialPricing) {
682
+ if (useBland) {
683
+ // Bland's rule: pick first eligible column (smallest index)
684
+ for (let c = 1; c <= lastColumn; c++) {
685
+ reducedCost = matrix[c];
686
+ unrestricted = unrestrictedVars[varIndexByCol[c]] === true;
687
+ if (unrestricted && reducedCost < 0) {
688
+ enteringColumn = c;
689
+ enteringValue = -reducedCost;
690
+ isReducedCostNegative = true;
691
+ break;
692
+ }
693
+ if (reducedCost > precision) {
694
+ enteringColumn = c;
695
+ enteringValue = reducedCost;
696
+ isReducedCostNegative = false;
697
+ break;
698
+ }
699
+ }
700
+ }
701
+ else if (usePartialPricing) {
385
702
  // Partial pricing: scan columns in batches
386
703
  const startBatch = this.pricingBatchStart;
387
704
  let batchesScanned = 0;
@@ -391,10 +708,10 @@ var solver = (function () {
391
708
  const batchStart = this.pricingBatchStart;
392
709
  const batchEnd = Math.min(batchStart + batchSize - 1, lastColumn);
393
710
  for (let c = batchStart; c <= batchEnd; c++) {
394
- reducedCost = matrix[costRowOffset + c];
395
- unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
711
+ reducedCost = matrix[c]; // costRowOffset is 0
712
+ unrestricted = unrestrictedVars[varIndexByCol[c]] === true;
396
713
  if (nOptionalObjectives > 0 &&
397
- -precision < reducedCost &&
714
+ negPrecision < reducedCost &&
398
715
  reducedCost < precision) {
399
716
  optionalCostsColumns === null || optionalCostsColumns === void 0 ? void 0 : optionalCostsColumns.push(c);
400
717
  continue;
@@ -425,10 +742,10 @@ var solver = (function () {
425
742
  else {
426
743
  // Full pricing for small problems
427
744
  for (let c = 1; c <= lastColumn; c++) {
428
- reducedCost = matrix[costRowOffset + c];
429
- unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
745
+ reducedCost = matrix[c]; // costRowOffset is 0
746
+ unrestricted = unrestrictedVars[varIndexByCol[c]] === true;
430
747
  if (nOptionalObjectives > 0 &&
431
- -precision < reducedCost &&
748
+ negPrecision < reducedCost &&
432
749
  reducedCost < precision) {
433
750
  optionalCostsColumns === null || optionalCostsColumns === void 0 ? void 0 : optionalCostsColumns.push(c);
434
751
  continue;
@@ -460,8 +777,8 @@ var solver = (function () {
460
777
  for (let i = 0; i < optionalCostsColumns.length; i++) {
461
778
  const c = optionalCostsColumns[i];
462
779
  reducedCost = reducedCosts[c];
463
- unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
464
- if (-precision < reducedCost && reducedCost < precision) {
780
+ unrestricted = unrestrictedVars[varIndexByCol[c]] === true;
781
+ if (negPrecision < reducedCost && reducedCost < precision) {
465
782
  optionalCostsColumns2.push(c);
466
783
  continue;
467
784
  }
@@ -490,15 +807,14 @@ var solver = (function () {
490
807
  }
491
808
  let leavingRow = 0;
492
809
  let minQuotient = Infinity;
493
- this.varIndexByRow;
494
810
  for (let r = 1; r <= lastRow; r++) {
495
811
  const rowOffset = r * width;
496
812
  const rhsValue = matrix[rowOffset + rhsColumn];
497
813
  const colValue = matrix[rowOffset + enteringColumn];
498
- if (-precision < colValue && colValue < precision) {
814
+ if (negPrecision < colValue && colValue < precision) {
499
815
  continue;
500
816
  }
501
- if (colValue > 0 && precision > rhsValue && rhsValue > -precision) {
817
+ if (colValue > 0 && precision > rhsValue && rhsValue > negPrecision) {
502
818
  minQuotient = 0;
503
819
  leavingRow = r;
504
820
  break;
@@ -512,15 +828,11 @@ var solver = (function () {
512
828
  if (minQuotient === Infinity) {
513
829
  this.evaluation = -Infinity;
514
830
  this.bounded = false;
515
- this.unboundedVarIndex = this.varIndexByCol[enteringColumn];
831
+ this.unboundedVarIndex = varIndexByCol[enteringColumn];
516
832
  return iterations;
517
833
  }
518
- if (debugCheckForCycles) {
519
- varIndexesCycle.push([
520
- this.varIndexByRow[leavingRow],
521
- this.varIndexByCol[enteringColumn],
522
- ]);
523
- const cycleData = this.checkForCycles(varIndexesCycle);
834
+ if (cycleDetector) {
835
+ const cycleData = cycleDetector.add(varIndexByRow[leavingRow], varIndexByCol[enteringColumn]);
524
836
  if (cycleData.length > 0) {
525
837
  this.model.messages.push("Cycle in phase 2");
526
838
  this.model.messages.push("Start :" + cycleData[0]);
@@ -533,13 +845,20 @@ var solver = (function () {
533
845
  iterations += 1;
534
846
  }
535
847
  }
536
- // Pre-allocated array for non-zero column tracking
537
- const nonZeroColumns = [];
848
+ // Pre-allocated typed arrays for pivot optimization (better cache performance)
849
+ let nonZeroColumns = new Int32Array(1024);
850
+ let pivotRowCache = new Float64Array(1024);
538
851
  function pivot(pivotRowIndex, pivotColumnIndex) {
539
852
  const matrix = this.matrix;
540
853
  const width = this.width;
854
+ // Ensure work arrays are large enough
855
+ if (width > nonZeroColumns.length) {
856
+ nonZeroColumns = new Int32Array(width * 2);
857
+ pivotRowCache = new Float64Array(width * 2);
858
+ }
541
859
  const pivotRowOffset = pivotRowIndex * width;
542
860
  const quotient = matrix[pivotRowOffset + pivotColumnIndex];
861
+ const invQuotient = 1 / quotient;
543
862
  const height = this.height;
544
863
  const leavingBasicIndex = this.varIndexByRow[pivotRowIndex];
545
864
  const enteringBasicIndex = this.varIndexByCol[pivotColumnIndex];
@@ -549,22 +868,24 @@ var solver = (function () {
549
868
  this.rowByVarIndex[leavingBasicIndex] = -1;
550
869
  this.colByVarIndex[enteringBasicIndex] = -1;
551
870
  this.colByVarIndex[leavingBasicIndex] = pivotColumnIndex;
552
- // Normalize pivot row and track non-zero columns
871
+ // Normalize pivot row, track non-zero columns, and cache values for locality
553
872
  let nNonZeroColumns = 0;
554
873
  for (let c = 0; c < width; c++) {
555
874
  const idx = pivotRowOffset + c;
556
875
  const val = matrix[idx];
557
876
  if (!(val >= -1e-16 && val <= 1e-16)) {
558
- matrix[idx] = val / quotient;
877
+ const normalized = val / quotient;
878
+ matrix[idx] = normalized;
559
879
  nonZeroColumns[nNonZeroColumns] = c;
880
+ pivotRowCache[nNonZeroColumns] = normalized;
560
881
  nNonZeroColumns++;
561
882
  }
562
883
  else {
563
884
  matrix[idx] = 0;
564
885
  }
565
886
  }
566
- matrix[pivotRowOffset + pivotColumnIndex] = 1 / quotient;
567
- // Update all other rows
887
+ matrix[pivotRowOffset + pivotColumnIndex] = invQuotient;
888
+ // Update all other rows using cached pivot row values
568
889
  for (let r = 0; r < height; r++) {
569
890
  if (r !== pivotRowIndex) {
570
891
  const rowOffset = r * width;
@@ -572,13 +893,16 @@ var solver = (function () {
572
893
  if (!(pivotColVal >= -1e-16 && pivotColVal <= 1e-16)) {
573
894
  const coefficient = pivotColVal;
574
895
  if (!(coefficient >= -1e-16 && coefficient <= 1e-16)) {
896
+ // Use cached pivot row values for better cache locality
575
897
  for (let i = 0; i < nNonZeroColumns; i++) {
576
898
  const c = nonZeroColumns[i];
577
- const v0 = matrix[pivotRowOffset + c];
899
+ const v0 = pivotRowCache[i];
900
+ // Inner zero check is critical for numerical stability
578
901
  if (!(v0 >= -1e-16 && v0 <= 1e-16)) {
579
- matrix[rowOffset + c] = matrix[rowOffset + c] - coefficient * v0;
902
+ matrix[rowOffset + c] -= coefficient * v0;
580
903
  }
581
904
  else if (v0 !== 0) {
905
+ // Clean up near-zero values in pivot row
582
906
  matrix[pivotRowOffset + c] = 0;
583
907
  }
584
908
  }
@@ -590,7 +914,7 @@ var solver = (function () {
590
914
  }
591
915
  }
592
916
  }
593
- // Update optional objectives
917
+ // Update optional objectives using cached pivot row values
594
918
  const optionalObjectives = this.optionalObjectives;
595
919
  const nOptionalObjectives = optionalObjectives.length;
596
920
  if (nOptionalObjectives > 0) {
@@ -600,12 +924,9 @@ var solver = (function () {
600
924
  if (coefficient !== 0) {
601
925
  for (let i = 0; i < nNonZeroColumns; i++) {
602
926
  const c = nonZeroColumns[i];
603
- const v0 = matrix[pivotRowOffset + c];
604
- if (v0 !== 0) {
605
- reducedCosts[c] = reducedCosts[c] - coefficient * v0;
606
- }
927
+ reducedCosts[c] -= coefficient * pivotRowCache[i];
607
928
  }
608
- reducedCosts[pivotColumnIndex] = -coefficient / quotient;
929
+ reducedCosts[pivotColumnIndex] = -coefficient * invQuotient;
609
930
  }
610
931
  }
611
932
  }
@@ -637,642 +958,6 @@ var solver = (function () {
637
958
  return [];
638
959
  }
639
960
 
640
- /**
641
- * @file src/tableau/sparse-matrix.ts
642
- * @description Compressed Sparse Column (CSC) matrix implementation
643
- *
644
- * Optimized for column operations which are frequent in the simplex algorithm.
645
- * Provides O(nnz) pivot operations instead of O(n*m) for dense matrices.
646
- *
647
- * CSC Storage Format:
648
- * - values: non-zero values stored column by column
649
- * - rowIndices: row index for each value
650
- * - colPointers: starting index in values/rowIndices for each column
651
- *
652
- * Column c's entries are at indices colPointers[c] to colPointers[c+1]-1
653
- */
654
- class SparseMatrix {
655
- constructor(nRows, nCols, precision = 1e-12) {
656
- this.nRows = nRows;
657
- this.nCols = nCols;
658
- this.precision = precision;
659
- // Initialize empty sparse matrix
660
- this.values = [];
661
- this.rowIndices = [];
662
- this.colPointers = new Array(nCols + 1).fill(0);
663
- // Workspace for row/column operations
664
- this.workVector = new Float64Array(Math.max(nRows, nCols));
665
- this.workIndices = [];
666
- }
667
- /**
668
- * Create sparse matrix from dense Float64Array
669
- */
670
- static fromDense(dense, width, height, precision = 1e-12) {
671
- const sparse = new SparseMatrix(height, width, precision);
672
- const values = [];
673
- const rowIndices = [];
674
- const colPointers = [0];
675
- // Build CSC by iterating column by column
676
- for (let c = 0; c < width; c++) {
677
- for (let r = 0; r < height; r++) {
678
- const val = dense[r * width + c];
679
- if (val < -precision || val > precision) {
680
- values.push(val);
681
- rowIndices.push(r);
682
- }
683
- }
684
- colPointers.push(values.length);
685
- }
686
- sparse.values = values;
687
- sparse.rowIndices = rowIndices;
688
- sparse.colPointers = colPointers;
689
- return sparse;
690
- }
691
- /**
692
- * Convert to dense Float64Array
693
- */
694
- toDense() {
695
- const dense = new Float64Array(this.nRows * this.nCols);
696
- for (let c = 0; c < this.nCols; c++) {
697
- const start = this.colPointers[c];
698
- const end = this.colPointers[c + 1];
699
- for (let i = start; i < end; i++) {
700
- const r = this.rowIndices[i];
701
- dense[r * this.nCols + c] = this.values[i];
702
- }
703
- }
704
- return dense;
705
- }
706
- /**
707
- * Get value at (row, col)
708
- */
709
- get(row, col) {
710
- const start = this.colPointers[col];
711
- const end = this.colPointers[col + 1];
712
- // Binary search for row in this column
713
- let lo = start;
714
- let hi = end;
715
- while (lo < hi) {
716
- const mid = (lo + hi) >>> 1;
717
- if (this.rowIndices[mid] < row) {
718
- lo = mid + 1;
719
- }
720
- else {
721
- hi = mid;
722
- }
723
- }
724
- if (lo < end && this.rowIndices[lo] === row) {
725
- return this.values[lo];
726
- }
727
- return 0;
728
- }
729
- /**
730
- * Set value at (row, col)
731
- * Handles insertion and removal of entries
732
- */
733
- set(row, col, value) {
734
- const start = this.colPointers[col];
735
- const end = this.colPointers[col + 1];
736
- const isZero = value >= -this.precision && value <= this.precision;
737
- // Binary search for insertion point
738
- let lo = start;
739
- let hi = end;
740
- while (lo < hi) {
741
- const mid = (lo + hi) >>> 1;
742
- if (this.rowIndices[mid] < row) {
743
- lo = mid + 1;
744
- }
745
- else {
746
- hi = mid;
747
- }
748
- }
749
- const exists = lo < end && this.rowIndices[lo] === row;
750
- if (exists) {
751
- if (isZero) {
752
- // Remove existing entry
753
- this.values.splice(lo, 1);
754
- this.rowIndices.splice(lo, 1);
755
- // Update column pointers
756
- for (let c = col + 1; c <= this.nCols; c++) {
757
- this.colPointers[c]--;
758
- }
759
- }
760
- else {
761
- // Update existing entry
762
- this.values[lo] = value;
763
- }
764
- }
765
- else if (!isZero) {
766
- // Insert new entry
767
- this.values.splice(lo, 0, value);
768
- this.rowIndices.splice(lo, 0, row);
769
- // Update column pointers
770
- for (let c = col + 1; c <= this.nCols; c++) {
771
- this.colPointers[c]++;
772
- }
773
- }
774
- }
775
- /**
776
- * Get column as sparse vector
777
- */
778
- getColumn(col) {
779
- const start = this.colPointers[col];
780
- const end = this.colPointers[col + 1];
781
- const len = end - start;
782
- return {
783
- indices: this.rowIndices.slice(start, end),
784
- values: this.values.slice(start, end),
785
- length: len,
786
- };
787
- }
788
- /**
789
- * Get row as sparse vector (less efficient - requires full scan)
790
- */
791
- getRow(row) {
792
- const indices = [];
793
- const values = [];
794
- for (let c = 0; c < this.nCols; c++) {
795
- const val = this.get(row, c);
796
- if (val !== 0) {
797
- indices.push(c);
798
- values.push(val);
799
- }
800
- }
801
- return { indices, values, length: indices.length };
802
- }
803
- /**
804
- * Get row into pre-allocated dense array (more efficient for repeated access)
805
- * Returns array of non-zero column indices
806
- */
807
- getRowDense(row, output) {
808
- const nonZeroCols = [];
809
- // Clear relevant portion
810
- output.fill(0, 0, this.nCols);
811
- for (let c = 0; c < this.nCols; c++) {
812
- const start = this.colPointers[c];
813
- const end = this.colPointers[c + 1];
814
- // Binary search for row
815
- let lo = start;
816
- let hi = end;
817
- while (lo < hi) {
818
- const mid = (lo + hi) >>> 1;
819
- if (this.rowIndices[mid] < row) {
820
- lo = mid + 1;
821
- }
822
- else {
823
- hi = mid;
824
- }
825
- }
826
- if (lo < end && this.rowIndices[lo] === row) {
827
- output[c] = this.values[lo];
828
- nonZeroCols.push(c);
829
- }
830
- }
831
- return nonZeroCols;
832
- }
833
- /**
834
- * Add a new row (expands matrix vertically)
835
- */
836
- addRow() {
837
- this.nRows++;
838
- if (this.workVector.length < this.nRows) {
839
- this.workVector = new Float64Array(this.nRows * 2);
840
- }
841
- }
842
- /**
843
- * Add a new column (expands matrix horizontally)
844
- */
845
- addColumn() {
846
- this.colPointers.push(this.colPointers[this.nCols]);
847
- this.nCols++;
848
- if (this.workVector.length < this.nCols) {
849
- this.workVector = new Float64Array(this.nCols * 2);
850
- }
851
- }
852
- /**
853
- * Set entire column from sparse vector
854
- */
855
- setColumn(col, sparseCol) {
856
- const oldStart = this.colPointers[col];
857
- const oldEnd = this.colPointers[col + 1];
858
- const oldLen = oldEnd - oldStart;
859
- const newLen = sparseCol.length;
860
- const diff = newLen - oldLen;
861
- if (diff !== 0) {
862
- // Need to resize
863
- if (diff > 0) {
864
- // Make room
865
- for (let i = 0; i < diff; i++) {
866
- this.values.splice(oldEnd, 0, 0);
867
- this.rowIndices.splice(oldEnd, 0, 0);
868
- }
869
- }
870
- else {
871
- // Remove excess
872
- this.values.splice(oldStart, -diff);
873
- this.rowIndices.splice(oldStart, -diff);
874
- }
875
- // Update column pointers
876
- for (let c = col + 1; c <= this.nCols; c++) {
877
- this.colPointers[c] += diff;
878
- }
879
- }
880
- // Copy new values
881
- const start = this.colPointers[col];
882
- for (let i = 0; i < newLen; i++) {
883
- this.values[start + i] = sparseCol.values[i];
884
- this.rowIndices[start + i] = sparseCol.indices[i];
885
- }
886
- }
887
- /**
888
- * Number of non-zero entries
889
- */
890
- get nnz() {
891
- return this.values.length;
892
- }
893
- /**
894
- * Density (fraction of non-zeros)
895
- */
896
- get density() {
897
- return this.nnz / (this.nRows * this.nCols);
898
- }
899
- /**
900
- * Scale a row by a factor
901
- */
902
- scaleRow(row, factor) {
903
- for (let c = 0; c < this.nCols; c++) {
904
- const start = this.colPointers[c];
905
- const end = this.colPointers[c + 1];
906
- for (let i = start; i < end; i++) {
907
- if (this.rowIndices[i] === row) {
908
- this.values[i] *= factor;
909
- break;
910
- }
911
- }
912
- }
913
- }
914
- /**
915
- * Add scaled row to another row: targetRow += factor * sourceRow
916
- * This is the core operation in Gaussian elimination / pivot
917
- */
918
- addScaledRow(targetRow, sourceRow, factor) {
919
- if (factor >= -this.precision && factor <= this.precision) {
920
- return;
921
- }
922
- // Get source row as dense for efficiency
923
- const sourceNonZeros = this.getRowDense(sourceRow, this.workVector);
924
- // Add scaled source to target
925
- for (const c of sourceNonZeros) {
926
- const sourceVal = this.workVector[c];
927
- const newVal = this.get(targetRow, c) + factor * sourceVal;
928
- this.set(targetRow, c, newVal);
929
- }
930
- }
931
- /**
932
- * Perform pivot operation at (pivotRow, pivotCol)
933
- * This is optimized for sparse operations
934
- */
935
- pivot(pivotRow, pivotCol) {
936
- const pivotVal = this.get(pivotRow, pivotCol);
937
- if (pivotVal === 0) {
938
- throw new Error("Cannot pivot on zero element");
939
- }
940
- const invPivot = 1 / pivotVal;
941
- // Get pivot row as dense
942
- const pivotRowNonZeros = this.getRowDense(pivotRow, this.workVector);
943
- // Scale pivot row
944
- for (const c of pivotRowNonZeros) {
945
- this.workVector[c] *= invPivot;
946
- }
947
- this.workVector[pivotCol] = invPivot;
948
- // Update pivot row in matrix
949
- for (const c of pivotRowNonZeros) {
950
- this.set(pivotRow, c, this.workVector[c]);
951
- }
952
- this.set(pivotRow, pivotCol, invPivot);
953
- // Get pivot column to find rows that need updating
954
- const pivotColData = this.getColumn(pivotCol);
955
- // Update all other rows
956
- for (let i = 0; i < pivotColData.length; i++) {
957
- const r = pivotColData.indices[i];
958
- if (r === pivotRow)
959
- continue;
960
- const coefficient = pivotColData.values[i];
961
- if (coefficient >= -this.precision && coefficient <= this.precision)
962
- continue;
963
- // row[r] -= coefficient * pivotRow
964
- for (const c of pivotRowNonZeros) {
965
- if (c === pivotCol)
966
- continue;
967
- const pivotRowVal = this.workVector[c];
968
- if (pivotRowVal >= -this.precision && pivotRowVal <= this.precision)
969
- continue;
970
- const newVal = this.get(r, c) - coefficient * pivotRowVal;
971
- this.set(r, c, newVal);
972
- }
973
- // Set pivot column value for this row
974
- this.set(r, pivotCol, -coefficient * invPivot);
975
- }
976
- return pivotRowNonZeros;
977
- }
978
- /**
979
- * Clone the matrix
980
- */
981
- clone() {
982
- const copy = new SparseMatrix(this.nRows, this.nCols, this.precision);
983
- copy.values = this.values.slice();
984
- copy.rowIndices = this.rowIndices.slice();
985
- copy.colPointers = this.colPointers.slice();
986
- return copy;
987
- }
988
- }
989
-
990
- /**
991
- * @file src/tableau/sparse-simplex.ts
992
- * @description Sparse simplex algorithm for large LP problems
993
- *
994
- * Optimized simplex implementation that operates directly on SparseMatrix
995
- * storage. Converts the dense tableau to CSC format, solves, and converts
996
- * back for solution extraction.
997
- *
998
- * Provides significant speedup for large, sparse problems where most
999
- * coefficients are zero.
1000
- */
1001
- /**
1002
- * Convert dense tableau to sparse and solve
1003
- */
1004
- function sparseSimplex() {
1005
- // Convert to sparse
1006
- const sparse = SparseMatrix.fromDense(this.matrix, this.width, this.height, this.precision);
1007
- this.bounded = true;
1008
- // Run sparse phase 1
1009
- sparsePhase1.call(this, sparse);
1010
- if (this.feasible === true) {
1011
- // Run sparse phase 2
1012
- sparsePhase2.call(this, sparse);
1013
- }
1014
- // Copy results back to dense matrix (needed for solution extraction)
1015
- const dense = sparse.toDense();
1016
- this.matrix.set(dense);
1017
- return this;
1018
- }
1019
- /**
1020
- * Sparse Phase 1: Find a basic feasible solution
1021
- */
1022
- function sparsePhase1(sparse) {
1023
- const debugCheckForCycles = this.model.checkForCycles;
1024
- const varIndexesCycle = [];
1025
- const rhsColumn = this.rhsColumn;
1026
- const lastColumn = this.width - 1;
1027
- const lastRow = this.height - 1;
1028
- const precision = this.precision;
1029
- let unrestricted;
1030
- let iterations = 0;
1031
- while (true) {
1032
- // Find leaving row (most negative RHS)
1033
- let leavingRowIndex = 0;
1034
- let rhsValue = -precision;
1035
- for (let r = 1; r <= lastRow; r++) {
1036
- const value = sparse.get(r, rhsColumn);
1037
- if (value < rhsValue) {
1038
- rhsValue = value;
1039
- leavingRowIndex = r;
1040
- }
1041
- }
1042
- if (leavingRowIndex === 0) {
1043
- this.feasible = true;
1044
- return iterations;
1045
- }
1046
- // Find entering column
1047
- let enteringColumn = 0;
1048
- let maxQuotient = -Infinity;
1049
- // Get leaving row as sparse
1050
- const leavingRowData = sparse.getRow(leavingRowIndex);
1051
- for (let i = 0; i < leavingRowData.length; i++) {
1052
- const c = leavingRowData.indices[i];
1053
- if (c === 0 || c === rhsColumn)
1054
- continue;
1055
- const coefficient = leavingRowData.values[i];
1056
- unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
1057
- if (unrestricted || coefficient < -precision) {
1058
- const costValue = sparse.get(0, c);
1059
- const quotient = -costValue / coefficient;
1060
- if (maxQuotient < quotient) {
1061
- maxQuotient = quotient;
1062
- enteringColumn = c;
1063
- }
1064
- }
1065
- }
1066
- // Also check columns with zero in leaving row but non-zero cost
1067
- for (let c = 1; c <= lastColumn; c++) {
1068
- if (c === rhsColumn)
1069
- continue;
1070
- const coefficient = sparse.get(leavingRowIndex, c);
1071
- unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
1072
- if (unrestricted || coefficient < -precision) {
1073
- const costValue = sparse.get(0, c);
1074
- const quotient = -costValue / coefficient;
1075
- if (maxQuotient < quotient) {
1076
- maxQuotient = quotient;
1077
- enteringColumn = c;
1078
- }
1079
- }
1080
- }
1081
- if (enteringColumn === 0) {
1082
- this.feasible = false;
1083
- return iterations;
1084
- }
1085
- if (debugCheckForCycles) {
1086
- varIndexesCycle.push([
1087
- this.varIndexByRow[leavingRowIndex],
1088
- this.varIndexByCol[enteringColumn],
1089
- ]);
1090
- const cycleData = this.checkForCycles(varIndexesCycle);
1091
- if (cycleData.length > 0) {
1092
- this.model.messages.push("Cycle in phase 1");
1093
- this.feasible = false;
1094
- return iterations;
1095
- }
1096
- }
1097
- // Perform pivot
1098
- sparsePivot.call(this, sparse, leavingRowIndex, enteringColumn);
1099
- iterations += 1;
1100
- }
1101
- }
1102
- /**
1103
- * Sparse Phase 2: Optimize the objective
1104
- */
1105
- function sparsePhase2(sparse) {
1106
- const debugCheckForCycles = this.model.checkForCycles;
1107
- const varIndexesCycle = [];
1108
- const rhsColumn = this.rhsColumn;
1109
- const lastColumn = this.width - 1;
1110
- this.height - 1;
1111
- const precision = this.precision;
1112
- this.optionalObjectives.length;
1113
- let iterations = 0;
1114
- let reducedCost;
1115
- let unrestricted;
1116
- // Partial pricing for sparse
1117
- const batchSize = Math.min(500, Math.max(50, Math.floor(Math.sqrt(lastColumn))));
1118
- let batchStart = 1;
1119
- while (true) {
1120
- const costRow = 0;
1121
- let enteringColumn = 0;
1122
- let enteringValue = precision;
1123
- let isReducedCostNegative = false;
1124
- // Partial pricing: scan columns in batches
1125
- let batchesScanned = 0;
1126
- const totalBatches = Math.ceil(lastColumn / batchSize);
1127
- while (enteringColumn === 0 && batchesScanned < totalBatches) {
1128
- const batchEnd = Math.min(batchStart + batchSize - 1, lastColumn);
1129
- for (let c = batchStart; c <= batchEnd; c++) {
1130
- if (c === rhsColumn)
1131
- continue;
1132
- reducedCost = sparse.get(costRow, c);
1133
- unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
1134
- if (unrestricted && reducedCost < 0) {
1135
- if (-reducedCost > enteringValue) {
1136
- enteringValue = -reducedCost;
1137
- enteringColumn = c;
1138
- isReducedCostNegative = true;
1139
- }
1140
- continue;
1141
- }
1142
- if (reducedCost > enteringValue) {
1143
- enteringValue = reducedCost;
1144
- enteringColumn = c;
1145
- isReducedCostNegative = false;
1146
- }
1147
- }
1148
- batchStart = batchEnd >= lastColumn ? 1 : batchEnd + 1;
1149
- batchesScanned++;
1150
- }
1151
- if (enteringColumn === 0) {
1152
- this.setEvaluation();
1153
- this.simplexIters += 1;
1154
- return iterations;
1155
- }
1156
- // Find leaving row using ratio test
1157
- let leavingRow = 0;
1158
- let minQuotient = Infinity;
1159
- // Get entering column as sparse
1160
- const enteringColData = sparse.getColumn(enteringColumn);
1161
- for (let i = 0; i < enteringColData.length; i++) {
1162
- const r = enteringColData.indices[i];
1163
- if (r === 0)
1164
- continue; // Skip cost row
1165
- const colValue = enteringColData.values[i];
1166
- if (colValue >= -precision && colValue <= precision)
1167
- continue;
1168
- const rhsValue = sparse.get(r, rhsColumn);
1169
- if (colValue > 0 && precision > rhsValue && rhsValue > -precision) {
1170
- minQuotient = 0;
1171
- leavingRow = r;
1172
- break;
1173
- }
1174
- const quotient = isReducedCostNegative ? -rhsValue / colValue : rhsValue / colValue;
1175
- if (quotient > precision && minQuotient > quotient) {
1176
- minQuotient = quotient;
1177
- leavingRow = r;
1178
- }
1179
- }
1180
- if (minQuotient === Infinity) {
1181
- this.evaluation = -Infinity;
1182
- this.bounded = false;
1183
- this.unboundedVarIndex = this.varIndexByCol[enteringColumn];
1184
- return iterations;
1185
- }
1186
- if (debugCheckForCycles) {
1187
- varIndexesCycle.push([
1188
- this.varIndexByRow[leavingRow],
1189
- this.varIndexByCol[enteringColumn],
1190
- ]);
1191
- const cycleData = this.checkForCycles(varIndexesCycle);
1192
- if (cycleData.length > 0) {
1193
- this.model.messages.push("Cycle in phase 2");
1194
- this.feasible = false;
1195
- return iterations;
1196
- }
1197
- }
1198
- // Perform pivot
1199
- sparsePivot.call(this, sparse, leavingRow, enteringColumn);
1200
- iterations += 1;
1201
- }
1202
- }
1203
- /**
1204
- * Sparse pivot operation
1205
- */
1206
- function sparsePivot(sparse, pivotRowIndex, pivotColumnIndex) {
1207
- // Update basis tracking
1208
- const leavingBasicIndex = this.varIndexByRow[pivotRowIndex];
1209
- const enteringBasicIndex = this.varIndexByCol[pivotColumnIndex];
1210
- this.varIndexByRow[pivotRowIndex] = enteringBasicIndex;
1211
- this.varIndexByCol[pivotColumnIndex] = leavingBasicIndex;
1212
- this.rowByVarIndex[enteringBasicIndex] = pivotRowIndex;
1213
- this.rowByVarIndex[leavingBasicIndex] = -1;
1214
- this.colByVarIndex[enteringBasicIndex] = -1;
1215
- this.colByVarIndex[leavingBasicIndex] = pivotColumnIndex;
1216
- // Perform sparse pivot
1217
- sparse.pivot(pivotRowIndex, pivotColumnIndex);
1218
- // Handle optional objectives (these are stored separately, not in sparse matrix)
1219
- const optionalObjectives = this.optionalObjectives;
1220
- const nOptionalObjectives = optionalObjectives.length;
1221
- if (nOptionalObjectives > 0) {
1222
- const pivotVal = sparse.get(pivotRowIndex, pivotColumnIndex);
1223
- const pivotRowData = sparse.getRow(pivotRowIndex);
1224
- for (let o = 0; o < nOptionalObjectives; o++) {
1225
- const reducedCosts = optionalObjectives[o].reducedCosts;
1226
- const coefficient = reducedCosts[pivotColumnIndex];
1227
- if (coefficient !== 0) {
1228
- for (let i = 0; i < pivotRowData.length; i++) {
1229
- const c = pivotRowData.indices[i];
1230
- const v0 = pivotRowData.values[i];
1231
- if (v0 !== 0) {
1232
- reducedCosts[c] = reducedCosts[c] - coefficient * v0;
1233
- }
1234
- }
1235
- reducedCosts[pivotColumnIndex] = -coefficient * pivotVal;
1236
- }
1237
- }
1238
- }
1239
- }
1240
- /**
1241
- * Threshold for using sparse (total cells)
1242
- * Currently disabled - CSC format overhead exceeds benefits.
1243
- * A dual-indexed (CSC+CSR) approach would be needed for efficient sparse simplex.
1244
- */
1245
- const SPARSE_THRESHOLD = Infinity; // Disabled
1246
- /**
1247
- * Density threshold - only use sparse if below this density
1248
- */
1249
- const DENSITY_THRESHOLD = 0.1; // 10%
1250
- /**
1251
- * Check if sparse mode should be used for this tableau
1252
- */
1253
- function shouldUseSparse(tableau) {
1254
- const totalCells = tableau.width * tableau.height;
1255
- if (totalCells < SPARSE_THRESHOLD) {
1256
- return false;
1257
- }
1258
- // Estimate density from constraint rows (skip row 0 which is cost row and often dense)
1259
- const matrix = tableau.matrix;
1260
- const width = tableau.width;
1261
- const startRow = 1;
1262
- const sampleRows = Math.min(20, tableau.height - 1);
1263
- let nonZeros = 0;
1264
- for (let r = startRow; r < startRow + sampleRows; r++) {
1265
- const rowOffset = r * width;
1266
- for (let c = 0; c < width; c++) {
1267
- if (matrix[rowOffset + c] !== 0) {
1268
- nonZeros++;
1269
- }
1270
- }
1271
- }
1272
- const estimatedDensity = nonZeros / (sampleRows * width);
1273
- return estimatedDensity < DENSITY_THRESHOLD;
1274
- }
1275
-
1276
961
  class Variable {
1277
962
  constructor(id, cost, index, priority) {
1278
963
  this.id = id;
@@ -1357,6 +1042,7 @@ var solver = (function () {
1357
1042
  setVariableCoefficient(newCoefficient, variable) {
1358
1043
  const varIndex = variable.index;
1359
1044
  if (varIndex === -1) {
1045
+ // eslint-disable-next-line no-console
1360
1046
  console.warn("[Constraint.setVariableCoefficient] Trying to change coefficient of inexistant variable.");
1361
1047
  return;
1362
1048
  }
@@ -1439,44 +1125,52 @@ var solver = (function () {
1439
1125
  const heightWithCuts = height + nCutConstraints;
1440
1126
  const width = this.width;
1441
1127
  const lastColumn = width - 1;
1442
- // Grow the matrix to accommodate new rows
1128
+ // Grow the matrix to accommodate new rows (with over-allocation to reduce reallocation frequency)
1443
1129
  const oldMatrix = this.matrix;
1444
1130
  const newSize = heightWithCuts * width;
1445
1131
  if (oldMatrix.length < newSize) {
1446
- const newMatrix = new Float64Array(newSize);
1132
+ // Over-allocate by 50% to reduce future reallocations
1133
+ const allocSize = Math.ceil(newSize * 1.5);
1134
+ const newMatrix = new Float64Array(allocSize);
1447
1135
  newMatrix.set(oldMatrix);
1448
1136
  this.matrix = newMatrix;
1449
1137
  }
1450
1138
  const matrix = this.matrix;
1451
1139
  this.height = heightWithCuts;
1452
1140
  this.nVars = this.width + this.height - 2;
1141
+ // Cache array references for faster access in loop
1142
+ const rhsColumn = this.rhsColumn;
1143
+ const rowByVarIndex = this.rowByVarIndex;
1144
+ const colByVarIndex = this.colByVarIndex;
1145
+ const varIndexByRow = this.varIndexByRow;
1146
+ const variablesPerIndex = this.variablesPerIndex;
1453
1147
  for (let h = 0; h < nCutConstraints; h += 1) {
1454
1148
  const cut = cutConstraints[h];
1455
1149
  const cutRow = height + h;
1456
1150
  const cutRowOffset = cutRow * width;
1457
1151
  const sign = cut.type === "min" ? -1 : 1;
1458
1152
  const varIndex = cut.varIndex;
1459
- let varRowIndex = this.rowByVarIndex[varIndex];
1153
+ let varRowIndex = rowByVarIndex[varIndex];
1460
1154
  if (varRowIndex === -1) {
1461
- matrix[cutRowOffset + this.rhsColumn] = sign * cut.value;
1155
+ matrix[cutRowOffset + rhsColumn] = sign * cut.value;
1462
1156
  for (let c = 1; c <= lastColumn; c += 1) {
1463
1157
  matrix[cutRowOffset + c] = 0;
1464
1158
  }
1465
- matrix[cutRowOffset + this.colByVarIndex[varIndex]] = sign;
1159
+ matrix[cutRowOffset + colByVarIndex[varIndex]] = sign;
1466
1160
  }
1467
1161
  else {
1468
1162
  const varRowOffset = varRowIndex * width;
1469
- const varValue = matrix[varRowOffset + this.rhsColumn];
1470
- matrix[cutRowOffset + this.rhsColumn] = sign * (cut.value - varValue);
1163
+ const varValue = matrix[varRowOffset + rhsColumn];
1164
+ matrix[cutRowOffset + rhsColumn] = sign * (cut.value - varValue);
1471
1165
  for (let c = 1; c <= lastColumn; c += 1) {
1472
1166
  matrix[cutRowOffset + c] = -sign * matrix[varRowOffset + c];
1473
1167
  }
1474
1168
  }
1475
1169
  varRowIndex = this.getNewElementIndex();
1476
- this.varIndexByRow[cutRow] = varRowIndex;
1477
- this.rowByVarIndex[varRowIndex] = cutRow;
1478
- this.colByVarIndex[varRowIndex] = -1;
1479
- this.variablesPerIndex[varRowIndex] = new SlackVariable("s" + varRowIndex, varRowIndex);
1170
+ varIndexByRow[cutRow] = varRowIndex;
1171
+ rowByVarIndex[varRowIndex] = cutRow;
1172
+ colByVarIndex[varRowIndex] = -1;
1173
+ variablesPerIndex[varRowIndex] = new SlackVariable("s" + varRowIndex, varRowIndex);
1480
1174
  this.nVars += 1;
1481
1175
  }
1482
1176
  }
@@ -1498,10 +1192,12 @@ var solver = (function () {
1498
1192
  }
1499
1193
  const height = this.height;
1500
1194
  const newRowOffset = height * width;
1501
- // Grow matrix to add new row
1195
+ // Grow matrix to add new row (with over-allocation to reduce reallocation frequency)
1502
1196
  const newSize = (height + 1) * width;
1503
1197
  if (matrix.length < newSize) {
1504
- const newMatrix = new Float64Array(newSize);
1198
+ // Over-allocate by 50% to reduce future reallocations
1199
+ const allocSize = Math.ceil(newSize * 1.5);
1200
+ const newMatrix = new Float64Array(allocSize);
1505
1201
  newMatrix.set(matrix);
1506
1202
  this.matrix = newMatrix;
1507
1203
  }
@@ -1513,18 +1209,23 @@ var solver = (function () {
1513
1209
  this.rowByVarIndex[slackVarIndex] = height;
1514
1210
  this.colByVarIndex[slackVarIndex] = -1;
1515
1211
  this.variablesPerIndex[slackVarIndex] = new SlackVariable("s" + slackVarIndex, slackVarIndex);
1516
- mat[newRowOffset + this.rhsColumn] = Math.floor(rhsValue);
1517
- for (let colIndex = 1; colIndex < this.varIndexByCol.length; colIndex += 1) {
1518
- const variable = this.variablesPerIndex[this.varIndexByCol[colIndex]];
1212
+ const rhsColumn = this.rhsColumn;
1213
+ mat[newRowOffset + rhsColumn] = Math.floor(rhsValue);
1214
+ // Cache array references for faster access in hot loop
1215
+ const variablesPerIndex = this.variablesPerIndex;
1216
+ const varIndexByCol = this.varIndexByCol;
1217
+ const varIndexByColLen = varIndexByCol.length;
1218
+ const oneMinusFrac = 1 - fractionalPart;
1219
+ for (let colIndex = 1; colIndex < varIndexByColLen; colIndex += 1) {
1220
+ const variable = variablesPerIndex[varIndexByCol[colIndex]];
1519
1221
  const coefficient = mat[cutRowOffset + colIndex];
1520
1222
  if (variable !== undefined && variable.isInteger) {
1521
- const termCoeff = Math.floor(coefficient) +
1522
- Math.max(0, coefficient - Math.floor(coefficient) - fractionalPart) /
1523
- (1 - fractionalPart);
1223
+ const floorCoeff = Math.floor(coefficient);
1224
+ const termCoeff = floorCoeff + Math.max(0, coefficient - floorCoeff - fractionalPart) / oneMinusFrac;
1524
1225
  mat[newRowOffset + colIndex] = termCoeff;
1525
1226
  }
1526
1227
  else {
1527
- mat[newRowOffset + colIndex] = Math.min(0, coefficient / (1 - fractionalPart));
1228
+ mat[newRowOffset + colIndex] = Math.min(0, coefficient / oneMinusFrac);
1528
1229
  }
1529
1230
  }
1530
1231
  for (let c = 0; c < width; c += 1) {
@@ -1550,10 +1251,12 @@ var solver = (function () {
1550
1251
  }
1551
1252
  const height = this.height;
1552
1253
  const newRowOffset = height * width;
1553
- // Grow matrix to add new row
1254
+ // Grow matrix to add new row (with over-allocation to reduce reallocation frequency)
1554
1255
  const newSize = (height + 1) * width;
1555
1256
  if (matrix.length < newSize) {
1556
- const newMatrix = new Float64Array(newSize);
1257
+ // Over-allocate by 50% to reduce future reallocations
1258
+ const allocSize = Math.ceil(newSize * 1.5);
1259
+ const newMatrix = new Float64Array(allocSize);
1557
1260
  newMatrix.set(matrix);
1558
1261
  this.matrix = newMatrix;
1559
1262
  }
@@ -1565,9 +1268,15 @@ var solver = (function () {
1565
1268
  this.rowByVarIndex[slackVarIndex] = height;
1566
1269
  this.colByVarIndex[slackVarIndex] = -1;
1567
1270
  this.variablesPerIndex[slackVarIndex] = new SlackVariable("s" + slackVarIndex, slackVarIndex);
1568
- mat[newRowOffset + this.rhsColumn] = -fractionalPart;
1569
- for (let colIndex = 1; colIndex < this.varIndexByCol.length; colIndex += 1) {
1570
- const variable = this.variablesPerIndex[this.varIndexByCol[colIndex]];
1271
+ const rhsColumn = this.rhsColumn;
1272
+ mat[newRowOffset + rhsColumn] = -fractionalPart;
1273
+ // Cache array references for faster access in hot loop
1274
+ const variablesPerIndex = this.variablesPerIndex;
1275
+ const varIndexByCol = this.varIndexByCol;
1276
+ const varIndexByColLen = varIndexByCol.length;
1277
+ const oneMinusFrac = 1 - fractionalPart;
1278
+ for (let colIndex = 1; colIndex < varIndexByColLen; colIndex += 1) {
1279
+ const variable = variablesPerIndex[varIndexByCol[colIndex]];
1571
1280
  const coefficient = mat[cutRowOffset + colIndex];
1572
1281
  const termCoeff = coefficient - Math.floor(coefficient);
1573
1282
  if (variable !== undefined && variable.isInteger) {
@@ -1578,9 +1287,7 @@ var solver = (function () {
1578
1287
  }
1579
1288
  else {
1580
1289
  mat[newRowOffset + colIndex] =
1581
- coefficient >= 0
1582
- ? -coefficient
1583
- : (coefficient * fractionalPart) / (1 - fractionalPart);
1290
+ coefficient >= 0 ? -coefficient : (coefficient * fractionalPart) / oneMinusFrac;
1584
1291
  }
1585
1292
  }
1586
1293
  return true;
@@ -1955,12 +1662,15 @@ var solver = (function () {
1955
1662
  const rhsColumn = this.rhsColumn;
1956
1663
  const integerVariables = this.model.integerVariables;
1957
1664
  const nIntegerVars = integerVariables.length;
1665
+ // Cache array reference for faster access in hot loop
1666
+ const rowByVarIndex = this.rowByVarIndex;
1667
+ const precision = this.precision;
1958
1668
  for (let v = 0; v < nIntegerVars; v++) {
1959
1669
  const varIndex = integerVariables[v].index;
1960
- const row = this.rowByVarIndex[varIndex];
1670
+ const row = rowByVarIndex[varIndex];
1961
1671
  if (row !== -1) {
1962
1672
  const value = matrix[row * width + rhsColumn];
1963
- if (Math.abs(value - Math.round(value)) > this.precision) {
1673
+ if (Math.abs(value - Math.round(value)) > precision) {
1964
1674
  return false;
1965
1675
  }
1966
1676
  }
@@ -1976,12 +1686,17 @@ var solver = (function () {
1976
1686
  const width = this.width;
1977
1687
  const matrix = this.matrix;
1978
1688
  const rhsColumn = this.rhsColumn;
1979
- for (let r = 1; r < this.height; r += 1) {
1980
- const variable = this.variablesPerIndex[this.varIndexByRow[r]];
1689
+ const height = this.height;
1690
+ // Cache array references for faster access in hot loop
1691
+ const variablesPerIndex = this.variablesPerIndex;
1692
+ const varIndexByRow = this.varIndexByRow;
1693
+ const precision = this.precision;
1694
+ for (let r = 1; r < height; r += 1) {
1695
+ const variable = variablesPerIndex[varIndexByRow[r]];
1981
1696
  if (variable !== undefined && variable.isInteger) {
1982
1697
  const value = matrix[r * width + rhsColumn];
1983
1698
  const distance = Math.abs(value);
1984
- if (Math.min(distance - Math.floor(distance), Math.floor(distance + 1)) < this.precision) {
1699
+ if (Math.min(distance - Math.floor(distance), Math.floor(distance + 1)) < precision) {
1985
1700
  if (ignoreIntegerValues !== true) {
1986
1701
  return 0;
1987
1702
  }
@@ -2010,9 +1725,11 @@ var solver = (function () {
2010
1725
  const rhsColumn = this.rhsColumn;
2011
1726
  const integerVars = this.model.integerVariables;
2012
1727
  const nIntegerVars = integerVars.length;
1728
+ // Cache array reference for faster access in hot loop
1729
+ const rowByVarIndex = this.rowByVarIndex;
2013
1730
  for (let v = 0; v < nIntegerVars; v += 1) {
2014
1731
  const varIndex = integerVars[v].index;
2015
- const row = this.rowByVarIndex[varIndex];
1732
+ const row = rowByVarIndex[varIndex];
2016
1733
  if (row !== -1) {
2017
1734
  const varValue = matrix[row * width + rhsColumn];
2018
1735
  const fraction = Math.abs(varValue - Math.round(varValue));
@@ -2229,13 +1946,7 @@ var solver = (function () {
2229
1946
  }
2230
1947
  // ========== Core Simplex Operations ==========
2231
1948
  simplex() {
2232
- // Use sparse simplex for large, sparse problems
2233
- if (shouldUseSparse(this)) {
2234
- sparseSimplex.call(this);
2235
- }
2236
- else {
2237
- simplex.call(this);
2238
- }
1949
+ simplex.call(this);
2239
1950
  return this;
2240
1951
  }
2241
1952
  phase1() {
@@ -2244,6 +1955,14 @@ var solver = (function () {
2244
1955
  phase2() {
2245
1956
  return phase2.call(this);
2246
1957
  }
1958
+ /**
1959
+ * Dual simplex for warm-starting after adding bound constraints.
1960
+ * Use when solution is dual feasible but may be primal infeasible.
1961
+ * @returns Number of iterations, or -1 if dual infeasible
1962
+ */
1963
+ dualSimplex() {
1964
+ return dualSimplex.call(this);
1965
+ }
2247
1966
  pivot(pivotRowIndex, pivotColumnIndex) {
2248
1967
  pivot.call(this, pivotRowIndex, pivotColumnIndex);
2249
1968
  }
@@ -2905,6 +2624,7 @@ var solver = (function () {
2905
2624
  _removeConstraint(constraint) {
2906
2625
  const idx = this.constraints.indexOf(constraint);
2907
2626
  if (idx === -1) {
2627
+ // eslint-disable-next-line no-console
2908
2628
  console.warn("[Model.removeConstraint] Constraint not present in model");
2909
2629
  return;
2910
2630
  }
@@ -2934,6 +2654,7 @@ var solver = (function () {
2934
2654
  removeVariable(variable) {
2935
2655
  const idx = this.variables.indexOf(variable);
2936
2656
  if (idx === -1) {
2657
+ // eslint-disable-next-line no-console
2937
2658
  console.warn("[Model.removeVariable] Variable not present in model");
2938
2659
  return;
2939
2660
  }
@@ -3053,11 +2774,20 @@ var solver = (function () {
3053
2774
  const unrestrictedVarIds = jsonModel.unrestricted || {};
3054
2775
  // Instantiating variables and constraint terms
3055
2776
  const objectiveName = jsonModel.optimize;
2777
+ // Check if objectiveName exists as a coefficient key in any variable.
2778
+ // If not, and it matches a variable name, the user wants to optimize
2779
+ // that variable directly (implicit cost of 1).
2780
+ const objectiveIsAttribute = variableIds.some((id) => objectiveName in variables[id]);
2781
+ const objectiveIsVariable = !objectiveIsAttribute && variableIds.includes(objectiveName);
3056
2782
  for (let v = 0; v < nVariables; v += 1) {
3057
2783
  // Creation of the variables
3058
2784
  const variableId = variableIds[v];
3059
2785
  const variableConstraints = variables[variableId];
3060
- const cost = variableConstraints[objectiveName] || 0;
2786
+ const cost = objectiveIsVariable
2787
+ ? variableId === objectiveName
2788
+ ? 1
2789
+ : 0
2790
+ : variableConstraints[objectiveName] || 0;
3061
2791
  const isBinary = !!binaryVarIds[variableId];
3062
2792
  const isInteger = !!integerVarIds[variableId] || isBinary;
3063
2793
  const isUnrestricted = !!unrestrictedVarIds[variableId];
@@ -3412,7 +3142,7 @@ var solver = (function () {
3412
3142
  }
3413
3143
  }
3414
3144
  // Strip metadata so each Pareto vertex only contains value-bearing fields.
3415
- const { feasible, result, bounded, ...paretoPayload } = solution;
3145
+ const { feasible: _feasible, result: _result, bounded: _bounded, ...paretoPayload } = solution;
3416
3146
  paretoVertices.push(paretoPayload);
3417
3147
  }
3418
3148
  // Derive equality constraints that represent the averaged objective values.
@@ -3738,8 +3468,16 @@ var solver = (function () {
3738
3468
  function createCut$1(type, varIndex, value) {
3739
3469
  return { type, varIndex, value };
3740
3470
  }
3741
- function createBranch$1(relaxedEvaluation, cuts, depth) {
3742
- return { relaxedEvaluation, cuts, depth };
3471
+ function createBranch$1(relaxedEvaluation, cuts, depth, branchVarIndex, branchDirection, branchFractionality, parentEvaluation) {
3472
+ return {
3473
+ relaxedEvaluation,
3474
+ cuts,
3475
+ depth,
3476
+ branchVarIndex,
3477
+ branchDirection,
3478
+ branchFractionality,
3479
+ parentEvaluation,
3480
+ };
3743
3481
  }
3744
3482
  /**
3745
3483
  * Enhanced branch-and-cut with:
@@ -3748,7 +3486,8 @@ var solver = (function () {
3748
3486
  * - Diving heuristic for quick feasible solutions
3749
3487
  */
3750
3488
  function createEnhancedBranchAndCutService(options = {}) {
3751
- const { nodeSelection = "hybrid", branching = "pseudocost", useDiving = true, strongBranchingCandidates = 5, } = options;
3489
+ const { nodeSelection = "hybrid", branching = "pseudocost", useDiving: _useDiving = true, // Reserved for future diving heuristic
3490
+ strongBranchingCandidates = 5, } = options;
3752
3491
  // Pseudocost data per variable index
3753
3492
  const pseudoCosts = new Map();
3754
3493
  const getPseudoCost = (varIndex) => {
@@ -3781,7 +3520,7 @@ var solver = (function () {
3781
3520
  // Product score (like SCIP's default)
3782
3521
  return Math.max(upEstimate, 1e-6) * Math.max(downEstimate, 1e-6);
3783
3522
  };
3784
- const selectBranchingVariable = (tableau, currentEval) => {
3523
+ const selectBranchingVariable = (tableau, _currentEval) => {
3785
3524
  const width = tableau.width;
3786
3525
  const matrix = tableau.matrix;
3787
3526
  const rhsColumn = tableau.rhsColumn;
@@ -3925,11 +3664,11 @@ var solver = (function () {
3925
3664
  else {
3926
3665
  break;
3927
3666
  }
3928
- if (activeBranch.relaxedEvaluation > bestEvaluation) {
3667
+ if (activeBranch.relaxedEvaluation >= bestEvaluation) {
3929
3668
  continue;
3930
3669
  }
3931
3670
  const cuts = activeBranch.cuts;
3932
- const parentEval = tableau.evaluation;
3671
+ tableau.evaluation;
3933
3672
  applyCuts(tableau, cuts);
3934
3673
  iterations++;
3935
3674
  if (!tableau.feasible) {
@@ -3940,12 +3679,12 @@ var solver = (function () {
3940
3679
  continue;
3941
3680
  }
3942
3681
  // Update pseudocosts based on observed improvement
3943
- if (cuts.length > 0 && parentEval !== 0) {
3944
- const lastCut = cuts[cuts.length - 1];
3945
- const improvement = Math.abs(evaluation - parentEval);
3946
- // Estimate fraction (simplified)
3947
- const fraction = 0.5;
3948
- updatePseudoCost(lastCut.varIndex, lastCut.type === "min" ? "up" : "down", improvement, fraction);
3682
+ if (activeBranch.branchVarIndex !== undefined &&
3683
+ activeBranch.branchDirection !== undefined &&
3684
+ activeBranch.branchFractionality !== undefined &&
3685
+ activeBranch.parentEvaluation !== undefined) {
3686
+ const improvement = Math.abs(evaluation - activeBranch.parentEvaluation);
3687
+ updatePseudoCost(activeBranch.branchVarIndex, activeBranch.branchDirection, improvement, activeBranch.branchFractionality);
3949
3688
  }
3950
3689
  if (evaluation === bestEvaluation) {
3951
3690
  let isCurrentEvaluationWorse = true;
@@ -4024,22 +3763,24 @@ var solver = (function () {
4024
3763
  cutsLow.push(cut);
4025
3764
  }
4026
3765
  }
4027
- const min = Math.ceil(varValue);
4028
- const max = Math.floor(varValue);
4029
- const cutHigh = createCut$1("min", varIndex, min);
3766
+ const ceilVal = Math.ceil(varValue);
3767
+ const floorVal = Math.floor(varValue);
3768
+ const fracUp = ceilVal - varValue; // Distance to ceil
3769
+ const fracDown = varValue - floorVal; // Distance to floor
3770
+ const cutHigh = createCut$1("min", varIndex, ceilVal);
4030
3771
  cutsHigh.push(cutHigh);
4031
- const cutLow = createCut$1("max", varIndex, max);
3772
+ const cutLow = createCut$1("max", varIndex, floorVal);
4032
3773
  cutsLow.push(cutLow);
4033
3774
  const newDepth = activeBranch.depth + 1;
4034
3775
  if (useDepthFirst) {
4035
3776
  // Push in reverse order so 'up' branch is explored first
4036
3777
  // (often better for minimization with binary vars)
4037
- depthFirstStack.push(createBranch$1(evaluation, cutsLow, newDepth));
4038
- depthFirstStack.push(createBranch$1(evaluation, cutsHigh, newDepth));
3778
+ depthFirstStack.push(createBranch$1(evaluation, cutsLow, newDepth, varIndex, "down", fracDown, evaluation));
3779
+ depthFirstStack.push(createBranch$1(evaluation, cutsHigh, newDepth, varIndex, "up", fracUp, evaluation));
4039
3780
  }
4040
3781
  else {
4041
- branches.push(createBranch$1(evaluation, cutsHigh, newDepth));
4042
- branches.push(createBranch$1(evaluation, cutsLow, newDepth));
3782
+ branches.push(createBranch$1(evaluation, cutsHigh, newDepth, varIndex, "up", fracUp, evaluation));
3783
+ branches.push(createBranch$1(evaluation, cutsLow, newDepth, varIndex, "down", fracDown, evaluation));
4043
3784
  }
4044
3785
  }
4045
3786
  }
@@ -4277,7 +4018,7 @@ var solver = (function () {
4277
4018
  else {
4278
4019
  break;
4279
4020
  }
4280
- if (activeBranch.relaxedEvaluation > bestEvaluation) {
4021
+ if (activeBranch.relaxedEvaluation >= bestEvaluation) {
4281
4022
  continue;
4282
4023
  }
4283
4024
  const parentEval = tableau.evaluation;