Skip to content

Commit

Permalink
Parses LP problems
Browse files Browse the repository at this point in the history
  • Loading branch information
octachrome committed Jun 22, 2014
1 parent 3c95b84 commit 3bdba0f
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
25 changes: 25 additions & 0 deletions js/lpParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,24 @@ function nameConstraint(name, colon, c) {
};
}

function mkObjective(dir, expr) {
return {
dir: dir,
expr: toArray(expr)
};
}

function mkConstraints(st, constraints) {
return toArray(constraints);
}

function mkLp(objective, constraints) {
return {
objective: objective,
constraints: constraints
};
}

function createLpParser() {
exports.pNum = pApply(pSat(isNum), parseFloat);
exports.pSym = pApply(pSat(isAlpha), mkTerm);
Expand All @@ -57,4 +75,11 @@ function createLpParser() {
exports.pAnonConstraint = pThen3(mkConstraint, pExpr, pIneq, pAlt(pNum, pSignedNum));
exports.pNamedConstraint = pThen3(nameConstraint, pSat(isAlpha), pLit(Tokens.COLON), pAnonConstraint);
exports.pConstraint = pAlt(pAnonConstraint, pNamedConstraint);

exports.pDirection = pAlt(pLit(Tokens.MIN), pLit(Tokens.MAX));
exports.pObjective = pThen(mkObjective, pDirection, pExpr);

exports.pConstraints = pThen(mkConstraints, pLit(Tokens.SUBJECT_TO), pOneOrMore(pConstraint));

exports.pLp = pThen3(mkLp, pObjective, pConstraints, pLit(Tokens.END));
}
60 changes: 60 additions & 0 deletions test/lpParserSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,5 +122,65 @@ describe('lp parser', function () {
rhs: -4
});
});

it('should parse an objective function', function () {
var toks = clex(fromArray(
"minimise\n\
12 var1 - var2"
));
var result = pObjective(toks);
expect(takeFirstParse(result)).toEqual({
dir: 'minimise',
expr: [{sym: 'var1', coef: 12}, {sym: 'var2', coef: -1}]
});
});

it('should parse a set of constraints', function () {
var toks = clex(fromArray(
"subject to\n\
12 var1 - var2 <= -30\n\
c: var1 + var2 >= 3\n"
));
var result = pConstraints(toks);
expect(takeFirstParse(result)).toEqual([{
expr: [{sym: 'var1', coef: 12}, {sym: 'var2', coef: -1}],
op: '<=',
rhs: -30
}, {
name: 'c',
expr: [{sym: 'var1', coef: 1}, {sym: 'var2', coef: 1}],
op: '>=',
rhs: 3
}]);
});

it('should parse an lp problem', function () {
var toks = clex(fromArray(
"maximise\n\
x + y\n\
subject to\n\
a: 3x - y >= 10\n\
b: 2z + 50y <= 100\n\
end\n"
));
var result = pLp(toks);
expect(takeFirstParse(result)).toEqual({
objective: {
dir: 'maximise',
expr: [{sym: 'x', coef: 1}, {sym: 'y', coef: 1}]
},
constraints: [{
name: 'a',
expr: [{sym: 'x', coef: 3}, {sym: 'y', coef: -1}],
op: '>=',
rhs: 10
}, {
name: 'b',
expr: [{sym: 'z', coef: 2}, {sym: 'y', coef: 50}],
op: '<=',
rhs: 100
}]
});
});
});
});

0 comments on commit 3bdba0f

Please sign in to comment.