3
d}e                 @   sr  d Z ddlZddlZddlZddlZddlmZ ddl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mZ G dd deZG dd	 d	eZd
d Zdd Zdd Zdd ZG dd de Z!ej"dZ#ej"dZ$ej"dej%Z&dd Z'd.ddZ(G dd de Z)G dd dZ*dZ+d/d d!Z,d0d#d$Z-d1d%d&Z.d2d'd(Z/d3d)d*Z0e1d+krne0d,dd- dS )4zK
This module provides data structures for representing first-order
models.
    N)pformat)	decorator)AbstractVariableExpressionAllExpressionAndExpressionApplicationExpressionEqualityExpressionExistsExpression
ExpressionIffExpressionImpExpressionIndividualVariableExpressionLambdaExpressionNegatedExpressionOrExpressionVariable	is_indvarc               @   s   e Zd ZdS )ErrorN)__name__
__module____qualname__ r   r   1/tmp/pip-build-v9q4h5k9/nltk/nltk/sem/evaluate.pyr   +   s   r   c               @   s   e Zd ZdS )	UndefinedN)r   r   r   r   r   r   r   r   /   s   r   c             O   sV   t j| }tt|d |}|jdd rLt  x|j D ]}td|  q8W | ||S )Nr   tracez%s => %s)inspectZgetfullargspecdictzippopprintitems)fargskwZargspecditemr   r   r   r   3   s    
r   c             C   sN   t | dkrdS tdd | D r>t t| t t| kr>dS td|  dS )z
    Check whether a set represents a relation (of any arity).

    :param s: a set containing tuples of str elements
    :type s: set
    :rtype: bool
    r   Tc             s   s   | ]}t |tV  qd S )N)
isinstancetuple).0elr   r   r   	<genexpr>I   s    zis_rel.<locals>.<genexpr>z.Set %r contains sequences of different lengthsN)lenallmaxmin
ValueError)sr   r   r   is_rel=   s
    	*r1   c             C   sT   t  }xH| D ]@}t|tr(|j|f qt|trB|jt| q|j| qW |S )aR  
    Convert a set containing individuals (strings or numbers) into a set of
    unary tuples. Any tuples of strings already in the set are passed through
    unchanged.

    For example:
      - set(['a', 'b']) => set([('a',), ('b',)])
      - set([3, 27]) => set([('3',), ('27',)])

    :type s: set
    :rtype: set of tuple of str
    )setr&   straddint)r0   newelemr   r   r   set2relO   s    


r8   c             C   s    t | dkrdS t t| d S )ze
    Check the arity of a relation.
    :type rel: set of tuples
    :rtype: int of tuple of str
    r   )r+   list)relr   r   r   arityg   s    r;   c                   sT   e Zd ZdZ fddZdd Zdd Zedd	 Zed
d Z	e
dd Z  ZS )	Valuationa  
    A dictionary which represents a model-theoretic Valuation of non-logical constants.
    Keys are strings representing the constants to be interpreted, and values correspond
    to individuals (represented as strings) and n-ary relations (represented as sets of tuples
    of strings).

    An instance of ``Valuation`` will raise a KeyError exception (i.e.,
    just behave like a standard  dictionary) if indexed with an expression that
    is not in its list of symbols.
    c                st   t  j  xd|D ]\\}}t|ts,t|tr6|| |< qt|trNt|| |< qtjd||f dd}t	|qW dS )z=
        :param xs: a list of (symbol, value) pairs.
        zGError in initializing Valuation. Unrecognized value for symbol '%s':
%sB   )widthN)
super__init__r&   r3   boolr2   r8   textwrapfillr/   )selfxssymvalmsg)	__class__r   r   r@   ~   s    


zValuation.__init__c             C   s$   || krt j| |S td| d S )NzUnknown expression: '%s')r   __getitem__r   )rD   keyr   r   r   rJ      s    zValuation.__getitem__c             C   s   t | S )N)r   )rD   r   r   r   __str__   s    zValuation.__str__c             C   sR   g }xD| j  D ]8}t|tr(|j| qt|ts|jdd |D  qW t|S )z7Set-theoretic domain of the value-space of a Valuation.c             S   s"   g | ]}|D ]}|d k	r|qqS )Nr   )r(   tuple_r7   r   r   r   
<listcomp>   s    z$Valuation.domain.<locals>.<listcomp>)valuesr&   r3   appendrA   extendr2   )rD   domrG   r   r   r   domain   s    

zValuation.domainc             C   s   t | j S )z9The non-logical constants which the Valuation recognizes.)sortedkeys)rD   r   r   r   symbols   s    zValuation.symbolsc             C   s   t |S )N)read_valuation)clsr0   r   r   r   
fromstring   s    zValuation.fromstring)r   r   r   __doc__r@   rJ   rL   propertyrS   rV   classmethodrY   __classcell__r   r   )rI   r   r<   r   s   
r<   z	\s*=+>\s*z\s*,\s*zg\s*
                                (\([^)]+\))  # tuple-expression
                                \s*c             C   s   t j| }|d }|d }|jdr|dd }tj|}|rvg }x<|D ](}|dd }ttj|}|j| qHW n
tj|}t|}||fS )a  
    Read a line in a valuation file.

    Lines are expected to be of the form::

      noosa => n
      girl => {g1, g2}
      chase => {(b1, g1), (b2, g1), (g1, d1), (g2, d2)}

    :param s: input line
    :type s: str
    :return: a pair (symbol, value)
    :rtype: tuple
    r      {r`   )	_VAL_SPLIT_REsplit
startswith
_TUPLES_REfindallr'   _ELEMENT_SPLIT_RErP   r2   )r0   piecessymbolvalueZtuple_stringsZset_elementstselementr   r   r   _read_valuation_line   s    




rl   c             C   s   |dk	r| j |} g }xt| j D ]p\}}|j }|jds$|dkrHq$y|jt| W q$ tk
r } ztd| d| |W Y dd}~X q$X q$W t|S )a  
    Convert a valuation string into a valuation.

    :param s: a valuation string
    :type s: str
    :param encoding: the encoding of the input string, if it is binary
    :type encoding: str
    :return: a ``nltk.sem`` valuation
    :rtype: Valuation
    N# zUnable to parse line z: )	decode	enumerate
splitlinesstriprc   rP   rl   r/   r<   )r0   encodingZ
statementslinenumlineer   r   r   rW      s    
,rW   c                   sT   e Zd ZdZd fdd	Zdd Zdd Zdd	d
Zdd Zdd Z	dd Z
  ZS )
Assignmentae  
    A dictionary which represents an assignment of values to variables.

    An assignment can only assign values from its domain.

    If an unknown expression *a* is passed to a model *M*\ 's
    interpretation function *i*, *i* will first check whether *M*\ 's
    valuation assigns an interpretation to *a* as a constant, and if
    this fails, *i* will delegate the interpretation of *a* to
    *g*. *g* only assigns values to individual variables (i.e.,
    members of the class ``IndividualVariableExpression`` in the ``logic``
    module. If a variable is not assigned a value by *g*, it will raise
    an ``Undefined`` exception.

    A variable *Assignment* is a mapping from individual variables to
    entities in the domain. Individual variables are usually indicated
    with the letters ``'x'``, ``'y'``, ``'w'`` and ``'z'``, optionally
    followed by an integer (e.g., ``'x0'``, ``'y332'``).  Assignments are
    created using the ``Assignment`` constructor, which also takes the
    domain as a parameter.

        >>> from nltk.sem.evaluate import Assignment
        >>> dom = set(['u1', 'u2', 'u3', 'u4'])
        >>> g3 = Assignment(dom, [('x', 'u1'), ('y', 'u2')])
        >>> g3 == {'x': 'u1', 'y': 'u2'}
        True

    There is also a ``print`` format for assignments which uses a notation
    closer to that in logic textbooks:

        >>> print(g3)
        g[u1/x][u2/y]

    It is also possible to update an assignment using the ``add`` method:

        >>> dom = set(['u1', 'u2', 'u3', 'u4'])
        >>> g4 = Assignment(dom)
        >>> g4.add('x', 'u1')
        {'x': 'u1'}

    With no arguments, ``purge()`` is equivalent to ``clear()`` on a dictionary:

        >>> g4.purge()
        >>> g4
        {}

    :param domain: the domain of discourse
    :type domain: set
    :param assign: a list of (varname, value) associations
    :type assign: list
    Nc                sp   t  j  || _|r^xH|D ]@\}}|| jks>tdj|| jt|sRtd| || |< qW d | _| j  d S )Nz'{}' is not in the domain: {}z-Wrong format for an Individual Variable: '%s')r?   r@   rS   AssertionErrorformatr   variant_addvariant)rD   rS   ZassignvarrG   )rI   r   r   r@   /  s    



zAssignment.__init__c             C   s$   || krt j| |S td| d S )Nz"Not recognized as a variable: '%s')r   rJ   r   )rD   rK   r   r   r   rJ   ?  s    zAssignment.__getitem__c             C   s   t | j}|j|  |S )N)rw   rS   update)rD   r6   r   r   r   copyE  s    

zAssignment.copyc             C   s    |r| |= n| j   | j  dS )z
        Remove one or all keys (i.e. logic variables) from an
        assignment, and update ``self.variant``.

        :param var: a Variable acting as a key for the assignment.
        N)clearr{   )rD   r|   r   r   r   purgeJ  s
    zAssignment.purgec             C   s:   d}t | j}x&|D ]\}}|d| d| d7 }qW |S )zQ
        Pretty printing for assignments. {'x', 'u'} appears as 'g[u/x]'
        g[/])rT   rz   )rD   Zgstringrz   rG   r|   r   r   r   rL   X  s
    
zAssignment.__str__c             C   s:   g }x*| j  D ]}|d |d f}|j| qW || _dS )zK
        Create a more pretty-printable version of the assignment.
        r^   r   N)r    rP   rz   )rD   list_r%   pairr   r   r   r{   c  s    zAssignment._addvariantc             C   sF   || j kst| d| j  t|s2td| || |< | j  | S )zh
        Add a new variable-value pair to the assignment, and update
        ``self.variant``.

        z is not in the domain z-Wrong format for an Individual Variable: '%s')rS   rx   r   r{   )rD   r|   rG   r   r   r   r4   n  s
    zAssignment.add)N)N)r   r   r   rZ   r@   rJ   r~   r   rL   r{   r4   r]   r   r   )rI   r   rw      s   3
rw   c               @   sP   e Zd ZdZdd Zdd Zdd Zdd	d
ZdddZdddZ	dddZ
dS )Modela[  
    A first order model is a domain *D* of discourse and a valuation *V*.

    A domain *D* is a set, and a valuation *V* is a map that associates
    expressions with values in the model.
    The domain of *V* should be a subset of *D*.

    Construct a new ``Model``.

    :type domain: set
    :param domain: A set of entities representing the domain of discourse of the model.
    :type valuation: Valuation
    :param valuation: the valuation of the model.
    :param prop: If this is set, then we are building a propositional    model and don't require the domain of *V* to be subset of *D*.
    c             C   s<   t |tst|| _|| _|j|js8td|j|f d S )NzDThe valuation domain, %s, must be a subset of the model's domain, %s)r&   r2   rx   rS   	valuation
issupersetr   )rD   rS   r   r   r   r   r@     s    zModel.__init__c             C   s   d| j d| jdS )N(z, ))rS   r   )rD   r   r   r   __repr__  s    zModel.__repr__c             C   s   d| j  d| j S )Nz	Domain = z,
Valuation = 
)rS   r   )rD   r   r   r   rL     s    zModel.__str__Nc             C   sz   yBt j|}| j|||d}|r@t  td| d| d|  |S  tk
rt   |rpt  td| d|  dS X dS )aA  
        Read input expressions, and provide a handler for ``satisfy``
        that blocks further propagation of the ``Undefined`` error.
        :param expr: An ``Expression`` of ``logic``.
        :type g: Assignment
        :param g: an assignment to individual variables.
        :rtype: bool or 'Undefined'
        )r   'z' evaluates to z
 under M, z' is undefined under M, r   N)r
   rY   satisfyr   r   )rD   exprr   r   parsedri   r   r   r   evaluate  s    	
zModel.evaluatec                sP  t |trt|j \}}t |trLj| }t fdd|D }||kS j|j }j|j }|| S nt |trj|j	  S t |t
rj|j oj|j S t |trڈj|j p؈j|j S t |trj|j  pj|j S t |tr.j|j j|j kS t |trVj|j j|j kS t |tr j }	x4jD ]*}
|	j|jj|
 j|j	|	srdS qrW dS t |tr j }	x4jD ]*}
|	j|jj|
 j|j	|	rdS qW dS t |tr>i }|jj}x.jD ]$}
j|j	 j||
}|||
< qW |S j| |S dS )a  
        Recursive interpretation function for a formula of first-order logic.

        Raises an ``Undefined`` error when ``parsed`` is an atomic string
        but is not a symbol or an individual variable.

        :return: Returns a truth value or ``Undefined`` if ``parsed`` is        complex, and calls the interpretation function ``i`` if ``parsed``        is atomic.

        :param parsed: An expression of ``logic``.
        :type g: Assignment
        :param g: an assignment to individual variables.
        c             3   s   | ]}j | V  qd S )N)r   )r(   arg)r   rD   r   r   r*     s    z Model.satisfy.<locals>.<genexpr>FTN)r&   r   Zuncurryr   r   r'   functionZargumentr   Ztermr   firstsecondr   r   r   r   r   r~   rS   r4   variablenamer	   r   i)rD   r   r   r   r   Z	argumentsfunvalZargvalsZargvalnew_guZcfr|   rG   r   )r   rD   r   r     sV    




 

zModel.satisfyFc             C   sD   |j j| jjkr| j|j j S t|tr4||j j S td| dS )a  
        An interpretation function.

        Assuming that ``parsed`` is atomic:

        - if ``parsed`` is a non-logical constant, calls the valuation *V*
        - else if ``parsed`` is an individual variable, calls assignment *g*
        - else returns ``Undefined``.

        :param parsed: an ``Expression`` of ``logic``.
        :type g: Assignment
        :param g: an assignment to individual variables.
        :return: a semantic value
        zCan't find a value for %sN)r   r   r   rV   r&   r   r   )rD   r   r   r   r   r   r   r     s
    
zModel.ir   c          	   C   s>  d}|||  }g }t |tr(t|}	n|}	|	|j kr&|r`t  t|| d| d|   x| jD ]}
|j }|j|	j|
 |r|dkr|d }nd}| j	|||}|rt|d|   |dkr|rt|d| d	| d
  qh|j
|
 |rht|d| d	| d|   qhW dd |D }nt|	j d| |S )a  
        Generate the entities from the model's domain that satisfy an open formula.

        :param parsed: an open formula
        :type parsed: Expression
        :param varex: the relevant free individual variable in ``parsed``.
        :type varex: VariableExpression or str
        :param g: a variable assignment
        :type g:  Assignment
        :return: a set of the entities that satisfy ``parsed``.
        z   zOpen formula is 'z' with assignment r^   r   z(trying assignment %s)Fz
value of 'z' under z	 is Falsez is c             S   s   h | ]}|qS r   r   )r(   cr   r   r   	<setcomp>F  s    z#Model.satisfiers.<locals>.<setcomp>z is not free in )r&   r3   r   freer   rS   r~   r4   r   r   rP   r   )rD   r   Zvarexr   r   ZnestingZspacerindent
candidatesr|   r   r   Zlowtraceri   resultr   r   r   
satisfiers  s<    



"zModel.satisfiers)N)N)F)Nr   )r   r   r   rZ   r@   r   rL   r   r   r   r   r   r   r   r   r   {  s   


E
r      c             C   s   t ddd gat atttattat  tdt	  td tdt	  td t  td	t tdt	  d
ddddddddddddddddg}xB|D ]:}| rt  tj
|t|  qtd| dtj
|t  qW dS )!z!Example of a propositional model.PTQRF*zPropositional Formulas Demoz7(Propositional constants treated as nullary predicates)z
Model m1:
z(P & Q)z(P & R)z- Pz- Rz- - Pz	- (P & R)z(P | R)z(R | P)z(R | R)z	(- P | R)z	(P | - P)z(P -> Q)z(P -> R)z(R -> P)z	(P <-> P)z	(R <-> R)z	(P <-> R)zThe value of 'z' is: N)r   T)r   T)r   F)r<   Zval1r2   Zdom1r   m1rw   g1r   multr   )r   Z	sentencessentr   r   r   propdemoV  sD    


r   Fc       
      C   s  d"d#d$dddhfd	dd
hfddhfdd%d&d'd(hfga tt atjatttattd)d*ga| st	  t	dt
  t	d t	dt
  t	dd+dt t	dt dd	dddddg}dd |D }t	  xL|D ]D}yt	d|tj|tf  W q tk
r   t	d|  Y qX qW d,d.d0d2g}x|D ]z\}}yDtjtj|t}tdd |D }	t	| d| d|	|k  W n* tk
r   t	| d| d  Y nX q$W d!S )3zExample of a first-order model.adamb1bettyr   fidod1Zgirlg2boyb2Zdoglovexyr   zModels Demoz
Model m2:
-   
zVariable assignment = walkszc             S   s   g | ]}t j|qS r   )r
   rY   )r(   rv   r   r   r   rN     s    zfolmodel.<locals>.<listcomp>z&The interpretation of '%s' in m2 is %sz-The interpretation of '%s' in m2 is Undefinedc             s   s    | ]}t jtj|tV  qd S )N)m2r   r
   rY   r   )r(   r   r   r   r   r*     s    zfolmodel.<locals>.<genexpr>r   z) evaluates to z) evaluates to UndefinedN)r   r   )r   r   )r   r   )r   r   )r   r   )r   r   )r   r   )r   r   )r   r   z--------------)r   r   r   )r   r   r   r   )r   r   r   r   )r   r   )Zv2r<   Zval2rS   Zdom2r   r   rw   r   r   r   r   r   r
   rY   r'   )
quietr   exprsZparsed_exprsr   ZapplicationsZfunr"   r   Zargsvalr   r   r   folmodel  sN    




 r   c             C   s   t dd t  tdt  td tdt  ddddd	d
ddddddddddddg}xD|D ]<}tj  | r~tj|t|  q^td| dtj|t  q^W dS )zF
    Interpretation of closed expressions in a first-order model.
    T)r   r   zFOL Formulas Demozlove (adam, betty)z(adam = mia)z\x. (boy(x) | girl(x))z\x. boy(x)(adam)z\x y. love(x, y)z\x y. love(x, y)(adam)(betty)z\x y. love(x, y)(adam, betty)z\x y. (boy(x) & love(x, y))z#\x. exists y. (boy(x) & love(x, y))zexists z1. boy(z1)z!exists x. (boy(x) &  -(x = adam))z&exists x. (boy(x) & all y. love(y, x))zall x. (boy(x) | girl(x))z1all x. (girl(x) -> exists y. boy(y) & love(x, y))z3exists x. (boy(x) & all y. (girl(y) -> love(y, x)))z3exists x. (boy(x) & all y. (girl(y) -> love(x, y)))zall x. (dog(x) -> - girl(x))z-exists x. exists y. (love(x, y) & love(x, y))zThe value of 'z' is: N)r   r   r   r   r   r   r   )r   formulasfmlar   r   r   foldemo  s8    

r   c             C   s   t   t dt  t d t dt  tdd ddddd	d
dddddddddddddg}| rft t x|D ]}t | tj| qlW dd |D }x0|D ](}tj  t dj|tj	|dt|  qW dS )z5Satisfiers of an open formula in a first order model.r   zSatisfiers DemoT)r   zboy(x)z(x = x)z(boy(x) | girl(x))z(boy(x) & girl(x))zlove(adam, x)zlove(x, adam)z-(x = adam)zexists z22. love(x, z22)zexists y. love(y, x)zall y. (girl(y) -> love(x, y))zall y. (girl(y) -> love(y, x))z)all y. (girl(y) -> (boy(x) & love(y, x)))z)(boy(x) & all y. (girl(y) -> love(x, y)))z)(boy(x) & all y. (girl(y) -> love(y, x)))z+(boy(x) & exists y. (girl(y) & love(y, x)))z(girl(x) -> dog(x))zall y. (dog(y) -> (x = y))z&exists y. (love(adam, y) & love(y, x))c             S   s   g | ]}t j|qS r   )r
   rY   )r(   r   r   r   r   rN     s    zsatdemo.<locals>.<listcomp>zThe satisfiers of '{}' are: {}r   N)
r   r   r   r   r
   rY   r   r   ry   r   )r   r   r   r   pr   r   r   satdemo  sD    


r   c             C   sV   t tttd}y||  |d W n0 tk
rP   x|D ]} ||  |d q6W Y nX dS )aO  
    Run exists demos.

     - num = 1: propositional logic demo
     - num = 2: first order model demo (only if trace is set)
     - num = 3: first order sentences demo
     - num = 4: satisfaction of open formulas demo
     - any other value: run all the demos

    :param trace: trace = 1, or trace = 2 for more verbose tracing
    )r^            )r   N)r   r   r   r   KeyError)numr   Zdemosr   r   r   demo  s    
r   __main__r   )r   )N)N)FN)N)N)r   N)2rZ   r   resysrB   pprintr   Znltk.decoratorsr   Znltk.sem.logicr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   	Exceptionr   r   r   r1   r8   r;   r   r<   compilera   rf   VERBOSErd   rl   rW   rw   r   r   r   r   r   r   r   r   r   r   r   r   <module>   sB   D
B

#
  X
1
<
,
0

