
    QdJ                     |   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)             dS dS )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dS )ProverParseErrorN)__name__
__module____qualname__     ;lib/python3.11/site-packages/nltk/inference/nonmonotonic.pyr   r   &   s        Dr   r   c                 |    | |}n||  gz   }t          t          j        d |D             t                                S )Nc              3   >   K   | ]}|                                 V  d S N)	constants.0as     r   	<genexpr>zget_domain.<locals>.<genexpr>/   s*       H H1 H H H H H Hr   )r   r   or_set)goalassumptionsall_expressionss      r   
get_domainr,   *   sC    |%%$/(, H H H H H#%%PPPr   c                   $    e Zd ZdZd Zd Zd ZdS )ClosedDomainProverz]
    This is a prover decorator that adds domain closure assumptions before
    proving.
    c                      d  j                                         D             } j                                         }t          ||           fd|D             S )Nc                     g | ]}|S r   r   r#   s     r   
<listcomp>z2ClosedDomainProver.assumptions.<locals>.<listcomp>9   s    >>>Qq>>>r   c                 <    g | ]}                     |          S r   replace_quants)r$   exdomainselfs     r   r1   z2ClosedDomainProver.assumptions.<locals>.<listcomp><   s)    FFFB##B//FFFr   )_commandr*   r)   r,   )r7   r*   r)   r6   s   `  @r   r*   zClosedDomainProver.assumptions8   sd    >>$-";";"="=>>>}!!##D+..FFFFF+FFFFr   c                     | j                                         }t          || j                                                   }|                     ||          S r!   )r8   r)   r,   r*   r4   )r7   r)   r6   s      r   r)   zClosedDomainProver.goal>   sH    }!!##D$-";";"="=>>""4000r   c                 4    t          t                    r.fdD             } fd|D             }t          d |          S t          t                    rH                                         j                                       j                            S t          t                    r                     j	                   S t          t                    r.fdD             } fd|D             }t          d |          S S )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                 j    g | ]/}j                             j        t          |                    0S r   termreplacevariabler   r$   dr5   s     r   r1   z5ClosedDomainProver.replace_quants.<locals>.<listcomp>Q   A       HI-?-B-BCC  r   c                 <    g | ]}                     |          S r   r3   )r$   cr6   r7   s     r   r1   z5ClosedDomainProver.replace_quants.<locals>.<listcomp>T   )    KKKA,,Q77KKKr   c                     | |z  S r!   r   xys     r   <lambda>z3ClosedDomainProver.replace_quants.<locals>.<lambda>U   
    q1u r   c                 j    g | ]/}j                             j        t          |                    0S r   r<   r@   s     r   r1   z5ClosedDomainProver.replace_quants.<locals>.<listcomp>^   rB   r   c                 <    g | ]}                     |          S r   r3   )r$   rA   r6   r7   s     r   r1   z5ClosedDomainProver.replace_quants.<locals>.<listcomp>a   rE   r   c                     | |z  S r!   r   rG   s     r   rJ   z3ClosedDomainProver.replace_quants.<locals>.<lambda>b   rK   r   )
isinstancer
   r   r   	__class__r4   firstsecondr   r=   r   )r7   r5   r6   	conjuncts	disjunctss   ```  r   r4   z!ClosedDomainProver.replace_quantsC   sj    b-(( 	   MS  I LKKKKKKKI,,i888-.. 	<<##BHf55##BIv66   -.. 		''8888,-- 	   MS  I LKKKKKKKI,,i888Ir   N)r   r   r   __doc__r*   r)   r4   r   r   r   r.   r.   2   sN         
G G G1 1 1
! ! ! ! !r   r.   c                       e Zd ZdZd ZdS )UniqueNamesProverz[
    This is a prover decorator that adds unique names assumptions before
    proving.
    c                    | j                                         }t          t          | j                                         |                    }t                      }|D ]J}t          |t                    r3|j        j	        }|j
        j	        }||                             |           Kg }t          |          D ]\  }}||dz   d         D ]}	|	||         vr~t          t          |          t          |	                    }
t                                          |
|          r||                             |	           t|                    |
            ||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)r8   r*   listr,   r)   	SetHolderrO   r   rQ   r?   rR   add	enumerater   r   proveappend)r7   r*   r6   eq_setsr%   avbvnew_assumptionsibnewEqExs              r   r*   zUniqueNamesProver.assumptionsm   se   
 m//11j!3!3!5!5{CCDD ++ 	$ 	$A!/00 $W%X&###f%% 	9 	9DAqAEGG_ 9 9GAJ&&0*1--/A!/D/D G yyw<< 9  
q)))) (..x8889 _,,r   N)r   r   r   rU   r*   r   r   r   rW   rW   g   s-         
"- "- "- "- "-r   rW   c                       e Zd ZdZd ZdS )r[   z&
    A list of sets of Variables.
    c                 ~    t          |t                    sJ | D ]
}||v r|c S |h}|                     |           |S )zV
        :param item: ``Variable``
        :return: the set containing 'item'
        )rO   r   r_   )r7   itemsnews       r   __getitem__zSetHolder.__getitem__   s`    
 $))))) 	 	Aqyy  fC
r   N)r   r   r   rU   rl   r   r   r   r[   r[      s-             r   r[   c                   0    e Zd ZdZd Zd Zd Zd Zd ZdS )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           	      x   | j                                         }|                     |          }g }|D ]}||         }|                     |          }d |D             }g }|j        D ]a}	g }
t          ||	          D ](\  }}|
                    t          ||                     )|                    t          d |
                     b|j	        D ]S}i }t          ||d                   D ]
\  }}|||<   |                    |d         
                    |                     T|r8|                     ||          }t          d |          }t          ||          }n#t          |                     ||                    }|d d d         D ]}t          ||          }|                    |           ||z   S )Nc                 ,    g | ]}t          |          S r   r   r$   vs     r   r1   z1ClosedWorldProver.assumptions.<locals>.<listcomp>   s!    BBBQ-a00BBBr   c                     | |z  S r!   r   rG   s     r   rJ   z/ClosedWorldProver.assumptions.<locals>.<lambda>   s
    QU r   r   rY   c                     | |z  S r!   r   rG   s     r   rJ   z/ClosedWorldProver.assumptions.<locals>.<lambda>   s
    Q r   )r8   r*   _make_predicate_dict_make_unique_signature
signatureszipr_   r   r   
propertiessubstitute_bindings_make_antecedentr   r   r
   )r7   r*   
predicatesrc   p
predHoldernew_signew_sig_exsrT   sigequality_exsv1v2propbindings
antecedent
consequentaccumnew_sig_vars                      r   r*   zClosedWorldProver.assumptions   s   m//11..{;;
 #	* #	*A#AJ11*==GBB'BBBKI ", K K!!+s33 D DFB ''(:2r(B(BCCCC  (:(:L!I!IJJJJ #- H H!+tAw77 & &FB#%HRLL  a!<!<X!F!FGGGG  M!221g>>
#$6$6	BB
%j*== *$*?*?7*K*KLL  'ttt} : :%k599""5))))_,,r   c                 X    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   2   K   | ]}t                      V  d S r!   )r   )r$   rd   s     r   r&   z;ClosedWorldProver._make_unique_signature.<locals>.<genexpr>   s(      PP1_&&PPPPPPr   )tuplerangesignature_len)r7   r   s     r   rx   z(ClosedWorldProver._make_unique_signature   s,    
 PPj6N0O0OPPPPPPr   c                 D    |}|D ]} |t          |                    }|S )z
        Return an application expression with 'predicate' as the predicate
        and 'signature' as the list of arguments.
        rq   )r7   	predicate	signaturer   rs   s        r   r}   z"ClosedWorldProver._make_antecedent   s8    
 
 	; 	;A#$6q$9$9::JJr   c                 d    t          t                    }|D ]}|                     ||           |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)r7   r*   r~   r%   s       r   rw   z&ClosedWorldProver._make_predicate_dict  s?     !,,
 	0 	0A  J////r   c                    t          |t                    rX|                                \  }}t          |t                    r*||                             t          |                     d S d S t          |t                    r8|                     |j        |           |                     |j	        |           d S t          |t                    rr|j        g}|j        }t          |t                    r6|                    |j                   |j        }t          |t                    6t          |t                    rt          |j        t                    rt          |j	        t                    r|j                                        \  }}|j	                                        \  }	}
t          |t                    rt          |	t                    rv|d |D             k    rh|d |
D             k    rZ||	                             t          |          |j        f           ||                             |           d S d S d S d S d S d S d S d S d S )Nc                     g | ]	}|j         
S r   r?   rr   s     r   r1   z5ClosedWorldProver._map_predicates.<locals>.<listcomp>(      #>#>#>1AJ#>#>#>r   c                     g | ]	}|j         
S r   r   rr   s     r   r1   z5ClosedWorldProver._map_predicates.<locals>.<listcomp>)  r   r   )rO   r   uncurryr	   
append_sigr   r   r   rQ   rR   r
   r?   r=   r_   r   append_propvalidate_sig_len)r7   
expressionpredDictfuncargsr   r=   func1args1func2args2s              r   r   z!ClosedWorldProver._map_predicates  sw   j"788 	>#++--JD$$ :;; 7))%++666667 7
M22 	>  !18<<<  !2H=====
M22 	>&'C?DT=11 !

4=)))y T=11 ! $.. >dj*?@@ >ZK!6F F > $(:#5#5#7#7LE5#';#6#6#8#8LE5"5*DEE>&u.HII>  #>#>#>#>#>>>#>#>#>#>#>>> 33U3ZZ4LMMM 88=====)	> 	>> >> > > >
> > > > ?>>>r   N)	r   r   r   rU   r*   rx   r}   rw   r   r   r   r   rn   rn      sm         >+- +- +-ZQ Q Q  
 
 
> > > > >r   rn   c                   6    e Zd ZdZd Zd Zd Zd Zd Zd Z	dS )	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                 0    g | _         g | _        d | _        d S r!   ry   r{   r   r7   s    r   __init__zPredHolder.__init__?  s    !r   c                 d    |                      |           | j                            |           d S r!   )r   ry   r_   r7   r   s     r   r   zPredHolder.append_sigD  s2    g&&&w'''''r   c                 p    |                      |d                    | j                            |           d S )Nr   )r   r{   r_   )r7   new_props     r   r   zPredHolder.append_propH  s6    hqk***x(((((r   c                     | j         t          |          | _         d S | j         t          |          k    rt          d          d S )NzSignature lengths do not match)r   len	Exceptionr   s     r   r   zPredHolder.validate_sig_lenL  sJ    %!$WD3w<<//<=== 0/r   c                 8    d| j          d| j         d| j         dS )N(,)r   r   s    r   __str__zPredHolder.__str__R  s*    L4?LLT_LLt7ILLLLr   c                     d| z  S )Nz%sr   r   s    r   __repr__zPredHolder.__repr__U  s    d{r   N)
r   r   r   rU   r   r   r   r   r   r   r   r   r   r   r   /  s{         " " "
( ( () ) )> > >M M M    r   r   c                  .	   t           j        }  | d          } | d          } | d          }t          |||g          }t          |                                           t          |          }t          d           |                                D ]}t          d|           t          d|                                           t          |                                            | d          } | d          } | d          } | d          }t          ||||g          }t          |                                           t          |          }t          d           |                                D ]}t          d|           t          d|                                           t          |                                            | d          } | d          } | d          } | d          }t          ||||g          }t          |                                           t          |          }t          d           |                                D ]}t          d|           t          d|                                           t          |                                            | d          } | d          } | d	          }t          |||g          }t          |                                           t          |          }t          d           |                                D ]}t          d|           t          d|                                           t          |                                            | d
          } | d          } | d          } | d          } | d          }	 | d          }t          ||||||	g          }t          |                                           t          |          }t          d           |                                D ]}t          d|           t          d|                                           t          |                                           d S )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   printr^   r.   r*   r)   )
lexprp1p2rD   provercdpr%   p3p4p5s
             r   closed_domain_demor   Y  sX   !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CCAABB344F	&,,..
V
$
$C	.__  eQ	'388::	#))++r   c                     t           j        }  | d          } | d          } | d          }t          |||g          }t          |                                           t          |          }t          d           |                                D ]}t          d|           t          d|                                           t          |                                            | d          } | d          } | d	          } | d
          }t          ||||g          }t          |                                           t          |          }t          d           |                                D ]}t          d|           t          d|                                           t          |                                           d S )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   r^   rW   r*   r)   )r   r   r   rD   r   unpr%   r   s           r   unique_names_demor     s   !E		 	 B	|		B+,,AABx((F	&,,..
F
#
#C	.__  eQ	'388::	#))++	3	4	4B	 	!	!B			B  AAB|,,F	&,,..
F
#
#C	.__  eQ	'388::	#))++r   c                     t           j        }  | d          } | d          } | d          }t          |||g          }t          |                                           t          |          }t          d           |                                D ]}t          d|           t          d|                                           t          |                                            | d          } | d          } | d	          } | d
          } | d          }t          |||||g          }t          |                                           t          |          }t          d           |                                D ]}t          d|           t          d|                                           t          |                                            | d          } | d          } | d          } | d          } | d          }t          |||||g          }t          |                                           t          |          }t          d           |                                D ]}t          d|           t          d|                                           t          |                                           d S )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   r^   rn   r*   r)   )	r   r   r   rD   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/00F	&,,..
F
#
#C	.__  eQ	'388::	#))++	/	0	0B			B		 	 B		 	 BmAABB/00F	&,,..
F
#
#C	.__  eQ	'388::	#))++r   c                     t           j        }  | d          } | d          } | d          }t          |||g          }t          |                                           t          t          t          |                              }|                                D ]}t          |           t          |                                           d S )Nr   r   r   )	r   r   r   r   r^   r.   rW   rn   r*   )r   r   r   rD   r   commandr%   s          r   combination_prover_demor     s    !E	%	&	&B	!	"	"B%&&AABx((F	&,,.. !23DV3L3L!M!MNNG  ""  a	'--//r   c                  n   t           j        } g }|                     | d                     |                     | d                     |                     | d                     |                     | d                     |                     | d                     |                     | d                     |                     | d                     |                     | d                     |                     | d	                     |                     | d
                     |                     | d                     |                     | d                     |                     | d                     |                     | d                     t          d |          }t	          t          |                    }|                                D ]}t          |           t          d|           t          d|           t          d|           d S )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   r_   r   rW   rn   r*   r   print_proof)r   premisesr   r   r%   s        r   default_reasoning_demor     sH   !EH OOEEDEEFFFOOEEDEEFFFOOEEBCCDDDOOEEBCCDDDOOEEEFFGGG OO:;;   OO9::   OO:;;  
 OOEE@AABBBOOEE@AABBBOOEE@AABBB OOEE.))***OOEE*%%&&&OOEE-(())) D(++F 1& 9 9::G  ""  a	8$$$(###	8$$$$$r   c                     t           j        }t           ||           |          }t          t	          |                    }t          | |                                |                                           d S r!   )r   r   r   rW   rn   r   r^   )r)   r   r   r   r   s        r   r   r   !  s_    !EEE$KK22F 1& 9 9::G	$00000r   c                      t                       t                       t                       t                       t	                       d S r!   )r   r   r   r   r   r   r   r   demor   (  sD    r   __main__N)+rU   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.   rW   rZ   r[   rn   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      s    $ # # # # #       = = = = = = = = : : : : : : : :                               $	 	 	 	 	y 	 	 	Q Q Q2 2 2 2 2/ 2 2 2j(- (- (- (- (-. (- (- (-V       (F> F> F> F> F>. F> F> F>R' ' ' ' ' ' ' 'TB B BJ  :) ) )X  )% )% )%X1 1 1   zDFFFFF r   