a
    –¥»amK  ã                   @   sî   d Z ddlmZ ddlmZ daeƒ a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'd(„ Zd)d*„ Zd+d,„ Zd-d.„ Zd/d0„ Zd6d2d3„Zd7d4d5„Zd1S )8z”
Implement functions for controlling execution of nets and steps, including
  Do
  DoParallel
  For-loop
  While-loop
  Do-While-loop
  Switch
  If
é    )Úcore)Ú	viewitemsé   c                 C   s<   d|| f }|}|t v r.d|tf }td7 aqt  |¡ |S )Nz%s/%sz%s_%dr   )Ú_used_step_namesÚ_current_idxÚadd)Úcontrol_nameÚ	base_nameZconcat_nameZ	next_name© r
   úO/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/caffe2/python/control.pyÚ_get_next_step_name   s    

r   c                 C   sH   t | ƒdkrtdƒ‚n.t | ƒdkr<| d }t|tƒsD|g}nt| ƒ}|S )zx input is a tuple.
    Example:
    (a, b, c)   --> [a, b, c]
    (a)         --> [a]
    ([a, b, c]) --> [a, b, c]
    r   zinput cannot be empty.r   )ÚlenÚ
ValueErrorÚ
isinstanceÚlist)ÚinputÚoutputr
   r
   r   Ú	_MakeList(   s    ÿ
r   c                 C   s,   t | tƒrtdd„ | D ƒƒS t | tjƒS d S )Nc                 s   s   | ]}t |tjƒV  qd S )N)r   r   ÚNet)Ú.0Únr
   r
   r   Ú	<genexpr>=   ó    z_IsNets.<locals>.<genexpr>)r   r   Úallr   r   )Únets_or_stepsr
   r
   r   Ú_IsNets;   s    
r   c                 G   s6   t | fƒ} t |ƒ}t| ƒr"||  S td|ƒg|  S d S )NÚprepend©r   r   ÚDo©r   Únetsr
   r
   r   Ú_PrependNetsB   s
    
r!   c                 G   s6   t | fƒ} t |ƒ}t| ƒr"| | S | td|ƒg S d S )NÚappendr   r   r
   r
   r   Ú_AppendNetsK   s
    
r#   c                 C   s6   t |  ¡ jƒdks"J d| jj ƒ‚t |  ¡ jd ¡S )zW
    The condition blob is the last external_output that must
    be a single bool
    r   z6Condition net %s must has at least one external outputéÿÿÿÿ)r   ÚProtoZexternal_outputÚnamer   ÚBlobReference)Úcondition_netr
   r
   r   ÚGetConditionBlobFromNetT   s    ÿÿr)   c                  G   sH   t | ƒ} t d¡}| D ],\}}|jg |gg |tjjd�}| |¡ q|S )aš  A net assigning constant bool values to blobs. It is mainly used for
    initializing condition blobs, for example, in multi-task learning, we
    need to access reader_done blobs before reader_net run. In that case,
    the reader_done blobs must be initialized.

    Args:
    blobs_with_bool_value: one or more (blob, bool_value) pairs. The net will
    assign each bool_value to the corresponding blob.

    returns
    bool_net: A net assigning constant bool values to blobs.

    Examples:
    - BoolNet((blob_1, bool_value_1), ..., (blob_n, bool_value_n))
    - BoolNet([(blob_1, net1), ..., (blob_n, bool_value_n)])
    - BoolNet((cond_1, bool_value_1))
    Úbool_net)ÚshapeÚvalueZdtype)r   r   r   ZConstantFillZDataTypeZBOOLÚAddExternalOutput)Zblobs_with_bool_valuer*   ZblobZ
bool_valueÚout_blobr
   r
   r   ÚBoolNetb   s    
ûr/   c                 C   s@   t | tjƒrt| ƒ}n| }t d¡}| |¡}| |¡ ||fS )a/  Not of a condition blob or net

    Args:
    condition_blob_or_net can be either blob or net. If condition_blob_or_net
    is Net, the condition is its last external_output
    that must be a single bool.

    returns
    not_net: the net NOT the input
    out_blob: the output blob of the not_net
    Únot_net)r   r   r   r)   ÚNotr-   )Úcondition_blob_or_netÚcondition_blobr0   r.   r
   r
   r   ÚNotNet‚   s    



r4   c                 C   s&   t  d¡}| | ¡}| |¡ ||fS )zÅMake a condition net that copies the condition_blob

    Args:
    condition_blob is a single bool.

    returns
    not_net: the net NOT the input
    out_blob: the output blob of the not_net
    Zcopy_condition_blob_net)r   r   ZCopyr-   )r3   r(   r.   r
   r
   r   Ú_CopyConditionBlobNetš   s    



r5   c           
      C   s  t |tƒs|S t|ƒdkr*|r&|d S dS t | ¡}tt|ƒƒD ]²}||  ¡ }|j| ¡ jksdJ ‚|j| ¡ jksxJ ‚| ¡ j	 
|j	¡ | ¡ j 
|j¡ t|| ƒ}|dkr¶|}n| |¡||gƒ}t|| jƒD ]\}}	|j|  |	7  < qÖq@| |¡ |S )a©  
    Merge multi condition nets into a single condition nets.

    Args:
        name: name of the new condition net.
        condition_nets: a list of condition nets. The last external_output
                        of each condition net must be single bool value.
        relation: can be 'And' or 'Or'.

    Returns:
        - A new condition net. Its last external output is relation of all
          condition_nets.
    r   r   N)r   r   r   r   r   Úranger%   Zdevice_optionÚtypeÚopÚextendZexternal_inputr)   Ú__getattr__r   Z
_attr_dictr-   )
r&   Úcondition_netsÚrelationZ
merged_netÚiZ	net_protoÚ	curr_condÚ	last_condÚkÚvr
   r
   r   ÚMergeConditionNets«   s&    


rB   c           
      C   s˜   |sdS t |tƒstdƒ‚t|ƒdkrBt|d ƒ}t|ƒ\}}|S t | ¡}tt|ƒƒD ]0}t|| ƒ}|dkrv|}	qX| 	|¡|	|gƒ}	qX| 
|	¡ |S )aá  
    Combine conditions of multi nets into a single condition nets. Unlike
    MergeConditionNets, the actual body of condition_nets is not copied into
    the combine condition net.

    One example is about multi readers. Each reader net has a reader_done
    condition. When we want to check whether all readers are done, we can
    use this function to build a new net.

    Args:
        name: name of the new condition net.
        condition_nets: a list of condition nets. The last external_output
                        of each condition net must be single bool value.
        relation: can be 'And' or 'Or'.

    Returns:
        - A new condition net. Its last external output is relation of all
          condition_nets.
    Nz&condition_nets must be a list of nets.r   r   )r   r   r   r   r)   r5   r   r   r6   r:   r-   )
r&   r;   r<   r3   r(   Ú_Zcombined_netr=   r>   r?   r
   r
   r   ÚCombineConditionsÔ   s$    

ÿ
rD   c                 G   sB   t |ƒ}t|ƒdkr,t|d tjƒr,|d S t td| ƒ|¡S dS )zØ
    Execute the sequence of nets or steps once.

    Examples:
    - Do('myDo', net1, net2, ..., net_n)
    - Do('myDo', list_of_nets)
    - Do('myDo', step1, step2, ..., step_n)
    - Do('myDo', list_of_steps)
    r   r   r   N©r   r   r   r   ZExecutionStepÚscoped_execution_stepr   ©r&   r   r
   r
   r   r      s    

ÿ
ÿr   c                 G   sF   t |ƒ}t|ƒdkr,t|d tjƒr,|d S tjtd| ƒ|dd�S dS )a  
    Execute the nets or steps in parallel, waiting for all of them to finish

    Examples:
    - DoParallel('pDo', net1, net2, ..., net_n)
    - DoParallel('pDo', list_of_nets)
    - DoParallel('pDo', step1, step2, ..., step_n)
    - DoParallel('pDo', list_of_steps)
    r   r   Ú
DoParallelT)Zconcurrent_substepsNrE   rG   r
   r
   r   rH     s    

ÿýrH   c                    st   t |ƒ\}‰t|tjƒr&tˆ||ƒ‰n
tˆ|ƒ‰‡ ‡‡fdd„}tˆƒrhtˆdfƒ}tˆ d ||dƒƒS |dƒS dS )a  
    Execute nets_or_steps once if condition_blob_or_net evaluates as true.

    If condition_blob_or_net is Net, the condition is its last external_output
    that must be a single bool. And this net will be executed before
    nets_or_steps so as to get the condition.
    c                    s   t jt| ˆ ƒˆˆdd�S )NT©Úshould_stop_blobZ	only_once©r   rF   r   ©r   ©r&   r   Ú	stop_blobr
   r   Úif_step7  s    üz_RunOnceIf.<locals>.if_stepFz/_RunOnceIfz_RunOnceIf-innerÚ
_RunOnceIfN©r4   r   r   r   r!   r   r/   r   )r&   r2   r   Úcondition_not_netrO   r*   r
   rM   r   rP   (  s    ÿ
ÿrP   c                 C   sN   t |tjƒr t|ƒ}t||ƒ}nt|ƒ\}}t||ƒ}tjtd| ƒ||dd�S )zq
    Similar to _RunOnceIf() but Execute nets_or_steps once if
    condition_blob_or_net evaluates as false.
    Ú_RunOnceIfNotTrI   )r   r   r   r)   r!   r5   rF   r   )r&   r2   r   r3   Zcopy_netr
   r
   r   rS   G  s    
ürS   c                 C   sd   t  d¡}|jg |d�}t  d¡}| |g¡}t jtd| ƒt||ƒ|d�}t| d t| d |ƒ|ƒS )a  
    Execute nets_or_steps iter_num times.

    Args:
    nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or
                   a list nets.
    iter_num:    the number times to execute the nets_or_steps.

    Returns:
    A ExecutionStep instance.
    zinit-net)Z
init_countzFor-iterz	For-inner©rJ   z/Forz/For-init-net)r   r   ZCreateCounterZ	CountDownrF   r   r!   r   )r&   r   Ziter_numZinit_netZiter_cntZiter_netZ	iter_doneZfor_stepr
   r
   r   ÚFor[  s    

ýþrU   c                    st   t |ƒ\}‰t|tjƒr&tˆ||ƒ‰n
tˆ|ƒ‰‡ ‡‡fdd„}tˆƒrhtˆdfƒ}tˆ d ||dƒƒS |dƒS dS )aX  
    Execute nets_or_steps when condition_blob_or_net returns true.

    Args:
    condition_blob_or_net: If it is an instance of Net, its last
      external_output must be a single bool.
    nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or
                   a list nets.

    Returns:
    A ExecutionStep instance.
    c                    s   t jt| ˆ ƒˆˆd�S )NrT   rK   rL   rM   r
   r   Ú
while_step‰  s
    ýzWhile.<locals>.while_stepFz/WhilezWhile-innerÚWhileNrQ   )r&   r2   r   rR   rV   r*   r
   rM   r   rW   u  s    ÿ
rW   c                 C   sD   t |tjƒr t|ƒ}t||ƒ}nt t|ƒ¡}tjtd| ƒ||d�S )zc
    Similar to While() but execute nets_or_steps when
    condition_blob_or_net returns false
    ÚUntilrT   )	r   r   r   r)   r!   r'   ÚstrrF   r   )r&   r2   r   rN   r
   r
   r   rX   �  s    ýrX   c                 C   s^   t |ƒ\}}t|tjƒr&t|||ƒ}n
t||ƒ}t|dfƒ}t| d |tjtd| ƒ||d�ƒS )a£  
    Execute nets_or_steps when condition_blob_or_net returns true. It will
    execute nets_or_steps before evaluating condition_blob_or_net.

    Args:
    condition_blob_or_net: if it is an instance of Net, tts last external_output
      must be a single bool.
    nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or
                   a list nets.

    Returns:
    A ExecutionStep instance.
    Fz/DoWhilezDoWhile-innerrT   )	r4   r   r   r   r#   r/   r   rF   r   )r&   r2   r   rR   rN   r*   r
   r
   r   ÚDoWhile®  s    ÿ
ýrZ   c                 C   sl   t |tjƒs,t |¡}tjtd| ƒ||d�S t||ƒ}t|ƒ}t|dfƒ}t	| d |tjtd| ƒ||d�ƒS )aÝ  
    Similar to DoWhile() but execute nets_or_steps when
    condition_blob_or_net returns false. It will execute
    nets_or_steps before evaluating condition_blob_or_net.

    Special case: if condition_blob_or_net is a blob and is pre-set to
    true, then only the first net/step of nets_or_steps will be executed and
    loop is exited. So you need to be careful about the initial value the
    condition blob when using DoUntil(), esp when DoUntil() is called twice.
    ÚDoUntilrT   Fz/DoUntilzDoUntil-inner)
r   r   r   r'   rF   r   r#   r)   r/   r   )r&   r2   r   rN   r*   r
   r
   r   r[   Ï  s    
ý
ýr[   c                    s(   t |ƒ}t tdˆ ƒ‡ fdd„|D ƒ¡S )aÿ  
    Execute the steps for which the condition is true.
    Each condition is a tuple (condition_blob_or_net, nets_or_steps).
    Note:
      1. Multi steps can be executed if their conditions are true.
      2. The conditions_blob_or_net (if it is Net) of all steps will be
         executed once.

    Examples:
    - Switch('name', (cond_1, net_1), (cond_2, net_2), ..., (cond_n, net_n))
    - Switch('name', [(cond_1, net1), (cond_2, net_2), ..., (cond_n, net_n)])
    - Switch('name', (cond_1, net_1))
    ÚSwitchc                    s    g | ]\}}t ˆ d  ||ƒ‘qS )z/Switch)rP   ©r   ZcondÚstep©r&   r
   r   Ú
<listcomp>  r   zSwitch.<locals>.<listcomp>©r   r   rF   r   ©r&   Z
conditionsr
   r_   r   r\   ð  s
    þr\   c                    s(   t |ƒ}t tdˆ ƒ‡ fdd„|D ƒ¡S )zU
    Similar to Switch() but execute the steps for which the condition is False.
    Ú	SwitchNotc                    s    g | ]\}}t ˆ d  ||ƒ‘qS )z
/SwitchNot)rS   r]   r_   r
   r   r`     s   ÿzSwitchNot.<locals>.<listcomp>ra   rb   r
   r_   r   rc     s    
ÿþrc   Nc                 C   sV   |st | d ||ƒS t|tjƒr*t|ƒ}n|}t| d t | d ||ƒt| d ||ƒƒS )a†  
    condition_blob_or_net is first evaluated or executed. If the condition is
    true, true_nets_or_steps is then executed, otherwise, false_nets_or_steps
    is executed.

    If condition_blob_or_net is Net, the condition is its last external_output
    that must be a single bool. And this Net will be executred before both
    true/false_nets_or_steps so as to get the condition.
    z/Ifz/If-truez	/If-false)rP   r   r   r   r)   r   rS   ©r&   r2   Ztrue_nets_or_stepsZfalse_nets_or_stepsr3   r
   r
   r   ÚIf  s    ÿ
ÿüre   c                 C   sV   |st | d ||ƒS t|tjƒr*t|ƒ}n|}t| d t | d ||ƒt| d ||ƒƒS )zy
    If condition_blob_or_net returns false, executes true_nets_or_steps,
    otherwise executes false_nets_or_steps
    z/IfNotz/IfNot-truez/IfNot-false)rS   r   r   r   r)   r   rP   rd   r
   r
   r   ÚIfNot+  s    ÿ
ÿürf   )N)N) Ú__doc__Zcaffe2.pythonr   Zfuture.utilsr   r   Úsetr   r   r   r   r!   r#   r)   r/   r4   r5   rB   rD   r   rH   rP   rS   rU   rW   rX   rZ   r[   r\   rc   re   rf   r
   r
   r
   r   Ú<module>   s<   		 ),(!! ÿ
 ÿ