U
    e7                     @   s   d 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 ddlmZ G dd dZG dd	 d	ZG d
d dZdddZedkredD ]Zee qe  edD ]Zee qdS )a  
An implementation of the Hole Semantics model, following Blackburn and Bos,
Representation and Inference for Natural Language (CSLI, 2005).

The semantic representations are built by the grammar hole.fcfg.
This module contains driver code to read in sentences and parse them
according to a hole semantics grammar.

After parsing, the semantic representation is in the form of an underspecified
representation that is not easy to read.  We use a "plugging" algorithm to
convert that representation into first-order logic formulas.
    )reduce)load_parser)	AllExpressionAndExpressionApplicationExpressionExistsExpressionIffExpressionImpExpressionLambdaExpressionNegatedExpressionOrExpression)	skolemizec                   @   sd   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZedd edd eeeeeeeee	ee
eiZdS )	ConstantsALLEXISTSNOTANDORIMPIFFPREDLEQHOLELABELc                 C   s   t | j|S N)r   variableve r   N/var/www/html/assets/scripts/venv/lib/python3.8/site-packages/nltk/sem/hole.py<lambda>>       zConstants.<lambda>c                 C   s   t | j|S r   )r   r   r   r   r   r    r!   ?   r"   N)__name__
__module____qualname__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	   r   r   MAPr   r   r   r    r   0   s8           r   c                   @   sx   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd ZdS )HoleSemanticsar  
    This class holds the broken-down components of a hole semantics, i.e. it
    extracts the holes, labels, logic formula fragments and constraints out of
    a big conjunction of such as produced by the hole semantics grammar.  It
    then provides some operations on the semantics dealing with holes, labels
    and finding legal ways to plug holes with labels.
    c                 C   s@   t  | _t  | _i | _t  | _| | |  | _|  | _	dS )aB  
        Constructor.  `usr' is a ``sem.Expression`` representing an
        Underspecified Representation Structure (USR).  A USR has the following
        special predicates:
        ALL(l,v,n),
        EXISTS(l,v,n),
        AND(l,n,n),
        OR(l,n,n),
        IMP(l,n,n),
        IFF(l,n,n),
        PRED(l,v,n,v[,v]*) where the brackets and star indicate zero or more repetitions,
        LEQ(n,n),
        HOLE(n),
        LABEL(n)
        where l is the label of the node described by the predicate, n is either
        a label or a hole, and v is a variable.
        N)
setholeslabels	fragmentsconstraints_break_down_find_top_most_labelstop_most_labels_find_top_holetop_hole)selfusrr   r   r    __init__R   s    

zHoleSemantics.__init__c                 C   s   || j | jB kS )ze
        Return true if x is a node (label or hole) in this semantic
        representation.
        )r*   r)   )r2   xr   r   r    is_nodel   s    zHoleSemantics.is_nodec                 C   s   t |tr$| |j | |j nt |tr| \}}|jjt	j
krd| jt|d |d  q|jjt	jkr| j|d  q|jjt	jkr| j|d  q|d }|| jkst||dd f| j|< nt| dS )z
        Extract holes, labels, formula fragments and constraints from the hole
        semantics underspecified representation (USR).
        r      N)
isinstancer   r-   firstsecondr   Zuncurryr   namer   r   r,   add
Constraintr   r)   r   r*   r+   AssertionError
ValueErrorlabel)r2   r3   funcargsr@   r   r   r    r-   s   s    

zHoleSemantics._break_downc                 C   s@   |  }| j D ](}|d }|D ]}||kr"|| q"q|S )Nr7   )copyr+   valuesdiscard)r2   Z	node_listZ	top_nodesfrB   argr   r   r    _find_top_nodes   s    zHoleSemantics._find_top_nodesc                 C   s   |  | jS )z
        Return the set of labels which are not referenced directly as part of
        another formula fragment.  These will be the top-most labels for the
        subtree that they are part of.
        )rH   r*   r2   r   r   r    r.      s    z#HoleSemantics._find_top_most_labelsc                 C   s$   |  | j}t|dkst| S )zK
        Return the hole that will be the top of the formula tree.
        r7   )rH   r)   lenr>   pop)r2   Z	top_holesr   r   r    r0      s    zHoleSemantics._find_top_holec                 C   s"   g }|  | jg fg| ji | |S )z
        Calculate and return all the legal pluggings (mappings of labels to
        holes) of this semantics given the constraints.
        )_plug_nodesr1   r/   )r2   recordr   r   r    	pluggings   s    zHoleSemantics.pluggingsc                    s   |g kr|d \} |j kr<| |dd ||| q|jksJtj| d } fdd|D }||dd  ||| ntddS )ac  
        Plug the nodes in `queue' with the labels in `potential_labels'.

        Each element of `queue' is a tuple of the node to plug and the list of
        ancestor holes from the root of the graph to that node.

        `potential_labels' is a set of the labels which are still available for
        plugging.

        `plug_acc' is the incomplete mapping of holes to labels made on the
        current branch of the search tree so far.

        `record' is a list of all the complete pluggings that we have found in
        total so far.  It is the only parameter that is destructively updated.
        r   r7   Nc                    s   g | ]} |r| fqS r   )r6   ).0a	ancestorsr2   r   r    
<listcomp>   s     
 z-HoleSemantics._plug_nodes.<locals>.<listcomp>zqueue empty)r)   
_plug_holer*   r>   r+   rL   	Exception)r2   queuepotential_labelsplug_accrM   noderB   headr   rQ   r    rL      s     
  
   zHoleSemantics._plug_nodesc                 C   s   ||kst |g| }|D ]v}| ||r,q| }	||	|< | }
|
| t|
dkrv| |	| jg  ||	 q| |||fg |
|	| qdS )z~
        Try all possible ways of plugging a single hole.
        See _plug_nodes for the meanings of the parameters.
        r   N)	r>   _violates_constraintsrC   removerJ   _sanity_check_pluggingr1   appendrL   )r2   holeZ
ancestors0rV   Zpotential_labels0Z	plug_acc0rM   rR   lrX   rW   r   r   r    rT      s$    


   zHoleSemantics._plug_holec                 C   s*   | j D ]}|j|kr|j|kr dS qdS )z
        Return True if the `label' cannot be placed underneath the holes given
        by the set `ancestors' because it would violate the constraints imposed
        on it.
        TF)r,   lhsrhs)r2   r@   rR   cr   r   r    r[      s
    


z#HoleSemantics._violates_constraintsc                 C   s   || j kr|g| }|| }n|}|| jks0t| jD ]}|j|kr6|j|ks6tq6| j| d }|D ]"}| |rf| |||g|  qfdS )z
        Make sure that a given plugging is legal.  We recursively go through
        each node and make sure that no constraints are violated.
        We also check that all holes have been filled.
        r7   N)	r)   r*   r>   r,   ra   rb   r+   r6   r]   )r2   pluggingrY   rR   r@   rc   rB   rG   r   r   r    r]     s    





z$HoleSemantics._sanity_check_pluggingc                 C   s   |  || jS )z
        Return the first-order logic formula tree for this underspecified
        representation using the plugging given.
        )_formula_treer1   )r2   rd   r   r   r    formula_tree  s    zHoleSemantics.formula_treec                    s`   | kr   | S |jkrXj| \}} fdd|D }ttj|jj |S |S d S )Nc                    s   g | ]}  |qS r   )re   )rO   rG   rd   r2   r   r    rS   %  s     z/HoleSemantics._formula_tree.<locals>.<listcomp>)re   r+   r   r   r&   r   r;   )r2   rd   rY   predrB   childrenr   rg   r    re      s    
zHoleSemantics._formula_treeN)r#   r$   r%   __doc__r4   r6   r-   rH   r.   r0   rN   rL   rT   r[   r]   rf   re   r   r   r   r    r'   I   s   
	!+r'   c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )r=   z~
    This class represents a constraint of the form (L =< N),
    where L is a label and N is a node (a label or a hole).
    c                 C   s   || _ || _d S r   ra   rb   )r2   ra   rb   r   r   r    r4   1  s    zConstraint.__init__c                 C   s,   | j |j kr$| j|jko"| j|jkS dS d S )NF)	__class__ra   rb   r2   otherr   r   r    __eq__5  s    zConstraint.__eq__c                 C   s
   | |k S r   r   rm   r   r   r    __ne__;  s    zConstraint.__ne__c                 C   s   t t| S r   )hashreprrI   r   r   r    __hash__>  s    zConstraint.__hash__c                 C   s   d| j  d| j dS )N(z < )rk   rI   r   r   r    __repr__A  s    zConstraint.__repr__N)	r#   r$   r%   rj   r4   ro   rp   rs   rv   r   r   r   r    r=   +  s   r=   NFc                 C   st  |sd}|rt d| t|}|  }t||}|rHt dt|  g }|D ]}| d  }|rtt d| t|t	r|j
}qtt|}	|rt d|	 t|	}
|rt d|
j t d|
j t d	|
j t d
|
j t d|
j t d |
j D ]\}}t d| d|  q|
 }tt|
j|}|rdt|D ] \}}t   t d||f  q<t   || qP|S )Nz"grammars/sample_grammars/hole.fcfgzReading grammar filezGot %d different parsesZSEMzRaw:       zSkolemized:zHoles:       zLabels:      zConstraints: zTop hole:    zTop labels:  z
Fragments:	z: z%d. %s)printr   splitlistparserJ   r@   simplifyr8   r
   termr   r'   r)   r*   r,   r1   r/   r+   itemsrN   maprf   	enumerateextend)ZsentenceZgrammar_filenameverboseparsertokensZtreesZall_readingstreeZsemZ
skolemizedZhole_semr`   rF   rN   Zreadingsirr   r   r    hole_readingsE  sL    




r   __main__za dog barkszevery girl chases a dog)NF)rj   	functoolsr   Z
nltk.parser   Znltk.sem.logicr   r   r   r   r   r	   r
   r   r   Znltk.sem.skolemizer   r   r'   r=   r   r#   r   rx   r   r   r   r    <module>
   s   , c
A
