
    z	ip"                     |    S r SSKrSSKrSSKrSSKJr  SSKJrJr  SSK	r
SSKJrJr   " S S5      r " S	 S
5      rg)z8A class for parsing and synthesizing boolean expressions    N)isfile)UnionCallable   )BooleanExpressionEvalVisitor%BooleanExpressionArgsCollectorVisitorc                   x    \ rS rSrSrSrS\S\4S jrS\	\
\      4S jrS	\\\
\   4   S\4S
 jrS\4S jrSrg)
TruthTable   a  A simple implementation of a truth table for a boolean function

The truth table is built from a callable which takes an assignment, which
is a tuple of boolean values of a fixed given length (the number of bits
of the truth table) and returns a boolean value.

For a number of bits at most `EXPLICIT_REP_THRESHOLD` the values of the table
are explicitly computed and stored. Otherwise, the values are computed on the fly
and stored in a dictionary.   funcnum_bitsc                 *   Xl         X l        U R                  U R                  :*  U l        U R                  (       aL  [        R
                  " U R                  5        Vs/ s H  o0R                  U5      PM     sn[        S9U l        g 0 U l	        g s  snf )N)dtype)
r   r   EXPLICIT_REP_THRESHOLDexplicit_storagenparrayall_assignmentsboolvaluesimplicit_values)selfr   r   
assignments       e/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/synthesis/boolean/boolean_expression.py__init__TruthTable.__init__+   ss    	  $1L1L L  ((9=9M9M9OP9O::&9OPDK
 $&D 	 Qs   Breturnc                     [         R                  " SS/U R                  S9 Vs/ s H  n[        [	        U5      5      PM     sn$ s  snf )zqReturn an ordered list of all assignments, ordered from right to left
i.e. 000, 100, 010, 110, 001, 101, 011, 111FT)repeat)	itertoolsproductr   tuplereversed)r   r   s     r   r   TruthTable.all_assignments7   sH    
 (//dmmT
T
 (:&'T
 	
 
s   Akeyc                    [        U[        5      (       a	  S U 5       nU R                  (       a*  [        S [	        U5       5       5      nU R
                  U   $ U R                  R                  XR                  U5      5      $ )Nc              3   *   #    U  H	  oS :g  v   M     g7f0N .0bits     r   	<genexpr>)TruthTable.__getitem__.<locals>.<genexpr>A   s     -##:   c              3   B   #    U  H  u  pU(       d  M  S U-  v   M     g7f)   Nr+   )r-   nr.   s      r   r/   r0   C   s     ?vq3dads   )	
isinstancestrr   sum	enumerater   r   
setdefaultr   )r   r&   s     r   __getitem__TruthTable.__getitem__?   sd    c3--C  ?3??C;;s##''223		#GG    c                    ^  T R                   (       a)  SR                  U 4S jT R                  5        5       5      $ ST R                   S3$ )N c              3   @   >#    U  H  nTU   (       a  S OSv   M     g7f)1r*   Nr+   )r-   
assignemntr   s     r   r/   %TruthTable.__str__.<locals>.<genexpr>J   s!      CYZtJ'S0CYs   zTruth table on z bits (implicit representation))r   joinr   r   r   s   `r   __str__TruthTable.__str__H   sI      77 CGCWCWCY   %T]]O3RSSr<   )r   r   r   r   r   N)__name__
__module____qualname____firstlineno____doc__r   r   intr   listr#   r   r   r   r6   r:   rE   __static_attributes__r+   r<   r   r
   r
      sk    # 	 
&X 
& 
&
eDk!2 
HuS%+%56 H4 HT Tr<   r
   c                       \ rS rSrSrSS\S\SS4S jjrS\\\	4   S\
4S	 jr\S\4S
 j5       rSS\4S jjr\S\4S j5       r\S\4S j5       rSrg)BooleanExpressionQ   zA Boolean ExpressionN
expression	var_orderr   c                    Xl         [        R                  " U5      U l        [	        5       nUR                  U R                  5        UR                  5       U l        [        U R                  5      U l	        Ubp  [        U R                  5      [        U5      -
  n[        U5      S:  a  [        SSR                  U5       35      eU R                  R                  UR                  S9  SU l        g)a  
Args:
    expression (str): The logical expression string.
    name (str): Optional. Instruction gate name. Otherwise part of the expression is
       going to be used.
    var_order(list): A list with the order in which variables will be created.
       (default: by appearance)
Nr   z"var_order missing the variable(s) z, )r&   )rR   astparseexpression_astr   visitget_sorted_argsargslenr   set
ValueErrorrC   sortindextruth_table_)r   rR   rS   args_collectormissing_argss        r   r   BooleanExpression.__init__T   s     %!ii
3>@T001"224	DII tyy>C	N:L< 1$ #EdiiP\F]E^!_``IINNyN/ r<   	bitstringc                 J   U R                   [        U5      :w  a$  [        S[        U5       SU R                    35      e[        U[        5      (       a	  S U 5       n[        5       n[        [        U R                  U5      5      Ul	        UR                  U R                  5      $ )zEvaluate the expression on a bitstring.

This evaluation is done classically.

Args:
    bitstring: The bitstring for which to evaluate,
    either as a string of 0 and 1 or a tuple of booleans.

Returns:
    bool: result of the evaluation.
z7bitstring length differs from the number of variables (z != c              3   *   #    U  H	  oS :g  v   M     g7fr)   r+   r,   s     r   r/   -BooleanExpression.simulate.<locals>.<genexpr>|   s     9yyr1   )r   r[   r]   r5   r6   r   dictziprZ   
arg_valuesrX   rW   )r   rd   eval_visitors      r   simulateBooleanExpression.simulatej   s     ==C	N*	N#48  i%%9y9I35"&s499i'@"A!!$"5"566r<   c                 ~    U R                   c%  [        U R                  U R                  5      U l         U R                   $ )zGenerates the full truth table for the expression
Returns:
    dict: A dictionary mapping boolean assignments to the boolean result
)r`   r
   rl   r   rD   s    r   truth_tableBooleanExpression.truth_table   s3     $ *4==$-- HD   r<   circuit_typec                     SSK JnJnJn  U" U R                  5      R
                  nUS:X  a  U" XPR                  S-   5      $ US:X  a  U" XPR                  5      $ [        S5      e)a|  Synthesize the logic network into a :class:`~qiskit.circuit.QuantumCircuit`.
There are two common types of circuits for a boolean function :math:`f(x)`:

1. **Bit-flip oracles** which compute:

 .. math::

    |x\rangle|y\rangle |-> |x\rangle|f(x)\oplusy\rangle

2. **Phase-flip** oracles which compute:

 .. math::

    |x\rangle |-> (-1)^{f(x)}|x\rangle

By default the bit-flip oracle is generated.

Args:
    circuit_type: which type of oracle to create, 'bit' or 'phase' flip oracle.
Returns:
    QuantumCircuit: A circuit implementing the logic network.
Raises:
    ValueError: If ``circuit_type`` is not either 'bit' or 'phase'.
r   )synth_bit_oracle_from_esopsynth_phase_oracle_from_esopEsopGeneratorr.   phasez.'circuit_type' must be either 'bit' or 'phase')boolean_expression_synthrs   rt   ru   ro   esopr   r]   )r   rq   rs   rt   ru   rx   s         r   synthBooleanExpression.synth   sc    4	
 	
 T--.335 -dMMA4EFF7"/mmDDIJJr<   dimacsc                    [         R                  " S5      n[         R                  " S5      nU R                  S5       Vs/ s H  o3R                  5       PM     nnU Vs/ s H$  o3R	                  S5      (       a  M  US:w  d  M"  UPM&     nnUR                  US   5      nU(       d  [        S5      e[        [        UR                  5       5      u  pg[        U5       Vs/ s H  nSUS	-    3PM     n	n/ n
US	S
  H\  nUR                  U5      n[        U5      S:X  d	  US   S:w  a  M.  U
R                  US
S  Vs/ s H  n[        U5      PM     sn5        M^     U
 VVs/ s H?  nSR                  U Vs/ s H  oS:  a  SOS U	[        U5      S	-
      3PM!     sn5      PMA     nnnSR                  U Vs/ s H	  nSU S3PM     sn5      n[!        UU	S9$ s  snf s  snf s  snf s  snf s  snf s  snnf s  snf )zCreate a BooleanExpression from a string in the DIMACS format.
Args:
    dimacs : A string in DIMACS format.

Returns:
    BooleanExpression: A gate for the input string

Raises:
    ValueError: If the string is not formatted according to DIMACS rules
zp\s+cnf\s+(\d+)\s+(\d+)z(-?\d+)
cr>   r   z"First line must start with 'p cnf'xr   Nr*   z | ~z & ())rS   )recompilesplitstrip
startswithmatchr]   maprL   groupsrangefindallr[   appendrC   absrP   )r{   header_regexclause_regexlinelinesheader_matchnum_vars_i	variablesclausesliteralsr~   clauselitclause_stringsexprs                    r   from_dimacsBooleanExpression.from_dimacs   s    zz"<=zz*-*0,,t*<=*<$*<="
"T//#*>D42:DU 	 
 $))%(3ABB#|2245(-h81q1Y	8!"ID#++D1H8}!Xb\S%8NNHSbM:MqCFM:;	  "
! JJV\]V\s'3r29SXaZ3H2IJV\]^! 	 
 zz^<^Qqc8^<= ;;) >
 9 ;]
 =sB    GG<GGG":G'
G14&G,G17G7,G1filenamec                     [        U 5      (       d  [        SU  S35      e[        U S5       nUR                  5       nSSS5        [        R                  W5      $ ! , (       d  f       N#= f)zCreate a BooleanExpression from a file in the DIMACS format.
Args:
    filename: A file in DIMACS format.

Returns:
    BooleanExpression: A gate for the input string

Raises:
    FileNotFoundError: If filename is not found.
z	The file z does not exists.rN)r   FileNotFoundErroropenreadrP   r   )r   dimacs_filer{   s      r   from_dimacs_file"BooleanExpression.from_dimacs_file   s]     h#iz9J$KLL(C K %%'F ! ,,V44 ! s   A
A()rZ   rR   rW   r   r`   )N)r.   )rG   rH   rI   rJ   rK   r6   rM   r   r   r#   r   rl   propertyrh   ro   ry   staticmethodr   r   rN   r+   r<   r   rP   rP   Q   s    !3 !4 !4 !,7%U
"3 7 7. !T ! !'K# 'KR !<C !< !<F 53 5 5r<   rP   )rK   rU   r!   r   os.pathr   typingr   r   numpyr   boolean_expression_visitorr   r   r
   rP   r+   r<   r   <module>r      s:    ? 
  	  " 2T 2TjW5 W5r<   