o
    iu                     @   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   e/var/www/html/eduruby.in/lip-sync/lip-sync-env/lib/python3.10/site-packages/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_libs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 ]$}| j|jkrtd|j }tt|D ]}|| || kr*tdqq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   r3   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
_targetctxrefresh_install_typegetr6   _type_cacher   	_lower_me)r   r:   r;   r<   r   r   r   r   H   s   



zStencilFunc.__init__c              
   C   s"  g }|  D ]\}}|j}|j}g }	|jD ]u}
t|
tjr|| t|dkrEt	|||}t	||d |}|	t
|||
j| qg }|D ]}t	|||}||g7 }qI|d|}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.
        r5   r   stencil_index)itemsscopelocbody
isinstancer   Returnappendr*   VarSetItemvalueredefineExprbuild_tupleAssign)r   blocks
index_varsout_name
ret_blockslabelblockrG   rH   new_bodystmtZrvarZivarZvar_index_varsZone_var	index_vars_index_var
tuple_callsir   r   r   replace_return_with_setitemZ   s2   

z'StencilFunc.replace_return_with_setitemc           *      C   s  i }g }	t jdkrtd|| t|j |du rd}
nd}
t||kr.tdt||f t|j}t	 }|j
 D ]}|j}|j}g }|jD ]o}t|tjrqt|jtjrqt jdkritd|jj|jj |jj||jj< t|tjrt|jtjr|jjdv r|jjj|jv st|tjr|jj|jv rtd	t|tjrt|jtjr|jjd
v r|jjj|jv r|jjj|vr|jjdkr|jj}n|jj}||jjj |
rt|dsJ |j|v r|	||j g7 }	n|j|v r|	||j g7 }	ntd|dkrt||d |}|d|}||j }t|t j!j"r|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| qJtj/t0j|||}|)t||| |)ttj.|jj|||j| qJg }g }|d|}g }g } ||j }t1|D ]}!|d|}|)tt|!||| ||g7 }t|||! |}||g7 }|d|}| |g7 } |d|}"tj.|||! |}#|)t|#|"| t|t j2r||! }$n|dd }$t|$t j!j"rx|d|}t#$t%}t j&'|}|||j< t(d||}|)t||| tj*||"||! gd|}|+| j,|$t j-gi ||< |)t||| qtj/t0j|"||! |}|)t||| qtj3| |}%|)t|%|| |)ttj.|jj|||j| qJ|)| qJ||_q<|
radd t1|D }t|	dkrtd|	D ]}&t|&t4st|&t5r/t1t|&D ]=}'|&|' }(t|(tjr|(j|v r||(j }(t|(t6r&t7||' d |(||' d< t8||' d |(||' d< qtdt|&})n't|&t6rRt7|d d |&|d d< t8|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].
        r5   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_getitemrd   namezDstencil kernel index is not constant, 'neighborhood' option requiredr   rE   r3   r   const_indexZind_stencil_indexc                 S   s   g | ]}d d gqS )r   r   ).0_r   r   r   
<listcomp>+      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.)9r   DEBUG_ARRAY_OPTprintr   dump_blocksrT   r*   r(   Zget_tuple_tablesetvaluesrG   rH   rI   rJ   r   rS   rO   ZConsttargetre   rQ   op	arg_namesrN   indexr\   addhasattrr   rM   rP   r   miscZ	SliceTypenumbaZnjitr3   Z	functionsZ
DispatcherGlobalrL   callZget_call_typer>   intprd   binopoperatorr)   Z
ConstSizedrR   tuplelistintminmax)*r   ZkernelZindex_namesr'   r6   standard_indexedtypemap	calltypesZ
const_dictZkernel_constsZneed_to_calc_kernelZtuple_tablerelatively_indexedrY   rG   rH   rZ   r[   Zstmt_index_varr\   ZtmpvarZstmt_index_var_typZsa_varZsa_funcZsa_func_typZg_saZslice_addition_callZacc_callrU   Zsum_resultsr]   Zconst_index_varsZind_stencilsdimZ
getitemvarZgetitemcallZone_index_typr^   rs   r-   teZ	index_lenr   r   r   ra      s6  




















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
r@tdtj	
||d j|d j}|||fS )Nr5   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   rk   rl   r   rm   r:   rT   rJ   r   npytypesArrayr   
numba.corer   Ztype_inference_stager>   r?   r'   Zlayout)r   argtysr   r   r   r   rh   real_retr   r   r   r   L  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)r7   strr9   r   dict_type_meZinsert_user_function)r   Z	typingctxZ_ty_clsr   r   r   rA   e  s   zStencilFunc._install_typec           
      C   s0   | j | \}}}}| j|||||g|R  }	|	S r   )rC   _stencil_wrapper)
r   r   kwtysr   sigretrh   resultr   r   new_funcr   r   r   r   o  s   
zStencilFunc.compile_for_argtysc                 C   s:  | j durt| j |d jkrtdt| j |d jf |}d}d}d|v r6||d f7 }|d7 }|d }d|v rE||d f7 }|d7 }|| jv rU| j| \}}}}|S | |\}}	}
t|g|R  }d	d
| j	j
|}t|t v 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   rb    outz
, out=Noner6   z, neighborhood=Nonez*def __numba_dummy_stencil({}{}):
    pass
,Z__numba_dummy_stencil)pysig)r6   r*   r'   r   rC   r   r
   formatjoinr:   rr   execglobalslocalsevalreplacer   pysignaturer?   Zinsert_func_defnrD   )r   r   r   Zargtys_extra	sig_extrar   _sigrh   r   r   r   r   Z
dummy_textZ
dummy_funcr   r   r   r   v  s:   

zStencilFunc._type_mec           
      C   s   i }|  }i |_|j D ]2\}}t |j| }g |_|j| jD ]}t |}	|j|	 ||v r:|| ||	< q#||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.
        )copyrT   rF   deepcopyrI   rL   )
r   r   r   copy_calltypeskernel_copyZblock_labelrY   Z	new_blockr[   Zscopyr   r   r   copy_ir_with_calltypes  s   
z"StencilFunc.copy_ir_with_calltypesc           C   
      s  |  | j|\}}t|j |jd }	t|j|\}
}t|j}t|j|
||| d|v r5t	dt
d|}tjdkrFtd|| |d }tjdkratd||jt|j| t|j dtt|d	d
| jf }g }t|jD ]}t
dt| |}||g7 }qwt
d|}t
d|}d}|d ur|d|7 }dt| jv r|d|7 }| jdg }|	|v rt	dtt|t|j dkrt	d| |||j| j|||\}}| jd u 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 ]-}t"|| d t#r:|| d }|| d }nd||}d||}|$||f q!t|dkrq|d|	 7 }|D ]}||	krk|d| 7 }q^|d7 }t
d|}|d||	7 }dd } |d u rt%&|jjj'}!d|||!}"d| jv r| jd }#t(j))|#}$| j*+|$|jsd }%t	|%nd}#|d!|" 7 }t|jD ]G}&d"g|j }'d"g|j }(d#| j|& d |'|&< d$| j|& d |(|&< |d!d%|d!|'| |# 7 }|d!d%|d!|(| |# 7 }qn.d| jv r<| jd }#t(j))|#}$| j*+|$|js.d }%t	|%d&|| |#}"|d!|" 7 }d})t|jD ](}t|)D ]}*|d!7 }qI|d'|| || d |||| d 7 }|)d7 })qCt|)D ]}*|d!7 }qp|d(|7 }|d)|7 }tjdkrtd* t| t,|t- v t. f t/|}+|d urt01|+},|,|_2dd+l3m4}- |-5|+}.t6|.j t|.j}/i }0||||g|j | }1|/7 D ]!\}2}3|2|1vrt"|3t8j9sJ |3j:;|3j<|3j=}4|4j<|0|2< qt>|.j|0 t?|.j@ d  tA|j |_t?|j@ d }5 fd,d-|D }tjdkrCtd.|  td/ t|.j td0 t|j |.j7 D ]{\}6}7tB|7jCD ]o\}}8t"|8t8jDr|8jEj<|kr|8j=}9|7j:}:t8F|:|9};|7jCd | |;_C|7jC|d d  |7_CtG|j@ }<|;$t8H|<|9 |j7 D ]
\}=}>|>|.j|=< q|7|.j|5< |;|.j|6< |D ]}?|.j|? $t8H|5|9 q nqQqH tI|.j|._t6|.j t"|tJjKsJ |}@tL|@}Atjdkrtd1|A t|.j tM|.j |-N| j*| jO|.|Ad |-jPi }B|BS )2Nr   r   z6Cannot use the reserved word 'out' in stencil kernels.Z__sentinel__r5   name_var_tabler   z__numba_stencil_%s_%s-rh   rs   r6   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 | st | rdS t | r| dk rdS dS d S t| S )Nznp.nanr   z-np.infznp.inf)npisfiniteisnanisinfr   )cvalr   r   r   cval_as_strD  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   rg   xZstencil_stub_last_labelr   r   ri     rj   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   r:   r   Zremove_argsrT   rr   Zcopy_propagateZget_name_var_tableZapply_copy_propagater   Zget_unused_var_namer   rk   rl   dtyper7   rm   hexr9   r   r)   r'   r   r   r   r=   r<   rB   r*   rn   ra   r6   r`   r   rJ   r   rL   r   Zas_dtyper"   r   typeofr>   Zcan_convertr   r   r   r   r   r   r   r   r   run_frontendZremove_delsrF   r   rM   rG   rP   re   rH   Zreplace_var_namesr   keysZadd_offset_to_labels	enumeraterI   rS   rp   ZBlockr   ZJumpZrename_labelsr   Typer~   Zfixup_var_define_in_scopeZ
compile_irr?   ZDEFAULT_FLAGS)Cr   r   r   r   r   r   r   r   r   Z	first_argZin_cpsZout_cpsr   Zsentinel_nameZ	the_arrayZstencil_func_namerU   r-   Zindex_var_namerV   Zneighborhood_namer   r   Zkernel_sizer   rW   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_namesre   varZnew_varZ	new_labelrX   rY   instrH   rG   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 urt| j |d jkrtdt| j |d jd|v rO|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rhtd	||| | |\}	}
}| j|d |	|
|g|R  }|d u r|j| S |j||f  S )
Nr   zD{} dimensional neighborhood specified for {} dimensional input arrayr   c                 S      g | ]}t j|qS r   r   r   r   r   r   r   ri         z(StencilFunc.__call__.<locals>.<listcomp>c                 S   r   r   r   r   r   r   r   ri     r   c                 S   r   r   r   r   r   r   r   ri     r   r5   r!   )r6   r*   r'   r(   r   r   r   Z
from_dtyper   r   r   Z
map_layoutr}   r   rk   rl   r   r   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%   r8   r   r`   ra   r   rA   r   r   r   r   r!   r   r   r   r   r4   A   s     * I
(  Ir4   constantc                 K   sX   t | ts
d}| }n| }d }|D ]}|dvrtd| qt||}|d ur*||S |S )Nr   )r   r   r6   zUnknown stencil option )rJ   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   r4   )r   r   r:   r;   r<   r   r   	decorated7  s   
z_stencil.<locals>.decorated)r(   )r;   r<   r   r   r   r   r   3  s   r   c                 C   s   t t tjjdS )z lowering for dummy stencil callsr   )lirConstantZIntTyper   rz   Zbitwidth)r   r   r   r   r   r   r   stencil_dummy_lower>  s   r   )r   )&r   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   rw   r|   Znumba.npr   objectr   r.   r3   r4   r   r   r   r   r   r   r   <module>   s4   $
     
e