3
I4W^þK  ã               @   s  d Z ddlmZ ddlmZ ddlmZ ddlm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/d0„ Z d1d2„ Z!d3d4„ Z"d:d6d7„Z#d;d8d9„Z$d5S )<z”
Implement functions for controlling execution of nets and steps, including
  Do
  DoParallel
  For-loop
  While-loop
  Do-While-loop
  Switch
  If
é    )Úabsolute_import)Údivision)Úprint_function)Úunicode_literals)Úcore)Ú	viewitemsé   c             C   s@   d|| f }|}x |t kr0d|tf }td7 aqW t j|ƒ |S )Nz%s/%sz%s_%dr   )Ú_used_step_namesÚ_current_idxÚadd)Úcontrol_nameÚ	base_nameZconcat_nameZ	next_name© r   ú6/tmp/pip-build-e66j97b2/torch/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>=   s    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Úappend)r   r   r    )r   r!   r   r   r   Ú_AppendNetsK   s
    
r$   c             C   s6   t | jƒ jƒdks"td| jj ƒ‚tj| jƒ 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 outputr   éÿÿÿÿ)r   ÚProtoZexternal_outputÚAssertionErrorÚnamer   ÚBlobReference)Úcondition_netr   r   r   ÚGetConditionBlobFromNetT   s    r+   c              G   sL   t | ƒ} tjdƒ}x4| D ],\}}|jg |gg |tjjd�}|j|ƒ qW |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    
r1   c             C   s@   t | tjƒrt| ƒ}n| }tjdƒ}|j|ƒ}|j|ƒ ||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_blobr2   r0   r   r   r   ÚNotNet‚   s    



r6   c             C   s&   t jdƒ}|j| ƒ}|j|ƒ ||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/   )r5   r*   r0   r   r   r   Ú_CopyConditionBlobNetš   s    



r7   c       
      C   s
  t |tƒs|S t|ƒdkr*|r&|d S dS tj| ƒ}xÆtt|ƒƒD ]¶}|| jƒ }|j|jƒ jksft‚|j	|jƒ j	kszt‚|jƒ j
j|j
ƒ |jƒ jj|jƒ t|| ƒ}|dkr¸|}n|j|ƒ||gƒ}x,t|| jƒD ]\}}	|j|  |	7  < qÚW qBW |j|ƒ |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_optionr'   Ú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&    


rD   c       
      C   sœ   |sdS t |tƒstdƒ‚t|ƒdkrBt|d ƒ}t|ƒ\}}|S tj| ƒ}x@tt|ƒƒD ]0}t|| ƒ}|dkrx|}	qZ|j	|ƒ|	|gƒ}	qZW |j
|	ƒ |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+   r7   r   r   r8   r<   r/   )
r(   r=   r>   r5   r*   Ú_Zcombined_netr?   r@   rA   r   r   r   ÚCombineConditionsÔ   s"    


rF   c             G   sB   t |ƒ}t|ƒdkr,t|d tjƒr,|d S tj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   Ú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_substepsN)r   r   r   r   rG   rH   r   )r(   r   r   r   r   rI     s    
rI   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_blobÚ	only_once)r   rH   r   )r   )r(   r   Ú	stop_blobr   r   Úif_step7  s
    z_RunOnceIf.<locals>.if_stepFz/_RunOnceIfz_RunOnceIf-innerÚ
_RunOnceIfN)r6   r   r   r   r"   r   r1   r    )r(   r4   r   Úcondition_not_netrM   r,   r   )r(   r   rL   r   rN   (  s    
rN   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.
    Ú_RunOnceIfNotT)rJ   rK   )r   r   r   r+   r"   r7   rH   r   )r(   r4   r   r5   Zcopy_netr   r   r   rP   G  s    
rP   c             C   sd   t jdƒ}|jg |d�}t jdƒ}|j|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	CountDownrH   r   r"   r    )r(   r   Ziter_numZinit_netZiter_cntZiter_netZ	iter_doneZfor_stepr   r   r   ÚFor[  s    

rQ   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 )N)rJ   )r   rH   r   )r   )r(   r   rL   r   r   Ú
while_step‰  s    zWhile.<locals>.while_stepFz/WhilezWhile-innerÚWhileN)r6   r   r   r   r"   r   r1   r    )r(   r4   r   rO   rR   r,   r   )r(   r   rL   r   rS   u  s    
rS   c             C   sD   t |tjƒr t|ƒ}t||ƒ}ntjt|ƒƒ}tjtd| ƒ||d�S )zc
    Similar to While() but execute nets_or_steps when
    condition_blob_or_net returns false
    ÚUntil)rJ   )	r   r   r   r+   r"   r)   ÚstrrH   r   )r(   r4   r   rL   r   r   r   rT   �  s    rT   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-inner)rJ   )	r6   r   r   r   r$   r1   r    rH   r   )r(   r4   r   rO   rL   r,   r   r   r   ÚDoWhile®  s    
rV   c             C   sl   t |tjƒs,tj|ƒ}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.
    ÚDoUntil)rJ   Fz/DoUntilzDoUntil-inner)
r   r   r   r)   rH   r   r$   r+   r1   r    )r(   r4   r   rL   r,   r   r   r   rW   Ï  s    

rW   c                s(   t |ƒ}tj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)rN   )r   ÚcondÚstep)r(   r   r   ú
<listcomp>  s    zSwitch.<locals>.<listcomp>)r   r   rH   r   )r(   Ú
conditionsr   )r(   r   rX   ð  s    rX   c                s(   t |ƒ}tj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)rP   )r   rY   rZ   )r(   r   r   r[     s   zSwitchNot.<locals>.<listcomp>)r   r   rH   r   )r(   r\   r   )r(   r   r]     s
    
r]   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)rN   r   r   r   r+   r    rP   )r(   r4   Útrue_nets_or_stepsÚfalse_nets_or_stepsr5   r   r   r   ÚIf  s    
r`   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)rP   r   r   r   r+   r    rN   )r(   r4   r^   r_   r5   r   r   r   ÚIfNot+  s    
ra   )N)N)%Ú__doc__Ú
__future__r   r   r   r   Zcaffe2.pythonr   Zfuture.utilsr   r
   Úsetr	   r   r   r   r"   r$   r+   r1   r6   r7   rD   rF   r    rI   rN   rP   rQ   rS   rT   rV   rW   rX   r]   r`   ra   r   r   r   r   Ú<module>   s@   		 ),(!!
