-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathderivations.py
More file actions
executable file
·658 lines (584 loc) · 20.6 KB
/
Copy pathderivations.py
File metadata and controls
executable file
·658 lines (584 loc) · 20.6 KB
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
#!/usr/bin/env python3
# ----------------------------------
#
# Module derivations.py
"""
A datatype for representing derivations, i.e. jusifications for
clauses and formulas. Derivations are recursively defined: A
derivation can be the trivial derivation (the clause or formula is
read directly from the input), or it consists of an operator (the
inference rule) and a list of parents.
Copyright 2011-2023 Stephan Schulz, schulz@eprover.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program ; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
The original copyright holder can be contacted as
Stephan Schulz
Auf der Altenburg 7
70376 Stuttgart
Germany
Email: schulz@eprover.org
"""
from lexer import Token,Lexer
from terms import parseTerm, termIsVar, termArgs, term2String
import unittest
from checkutil import VerificationStatus
class Derivable(object):
"""
This class represents "derivable" objects. Derivable objects have
a name and a justification. Names can be generated
automatically. They are required to be different for different
objects in the same proof structure, but this is enforced at the
FOFSpec level. Derivable objects will typically be logical formulas,
either full FOF formulas, or clauses.
"""
derivedIdCounter = 0
"""
Counter for generating new clause names.
"""
printDerivation = False
"""
Indicate if derivations should be printed as part of Derivable
objects. It's up to the concrete classes to support this.
"""
def __init__(self, name=None, derivation = None):
"""
Initialize the object..
"""
self.setName(name)
self.derivation = derivation
self.refCount = 0
self.eqLen = None # How many applications of original axioms
# lead to this? Probably only useful in a
# purely UEQ setting.
self.rwSteps = None
self.number = None
def __repr__(self):
return self.name
def setName(self, name = None):
"""
Set the name. If no name is given, generate a default name.
"""
if name:
self.name = name
else:
self.name = "c%d"%(Derivable.derivedIdCounter,)
Derivable.derivedIdCounter=Derivable.derivedIdCounter+1
def setNumber(self, number):
"""
Set the serial number of the step in a linearized derivation.
"""
self.number = number
def setDerivation(self, derivation):
"""
Set the derivation that created this derivable.
"""
self.derivation = derivation
def setInputDeriv(self, filename, name):
"""
Special case: It's an input object.
"""
self.derivation = Derivation("file", (filename,name))
def getParents(self):
"""
Return a list of all parents of this node in the derivation
graph.
"""
if self.derivation:
return self.derivation.getParents()
else:
return []
def getAncestors(self):
"""
Return a list of all ancestors of this node in the derivation
graph.
"""
if self.derivation:
return self.derivation.getAncestors()
else:
return set()
def incRefCount(self):
"""
Increase reference counter (counts virtual edges in the
derivation graph coming from the children).
"""
self.refCount = self.refCount+1
def decRefCount(self):
"""
See above.
"""
self.refCount = self.refCount-1
def strDerivation(self):
"""
If printing of derivations is enabled, return a string
representartion suitable as part of TPTP-3 output. Otherwise
return the empty string.
"""
if not self.derivation:
return ""
if Derivable.printDerivation:
return ","+repr(self.derivation)
return ""
def annotateDerivationGraph(self):
"""
Compute and set the number of virtual edges in all descendents
of self. The root node has one "virtual" edge.
"""
self.incRefCount()
if self.refCount == 1:
parents = self.getParents()
for p in parents:
p.annotateDerivationGraph()
def linearizeDerivation(self, res = None):
"""
Return linearized derivation.
"""
if res == None:
res = list()
self.decRefCount()
if self.refCount==0:
res.append(self)
parents = self.getParents()
for p in parents:
p.linearizeDerivation(res)
return res
def orderedDerivation(self):
self.annotateDerivationGraph()
res = self.linearizeDerivation()
res.reverse()
return res
def computeEqLen(self):
if self.derivation.isInputDeriv() and "conjecture" in self.type:
self.eqLen = 0
if self.eqLen == None:
self.eqLen = self.derivation.computeEqLen()
return self.eqLen
def computeRWSteps(self):
if self.derivation.isInputDeriv() and "conjecture" in self.type:
self.rwSteps = 0
if self.rwSteps == None:
self.rwSteps = self.derivation.computeRWSteps()
return self.rwSteps
def checkForwardReferences(self):
"""
Check if all references point (topologically)
backwards. Terminate with Verification failure if not.
"""
for i in self.getParents():
if i.number > self.number:
VerificationStatus(f"VerifiedBad: Step {self.name} references topologically later {i.name}")
def enableDerivationOutput():
Derivable.printDerivation = True
def disableDerivationOutput():
Derivable.printDerivation = False
def toggleDerivationOutput():
Derivable.printDerivation = not Derivable.printDerivation
class Derivation(object):
"""
A derivation object. A derivation is either trivial ("input"), a
reference to an existing Derivable object ("reference"), or an
inference with a list of premises.
"""
def __init__(self, operator, parents=None, status="status(thm)", skolemdata=None):
"""
Initialize a derivation object with the operator and a list
of parents (which can be Derivations or, in the case of
"reference", Derivables).
"""
if operator in ["reference", "quasi_ref"]:
# print(f"Parents: {parents}")
assert(len(parents)==1)
self.operator = operator
self.parents = parents
self.status = status
self.skolemdata = skolemdata
def __repr__(self):
"""
Return a string for the derivation in TPTP-3 format.
"""
if self.isInputDeriv():
return f"file('{self.parents[0]}', {self.parents[1]})"
elif self.operator.startswith("theory("):
return self.operator
elif self.operator == "reference":
# print("reference:", self.parents)
assert(len(self.parents)==1)
return self.parents[0].name
elif self.operator == "quasi_ref":
assert(len(self.parents)==1)
return self.parents[0]
elif self.operator == "skolemize":
return f"inference({self.operator},[{self.status},"+\
f"new_symbols(skolem,[{self.skolemdata[0]}])"+\
f",skolemize({self.skolemdata[1]},"+\
f"{term2String(self.skolemdata[2])})],{self.parents})"
else:
return "inference(%s,[%s],%s)"%\
(self.operator, self.status, repr(self.parents))
def isInputDeriv(self):
"""
Return true if this derivation corresponds to an input
clause/formula, i.e. it is justified simply by pointing to its
origin.
"""
return self.operator == "file"
def isSimpleQuotation(self):
return self.operator == "reference"
def getInputParts(self):
"""
Return file and name of an input step.
"""
def getParents(self):
"""
Return a list of all derived objects that are used in this
derivation.
"""
if self.isInputDeriv():
return []
elif self.operator.startswith("theory("):
return []
elif self.operator == "reference":
assert(len(self.parents)==1)
return self.parents
elif self.operator == "quasi_ref":
return []
else:
res = list()
for p in self.parents:
res.extend(p.getParents())
return res
def getAncestors(self):
parents = self.getParents()
res = set(parents)
for p in parents:
res |= p.getAncestors()
return res
def getRecDerivationStatuses(self):
"""
Return a set of all statuses used in the
derivation.
"""
if self.operator.startswith("theory("):
return set()
elif self.operator == "reference":
return set()
else:
res = set([self.status])
for p in self.parents:
res = res|p.getRecDerivationStatuses()
return res
def getDerivationStatuses(self):
"""
Return a set of all statuses used in the
derivation.
"""
if self.isInputDeriv():
return set()
if self.isSimpleQuotation():
return set(["status(thm)"])
else:
return self.getRecDerivationStatuses()
def resolveQuasiReferences(self, index):
if self.operator == "quasi_ref":
self.operator = "reference"
# print("QParents: ", self.parents)
assert(len(self.parents)==1)
for p in self.parents:
if not p in index:
VerificationStatus(f"VerifiedBad: Identifier '{p}' cannot be resolved")
parents = [index[p] for p in self.parents]
assert(len(parents)==1)
self.parents = parents
elif self.isInputDeriv():
pass
else:
# print(self.parents)
if self.parents:
for p in self.parents:
p.resolveQuasiReferences(index)
def computeEqLen(self):
if self.isInputDeriv():
return 1
elif self.operator == "reference":
return self.parents[0].computeEqLen()
else:
# print(self.operator, len(self.parents))
res = 0
if self.parents:
for p in self.parents:
res += p.computeEqLen()
return res
def computeRWSteps(self):
if self.isInputDeriv():
return 0
elif self.operator == "reference":
return 0
else:
res = 0
if(self.operator in ["rw", "sr"]):
res = 1
if self.parents:
for p in self.parents:
res += p.computeRWSteps()
return res
def parseSkolemData(lexer):
lexer.AcceptTok(Token.OpenSquare)
lexer.AcceptLit("status")
lexer.AcceptTok(Token.OpenPar)
lexer.CheckLit("esa")
status = "status(%s)"%(lexer.LookLit(),)
lexer.AcceptTok(Token.IdentLower)
lexer.AcceptTok(Token.ClosePar)
lexer.AcceptTok(Token.Comma)
lexer.AcceptLit("new_symbols")
lexer.AcceptTok(Token.OpenPar)
lexer.AcceptLit("skolem")
lexer.AcceptTok(Token.Comma)
lexer.AcceptTok(Token.OpenSquare)
skolem = lexer.LookLit()
lexer.AcceptTok(Token.IdentLower)
lexer.AcceptTok(Token.CloseSquare)
lexer.AcceptTok(Token.ClosePar)
lexer.AcceptTok(Token.Comma)
lexer.AcceptLit("skolemize")
lexer.AcceptTok(Token.OpenPar)
lexer.CheckTok(Token.IdentUpper)
var = parseTerm(lexer)
lexer.AcceptTok(Token.Comma)
lexer.CheckLit(skolem)
skolemterm = parseTerm(lexer)
varlist = termArgs(skolemterm)
for t in varlist:
if not termIsVar(t):
raise ScannerError(f"All arguments of a Skolem term must be variables, {term2String(t)} is not")
lexer.AcceptTok(Token.ClosePar)
lexer.AcceptTok(Token.CloseSquare)
return status,skolem,var,skolemterm,varlist
def parsePrologishTermList(lexer):
"""
Parse (and ignore) something that seems to be a (non-empty)
Prolog-term list.
"""
parsePrologishTerm(lexer)
while lexer.TestTok(Token.Comma):
lexer.AcceptTok(Token,Comma)
parsePrologishTerm(lexer)
def parsePrologishTerm(lexer):
"""
Parse (and ignore) something that seems to be a Prolog-term.
"""
if lexer.TestTok(Token.OpenSquare):
lexer.AcceptTok(Token.OpenSquare)
parsePrologishTermList(lexer)
lexer.AcceptTok(Token.CloseSquare)
else:
lexer.AcceptTok([Token.IdentUpper, Token.IdentLower])
if lexer.TestTok(Token.OpenPar):
lexer.AcceptTok(Token.OpenPar)
if not lexer.TestTok(Token.ClosePar):
parsePrologishTermList(lexer)
lexer.AcceptTok(Token.ClosePar)
def parseInfDataItem(lexer):
"""
Parse one annotation item of an inference step. This can be
status(<status>), new_symbols(<bla>, [<symbols>],
skolemize(<Var>,<term>), or a random nested something.
We return a tuple with the recognized components != None.
"""
status = None
skolem = None
var = None
skolemterm = None
varlist = None
if lexer.TestLit("status"):
lexer.AcceptLit("status")
lexer.AcceptTok(Token.OpenPar)
status = "status(%s)"%(lexer.LookLit(),)
lexer.AcceptTok(Token.IdentLower)
lexer.AcceptTok(Token.ClosePar)
elif lexer.TestLit("new_symbols"):
lexer.AcceptLit("new_symbols")
lexer.AcceptTok(Token.OpenPar)
lexer.AcceptTok(Token.IdentLower)
lexer.AcceptTok(Token.Comma)
lexer.AcceptTok(Token.OpenSquare)
skolem = lexer.LookLit()
lexer.AcceptTok(Token.IdentLower)
lexer.AcceptTok(Token.CloseSquare)
lexer.AcceptTok(Token.ClosePar)
elif lexer.TestLit("skolemize"):
lexer.AcceptLit("skolemize")
lexer.AcceptTok(Token.OpenPar)
lexer.CheckTok(Token.IdentUpper)
var = parseTerm(lexer)
lexer.AcceptTok(Token.Comma)
# lexer.CheckLit(skolem)
skolemterm = parseTerm(lexer)
varlist = termArgs(skolemterm)
for t in varlist:
if not termIsVar(t):
raise ScannerError(f"All arguments of a Skolem term must be variables, {term2String(t)} is not")
lexer.AcceptTok(Token.ClosePar)
else:
parsePrologishTerm()
return status,skolem,var,skolemterm,varlist
def parseInfData(lexer):
status = None
skolem = None
var = None
skolemterm = None
varlist = None
first = True
lexer.AcceptTok(Token.OpenSquare)
while not lexer.TestTok(Token.CloseSquare):
if first:
first = False
else:
lexer.AcceptTok(Token.Comma)
lstatus,lskolem,lvar,lskolemterm,lvarlist = parseInfDataItem(lexer)
if lstatus != None:
status = lstatus
if lskolem != None:
skolem = lskolem
if lvar != None:
var = lvar
if lskolemterm != None:
skolemterm = lskolemterm
if lvarlist != None:
varlist = lvarlist
lexer.AcceptTok(Token.CloseSquare)
return status,skolem,var,skolemterm,varlist
def parseRecDerivation(lexer):
if lexer.TestLit("inference"):
lexer.AcceptLit("inference")
lexer.AcceptTok(Token.OpenPar)
operator = lexer.LookLit()
lexer.AcceptTok(Token.IdentLower)
lexer.AcceptTok(Token.Comma)
tmp = parseInfData(lexer)
status = tmp[0]
skolemdata = tmp[1:]
if operator == "skolemize":
if None in skolemdata:
raise IncompleteDataError("Skolem informatiom incomplete")
skolem,var,skolemterm,varlist = skolemdata
if skolem!=skolemterm[0]:
raise InconsistentDataError(f"Skolem symbol {skolem} not heading skolem term {term2String(skolemterm)}")
if not status:
raise IncompleteDataError("Inference record has no status")
lexer.AcceptTok(Token.Comma)
lexer.AcceptTok(Token.OpenSquare)
parents = list()
if not lexer.TestTok(Token.CloseSquare):
parent = parseRecDerivation(lexer)
parents.append(parent)
while lexer.TestTok(Token.Comma):
lexer.AcceptTok(Token.Comma)
parent = parseRecDerivation(lexer)
parents.append(parent)
lexer.AcceptTok(Token.CloseSquare)
lexer.AcceptTok(Token.ClosePar)
return Derivation(operator, parents, status, skolemdata)
elif lexer.TestTok([Token.IdentLower, Token.Integer]):
name = lexer.LookLit()
lexer.AcceptTok([Token.IdentLower,Token.Integer])
return Derivation("quasi_ref", [name])
def parseDerivation(lexer):
if lexer.TestLit("file"):
lexer.AcceptLit("file")
lexer.AcceptTok(Token.OpenPar)
filename = lexer.LookLit().strip("'")
lexer.AcceptTok(Token.SQString)
lexer.AcceptTok(Token.Comma)
name = lexer.LookLit()
lexer.AcceptTok([Token.IdentLower,Token.SQString])
lexer.AcceptTok(Token.ClosePar)
return Derivation("file", (filename,name))
else:
return parseRecDerivation(lexer)
def flatDerivation(operator, parents, status="status(thm)"):
"""
Simple convenience function: Create a derivation which directly
references all parents.
"""
parentlist = [Derivation("reference", [p]) for p in parents]
return Derivation(operator, parentlist, status)
class TestDerivations(unittest.TestCase):
"""
"""
def setUp(self):
print()
def testDerivable(self):
"""
Test basic properties of derivations.
"""
o1 = Derivable()
o2 = Derivable()
o3 = Derivable()
o3.setDerivation(flatDerivation("resolution", [o1, o2]))
self.assertEqual(o1.getParents(),[])
self.assertEqual(o2.getParents(),[])
self.assertEqual(len(o3.getParents()), 2)
print(o3)
print(o3.derivation)
o3.setDerivation(flatDerivation("factor", [o1]))
print(o3.derivation)
self.assertEqual(len(o3.getParents()), 1)
def testProofExtraction(self):
"""
Test basic proof extraction.
"""
o1 = Derivable()
o2 = Derivable()
o3 = Derivable()
o4 = Derivable()
o5 = Derivable()
o6 = Derivable()
o7 = Derivable()
o1.setDerivation(Derivation("theory(equality)"))
print(repr(o1.derivation))
o2.setDerivation(Derivation("file", ('\'fake\'', 'fake')))
o3.setDerivation(flatDerivation("factor", [o1]))
o4.setDerivation(flatDerivation("factor", [o3]))
o5.setDerivation(flatDerivation("resolution", [o1,o2]))
o6.setDerivation(Derivation("reference", [o5]))
o7.setDerivation(flatDerivation("resolution", [o5,o1]))
proof = o7.orderedDerivation()
print(proof)
self.assertEqual(len(proof),4)
self.assertTrue(o1 in proof)
self.assertTrue(o2 in proof)
self.assertTrue(o5 in proof)
self.assertTrue(o7 in proof)
def testOutput(self):
"""
Test derivation output functions.
"""
o1 = Derivable()
o2 = Derivable()
o3 = Derivable()
o4 = Derivable()
o1.setDerivation(Derivation("theory(equality)"))
o2.setDerivation(Derivation("input"))
o3.setDerivation(flatDerivation("resolution", [o1, o2]))
enableDerivationOutput()
self.assertTrue(o2.strDerivation()!="")
self.assertTrue(o3.strDerivation()!="")
self.assertTrue(o4.strDerivation()=="")
disableDerivationOutput()
self.assertTrue(o3.strDerivation()=="")
self.assertTrue(o4.strDerivation()=="")
toggleDerivationOutput()
self.assertTrue(o3.strDerivation()!="")
self.assertTrue(o4.strDerivation()=="")
if __name__ == '__main__':
unittest.main()