Skip to content

Commit

Permalink
Pivoting
Browse files Browse the repository at this point in the history
  • Loading branch information
octachrome committed Jun 26, 2014
1 parent ad6bcf0 commit dc02aba
Show file tree
Hide file tree
Showing 2 changed files with 123 additions and 3 deletions.
44 changes: 43 additions & 1 deletion js/simplex.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function initialSol(prob, mat) {
function solution(prob, mat) {
var sol = {};
var constraints = prob.constraints;
if (constraints) {
Expand All @@ -12,3 +12,45 @@ function initialSol(prob, mat) {
}
return sol;
}

function pivotVar(mat) {
var p = {
sym: mat.vars[0],
index: 0
};
var obj = mat.rows[mat.rows.length - 1] ;
var min = obj[0];
for (var i = 1; i < mat.vars.length; i++) {
if (obj[i] < min) {
p = {
sym: mat.vars[i],
index: i
}
min = obj[i];
}
}
if (min < 0) {
return p;
} else {
return null;
}
}

function pivotRow(mat, pivotVar) {
var index = null;
var min = null;

for (var i = 0; i < mat.rows.length - 1; i++) {
var v = mat.rows[i][pivotVar.index];
if (v <= 0) {
continue;
}
var r = mat.rhs[i] / v;
if (min === null || r < min) {
min = r;
index = i;
}
}

return index;
}
82 changes: 80 additions & 2 deletions test/simplexSpec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
describe('simplex', function () {
describe('initialSol', function () {
describe('solution', function () {
it('should set up the initial solution', function () {
var prob = {
constraints: [
Expand All @@ -23,12 +23,90 @@ describe('simplex', function () {
};

var mat = toMatrix(prob);
var sol = initialSol(prob, mat);
var sol = solution(prob, mat);

expect(sol).toEqual({
'_s0': -14,
'_s1': 5
});
});
});

describe('pivotVar', function () {
it('should select the correct pivot variable', function () {
var mat = {
vars: ['a', 'b', 'c', 'd', 'e'],
varIndices: {},
rows: [
[],
[1, -4, 2, -1, 5]
],
rhs: []
};

var pv = pivotVar(mat);
expect(pv).toEqual({
sym: 'b',
index: 1
});
});

it('should return null if there is no appropriate pivot variable', function () {
var mat = {
vars: ['a', 'b', 'c', 'd', 'e'],
varIndices: {},
rows: [
[],
[1, 0, 2, 1, 0]
],
rhs: []
};

var pv = pivotVar(mat);
expect(pv).toBe(null);
});
});

describe('pivotRow', function () {
it('should select the correct pivot row', function () {
var mat = {
vars: ['a'],
varIndices: {},
rows: [
[1],
[0],
[2],
[3],
[-1]
],
rhs: [4, 1, 6, 10, 1]
};

var pv = {
sym: 'a',
index: 0
};
var pr = pivotRow(mat, pv);
expect(pr).toBe(2);
});

it('should return null if no pivot row candidates', function () {
var mat = {
vars: ['a'],
varIndices: {},
rows: [
[0],
[-1]
],
rhs: [1, 1]
};

var pv = {
sym: 'a',
index: 0
};
var pr = pivotRow(mat, pv);
expect(pr).toBe(null);
});
});
});

0 comments on commit dc02aba

Please sign in to comment.