o
    §ƒðjùS  ã                   @   sv   d Z ddlmZ ddlmZmZ ddlmZ ddlm	Z	 ddl
mZ ddd	„Zd
d„ ZG dd„ dƒZG dd„ dƒZdS )z«Implementation of DPLL algorithm

Features:
  - Clause learning
  - Watch literal scheme
  - VSIDS heuristic

References:
  - https://en.wikipedia.org/wiki/DPLL_algorithm
é    )Údefaultdict)ÚheappushÚheappop)Úordered)Ú
EncodedCNF)Ú	LRASolverFc                 C   s®   t | tƒstƒ }| | ¡ |} dh| jv r |rdd„ dD ƒS dS |r*t | ¡\}}nd}g }t| j| | jtƒ | j	|d�}| 
¡ }|rGt|ƒS zt|ƒW S  tyV   Y dS w )a˜  
    Check satisfiability of a propositional sentence.
    It returns a model rather than True when it succeeds.
    Returns a generator of all models if all_models is True.

    Examples
    ========

    >>> from sympy.abc import A, B
    >>> from sympy.logic.algorithms.dpll2 import dpll_satisfiable
    >>> dpll_satisfiable(A & ~B)
    {A: True, B: False}
    >>> dpll_satisfiable(A & ~A)
    False

    r   c                 s   s   � | ]}|V  qd S ©N© )Ú.0Úfr	   r	   úž/tmp/claude-1000/-var-www-html-academy/3f42efd1-c2b7-4d08-9b05-30d86bb35479/scratchpad/piper/venv/lib/python3.10/site-packages/sympy/logic/algorithms/dpll2.pyÚ	<genexpr>.   s   € z#dpll_satisfiable.<locals>.<genexpr>©FFN)Ú
lra_theory)Ú
isinstancer   Úadd_propÚdatar   Úfrom_encoded_cnfÚ	SATSolverÚ	variablesÚsetÚsymbolsÚ_find_modelÚ_all_modelsÚnextÚStopIteration)ÚexprÚ
all_modelsÚuse_lra_theoryÚexprsÚlraÚimmediate_conflictsÚsolverÚmodelsr	   r	   r   Údpll_satisfiable   s*   


ÿr$   c                 c   s>   � d}z		 t | ƒV  d}q ty   |sdV  Y d S Y d S w )NFT)r   r   )r#   Úsatisfiabler	   r	   r   r   G   s   €
þÿÿr   c                   @   sÆ   e Zd ZdZ			d0dd„Zdd	„ Zd
d„ Zdd„ Ze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(d)„ Zd*d+„ Zd,d-„ Zd.d/„ ZdS )1r   z‚
    Class for representing a SAT solver capable of
     finding a model to a boolean theory in conjunctive
     normal form.
    NÚvsidsÚnoneéô  c	           	      C   s  || _ || _d| _g | _g | _|| _|d u rtt|ƒƒ| _n|| _|  	|¡ |  
|¡ d|krD|  ¡  | j| _| j| _| j| _| j| _nt‚d|krZ| j| _| j| _| j | j¡ nd|kridd„ | _dd„ | _nt‚tdƒg| _|| j_d| _d| _ t!| j"ƒ| _#|| _$d S )	NFr&   Úsimpler'   c                 S   ó   d S r   r	   )Úxr	   r	   r   Ú<lambda>~   ó    z$SATSolver.__init__.<locals>.<lambda>c                   S   r*   r   r	   r	   r	   r	   r   r,      r-   r   )%Úvar_settingsÚ	heuristicÚis_unsatisfiedÚ_unit_prop_queueÚupdate_functionsÚINTERVALÚlistr   r   Ú_initialize_variablesÚ_initialize_clausesÚ_vsids_initÚ_vsids_calculateÚheur_calculateÚ_vsids_lit_assignedÚheur_lit_assignedÚ_vsids_lit_unsetÚheur_lit_unsetÚ_vsids_clause_addedÚheur_clause_addedÚNotImplementedErrorÚ_simple_add_learned_clauseÚadd_learned_clauseÚ_simple_compute_conflictÚcompute_conflictÚappendÚ_simple_clean_clausesÚLevelÚlevelsÚ_current_levelÚvarsettingsÚnum_decisionsÚnum_learned_clausesÚlenÚclausesÚoriginal_num_clausesr    )	ÚselfrN   r   r.   r   r/   Úclause_learningr3   r   r	   r	   r   Ú__init__Y   s@   




zSATSolver.__init__c                 C   s,   t tƒ| _t tƒ| _dgt|ƒd  | _dS )z+Set up the variable data structures needed.Fé   N)r   r   Ú	sentinelsÚintÚoccurrence_countrM   Úvariable_set)rP   r   r	   r	   r   r5   Ž   s   

zSATSolver._initialize_variablesc                 C   sŠ   dd„ |D ƒ| _ t| j ƒD ]5\}}dt|ƒkr | j |d ¡ q| j|d   |¡ | j|d   |¡ |D ]}| j|  d7  < q6qdS )a<  Set up the clause data structures needed.

        For each clause, the following changes are made:
        - Unit clauses are queued for propagation right away.
        - Non-unit clauses have their first and last literals set as sentinels.
        - The number of clauses a literal appears in is computed.
        c                 S   s   g | ]}t |ƒ‘qS r	   )r4   )r
   Úclauser	   r	   r   Ú
<listcomp>œ   ó    z1SATSolver._initialize_clauses.<locals>.<listcomp>rS   r   éÿÿÿÿN)rN   Ú	enumeraterM   r1   rE   rT   ÚaddrV   )rP   rN   ÚirX   Úlitr	   r	   r   r6   ”   s   ÿözSATSolver._initialize_clausesc                 #   s  � d}ˆ  ¡  ˆjrdS 	 ˆjˆj dkrˆjD ]}|ƒ  q|r'd}ˆjj}n�ˆ ¡ }ˆ jd7  _d|kr¼ˆjrVˆj	D ]}ˆj 
|¡‰ ˆ durJ nq<ˆj ¡ ‰ ˆj ¡  nd‰ ˆ du s`ˆ d rl‡fdd„ˆj	D ƒV  n%ˆ ˆ d ¡ t‡ fdd	„ˆjj	D ƒƒs‘ˆ ¡  t‡ fdd	„ˆjj	D ƒƒr€ˆjjr�ˆ ¡  ˆjjs•tˆjƒdkr¦dS ˆjj }ˆ ¡  ˆj t|dd
�¡ d}qˆj t|ƒ¡ ˆ |¡ ˆ  ¡  ˆj�rdˆ_ˆjjréˆ ¡  dtˆjƒkrådS ˆjjsØˆ ˆ ¡ ¡ ˆjj }ˆ ¡  ˆj t|dd
�¡ d}q)an  
        Main DPLL loop. Returns a generator of models.

        Variables are chosen successively, and assigned to be either
        True or False. If a solution is not found with this setting,
        the opposite is chosen and the search continues. The solver
        halts when every variable has a setting.

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())
        >>> list(l._find_model())
        [{1: True, 2: False, 3: False}, {1: True, 2: True, 3: True}]

        >>> from sympy.abc import A, B, C
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set(), [A, B, C])
        >>> list(l._find_model())
        [{A: True, B: False, C: False}, {A: True, B: True, C: True}]

        FNTr   rS   c                    s$   i | ]}ˆ j t|ƒd   |dk“qS )rS   r   )r   Úabs©r
   r_   ©rP   r	   r   Ú
<dictcomp>í   s
    ÿÿz)SATSolver._find_model.<locals>.<dictcomp>c                 3   s   � | ]
}| ˆ d  v V  qdS )rS   Nr	   ra   )Úresr	   r   r   ó   s   € z(SATSolver._find_model.<locals>.<genexpr>)Úflipped)Ú	_simplifyr0   rK   r3   r2   rI   Údecisionr9   r    r.   Ú
assert_litÚcheckÚreset_boundsrA   ÚanyÚ_undore   rM   rH   rE   rG   Ú_assign_literalrB   rD   )rP   Úflip_varÚfuncr_   Úenc_varÚflip_litr	   )rd   rP   r   r   «   st   €


ÿ


ÿÿÿ

û
²zSATSolver._find_modelc                 C   s
   | j d S )a¤  The current decision level data structure

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{1}, {2}], {1, 2}, set())
        >>> next(l._find_model())
        {1: True, 2: True}
        >>> l._current_level.decision
        0
        >>> l._current_level.flipped
        False
        >>> l._current_level.var_settings
        {1, 2}

        r[   ©rH   rb   r	   r	   r   rI   "  s   
zSATSolver._current_levelc                 C   s$   | j | D ]
}|| jv r dS qdS )a¢  Check if a clause is satisfied by the current variable setting.

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{1}, {-1}], {1}, set())
        >>> try:
        ...     next(l._find_model())
        ... except StopIteration:
        ...     pass
        >>> l._clause_sat(0)
        False
        >>> l._clause_sat(1)
        True

        TF)rN   r.   ©rP   Úclsr_   r	   r	   r   Ú_clause_sat7  s
   
ÿzSATSolver._clause_satc                 C   s   || j | v S )a©  Check if a literal is a sentinel of a given clause.

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())
        >>> next(l._find_model())
        {1: True, 2: False, 3: False}
        >>> l._is_sentinel(2, 3)
        True
        >>> l._is_sentinel(-3, 1)
        False

        )rT   )rP   r_   rt   r	   r	   r   Ú_is_sentinelN  s   zSATSolver._is_sentinelc                 C   sÒ   | j  |¡ | jj  |¡ d| jt|ƒ< |  |¡ t| j|  ƒ}|D ]C}|  |¡sfd}| j	| D ],}|| kr]|  
||¡rA|}q1| jt|ƒ s]| j|   |¡ | j|  |¡ d} nq1|rf| j |¡ q#dS )aÜ  Make a literal assignment.

        The literal assignment must be recorded as part of the current
        decision level. Additionally, if the literal is marked as a
        sentinel of any clause, then a new sentinel must be chosen. If
        this is not possible, then unit propagation is triggered and
        another literal is added to the queue to be set in the future.

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())
        >>> next(l._find_model())
        {1: True, 2: False, 3: False}
        >>> l.var_settings
        {-3, -2, 1}

        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())
        >>> l._assign_literal(-1)
        >>> try:
        ...     next(l._find_model())
        ... except StopIteration:
        ...     pass
        >>> l.var_settings
        {-1}

        TN)r.   r]   rI   rW   r`   r;   r4   rT   ru   rN   rv   Úremover1   rE   )rP   r_   Úsentinel_listrt   Úother_sentinelÚnewlitr	   r	   r   rm   a  s,   


€€ñzSATSolver._assign_literalc                 C   s@   | j jD ]}| j |¡ |  |¡ d| jt|ƒ< q| j ¡  dS )ag  
        _undo the changes of the most recent decision level.

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())
        >>> next(l._find_model())
        {1: True, 2: False, 3: False}
        >>> level = l._current_level
        >>> level.decision, level.var_settings, level.flipped
        (-3, {-3, -2}, False)
        >>> l._undo()
        >>> level = l._current_level
        >>> level.decision, level.var_settings, level.flipped
        (0, {1}, False)

        FN)rI   r.   rw   r=   rW   r`   rH   Úpop©rP   r_   r	   r	   r   rl   ˜  s
   
zSATSolver._undoc                 C   s0   d}|rd}||   ¡ O }||  ¡ O }|sdS dS )ad  Iterate over the various forms of propagation to simplify the theory.

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())
        >>> l.variable_set
        [False, False, False, False]
        >>> l.sentinels
        {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}

        >>> l._simplify()

        >>> l.variable_set
        [False, True, False, False]
        >>> l.sentinels
        {-3: {0, 2}, -2: {3, 4}, -1: set(), 2: {0, 3},
        ...3: {2, 4}}

        TFN)Ú
_unit_propÚ_pure_literal)rP   Úchangedr	   r	   r   rf   ¾  s   ýzSATSolver._simplifyc                 C   sN   t | jƒdk}| jr%| j ¡ }| | jv rd| _g | _dS |  |¡ | js
|S )z/Perform unit propagation on the current theory.r   TF)rM   r1   r{   r.   r0   rm   )rP   ÚresultÚnext_litr	   r	   r   r}   Û  s   

ù	zSATSolver._unit_propc                 C   ó   dS )z2Look for pure literals and assign them when found.Fr	   rb   r	   r	   r   r~   é  ó   zSATSolver._pure_literalc                 C   s†   g | _ i | _tdt| jƒƒD ]2}t| j|  ƒ| j|< t| j|   ƒ| j| < t| j | j| |fƒ t| j | j|  | fƒ qdS )z>Initialize the data structures needed for the VSIDS heuristic.rS   N)Úlit_heapÚ
lit_scoresÚrangerM   rW   ÚfloatrV   r   )rP   Úvarr	   r	   r   r7   ð  s   üzSATSolver._vsids_initc                 C   s&   | j  ¡ D ]}| j |  d  < qdS )aË  Decay the VSIDS scores for every literal.

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())

        >>> l.lit_scores
        {-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}

        >>> l._vsids_decay()

        >>> l.lit_scores
        {-3: -1.0, -2: -1.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -1.0}

        g       @N)r…   Úkeysr|   r	   r	   r   Ú_vsids_decayû  s   ÿzSATSolver._vsids_decayc                 C   sl   t | jƒdkr	dS | jt| jd d ƒ r/t| jƒ t | jƒdkr#dS | jt| jd d ƒ st| jƒd S )aá  
            VSIDS Heuristic Calculation

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())

        >>> l.lit_heap
        [(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]

        >>> l._vsids_calculate()
        -3

        >>> l.lit_heap
        [(-2.0, -2), (-2.0, 2), (0.0, -1), (0.0, 1), (-2.0, 3)]

        r   rS   )rM   r„   rW   r`   r   rb   r	   r	   r   r8     s   
ýzSATSolver._vsids_calculatec                 C   r‚   )z;Handle the assignment of a literal for the VSIDS heuristic.Nr	   r|   r	   r	   r   r:   3  rƒ   zSATSolver._vsids_lit_assignedc                 C   s<   t |ƒ}t| j| j| |fƒ t| j| j|  | fƒ dS )a  Handle the unsetting of a literal for the VSIDS heuristic.

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())
        >>> l.lit_heap
        [(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]

        >>> l._vsids_lit_unset(2)

        >>> l.lit_heap
        [(-2.0, -3), (-2.0, -2), (-2.0, -2), (-2.0, 2), (-2.0, 3), (0.0, -1),
        ...(-2.0, 2), (0.0, 1)]

        N)r`   r   r„   r…   )rP   r_   rˆ   r	   r	   r   r<   7  s   zSATSolver._vsids_lit_unsetc                 C   s.   |  j d7  _ |D ]}| j|  d7  < q	dS )aD  Handle the addition of a new clause for the VSIDS heuristic.

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())

        >>> l.num_learned_clauses
        0
        >>> l.lit_scores
        {-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}

        >>> l._vsids_clause_added({2, -3})

        >>> l.num_learned_clauses
        1
        >>> l.lit_scores
        {-3: -1.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -2.0}

        rS   N)rL   r…   rs   r	   r	   r   r>   N  s   ÿzSATSolver._vsids_clause_addedc                 C   sh   t | jƒ}| j |¡ |D ]}| j|  d7  < q| j|d   |¡ | j|d   |¡ |  |¡ dS )a‚  Add a new clause to the theory.

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())

        >>> l.num_learned_clauses
        0
        >>> l.clauses
        [[2, -3], [1], [3, -3], [2, -2], [3, -2]]
        >>> l.sentinels
        {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}

        >>> l._simple_add_learned_clause([3])

        >>> l.clauses
        [[2, -3], [1], [3, -3], [2, -2], [3, -2], [3]]
        >>> l.sentinels
        {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4, 5}}

        rS   r   r[   N)rM   rN   rE   rV   rT   r]   r?   )rP   rt   Úcls_numr_   r	   r	   r   rA   l  s   
z$SATSolver._simple_add_learned_clausec                 C   s   dd„ | j dd… D ƒS )a«   Build a clause representing the fact that at least one decision made
        so far is wrong.

        Examples
        ========

        >>> from sympy.logic.algorithms.dpll2 import SATSolver
        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
        ... {3, -2}], {1, 2, 3}, set())
        >>> next(l._find_model())
        {1: True, 2: False, 3: False}
        >>> l._simple_compute_conflict()
        [3]

        c                 S   s   g | ]}|j  ‘qS r	   )rg   )r
   Úlevelr	   r	   r   rY      rZ   z6SATSolver._simple_compute_conflict.<locals>.<listcomp>rS   Nrr   rb   r	   r	   r   rC   �  s   z"SATSolver._simple_compute_conflictc                 C   r‚   )zClean up learned clauses.Nr	   rb   r	   r	   r   rF   ¢  rƒ   zSATSolver._simple_clean_clauses)Nr&   r'   r(   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rR   r5   r6   r   ÚpropertyrI   ru   rv   rm   rl   rf   r}   r~   r7   rŠ   r8   r:   r<   r>   rA   rC   rF   r	   r	   r	   r   r   R   s8    
þ5w
7! $r   c                   @   s   e Zd ZdZddd„ZdS )rG   z‚
    Represents a single level in the DPLL algorithm, and contains
    enough information for a sound backtracking procedure.
    Fc                 C   s   || _ tƒ | _|| _d S r   )rg   r   r.   re   )rP   rg   re   r	   r	   r   rR   ­  s   
zLevel.__init__Nr   )r�   rŽ   r�   r�   rR   r	   r	   r	   r   rG   §  s    rG   N)FF)r�   Úcollectionsr   Úheapqr   r   Úsympy.core.sortingr   Úsympy.assumptions.cnfr   Ú!sympy.logic.algorithms.lra_theoryr   r$   r   r   rG   r	   r	   r	   r   Ú<module>   s    
2    Y