
    gH                     L   d Z ddlmZ ddlmZ ddlmZmZ ddlm	Z	m
Z
 ddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZ  G d de      Zd	 Z G d
 de      Z G d de      Z G d de      Z  G d de      Z! G d d      Z"d Z#d Z$d Z%d Z&d Z'd Z(d Z)e*dk(  r e)        yy)z
A module to perform nonmonotonic reasoning.  The ideas and demonstrations in
this module are based on "Logical Foundations of Artificial Intelligence" by
Michael R. Genesereth and Nils J. Nilsson.
    )defaultdict)reduce)ProverProverCommandDecorator)Prover9Prover9Command)AbstractVariableExpressionAllExpressionAndExpressionApplicationExpressionBooleanExpressionEqualityExpressionExistsExpression
ExpressionImpExpressionNegatedExpressionVariableVariableExpressionoperatorunique_variablec                       e Zd Zy)ProverParseErrorN)__name__
__module____qualname__     P/var/www/openai/venv/lib/python3.12/site-packages/nltk/inference/nonmonotonic.pyr   r   &   s    r   r   c                 n    | |}n||  gz   }t        t        j                  d |D        t                     S )Nc              3   <   K   | ]  }|j                           y wN)	constants).0as     r   	<genexpr>zget_domain.<locals>.<genexpr>/   s      H1s   )r   r   or_set)goalassumptionsall_expressionss      r   
get_domainr+   *   s5    |%%$/(,, H H#%PPr   c                   "    e Zd ZdZd Zd Zd Zy)ClosedDomainProverz]
    This is a prover decorator that adds domain closure assumptions before
    proving.
    c                     | j                   j                         D cg c]  }| }}| j                   j                         }t        ||      }|D cg c]  }| j	                  ||       c}S c c}w c c}w r!   )_commandr)   r(   r+   replace_quants)selfr$   r)   r(   domainexs         r   r)   zClosedDomainProver.assumptions8   sp    "&--";";"=>"=Qq"=>}}!!#D+.:EF+B##B/+FF ? Gs   	A.A3c                     | j                   j                         }t        || j                   j                               }| j	                  ||      S r!   )r/   r(   r+   r)   r0   )r1   r(   r2   s      r   r(   zClosedDomainProver.goal>   s@    }}!!#D$--";";"=>""400r   c           	         t        |t              rh|D cg c]1  }|j                  j                  |j                  t        |            3 }}|D cg c]  }| j                  ||       }}t        d |      S t        |t              rF|j                  | j                  |j                  |      | j                  |j                  |            S t        |t              r| j                  |j                  |       S t        |t              rh|D cg c]1  }|j                  j                  |j                  t        |            3 }}|D cg c]  }| j                  ||       }}t        d |      S |S c c}w c c}w c c}w c c}w )a  
        Apply the closed domain assumption to the expression

        - Domain = union([e.free()|e.constants() for e in all_expressions])
        - translate "exists x.P" to "(z=d1 | z=d2 | ... ) & P.replace(x,z)" OR
                    "P.replace(x, d1) | P.replace(x, d2) | ..."
        - translate "all x.P" to "P.replace(x, d1) & P.replace(x, d2) & ..."

        :param ex: ``Expression``
        :param domain: set of {Variable}s
        :return: ``Expression``
        c                     | |z  S r!   r   xys     r   <lambda>z3ClosedDomainProver.replace_quants.<locals>.<lambda>U       q1ur   c                     | |z  S r!   r   r7   s     r   r:   z3ClosedDomainProver.replace_quants.<locals>.<lambda>b   r;   r   )
isinstancer
   termreplacevariabler   r0   r   r   	__class__firstsecondr   r   )r1   r3   r2   d	conjunctsc	disjunctss          r   r0   z!ClosedDomainProver.replace_quantsC   so    b-(MSMS-?-BCV   BKKA,,Q7IK,i88-.<<##BHHf5##BIIv6  -.''888,-MSMS-?-BCV   BKKA,,Q7IK,i88I' L Ls   6E6E;6F FN)r   r   r   __doc__r)   r(   r0   r   r   r   r-   r-   2   s    
G1
!r   r-   c                       e Zd ZdZd Zy)UniqueNamesProverz[
    This is a prover decorator that adds unique names assumptions before
    proving.
    c                 p   | j                   j                         }t        t        | j                   j	                         |            }t               }|D ]S  }t        |t              s|j                  j                  }|j                  j                  }||   j                  |       U g }t        |      D ]y  \  }}||dz   d D ]i  }	|	||   vst        t        |      t        |	            }
t               j                  |
|      r||   j                  |	       X|j!                  |
        k { ||z   S )z
        - Domain = union([e.free()|e.constants() for e in all_expressions])
        - if "d1 = d2" cannot be proven from the premises, then add "d1 != d2"
           N)r/   r)   listr+   r(   	SetHolderr=   r   rB   r@   rC   add	enumerater   r   proveappend)r1   r)   r2   eq_setsr$   avbvnew_assumptionsibnewEqExs              r   r)   zUniqueNamesProver.assumptionsm   s   
 mm//1j!3!3!5{CD +A!/0WW%%XX&&#  f%DAqAEG_GAJ&0*1-/A!/DG yw<  
q) (..x8 % & _,,r   N)r   r   r   rH   r)   r   r   r   rJ   rJ   g   s    
"-r   rJ   c                       e Zd ZdZd Zy)rN   z&
    A list of sets of Variables.
    c                 p    t        |t              sJ | D ]
  }||v s|c S  |h}| j                  |       |S )zV
        :param item: ``Variable``
        :return: the set containing 'item'
        )r=   r   rR   )r1   itemsnews       r   __getitem__zSetHolder.__getitem__   sD    
 $)))Aqy  fC
r   N)r   r   r   rH   r_   r   r   r   rN   rN      s    r   rN   c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)ClosedWorldProvera  
    This is a prover decorator that completes predicates before proving.

    If the assumptions contain "P(A)", then "all x.(P(x) -> (x=A))" is the completion of "P".
    If the assumptions contain "all x.(ostrich(x) -> bird(x))", then "all x.(bird(x) -> ostrich(x))" is the completion of "bird".
    If the assumptions don't contain anything that are "P", then "all x.-P(x)" is the completion of "P".

    walk(Socrates)
    Socrates != Bill
    + all x.(walk(x) -> (x=Socrates))
    ----------------
    -walk(Bill)

    see(Socrates, John)
    see(John, Mary)
    Socrates != John
    John != Mary
    + all x.all y.(see(x,y) -> ((x=Socrates & y=John) | (x=John & y=Mary)))
    ----------------
    -see(Socrates, Mary)

    all x.(ostrich(x) -> bird(x))
    bird(Tweety)
    -ostrich(Sam)
    Sam != Tweety
    + all x.(bird(x) -> (ostrich(x) | x=Tweety))
    + all x.-ostrich(x)
    -------------------
    -bird(Sam)
    c           	      (   | j                   j                         }| j                  |      }g }|D ]V  }||   }| j                  |      }|D cg c]  }t	        |       }}g }	|j
                  D ]O  }
g }t        ||
      D ]   \  }}|j                  t        ||             " |	j                  t        d |             Q |j                  D ]C  }i }t        ||d         D ]
  \  }}|||<    |	j                  |d   j                  |             E |	r,| j                  ||      }t        d |	      }t        ||      }nt        | j                  ||            }|d d d   D ]  }t        ||      } |j                  |       Y ||z   S c c}w )Nc                     | |z  S r!   r   r7   s     r   r:   z/ClosedWorldProver.assumptions.<locals>.<lambda>   s    QUr   r   rL   c                     | |z  S r!   r   r7   s     r   r:   z/ClosedWorldProver.assumptions.<locals>.<lambda>   s    Qr   )r/   r)   _make_predicate_dict_make_unique_signaturer   
signaturesziprR   r   r   
propertiessubstitute_bindings_make_antecedentr   r   r
   )r1   r)   
predicatesrV   p
predHoldernew_sigvnew_sig_exsrG   sigequality_exsv1v2propbindings
antecedent
consequentaccumnew_sig_vars                       r   r)   zClosedWorldProver.assumptions   s   mm//1..{;
A#AJ11*=G:AB'Q-a0'KBI ",,!!+s3FB ''(:2r(BC 4  (:L!IJ	 - #--!+tAw7FB#%HRL 8  a!<!<X!FG . !221g>
#$6	B
%j*= *$*?*?7*KL  'tt}%k59  -""5)G J _,,E Cs   Fc                 L    t        d t        |j                        D              S )z
        This method figures out how many arguments the predicate takes and
        returns a tuple containing that number of unique variables.
        c              3   0   K   | ]  }t                 y wr!   )r   )r#   rW   s     r   r%   z;ClosedWorldProver._make_unique_signature.<locals>.<genexpr>   s     P0O1_&0Os   )tuplerangesignature_len)r1   ro   s     r   rg   z(ClosedWorldProver._make_unique_signature   s     
 Pj6N6N0OPPPr   c                 :    |}|D ]  } |t        |            } |S )z
        Return an application expression with 'predicate' as the predicate
        and 'signature' as the list of arguments.
        )r   )r1   	predicate	signaturery   rq   s        r   rl   z"ClosedWorldProver._make_antecedent   s)    
 
A#$6q$9:J r   c                 V    t        t              }|D ]  }| j                  ||        |S )z
        Create a dictionary of predicates from the assumptions.

        :param assumptions: a list of ``Expression``s
        :return: dict mapping ``AbstractVariableExpression`` to ``PredHolder``
        )r   
PredHolder_map_predicates)r1   r)   rm   r$   s       r   rf   z&ClosedWorldProver._make_predicate_dict  s.     !,
A  J/ r   c                 n   t        |t              rB|j                         \  }}t        |t              r||   j	                  t        |             y y t        |t              r9| j                  |j                  |       | j                  |j                  |       y t        |t              r|j                  g}|j                  }t        |t              r8|j                  |j                         |j                  }t        |t              r8t        |t              rt        |j                  t              rt        |j                  t              r|j                  j                         \  }}|j                  j                         \  }	}
t        |t              rt        |	t              rz||D cg c]  }|j                   c}k(  r\||
D cg c]  }|j                   c}k(  r>||	   j                  t        |      |j                  f       ||   j!                  |       y y y y y y y y y c c}w c c}w r!   )r=   r   uncurryr	   
append_sigr   r   r   rB   rC   r
   r@   r>   rR   r   append_propvalidate_sig_len)r1   
expressionpredDictfuncargsrs   r>   func1args1func2args2rq   s               r   r   z!ClosedWorldProver._map_predicates  s   j"78#++-JD$$ :;))%+6 <
M2  !1!18<  !2!2H=
M2&&'C??DT=1

4==)yy T=1 $.djj*?@ZKK!6F $(::#5#5#7LE5#';;#6#6#8LE5"5*DE&u.HI#>1AJJ#>>#>1AJJ#>> 33U3Z4LM 88= ? ? J FF@ / 3  $?#>s   2H-H2N)	r   r   r   rH   r)   rg   rl   rf   r   r   r   r   ra   ra      s"    >+-ZQ
>r   ra   c                   4    e Zd ZdZd Zd Zd Zd Zd Zd Z	y)	r   a  
    This class will be used by a dictionary that will store information
    about predicates to be used by the ``ClosedWorldProver``.

    The 'signatures' property is a list of tuples defining signatures for
    which the predicate is true.  For instance, 'see(john, mary)' would be
    result in the signature '(john,mary)' for 'see'.

    The second element of the pair is a list of pairs such that the first
    element of the pair is a tuple of variables and the second element is an
    expression of those variables that makes the predicate true.  For instance,
    'all x.all y.(see(x,y) -> know(x,y))' would result in "((x,y),('see(x,y)'))"
    for 'know'.
    c                 .    g | _         g | _        d | _        y r!   rh   rj   r   r1   s    r   __init__zPredHolder.__init__?  s    !r   c                 \    | j                  |       | j                  j                  |       y r!   )r   rh   rR   r1   rp   s     r   r   zPredHolder.append_sigD  s"    g&w'r   c                 b    | j                  |d          | j                  j                  |       y )Nr   )r   rj   rR   )r1   new_props     r   r   zPredHolder.append_propH  s&    hqk*x(r   c                     | j                   t        |      | _         y | j                   t        |      k7  rt        d      y )NzSignature lengths do not match)r   len	Exceptionr   s     r   r   zPredHolder.validate_sig_lenL  s=    %!$WD3w</<== 0r   c                 V    d| j                    d| j                   d| j                   dS )N(,)r   r   s    r   __str__zPredHolder.__str__R  s.    4??#1T__$5Qt7I7I6J!LLr   c                     d| z  S )Nz%sr   r   s    r   __repr__zPredHolder.__repr__U  s    d{r   N)
r   r   r   rH   r   r   r   r   r   r   r   r   r   r   r   /  s&    "
()>Mr   r   c                     t         j                  }  | d      } | d      } | d      }t        |||g      }t        |j	                                t        |      }t        d       |j                         D ]  }t        d|        t        d|j                                t        |j	                                 | d      } | d      } | d      } | d      }t        ||||g      }t        |j	                                t        |      }t        d       |j                         D ]  }t        d|        t        d|j                                t        |j	                                 | d      } | d      } | d      } | d      }t        ||||g      }t        |j	                                t        |      }t        d       |j                         D ]  }t        d|        t        d|j                                t        |j	                                 | d      } | d      } | d	      }t        |||g      }t        |j	                                t        |      }t        d       |j                         D ]  }t        d|        t        d|j                                t        |j	                                 | d
      } | d      } | d      } | d      } | d      }	 | d      }t        ||||||	g      }t        |j	                                t        |      }t        d       |j                         D ]  }t        d|        t        d|j                                t        |j	                                y )Nzexists x.walk(x)man(Socrates)walk(Socrates)assumptions:   goal:-walk(Bill)z
walk(Bill)zall x.walk(x)z
girl(mary)z
dog(rover)zall x.(girl(x) -> -dog(x))zall x.(dog(x) -> -girl(x))zchase(mary, rover)z1exists y.(dog(y) & all x.(girl(x) -> chase(x,y))))r   
fromstringr   printrQ   r-   r)   r(   )
lexprp1p2rF   provercdpr$   p3p4p5s
             r   closed_domain_demor   Y  s   !!E	"	#B		 B AABx(F	&,,.
V
$C	.__eQ 	'388:	#))+	"	#B		 B	~	B AAB|,F	&,,.
V
$C	.__eQ 	'388:	#))+	"	#B		 B	~	B AAB|,F	&,,.
V
$C	.__eQ 	'388:	#))+	 	!B	}	BAABx(F	&,,.
V
$C	.__eQ 	'388:	#))+	}	B	}	B	,	-B	,	-B	$	%BBCAABB34F	&,,.
V
$C	.__eQ 	'388:	#))+r   c                     t         j                  }  | d      } | d      } | d      }t        |||g      }t        |j	                                t        |      }t        d       |j                         D ]  }t        d|        t        d|j                                t        |j	                                 | d      } | d      } | d	      } | d
      }t        ||||g      }t        |j	                                t        |      }t        d       |j                         D ]  }t        d|        t        d|j                                t        |j	                                y )Nr   z	man(Bill)zexists x.exists y.(x != y)r   r   r   z!all x.(walk(x) -> (x = Socrates))zBill = WilliamzBill = Billyz-walk(William))r   r   r   r   rQ   rJ   r)   r(   )r   r   r   rF   r   unpr$   r   s           r   unique_names_demor     s*   !!E		 B	|	B+,AABx(F	&,,.
F
#C	.__eQ 	'388:	#))+	3	4B	 	!B		B AAB|,F	&,,.
F
#C	.__eQ 	'388:	#))+r   c                  b   t         j                  }  | d      } | d      } | d      }t        |||g      }t        |j	                                t        |      }t        d       |j                         D ]  }t        d|        t        d|j                                t        |j	                                 | d      } | d      } | d	      } | d
      } | d      }t        |||||g      }t        |j	                                t        |      }t        d       |j                         D ]  }t        d|        t        d|j                                t        |j	                                 | d      } | d      } | d      } | d      } | d      }t        |||||g      }t        |j	                                t        |      }t        d       |j                         D ]  }t        d|        t        d|j                                t        |j	                                y )Nr   z(Socrates != Bill)r   r   r   r   see(Socrates, John)see(John, Mary)z(Socrates != John)z(John != Mary)-see(Socrates, Mary)zall x.(ostrich(x) -> bird(x))zbird(Tweety)z-ostrich(Sam)zSam != Tweetyz
-bird(Sam))r   r   r   r   rQ   ra   r)   r(   )	r   r   r   rF   r   cwpr$   r   r   s	            r   closed_world_demor     s   !!E	 	!B	$	%BnAABx(F	&,,.
F
#C	.__eQ 	'388:	#))+	%	&B	!	"B	$	%B	 	!B%&AABB/0F	&,,.
F
#C	.__eQ 	'388:	#))+	/	0B		B		 B		 BmAABB/0F	&,,.
F
#C	.__eQ 	'388:	#))+r   c                  N   t         j                  }  | d      } | d      } | d      }t        |||g      }t        |j	                                t        t        t        |                  }|j                         D ]  }t        |        t        |j	                                y )Nr   r   r   )	r   r   r   r   rQ   r-   rJ   ra   r)   )r   r   r   rF   r   commandr$   s          r   combination_prover_demor     s    !!E	%	&B	!	"B%&AABx(F	&,,. !23DV3L!MNG  "a #	'--/r   c                  t   t         j                  } g }|j                   | d             |j                   | d             |j                   | d             |j                   | d             |j                   | d             |j                   | d             |j                   | d             |j                   | d             |j                   | d	             |j                   | d
             |j                   | d             |j                   | d             |j                   | d             |j                   | d             t        d |      }t	        t        |            }|j                         D ]  }t        |        t        d|       t        d|       t        d|       y )Nz'all x.(elephant(x)        -> animal(x))z'all x.(bird(x)            -> animal(x))z%all x.(dove(x)            -> bird(x))z%all x.(ostrich(x)         -> bird(x))z(all x.(flying_ostrich(x)  -> ostrich(x))z)all x.((animal(x)  & -Ab1(x)) -> -fly(x))z(all x.((bird(x)    & -Ab2(x)) -> fly(x))z)all x.((ostrich(x) & -Ab3(x)) -> -fly(x))z#all x.(bird(x)           -> Ab1(x))z#all x.(ostrich(x)        -> Ab2(x))z#all x.(flying_ostrich(x) -> Ab3(x))zelephant(E)zdove(D)z
ostrich(O)z-fly(E)zfly(D)z-fly(O))	r   r   rR   r   rJ   ra   r)   r   print_proof)r   premisesr   r   r$   s        r   default_reasoning_demor     sx   !!EH OOEDEFOOEDEFOOEBCDOOEBCDOOEEFG OO:; OO9: OO:;
 OOE@ABOOE@ABOOE@AB OOE.)*OOE*%&OOE-() D(+F 1& 9:G  "a # 	8$(#	8$r   c                     t         j                  }t         ||       |      }t        t	        |            }t        | |j                         |j                                y r!   )r   r   r   rJ   ra   r   rQ   )r(   r   r   r   r   s        r   r   r   !  sE    !!EE$K2F 1& 9:G	$0r   c                  h    t                t                t                t                t	                y r!   )r   r   r   r   r   r   r   r   demor   (  s     r   __main__N)+rH   collectionsr   	functoolsr   nltk.inference.apir   r   nltk.inference.prover9r   r   nltk.sem.logicr	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r+   r-   rJ   rM   rN   ra   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      s    $  = :   $	y 	Q2/ 2j(-. (-V (F>. F>R' 'TBJ:)X)%X1 zF r   