forked from aimacode/aima-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFOLTFMResolution.cs
359 lines (313 loc) · 8.59 KB
/
FOLTFMResolution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
using System;
using System.Collections.Generic;
using System.Text;
using aima.core.logic.fol;
using aima.core.logic.fol.inference.proof;
using aima.core.logic.fol.inference.trace;
using aima.core.logic.fol.kb;
using aima.core.logic.fol.kb.data;
using aima.core.logic.fol.parsing.ast;
namespace aima.core.logic.fol.inference
{
/**
* Artificial Intelligence A Modern Approach (3rd Edition): page 347.<br>
* <br>
* The algorithmic approach is identical to the propositional case, described in
* Figure 7.12.<br>
* <br>
* However, this implementation will use the T)wo F)inger M)ethod for looking
* for resolvents between clauses, which is very inefficient.<br>
* <br>
* see:<br>
* <a
* href="http://logic.stanford.edu/classes/cs157/2008/lectures/lecture04.pdf">
* http://logic.stanford.edu/classes/cs157/2008/lectures/lecture04.pdf</a>,
* slide 21 for the propositional case. In addition, an Answer literal will be
* used so that queries with Variables may be answered (see pg. 350 of AIMA3e).
*
* @author Ciaran O'Reilly
*
*/
public class FOLTFMResolution : InferenceProcedure
{
private long maxQueryTime = 10 * 1000;
private FOLTFMResolutionTracer tracer = null;
public FOLTFMResolution()
{
}
public FOLTFMResolution(long maxQueryTime)
{
setMaxQueryTime(maxQueryTime);
}
public FOLTFMResolution(FOLTFMResolutionTracer tracer)
{
setTracer(tracer);
}
public long getMaxQueryTime()
{
return maxQueryTime;
}
public void setMaxQueryTime(long maxQueryTime)
{
this.maxQueryTime = maxQueryTime;
}
public FOLTFMResolutionTracer getTracer()
{
return tracer;
}
public void setTracer(FOLTFMResolutionTracer tracer)
{
this.tracer = tracer;
}
// START-InferenceProcedure
public InferenceResult ask(FOLKnowledgeBase KB, Sentence alpha)
{
// clauses <- the set of clauses in CNF representation of KB ^ ~alpha
List<Clause> clauses = new List<Clause>();
foreach (Clause c in KB.getAllClauses())
{
Clause c2 = KB.standardizeApart(c);
c2.setStandardizedApartCheckNotRequired();
clauses.AddRange(c2.getFactors());
}
Sentence notAlpha = new NotSentence(alpha);
// Want to use an answer literal to pull
// query variables where necessary
Literal answerLiteral = KB.createAnswerLiteral(notAlpha);
List<Variable> answerLiteralVariables = KB
.collectAllVariables(answerLiteral.getAtomicSentence());
Clause answerClause = new Clause();
if (answerLiteralVariables.Count > 0)
{
Sentence notAlphaWithAnswer = new ConnectedSentence(Connectors.OR,
notAlpha, answerLiteral.getAtomicSentence());
foreach (Clause c in KB.convertToClauses(notAlphaWithAnswer))
{
Clause c2 = KB.standardizeApart(c);
c2.setProofStep(new ProofStepGoal(c2));
c2.setStandardizedApartCheckNotRequired();
clauses.AddRange(c2.getFactors());
}
answerClause.addLiteral(answerLiteral);
}
else
{
foreach (Clause c in KB.convertToClauses(notAlpha))
{
Clause c2 = KB.standardizeApart(c);
c2.setProofStep(new ProofStepGoal(c2));
c2.setStandardizedApartCheckNotRequired();
clauses.AddRange(c2.getFactors());
}
}
TFMAnswerHandler ansHandler = new TFMAnswerHandler(answerLiteral,
answerLiteralVariables, answerClause, maxQueryTime);
// new <- {}
List<Clause> newClauses = new List<Clause>();
List<Clause> toAdd = new List<Clause>();
// loop do
int noOfPrevClauses = clauses.Count;
do
{
if (null != tracer)
{
tracer.stepStartWhile(new HashSet<Clause>(clauses), clauses.Count, newClauses
.Count);
}
newClauses.Clear();
// for each Ci, Cj in clauses do
Clause[] clausesA = new Clause[clauses.Count];
clausesA = clauses.ToArray();
// Basically, using the simple T)wo F)inger M)ethod here.
for (int i = 0; i < clausesA.Length; i++)
{
Clause cI = clausesA[i];
if (null != tracer)
{
tracer.stepOuterFor(cI);
}
for (int j = i; j < clausesA.Length; j++)
{
Clause cJ = clausesA[j];
if (null != tracer)
{
tracer.stepInnerFor(cI, cJ);
}
// resolvent <- FOL-RESOLVE(Ci, Cj)
List<Clause> resolvents = cI.binaryResolvents(cJ);
if (resolvents.Count > 0)
{
toAdd.Clear();
// new <- new <UNION> resolvent
foreach (Clause rc in resolvents)
{
toAdd.AddRange(rc.getFactors());
}
if (null != tracer)
{
tracer.stepResolved(cI, cJ, new HashSet<Clause>(toAdd));
}
ansHandler.checkForPossibleAnswers(toAdd);
if (ansHandler.isComplete())
{
break;
}
newClauses.AddRange(toAdd);
}
if (ansHandler.isComplete())
{
break;
}
}
if (ansHandler.isComplete())
{
break;
}
}
noOfPrevClauses = clauses.Count;
// clauses <- clauses <UNION> new
clauses.AddRange(newClauses);
if (ansHandler.isComplete())
{
break;
}
// if new is a <SUBSET> of clauses then finished
// searching for an answer
// (i.e. when they were added the # clauses
// did not increase).
} while (noOfPrevClauses < clauses.Count);
if (null != tracer)
{
tracer.stepFinished(new HashSet<Clause>(clauses), ansHandler);
}
return ansHandler;
}
// END-InferenceProcedure
//
//
// PRIVATE METHODS
//
class TFMAnswerHandler : InferenceResult
{
private Literal answerLiteral = null;
private List<Variable> answerLiteralVariables = null;
private Clause answerClause = null;
private long finishTime = 0L;
private bool complete = false;
private List<Proof> proofs = new List<Proof>();
private bool timedOut = false;
public TFMAnswerHandler(Literal answerLiteral,
List<Variable> answerLiteralVariables, Clause answerClause,
long maxQueryTime)
{
this.answerLiteral = answerLiteral;
this.answerLiteralVariables = answerLiteralVariables;
this.answerClause = answerClause;
//
this.finishTime = DateTime.UtcNow.Ticks + maxQueryTime;
}
//
// START-InferenceResult
public bool isPossiblyFalse()
{
return !timedOut && proofs.Count == 0;
}
public bool isTrue()
{
return proofs.Count > 0;
}
public bool isUnknownDueToTimeout()
{
return timedOut && proofs.Count == 0;
}
public bool isPartialResultDueToTimeout()
{
return timedOut && proofs.Count > 0;
}
public List<Proof> getProofs()
{
return proofs;
}
// END-InferenceResult
public bool isComplete()
{
return complete;
}
public void checkForPossibleAnswers(List<Clause> resolvents)
{
// If no bindings being looked for, then
// is just a true false query.
foreach (Clause aClause in resolvents)
{
if (answerClause.isEmpty())
{
if (aClause.isEmpty())
{
proofs.Add(new ProofFinal(aClause.getProofStep(),
new Dictionary<Variable, Term>()));
complete = true;
}
}
else
{
if (aClause.isEmpty())
{
// This should not happen
// as added an answer literal, which
// implies the database (i.e. premises) are
// unsatisfiable to begin with.
throw new ApplicationException(
"Generated an empty clause while looking for an answer, implies original KB is unsatisfiable");
}
if (aClause.isUnitClause()
&& aClause.isDefiniteClause()
&& aClause.getPositiveLiterals()[0]
.getAtomicSentence().getSymbolicName()
.Equals(
answerLiteral.getAtomicSentence()
.getSymbolicName()))
{
Dictionary<Variable, Term> answerBindings = new Dictionary<Variable, Term>();
List<Term> answerTerms = aClause.getPositiveLiterals()
[0].getAtomicSentence().getArgs();
int idx = 0;
foreach (Variable v in answerLiteralVariables)
{
answerBindings.Add(v, (Term)answerTerms[idx]);
idx++;
}
bool addNewAnswer = true;
foreach (Proof p in proofs)
{
if (p.getAnswerBindings().Equals(answerBindings))
{
addNewAnswer = false;
break;
}
}
if (addNewAnswer)
{
proofs.Add(new ProofFinal(aClause.getProofStep(),
answerBindings));
}
}
}
if (DateTime.UtcNow.Ticks > finishTime)
{
complete = true;
// Indicate that I have run out of query time
timedOut = true;
}
}
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("isComplete=" + complete);
sb.Append("\n");
sb.Append("result=" + proofs);
return sb.ToString();
}
}
}
}