Best Python code snippet using hypothesis
lambek.py
Source:lambek.py
1#2# lambek.py3#4# Edward Loper5# Created [12/10/00 03:41 AM]6# $Id$7#8"""Lambek Calculus Theorem Prover9"""10# For while I'm coding..11#import term;reload(term)12#import typedterm; reload(typedterm)13_VERBOSE = 014_VAR_NAMES = 115_SHOW_VARMAP = not _VAR_NAMES16from term import *17from typedterm import *18from lexicon import *19import sys, re20class Sequent:21 """A sequent maps an ordered sequence of TypedTerm's to an ordered 22 sequence of TypedTerm's."""23 # left and right are lists of TypedTerms.24 def __init__(self, left, right):25 # Check types, because we're paranoid.26 if type(left) not in [types.ListType, types.TupleType] or \27 type(right) not in [types.ListType, types.TupleType]:28 raise TypeError('Expected lists of TypedTerms')29 for elt in left+right:30 if not isinstance(elt, TypedTerm):31 raise TypeError('Expected lists of TypedTerms')32 33 self.left = left34 self.right = right35 def __repr__(self):36 left_str = `self.left`[1:-1]37 right_str = `self.right`[1:-1]38 return left_str + ' => ' + right_str39 def to_latex(self, pp_varmap=None):40 if pp_varmap == None: pp_varmap = {}41 for te in self.left+self.right:42 extend_pp_varmap(pp_varmap, te.term)43 str = ''44 for i in range(len(self.left)):45 str += self.left[i].to_latex(pp_varmap) + ', '46 str = str[:-2] + ' \Rightarrow '47 for i in range(len(self.right)):48 str += self.right[i].to_latex(pp_varmap) + ', '49 return str[:-2]50 51 def pp(self, pp_varmap=None):52 if pp_varmap == None: pp_varmap = {}53 for te in self.left+self.right:54 extend_pp_varmap(pp_varmap, te.term)55 str = ''56 for i in range(len(self.left)):57 str += self.left[i].pp(pp_varmap) + ', '58 str = str[:-2] + ' => '59 for i in range(len(self.right)):60 str += self.right[i].pp(pp_varmap) + ', '61 return str[:-2]62 def simplify(self, varmap):63 left = [te.simplify(varmap) for te in self.left]64 right = [te.simplify(varmap) for te in self.right]65 return Sequent(left, right)66 67class Proof:68 "Represents 1 step of a proof tree.."69 # rule: which rule was used (str)70 # assumptions: what is assumed (list of Proofs)71 # conclusion: what is concluded (Sequent)72 def __init__(self, rule, assumptions, conclusion, varmap):73 self.rule = rule74 self.assumptions = assumptions75 self.conclusion = conclusion76 self.varmap = varmap77 def __repr__(self):78 return self.rule+' '+`self.assumptions`+' -> '\79 +`self.conclusion`80 def simplify(self, varmap=None):81 if varmap == None:82 varmap = self.varmap83 assum = [a.simplify(varmap) for a in self.assumptions] 84 concl = self.conclusion.simplify(varmap)85 return Proof(self.rule, assum, concl, varmap)86 def to_latex_array(self, depth = 1, pp_varmap=None):87 if pp_varmap == None: pp_varmap={}88 # Draw asumptions89 str = '\\begin{array}{c}\n'90 for assumption in self.assumptions:91 str += ' '*depth + \92 assumption.to_latex(depth+1, pp_varmap) + \93 ' \\quad \n'94 str = str[:-1] + '\\\\'+'\\hline'+'\n'95 # Add conclusion96 str += ' '*depth + '{' + \97 self.conclusion.to_latex(pp_varmap) + '}'98 # Close array99 str += '\\\\\n'+' '*depth+'\\end{array}'100 101 # The rule type102 str += ' \\textrm{' + \103 re.sub(r'\\', r'$\\backslash$', self.rule) + '}' 104 if depth == 1:105 return '$$\n'+str+'\n$$'106 else:107 return '{'+str+'}'108 109 def to_latex(self, depth = 1, pp_varmap=None):110 if pp_varmap == None: pp_varmap={}111 # Draw asumptions112 str = '\\frac{\\textrm{$ \n'113 for assumption in self.assumptions:114 str += ' '*depth + \115 assumption.to_latex(depth+1, pp_varmap) + \116 ' \\quad \n'117 str = str[:-1] + '$}}\n'118 # Add conclusion119 str += ' '*depth + '{' + \120 self.conclusion.to_latex(pp_varmap) + '}'121 # The rule type122 rule = re.sub(r'\\', r'$\\backslash$', self.rule)123 rule = re.sub(r'\*', r'$\\cdot$', rule)124 str += ' \\textrm{' + rule + '}'125 if depth == 1:126 return '$$\n'+str+'\n$$'127 else:128 return '{'+str+'}'129 130 # Returns (str, right)131 def pp(self, left=0, toplevel=1, pp_varmap=None):132 if pp_varmap == None: pp_varmap={}133 right = left134 str = ''135 136 if _VAR_NAMES:137 concl = self.conclusion.pp(pp_varmap)138 else:139 concl = `self.conclusion`140 # Draw assumptions141 for assumption in self.assumptions:142 (s, right) = assumption.pp(right, 0, pp_varmap)143 str = _align_str(str, s)144 right += 5145 # Draw line.146 right = max(right-5, left+len(concl))147 str += ' '*left + '-'*(right-left) + ' ' + self.rule + '\n' 148 # Draw conclusion149 start = left+(right-left-len(concl))/2150 str += ' '*start + concl + '\n'151 if toplevel:152 if _SHOW_VARMAP:153 return str+'\nVarmap: '+ `self.varmap`+'\n'154 else:155 return str156 else:157 return (str, right)158def _align_str(s1, s2):159 lines1 = s1.split('\n')160 lines2 = s2.split('\n')161 if lines1[-1] == '': lines1 = lines1[:-1]162 if lines2[-1] == '': lines2 = lines2[:-1]163 str = ''164 while len(lines1) > len(lines2):165 str += lines1[0] + '\n'166 lines1 = lines1[1:]167 168 while len(lines2) > len(lines1):169 str += lines2[0] + '\n'170 lines2 = lines2[1:]171 for n in range(len(lines1)):172 x = 0173 for x in range(min(len(lines1[n]), len(lines2[n]))):174 if lines1[n][x] == ' ':175 str += lines2[n][x]176 elif lines2[n][x] == ' ':177 str += lines1[n][x]178 else:179 raise ValueError('Overlapping strings')180 str += lines1[n][x+1:]181 str += lines2[n][x+1:]182 str += '\n'183 return str184 185######################################186# PROOF LOGIC187######################################188# Prove a sequent. Variables can have their values filled in.189# If short_circuit is 1, return once we find any proof. If190# short_circuit is 0, return all proofs.191def prove(sequent, short_circuit=0):192 proofs = _prove(sequent, VarMap(), short_circuit, 0)193 return [proof.simplify() for proof in proofs]194def _prove(sequent, varmap, short_circuit, depth):195 if _VERBOSE:196 print (' '*depth)+'Trying to prove', sequent197 proofs = []198 if proofs == [] or not short_circuit:199 proofs = proofs + introduce(sequent, varmap, short_circuit, depth+1)200 if proofs == [] or not short_circuit:201 proofs = proofs + rslash_l(sequent, varmap, short_circuit, depth+1)202 if proofs == [] or not short_circuit:203 proofs = proofs + lslash_l(sequent, varmap, short_circuit, depth+1)204 if proofs == [] or not short_circuit:205 proofs = proofs + rslash_r(sequent, varmap, short_circuit, depth+1)206 if proofs == [] or not short_circuit:207 proofs = proofs + lslash_r(sequent, varmap, short_circuit, depth+1)208 if proofs == [] or not short_circuit:209 proofs = proofs + dot_l(sequent, varmap, short_circuit, depth+1)210 if proofs == [] or not short_circuit:211 proofs = proofs + dot_r(sequent, varmap, short_circuit, depth+1)212 if _VERBOSE:213 print ' '*depth+'Found '+`len(proofs)`+' proof(s)'214 return proofs215def introduce(sequent, varmap, short_circuit, depth):216 if len(sequent.left) != 1 or \217 len(sequent.right) != 1 or \218 sequent.left[0].type != sequent.right[0].type:219 return []220 newseq = Sequent(sequent.left, sequent.right)221 r_term = sequent.right[0].term222 l_term = sequent.left[0].term223 # Try to unify224 te = sequent.left[0].unify(sequent.right[0], varmap)225 if te == None: newseq = sequent226 else: newseq = Sequent([te], [te])227 return [Proof('I', (), newseq, varmap)]228def rslash_l(sequent, varmap_in, short_circuit, depth):229 proofs = []230 for i in range(len(sequent.left)-1):231 if isinstance(sequent.left[i].type, RSlash) and \232 len(sequent.right) == 1:233 # Set up some variables...234 beta = Var()235 alpha = sequent.left[i].term236 A = sequent.left[i].type.result237 B = sequent.left[i].type.arg238 Gamma1 = sequent.left[:i]239 gamma = sequent.right[0].term240 C = sequent.right[0].type241 # Try all combinations of Delta, Gamma2..242 for j in range(i+1, len(sequent.left)):243 Delta = sequent.left[i+1:j+1]244 Gamma2 = sequent.left[j+1:]245 # Try proving the left assumption.246 l_seq = Sequent(Delta, [TypedTerm(beta, B)])247 l_proofs = _prove(l_seq, varmap_in, short_circuit, depth)248 # For each proof, try proving the right half. Make249 # sure to keep beta bound to the same thing..250 for l_proof in l_proofs:251 beta = l_proof.conclusion.right[0].term252 r_seq = Sequent(Gamma1+\253 [TypedTerm(Appl(alpha, beta), A)]+\254 Gamma2, [TypedTerm(gamma, C)])255 r_proofs = _prove(r_seq, varmap_in, short_circuit, depth)256 for r_proof in r_proofs:257 varmap = r_proof.varmap + l_proof.varmap258 right = r_proof.conclusion.right[0]259 right = right.unify(TypedTerm(gamma, C), varmap)260 proofs.append(Proof('/L', [l_proof, r_proof],\261 Sequent(sequent.left,[right]),\262 varmap))263 if short_circuit: return proofs264 return proofs265def lslash_l(sequent, varmap_in, short_circuit, depth):266 proofs = []267 for i in range(1, len(sequent.left)):268 if isinstance(sequent.left[i].type, LSlash) and \269 len(sequent.right) == 1:270 # Set up some variables...271 beta = Var()272 alpha = sequent.left[i].term273 A = sequent.left[i].type.result274 B = sequent.left[i].type.arg275 gamma = sequent.right[0].term276 C = sequent.right[0].type277 Gamma2 = sequent.left[i+1:]278 # Try all combinations of Delta, Gamma2..279 for j in range(i):280 Delta = sequent.left[j:i]281 Gamma1 = sequent.left[:j]282 # Try proving the left assumption.283 l_seq = Sequent(Delta, [TypedTerm(beta, B)])284 l_proofs = _prove(l_seq, varmap_in, short_circuit, depth)285 # For each proof, try proving the right half. Make286 # sure to keep beta bound to the same thing..287 for l_proof in l_proofs:288 beta = l_proof.conclusion.right[0].term289 r_seq = Sequent(Gamma1+\290 [TypedTerm(Appl(alpha, beta), A)]+\291 Gamma2, [TypedTerm(gamma, C)])292 r_proofs = _prove(r_seq, varmap_in, short_circuit, depth)293 for r_proof in r_proofs:294 varmap = r_proof.varmap + l_proof.varmap295 right = r_proof.conclusion.right[0]296 right = right.unify(TypedTerm(gamma, C), varmap)297 298 proofs.append(Proof('\\L', [l_proof, r_proof],\299 Sequent(sequent.left,[right]),300 varmap))301 if short_circuit: return proofs302 return proofs303def rslash_r(sequent, varmap, short_circuit, depth):304 proofs = []305 # Make sure the right side is properly formatted..306 if len(sequent.right) != 1 or \307 not isinstance(sequent.right[0].type, RSlash):308 return proofs309 # Set up variables..310 x = Var()311 varmap.add(x, None)312 alpha = Appl(sequent.right[0].term, x)313 B = sequent.right[0].type.result314 A = sequent.right[0].type.arg315 Gamma = sequent.left316 seq = Sequent(Gamma + [TypedTerm(x, A)], \317 [TypedTerm(alpha, B)])318 s_proofs = _prove(seq, varmap, short_circuit, depth)319 for proof in s_proofs:320 varmap = proof.varmap.copy()321 right1 = TypedTerm(Abstr(x, proof.conclusion.right[0].term),\322 RSlash(B, A))323 right2 = TypedTerm(Abstr(x, alpha), sequent.right[0].type)324 right = right1.unify(right2, varmap)325 if right == None: continue326 varmap.add(x, None)327 concl = Sequent(Gamma, [right])328 proofs.append(Proof('/R', [proof], concl, varmap))329 return proofs330def lslash_r(sequent, varmap, short_circuit, depth):331 proofs = []332 # Make sure the right side is properly formatted..333 if len(sequent.right) != 1 or \334 not isinstance(sequent.right[0].type, LSlash):335 return proofs336 # Set up variables..337 x = Var()338 varmap.add(x, None)339 alpha = Appl(sequent.right[0].term, x)340 B = sequent.right[0].type.result341 A = sequent.right[0].type.arg342 Gamma = sequent.left343 seq = Sequent([TypedTerm(x, A)] + Gamma, \344 [TypedTerm(alpha, B)])345 s_proofs = _prove(seq, varmap, short_circuit, depth)346 for proof in s_proofs:347 right1 = TypedTerm(Abstr(x, proof.conclusion.right[0].term),\348 LSlash(A, B))349 right2 = TypedTerm(Abstr(x, alpha), sequent.right[0].type)350 right = right1.unify(right2, varmap)351 if right == None: continue352 varmap = varmap + proof.varmap353 varmap.add(x, None)354 concl = Sequent(Gamma, [right])355 proofs.append(Proof('\\R', [proof], concl, varmap))356 return proofs357def dot_l(sequent, varmap, short_circuit, depth):358 proofs = []359 for i in range(0, len(sequent.left)):360 if isinstance(sequent.left[i].type, Dot) and \361 len(sequent.right) == 1:362 Gamma1 = sequent.left[:i]363 Gamma2 = sequent.left[i+1:]364 A = sequent.left[i].type.left365 B = sequent.left[i].type.right366 alpha = sequent.left[i].term367 # Deal with alpha if we can368 if isinstance(alpha, Tuple):369 alpha1 = alpha.left370 alpha2 = alpha.right371 elif isinstance(alpha, Var):372 alpha_var = alpha373 alpha1 = Var()374 alpha2 = Var()375 alpha = Tuple(alpha1, alpha2)376 varmap.add(alpha_var, alpha)377 else:378 # We can't deal.. :( Move on...379 continue380 left = Gamma1 + [TypedTerm(alpha1, A)] + \381 [TypedTerm(alpha2, B)] + Gamma2382 right = sequent.right383 s_proofs = _prove(Sequent(left, right), varmap, \384 short_circuit, depth)385 for proof in s_proofs:386 varmap = proof.varmap.copy()387 sequent.right[0].unify(proof.conclusion.right[0], varmap) 388 proofs.append(Proof('*L', [proof], sequent, varmap))389 if short_circuit: return proofs390 391 return proofs392def dot_r(sequent, varmap_in, short_circuit, depth):393 proofs = []394 for i in range(1, len(sequent.left)):395 if isinstance(sequent.right[0].type, Dot) and \396 len(sequent.right) == 1:397 Gamma1 = sequent.left[:i]398 Gamma2 = sequent.left[i:]399 A = sequent.right[0].type.left400 B = sequent.right[0].type.right401 alphabeta = sequent.right[0].term402 # Deal with alpha if we can403 if isinstance(alphabeta, Tuple):404 alpha = alphabeta.left405 beta = alphabeta.right406 elif isinstance(alphabeta, Var):407 alphabeta_var = alphabeta408 alpha = Var()409 beta = Var()410 alphabeta = Tuple(alpha, beta)411 varmap_in.add(alphabeta_var, alphabeta)412 else:413 # We can't deal.. :( Move on...414 continue415 left = Sequent(Gamma1, [TypedTerm(alpha, A)])416 right = Sequent(Gamma2, [TypedTerm(beta, B)])417 for r_proof in _prove(right, varmap_in, short_circuit, depth):418 for l_proof in _prove(left, varmap_in, short_circuit, depth):419 varmap = r_proof.varmap + l_proof.varmap420 right = TypedTerm(Tuple(l_proof.conclusion.right[0].term,\421 r_proof.conclusion.right[0].term),422 sequent.right[0].type)423 right = right.unify(sequent.right[0], varmap)424 concl = Sequent(Gamma1+Gamma2, [right])425 proofs.append(Proof('*R', [l_proof, r_proof],\426 concl, varmap))427 if short_circuit: return proofs428 return proofs429######################################430# TESTING431######################################432def find_proof(left, right, short_circuit=1):433 sq = Sequent(left, right)434 proofs = prove(sq, short_circuit)435 if proofs:436 print '#'*60437 print "## Proof(s) for", sq.pp()438 for proof in proofs:439 print440 print proof.to_latex()441 else:442 print '#'*60443 print "## Can't prove", sq.pp()444def test_lambek():445 lex = Lexicon()446 lex.load(open('lexicon.txt', 'r'))447 find_proof(lex.parse('[np/n] [n]'), lex.parse('[np]'))448 find_proof(lex.parse('[np] [np\s]'), lex.parse('[s]'))449 find_proof(lex.parse('[n] [np\s]'), lex.parse('[(np/n)\s]'))450 find_proof(lex.parse('dog sleeps'), lex.parse('[(np/n)\s]'))451 find_proof(lex.parse('the kid runs'), lex.parse('[s]'))452 find_proof(lex.parse('john believes tom likes'), lex.parse('[s/np]'))453 find_proof(lex.parse('john likes mary'), lex.parse('[s]'))454 find_proof(lex.parse('likes'), lex.parse('[np\s/np]'), 0)455 find_proof(lex.parse('[a/b] [b]'), lex.parse('foo'))456 find_proof(lex.parse('[(np/n)*n]'), lex.parse('[np]'))457 find_proof(lex.parse('[(np\\s)/np]'), lex.parse('[np\\(s/np)]'))458 find_proof(lex.parse('gives2 tom mary'), lex.parse('[np\\s]'))459 find_proof(lex.parse('gives'), lex.parse('[np\\s/(np*np)]'))460 find_proof(lex.parse('the city tom likes'), lex.parse('[np*(s/np)]'))461HELP="""% Lambek Calculus Theorem Proover462%463% Type a sequent you would like prooved. Examples are:464% [np/n] [n] => [np]465% [np] [np\s] => [s]466% [n] [np\s] => [(np/n)\s]467% dog sleeps => [(np/n)\s]468% the kid runs => [s]469% john believes tom likes => [s/np]470% john likes mary => [s]471% likes => [np\s/np]472% [a/b] [b] => foo473% [(np/n)*n] => [np]474% [(np\\s)/np] => [np\\(s/np)]475% gives2 tom mary => [np\\s]476% gives => [np\\s/(np*np)]477% the city tom likes => [np*(s/np)]478%479% Other commands:480% help -- show this information481% latexmode -- toggle latexmode (outputs in LaTeX)482% shortcircuit -- toggle shortcircuit mode (return just one proof)483% lexicon -- display the lexicon contents484% quit -- quit485"""486 487def mainloop(input, out, lex, latexmode, shortcircuit):488 while 1:489 out.write('%>> ')490 str = input.readline()491 if str == '': return492 str = str.strip()493 if (str=='') or (str[0]=='#') or (str[0]=='%'): continue494 if str.find('=>') == -1:495 if str.lower().startswith('latex'):496 if str.lower().endswith('off'): latexmode = 0497 elif str.lower().endswith('on'): latexmode = 1498 else: latexmode = not latexmode499 if latexmode: print >>out, '% latexmode on'500 else: print >>out, 'latexmode off'501 elif str.lower().startswith('short'):502 if str.lower().endswith('off'): shortcircuit = 0503 elif str.lower().endswith('on'): shortcircuit = 1504 else: shortcircuit = not shortcircuit505 if shortcircuit: print >>out, '%shortcircuit on'506 else: print >>out, '% shortcircuit off'507 elif str.lower().startswith('lex'):508 words = lex.words()509 print >>out, '% Lexicon: '510 for word in words:511 print >>out, '% ' + word + ':', \512 ' '*(14-len(word)) + lex[word].pp() 513 elif str.lower().startswith('q'): return514 elif str.lower().startswith('x'): return515 else:516 print >>out, HELP517 else:518 try:519 (left, right) = str.split('=>')520 seq = Sequent(lex.parse(left), lex.parse(right))521 proofs = prove(seq, shortcircuit)522 print >>out523 print >>out, '%'*60524 if proofs:525 print >>out, "%% Proof(s) for", seq.pp()526 for proof in proofs:527 print >>out528 if latexmode: print >>out, proof.to_latex()529 else: print >>out, proof.pp()530 else:531 print >>out, "%% Can't prove", seq.pp()532 except KeyError, e:533 print 'Mal-formatted sequent'534 print 'Key error (unknown lexicon entry?)'535 print e536 except ValueError, e:537 print 'Mal-formatted sequent'538 print e539# Usage: argv[0] lexiconfile540def main(argv):541 if (len(argv) != 2) and (len(argv) != 4):542 print 'Usage:', argv[0], '<lexicon_file>'543 print 'Usage:', argv[0], '<lexicon_file> <input_file> <output file>'544 return545 lex = Lexicon()546 try: lex.load(open(argv[1], 'r'))547 except:548 print "Error loading lexicon file"549 return550 if len(argv) == 2:551 mainloop(sys.stdin, sys.stdout, lex, 0, 1)552 else:553 out = open(argv[3], 'w')554 print >>out, '\documentclass{article}'555 print >>out, '\usepackage{fullpage}'556 print >>out, '\\begin{document}'557 print >>out558 mainloop(open(argv[2], 'r'), out, lex, 1, 1)559 print >>out560 print >>out, '\\end{document}'561if __name__ == '__main__':562 main(sys.argv)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!