Skip to content

Instantly share code, notes, and snippets.

@sakekasi
Last active May 7, 2017 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakekasi/91a26b0513d521924c35a3b9b08b46a0 to your computer and use it in GitHub Desktop.
Save sakekasi/91a26b0513d521924c35a3b9b08b46a0 to your computer and use it in GitHub Desktop.
An implementation of directed resolution for CNF knowledge bases
class Literal {
constructor(variable, same) {
this.variable = variable;
this.same = same;
}
equal(other) {
return other instanceof Literal &&
other.variable === this.variable &&
other.same === this.same;
}
toString() {
return `${this.same ? '' : '~'}${this.variable}`;
}
}
class Clause {
constructor(...literals) {
this.literals = Object.create(null);
this.enabled = Object.create(null);
this.clauseEnabled = true;
literals.forEach(literal => {
if (!(literal.variable in this.literals)) {
this.literals[literal.variable] = literal;
this.enabled[literal.variable] = true;
} else {
console.assert(literal.equal(this.literals[literal.variable]));
}
})
}
get length() {
return Object.values(this.enabled)
.map(value => value === true ? 1 : 0)
.reduce((agg, b) => agg + b, 0);
}
toString(showState = false) {
return `{${showState ? (this.clauseEnabled ? '' : 'X') : ''} ${Object.values(this.literals)
.map(literal => (showState ?
(this.enabled[literal.variable] ? '': 'x') : '') +
literal.toString())
.join(", ")}}`
}
resolve(variable, other) {
console.assert(
!this.literals[variable].equal(other.literals[variable]));
const combinedLiterals = Object.create(null);
objectForEach(this.literals, (literal, variable) => {
if (!(variable in combinedLiterals)) {
combinedLiterals[variable] = [];
}
combinedLiterals[variable].push(literal);
});
objectForEach(other.literals, (literal, variable) => {
if (!(variable in combinedLiterals)) {
combinedLiterals[variable] = [];
}
combinedLiterals[variable].push(literal);
});
delete combinedLiterals[variable];
for (let variable in combinedLiterals) {
const literals = combinedLiterals[variable];
if (literals.length === 2) {
if (! literals[0].equal(literals[1])) {
return null;
} else {
combinedLiterals[variable] = [literals[0]];
}
}
}
objectForEach(combinedLiterals, ([literal], variable) => {
combinedLiterals[variable] = literal;
});
return new Clause(...Object.values(combinedLiterals));
}
}
class CNF { // TODO: length should be dynamic
constructor(length, ...clauses) { // any checks for CNF?
this.length = length; // number of variables
this.clauses = clauses;
}
toString() {
return `{${Object.values(this.clauses)
.map(clause => clause.toString())
.join(", ")}}`;
}
directedResolution(variableOrdering) {
const buckets = new Buckets(variableOrdering);
this.clauses.forEach(clause => buckets.add(clause));
return buckets;
} // TODO
}
const SAT = 0;
const UNSAT = 1;
const NEITHER = 2;
class Buckets {
constructor(variableOrdering) {
this.variableOrdering = variableOrdering;
this.buckets = range(variableOrdering.length)
.map(_ => []);
// TODO: should we have a directed extension?
this.sat = null;
}
add(clause) {
for (let [idx, variable] of this.variableOrdering.entries()) {
if (clause.enabled[variable]) {
this.buckets[idx].push(clause);
return;
}
}
}
resolve() {
for (let [idx, bucket] of this.buckets.entries()) {
const variable = this.variableOrdering[idx];
for (let [i, clauseA] of bucket.entries()) {
for (let [j, clauseB] of bucket.entries()) {
if (j <= i) { continue; }
const literalA = clauseA.literals[variable];
const literalB = clauseB.literals[variable];
if (!(literalA.equal(literalB))) {
const resolvant = clauseA.resolve(variable, clauseB);
this.add(resolvant);
if (resolvant.length === 0) {
this.sat = false;
return this.sat;
}
}
}
}
}
this.sat = true;
return this.sat;
}
decisionTree() {
console.assert(this.sat === true);
return this._buildDecisionTree(
Object.create(null),
this.variableOrdering[this.variableOrdering.length - 1]);
}
_buildDecisionTree(assignment, variable, parent = null) {
const node = new DecisionNode(variable, parent);
const nextVariableIdx = this.variableOrdering.indexOf(variable) - 1;
const nextVariable = this.variableOrdering[nextVariableIdx];
// try assigning node true
assignment[variable] = true;
let result = this._assign(variable, true);
if (result === UNSAT) {
node.true = false;
} else if (result === SAT) {
node.true = true;
} else {
if (nextVariableIdx === -1) {
node.true = true;
} else {
node.true = this._buildDecisionTree(
assignment, nextVariable, node);
}
}
delete assignment[variable];
this._unassign(variable, assignment); // TODO
// try assigning node false
assignment[variable] = false;
result = this._assign(variable, false);
if (result === UNSAT) {
node.false = false;
} else if (result === SAT) {
node.false = true;
} else {
if (nextVariableIdx === -1) {
node.false = true;
} else {
node.false = this._buildDecisionTree(
assignment, nextVariable, node);
}
}
delete assignment[variable];
this._unassign(variable, assignment);
return node;
}
_assign(variable, value) {
let unsat = false;
this.buckets.forEach(bucket => {
bucket.forEach(clause => {
const literal = clause.literals[variable];
if (!literal) {
return;
} else {
if (literal.same === value) {
clause.clauseEnabled = false;
} else {
clause.enabled[variable] = false;
if (clause.length === 0) {
unsat = true;
}
}
}
})
});
if (unsat) {
return UNSAT;
} else if (this._sat()) {
debugger;
return SAT;
} else {
return NEITHER;
}
}
_unassign(variable, assignment) {
this.buckets.forEach(bucket => {
bucket.forEach(clause => {
if (variable in clause.literals) {
clause.enabled[variable] = true;
let satisfied = false;
objectForEach(assignment, (value, variable) => {
if (clause.literals[variable] &&
clause.literals[variable].same === value
) {
satisfied = true;
}
});
if (!satisfied) {
clause.clauseEnabled = true;
}
}
})
});
}
_sat() {
let allDisabled = true;
this.buckets.forEach(bucket => {
bucket.forEach(clause => {
if (clause.clauseEnabled) {
allDisabled = false;
}
});
});
return allDisabled;
}
toString() {
return this.buckets.map(bucket =>
bucket.map(clause => clause.toString(true)).join(', ')
).join('\n');
}
}
class DecisionNode {
constructor(variable, parent) {
this.parent = parent;
this.variable = variable;
this.true = false;
this.false = false;
}
toString(indentation = 0) {
const indentStr = Array(indentation).join(' ');
return [
'{ ' + this.variable,
indentStr + ' t: ' + this.true.toString(indentation+1) + ', ',
indentStr + ' f: ' + this.false.toString(indentation+1) + ', ',
indentStr + '}'].join('\n');
}
}
<html>
<body>
<script src="utils.js"></script>
<script src="CNF.js"></script>
<script>
const KB = new CNF(
4,
new Clause(
new Literal(1, true),
new Literal(2, true),
new Literal(3, true)
),
new Clause(
new Literal(1, false),
new Literal(4, true)
),
new Clause(
new Literal(2, false),
new Literal(4, true)
),
new Clause(
new Literal(3, false),
new Literal(4, true)
)
);
console.log(KB.toString());
var buckets = KB.directedResolution([1, 2, 3, 4]);
console.log(buckets.toString());
buckets.resolve();
console.log(buckets.toString());
var decisionTree = buckets.decisionTree();
console.log(decisionTree.toString());
</script>
</body>
</html>
function objectForEach(obj, fn) {
Object.keys(obj)
.forEach(key => fn(obj[key], key, obj));
}
function range(num) {
const ans = [];
for (let i = 0; i < num; i++) {
ans.push(i);
}
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment