Loading solver…

MathOpt — two choices

Problem: choose the most valuable combination of two items within a shared capacity.

Model

  • Choose the most valuable combination of two items within one shared capacity.
  • LP solvers allow fractions; CP-SAT and SCIP choose whole items.
  • The result shows the objective value and how much of each item was chosen.
Advanced settings

Model and callbacks

Serialization and logging

Solution

Run the solver to view the solution.
Solve log
Show code
Show serialized-model solve
// You can also supply a typed ModelProto object from another tool.
const { bytes, response } = await MathOpt.solveProto(model.encodeModelProto(), {
  executor: 'worker',
  solverType: MathOpt.SolverType.GLOP,
});
console.log(response.termination, response.solutions);
// bytes contains the native SolveResultProto for saving or importing.
Show native incremental update
const solver = new MathOpt.ProtoIncrementalSolver(
  model.encodeModelProto(), MathOpt.SolverType.GLOP, { executor: 'worker' });
try {
  console.log((await solver.solve()).response.termination);
  const applied = await solver.update({
    variableUpdates: { upperBounds: { ids: [x.id], values: [0] } },
  });
  if (applied) console.log((await solver.solve()).response.solutions);
  // A false update leaves the native solver unusable; close and recreate it.
} finally {
  await solver.close();
}
Show SCIP lazy constraint callback
const model = MathOpt.Model('lazy capacity');
const x = model.addBinaryVariable({ name: 'x' });
const y = model.addBinaryVariable({ name: 'y' });
model.maximize([{ variable: x, coefficient: 2 }, { variable: y, coefficient: 1 }]);

const result = await MathOpt.solve(model, {
  executor: 'worker',
  solverType: MathOpt.SolverType.GSCIP,
  callbackRegistration: {
    requestRegistration: [MathOptCallbackEventProto.CALLBACK_EVENT_MIP_SOLUTION],
    addLazyConstraints: true,
  },
  callback: data => {
    const sum = (data.primalSolutionVector?.values ?? []).reduce((a, b) => a + b, 0);
    if (sum > 1 + 1e-6) return { cuts: [{
      linearExpression: { ids: [x.id, y.id], values: [1, 1] },
      lowerBound: -Infinity, upperBound: 1, isLazy: true,
    }] };
  },
});
console.log(result.objectiveValue, result.variableValuesById);