Skip to content

Commit

Permalink
Negate constraints with -ve rhs and objectives to be minimised
Browse files Browse the repository at this point in the history
  • Loading branch information
octachrome committed Jun 23, 2014
1 parent 6641ca0 commit 59c02fc
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 1 deletion.
2 changes: 1 addition & 1 deletion js/lpParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ function createLpParser() {

exports.pSignedNum = pThen(mul, pSign, pNum);

exports.pIneq = pAlt(pLit(Tokens.LE), pLit(Tokens.GE));
exports.pIneq = pAlt(pLit(Tokens.LE), pLit(Tokens.GE), pLit(Tokens.EQ));
exports.pAnonConstraint = pThen3(mkConstraint, pExpr, pIneq, pAlt(pNum, pSignedNum));
exports.pNamedConstraint = pThen3(nameConstraint, pSat(isAlpha), pLit(Tokens.COLON), pAnonConstraint);
exports.pConstraint = pAlt(pAnonConstraint, pNamedConstraint);
Expand Down
25 changes: 25 additions & 0 deletions js/preproc.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,35 @@
function negateExpr(expr) {
for (var i = 0; i < expr.length; i++) {
var term = expr[i];
term.coef = -term.coef;
}
}

function canonical(prob) {
var nextSlack = 0;

var objective = prob.objective;
if (objective) {
if (objective.dir === 'minimise') {
objective.dir = 'maximise';
negateExpr(objective.expr);
}
}

var constraints = prob.constraints;
if (constraints) {
for (var i = 0; i < constraints.length; i++) {
var constraint = constraints[i];
if (constraint.rhs < 0) {
constraint.rhs = -constraint.rhs;
negateExpr(constraint.expr);
if (constraint.op === '<=') {
constraint.op = '>=';
} else if (constraint.op === '>=') {
constraint.op = '<=';
}
}

if (constraint.op === '<=') {
var coef = 1;
} else if (constraint.op === '>=') {
Expand Down
43 changes: 43 additions & 0 deletions test/preprocSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,5 +109,48 @@ describe('preproc', function () {
]
});
});

it('should convert a constraint with a negative rhs into one with a positive rhs', function () {
var prob = {
constraints: [
{
expr: [{sym: 'x', coef: 1}, {sym: 'y', coef: 1}],
op: '<=',
rhs: -14
}
]
};

var can = canonical(prob);

expect(can).toEqual({
constraints: [
{
expr: [{sym: 'x', coef: -1}, {sym: 'y', coef: -1}, {sym: '_s0', coef: -1}],
op: '=',
rhs: 14,
slackVar: '_s0'
}
]
});
});

it('should convert a minimisation problem to a minimisation problem', function () {
var prob = {
objective: {
dir: 'minimise',
expr: [{sym: 'x', coef: 1}, {sym: 'y', coef: -1}]
}
};

var can = canonical(prob);

expect(can).toEqual({
objective: {
dir: 'maximise',
expr: [{sym: 'x', coef: -1}, {sym: 'y', coef: 1}]
}
});
});
});
});

0 comments on commit 59c02fc

Please sign in to comment.