U
    ,d                     @   s   d dl Z d dlZd dlmZ d dlmZmZm	Z	mZm
Z
mZmZ d dlmZmZmZ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Zd dlZd d	lmZ G d
d deZedd Z dd Z!G dd deZ"dddZ#dd Z$ee#dd Z%dS )    N)ir)typestypingutilsr   configir_utilsregistry)CallableTemplate	signatureinfer_globalAbstractTemplate)lower_builtin)register_jitable)NumbaValueError)literal_unroll)numpy_supportc                   @   s    e Zd ZdZdd Zdd ZdS )StencilFuncLowererzMCallable class responsible for lowering calls to a specific StencilFunc.
    c                 C   s
   || _ d S N)stencilFunc)selfZsf r   :/tmp/pip-unpacked-wheel-eu7e0c37/numba/stencils/stencil.py__init__   s    zStencilFuncLowerer.__init__c                 C   s:   | j |ji |jd }|||j||}||jg |S r   )r   compile_for_argtysargsreturn_typeZcall_internalZfndescZadd_linking_libsZlibrary)r   contextbuildersigr   Zcresresr   r   r   __call__   s     zStencilFuncLowerer.__call__N)__name__
__module____qualname____doc__r   r    r   r   r   r   r      s   r   c                 G   s\   | j }t|D ]H}| j|jkr&td|j }tt|D ]}|| || kr8tdq8qd S )Nz\Secondary stencil array does not have same number  of dimensions as the first stencil input.zaSecondary stencil array has some dimension smaller the same dimension in the first stencil input.)shaper   ndim
ValueErrorrangelen)ar   ZashapeargZargshapeir   r   r   !raise_if_incompatible_array_sizes$   s    
r-   c                 C   s   t | j| | j| S )z_ Called by stencil in Python mode to add the loop index to a
        user-specified slice.
    )slicestartstop)Z	the_sliceaddendr   r   r   slice_addition;   s    r2   c                   @   sd   e Zd 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S )StencilFuncz@
    A special type to hold stencil information for the IR.
    r   c                 C   s   t | j| _t |  jd7  _|| _|| _|| _g | _tjj	| _
tjj| _| j
  | j  | | j
 | jd| _i | _t| | _d S )N   neighborhood)type
id_counterid	kernel_irmodeoptionskwsr   Z
cpu_targetZtyping_context
_typingctxZtarget_context
_targetctxZrefresh_install_typegetr5   _type_cacher   	_lower_me)r   r9   r:   r;   r   r   r   r   H   s    



zStencilFunc.__init__c              
   C   s2  g }|  D ]\}}|j}|j}g }	|jD ]}
t|
tjr|| t|dkrt	|||}t	||d |}|	t
|||
j| ng }|D ]}t	|||}||g7 }qtd}t	|||}tj||}|	t||| t	|||}t
|||
j|}|	| q,|	|
 q,|	|_q|S )z
        Find return statements in the IR and replace them with a SetItem
        call of the value "returned" by the kernel into the result array.
        Returns the block labels that contained return statements.
        r4   r   stencil_index)itemsscopelocbody
isinstancer   ZReturnappendr)   VarSetItemvaluer   mk_unique_varExprbuild_tupleAssign)r   blocks
index_varsout_name
ret_blockslabelblockrE   rF   new_bodystmtZrvarZivarZvar_index_varsZone_var	index_vars_index_names_index_var
tuple_callsir   r   r   replace_return_with_setitemZ   s4    


z'StencilFunc.replace_return_with_setitemc           -      C   s.  i }g }	t jdkr*td|| t|j |dkr8d}
n$d}
t||kr\tdt||f t|j}t	 }|j
 D ]b}|j}|j}g }|jD ]>}t|tjrt|jtjrt jdkrtd|jj|jj |jj||jj< t|tjr t|jtjr |jjdkr |jjj|jks>t|tjrF|jj|jkrFtd	t|tjrt|jtjr|jjd
kr|jjj|jkr|jjj|kr|jjdkr|jj}n|jj}||jjj |
rt|dst|j|kr|	||j g7 }	n&|j|kr|	||j g7 }	ntd|dkrt||d |}t d}t|||}||j }t|t!j"j#r.t|t d|}t$%t&}t!j'(|}|||j< t)d||}|*t||| tj+|||gd|}|,| j-|t!j.gi ||< |*t||| |*ttj/|jj|||j| nNtj0t1j|||}|*t||| |*ttj/|jj|||j| qg }g }t d}t|||} g }!g }"||j }t2|D ]}#t d}t|||}|*tt|#||| |!|g7 }!t|||# |}||g7 }t d}t|||}|"|g7 }"t d}$t||$|}%tj/||!|# |}&|*t|&|%| t|t!j3r||# }'n|dd }'t|'t!j"j#rPt|t d|}t$%t&}t!j'(|}|||j< t)d||}|*t||| tj+||%||# gd|}|,| j-|'t!j.gi ||< |*t||| n,tj0t1j|%||# |}|*t||| qtj4|"|}(|*t|(| | |*ttj/|jj| ||j| q|*| q||_qx|
r&dd t2|D }t|	dkrtd|	D ]})t|)t5s.t|)t6rt2t|)D ]|}*|)|* }+t|+tjrj|+j|krj||+j }+t|+t7rt8||* d |+||* d< t9||* d |+||* d< ntdq:t|)},nNt|)t7rt8|d d |)|d d< t9|d d |)|d d< d},ntd|,|krtdq||fS )z
        Transforms the stencil kernel as specified by the user into one
        that includes each dimension's index variable as part of the getitem
        calls.  So, in effect array[-1] becomes array[index0-1].
        r4   add_indices_to_kernelNTFD%d dimensional neighborhood specified for %d dimensional input arrayzremembering in const_dict)setitemZstatic_setitemz?Assignments to arrays passed to stencil kernels is not allowed.)getitemZstatic_getitemrb   namezDstencil kernel index is not constant, 'neighborhood' option requiredr   rC   r2   r   const_indexZind_stencil_indexc                 S   s   g | ]}d d gqS )r   r   ).0_r   r   r   
<listcomp>1  s     z5StencilFunc.add_indices_to_kernel.<locals>.<listcomp>z=Stencil kernel with no accesses to relatively indexed arrays.zCstencil kernel index is not constant,'neighborhood' option requiredz/Non-tuple or non-integer used as stencil index.z2Stencil index does not match array dimensionality.):r   DEBUG_ARRAY_OPTprintr   dump_blocksrQ   r)   r'   Zget_tuple_tablesetvaluesrE   rF   rG   rH   r   rP   rL   ZConsttargetrc   rN   op	arg_namesrK   indexrY   addhasattrAssertionErrorr   rJ   rM   r   miscZ	SliceTypenumbaZnjitr2   Z	functionsZ
DispatcherZGlobalrI   callZget_call_typer=   intprb   Zbinopoperatorr(   Z
ConstSizedrO   tuplelistintminmax)-r   kernelZindex_namesr&   r5   standard_indexedtypemap	calltypesZ
const_dictZkernel_constsZneed_to_calc_kernelZtuple_tablerelatively_indexedrV   rE   rF   rW   rX   Zstmt_index_varrY   ZtmpnameZtmpvarZstmt_index_var_typZsa_varZsa_funcZsa_func_typZg_saZslice_addition_callZacc_callrR   Zsum_resultsrZ   r[   Zconst_index_varsZind_stencilsdimZgetitemnameZ
getitemvarZgetitemcallZone_index_typr\   rp   r,   teZ	index_lenr   r   r   r_      sX   












   



 




 


  



z!StencilFunc.add_indices_to_kernelc                 C   s   t jdkr"td| t| jj t|d tj	j
s<tdddlm} || j| j| j|d i \}}}}t|tj	j
rtdtj	
||d j|d j}|||fS )Nr4   get_return_typer   zGThe first argument to a stencil kernel must be the primary input array.)typed_passesz:Stencil kernel must return a scalar and not a numpy array.)r   rh   ri   r   rj   r9   rQ   rH   r   npytypesArrayr   
numba.corer   Ztype_inference_stager=   r>   r&   Zlayout)r   argtysr   r   r   r   rf   real_retr   r   r   r   R  s,    

zStencilFunc.get_return_typec                 C   s2   t dt| j tft| | jd}|| | dS )zmConstructs and installs a typing class for a StencilFunc object in
        the input typing context.
        ZStencilFuncTyping_)keyZgenericN)r6   strr8   r   dict_type_meZinsert_user_function)r   Z	typingctxZ_ty_clsr   r   r   r?   k  s    zStencilFunc._install_typec           
      C   s.   | j | \}}}}| j|||||f| }	|	S r   )rA   _stencil_wrapper)
r   r   kwtysr   sigretrf   resultr   r   new_funcr   r   r   r   u  s    
 zStencilFunc.compile_for_argtysc                 C   s8  | j dk	r:t| j |d jkr:tdt| j |d jf |}d}d}d|krl||d f7 }|d7 }|d }d|kr||d f7 }|d7 }|| jkr| j| \}}}}|S | |\}}	}
t|f| }d	d
| j	j
|}t|t kt f td}|jt|d}| j| j| |fg |||	|
f| j|< |S )z
        Implement AbstractTemplate.generic() for the typing class
        built by StencilFunc._install_type().
        Return the call-site signature.
        Nr   r`    outz
, out=Noner5   z, neighborhood=Nonez*def __numba_dummy_stencil({}{}):
    pass
,Z__numba_dummy_stencil)pysig)r5   r)   r&   r   rA   r   r
   formatjoinr9   ro   execglobalslocalsevalreplacer   pysignaturer>   Zinsert_func_defnrB   )r   r   r   Zargtys_extra	sig_extrar   Z_sigrf   r   r   r   r   Z
dummy_textZ
dummy_funcr   r   r   r   |  s>    

 zStencilFunc._type_mec           
      C   s   i }|  }i |_|j D ]d\}}t |j| }g |_|j| jD ].}t |}	|j|	 ||krF|| ||	< qF||j|< q||fS )a  
        Create a copy of a given IR along with its calltype information.
        We need a copy of the calltypes because copy propagation applied
        to the copied IR will change the calltypes and make subsequent
        uses of the original IR invalid.
        )copyrQ   rD   deepcopyrG   rI   )
r   r   r   copy_calltypeskernel_copyZblock_labelrV   Z	new_blockrX   Zscopyr   r   r   copy_ir_with_calltypes  s    
z"StencilFunc.copy_ir_with_calltypesc           B   
      s  |  | j|\}}t|j |jd }	t|j|\}
}t|j}t|j|
||| d|krjt	dt
d|}tjdkrtd|| |d }tjdkrtd||jt|j| t|j dtt|d	d
| jf }g }t|jD ]"}t
dt| |}||g7 }qt
d|}t
d|}d}|d k	rF|d|7 }dt| jkrd|d|7 }| jdg }|	|krt	dtt|t|j dkrt	d| |||j| j|||\}}| jd kr|| _tjdkrtd t|j |  |j||}tjdkr*td| t|j d|d!|j|}g }t|jD ]Z}t"|| d t#r|| d }|| d }nd||}d||}|$||f qNt|dkr|d|	 7 }|D ]}||	kr|d| 7 }q|d7 }t
d|}|d||	7 }dd } |d kr(t%&|jjj'}!d|||!}"d| jkr|| jd }#t(j))|#}$| j*+|$|jsd }%t	|%nd}#|d!|" 7 }t|jD ]}&d"g|j }'d"g|j }(d#| j|& d |'|&< d$| j|& d |(|&< |d!d%|d!|'| |# 7 }|d!d%|d!|(| |# 7 }qn\d| jkr| jd }#t(j))|#}$| j*+|$|jshd }%t	|%d&|| |#}"|d!|" 7 }d})t|jD ]P}t|)D ]}*|d!7 }q|d'|| || d |||| d 7 }|)d7 })qt|)D ]}*|d!7 }q|d(|7 }|d)|7 }tjdkr4td* t| t,|t- kt. f t/|}+|d k	rjt01|+},|,|_2dd+l3m4}- |-5|+}.t6|.j t|.j}/i }0||||g|j | }1|/7 D ]"\}2}3|2|1krt8|2|0|2< qt9|.j|0 t:|.j; d  t<|j |_t:|j; d }4 fd,d-|D }tjdkrrtd.|  td/ t|.j td0 t|j |.j7 D ] \}5}6t=|6j>D ]\}}7t"|7t?j@r|7jAjB|kr|7jC}8|6jD}9t?E|9|8}:|6j>d | |:_>|6j>|d d  |6_>tF|j; };|:$t?G|;|8 |j7 D ]\}<}=|=|.j|<< q|6|.j|4< |:|.j|5< |D ]}>|.j|> $t?G|4|8 qH qvqq| qq|tH|.j|._t6|.j t"|tIjJstK|}?tL|?}@tjdkrtd1|@ t|.j tM|.j |-N| j*| jO|.|@d |-jPi }A|AS )2Nr   r   z6Cannot use the reserved word 'out' in stencil kernels.Z__sentinel__r4   name_var_tabler   z__numba_stencil_%s_%s-rf   rp   r5   r   z	, {}=Nonestandard_indexingzYThe first argument to a stencil kernel must use relative indexing, not standard indexing.z[Standard indexing requested for an array name not present in the stencil kernel definition.zAfter add_indices_to_kernelz!After replace_return_with_setitemzdef {}({}{}):
r   z	{}[{}][0]z	{}[{}][1]z&    raise_if_incompatible_array_sizes(z)
Z
full_shapez    {} = {}.shape
c                 S   s@   t | s4t | rdS t | r<| dk r.dS dS nt| S d S )Nznp.nanr   z-np.infznp.inf)npisfiniteisnanisinfr   )cvalr   r   r   cval_as_strJ  s    


z1StencilFunc._stencil_wrapper.<locals>.cval_as_strz{} = np.empty({}, dtype=np.{})
r   z-cval type does not match stencil return type.z    :z:-{}z-{}:z{}[{}] = {}
z{}[:] = {}
z.for {} in range(-min(0,{}),{}[{}]-max(0,{})):
z{} = 0
z    return {}
znew stencil func textcompilerc                    s   g | ]}|  qS r   r   re   xZstencil_stub_last_labelr   r   rg     s     z0StencilFunc._stencil_wrapper.<locals>.<listcomp>zret_blocks w/ offsetsz"before replace sentinel stencil_irz#before replace sentinel kernel_copynew_stencil_param_types)Qr   r9   r   Zremove_argsrQ   ro   Zcopy_propagateZget_name_var_tableZapply_copy_propagater   Zget_unused_var_namer   rh   ri   dtyper6   rj   hexr8   r   r(   r&   r   r   r   r<   r;   r@   r)   rk   r_   r5   r^   r   rH   r{   rI   r   Zas_dtyper!   r   typeofr=   Zcan_convertr   r   r   r   r   r   r   r   r   run_frontendZremove_delsrD   rM   Zreplace_var_namesr}   keysZadd_offset_to_labels	enumeraterG   r   rP   rm   rc   rF   rE   ZBlockr|   ZJumpZrename_labelsr   Typers   rz   Zfixup_var_define_in_scopeZ
compile_irr>   ZDEFAULT_FLAGS)Br   r   r   r   r   r   r   r   r   Z	first_argZin_cpsZout_cpsr   Zsentinel_nameZ	the_arrayZstencil_func_namerR   r,   Zindex_var_namerS   Zneighborhood_namer   r   Zkernel_sizer   rT   Z	func_textrangeslohiZother_arrayZ
shape_namer   Zreturn_type_nameZout_initr   Zcval_tymsgr   Zstart_itemsZ	end_itemsoffsetjZstencil_funcr   r   Z
stencil_irZ	var_tableZnew_var_dictreserved_namesrc   varZ	new_labelrU   rV   instrF   rE   Z
prev_blockZbody_first_labellbZ	ret_blockarray_typesr   r   r   r   r   r     s    



 

      

 

  

 &







 







zStencilFunc._stencil_wrapperc                 O   s   | j d k	r:t| j |d jkr:tdt| j |d jd|kr|d }|j}t|}tj	
||jt|}tdd |D }tdd |D |g }nd }tdd |D }|}tjdkrtd	||| | |\}	}
}| j|d |	|
|f| }|d kr|j| S |j||f  S d S )
Nr   zD{} dimensional neighborhood specified for {} dimensional input arrayr   c                 S   s   g | ]}t j|qS r   r   r   r   r   r   r   rg     s     z(StencilFunc.__call__.<locals>.<listcomp>c                 S   s   g | ]}t j|qS r   r   r   r   r   r   rg     s     c                 S   s   g | ]}t j|qS r   r   r   r   r   r   rg     s     r4   r    )r5   r)   r&   r'   r   r   r   Z
from_dtyper   r   r   Z
map_layoutry   r   rh   ri   r   r   Zentry_point)r   r   kwargsr   ZrdtypeZrttypeZresult_typer   Zarray_types_fullr   r   r   r   r   r   r   r      s@    
 



zStencilFunc.__call__N)r!   r"   r#   r$   r7   r   r^   r_   r   r?   r   r   r   r   r    r   r   r   r   r3   A   s   + N
(  Gr3   constantc                 K   sX   t | tsd}| }n| }d }|D ]}|dkr td| q t||}|d k	rT||S |S )Nr   )r   r   r5   zUnknown stencil option )rH   r   r'   _stencil)Zfunc_or_moder;   r:   funcoptionwrapperr   r   r   stencil%  s    

r   c                    s&    dkrt d   fdd}|S )Nr   zUnsupported mode style c                    s"   ddl m} || }t| S )Nr   r   )r   r   r   r3   )r   r   r9   r:   r;   r   r   	decorated;  s    
z_stencil.<locals>.decorated)r'   )r:   r;   r   r   r   r   r   7  s    r   c                 C   s   t t tjjdS )z lowering for dummy stencil callsr   )lirConstantZIntTyper   rw   Zbitwidth)r   r   r   r   r   r   r   stencil_dummy_lowerB  s    r   )r   )&r   Znumpyr   Zllvmliter   r   r   r   r   r   r   r   r   Znumba.core.typing.templatesr	   r
   r   r   Znumba.core.imputilsr   Znumba.core.extendingr   Znumba.core.errorsr   Znumba.misc.specialr   ru   rx   Znumba.npr   objectr   r-   r2   r3   r   r   r   r   r   r   r   <module>   s2   $
     i
