U
    [eMM                  
   @   s*  d dl Z d dlZd dlmZ d dlm  mZ d dlZej	ddddd Z
ej	dddd	d
 Zej	ddddd Zej	dejejjejjddddgejjejjdddddd Zej	dddd ZejG dd dejZG dd dejZej	dddd Zej	dddd Zej	ddd d! Zeeed"d#d$g ej	ddd%d& Zej	ddd'd( Zej	dd)d*d+d, Zej	dd-ejjid)d.d/d0 Z ej	d1ddd2d3 Z!ej	d4ddd5d6 Z"ej	d7dejjejj#ejj#ejj#ejj#d8dd9d:d; Z$ej	d7dejjejj#ejj#ejj#ejj#d8dd9d<d= Z%ej	d>dejjejj#ejj#ejj#ejj#d8dd9d?d@ Z&ej	dej'ej'ejej(ejejejdAd)d.dBdC Z)ej	ejjejjdDddEdFdG Z*ej	d)ddHdI Z+ej	dddJdK Z,ej	dd)d*dLdM Z-dNdO Z.dS )P    N)typeszvoid(i8[:], i8)T)cachec                 C   s   |  |d  dS )z3Seed the random number generator with a given seed.i  N)fill)	rng_stateseed r   p/mounts/lovelace/software/anaconda3/envs/qiime2-amplicon-2024.2/lib/python3.8/site-packages/pynndescent/utils.pyr      s    r   z	i4(i8[:])c                 C   s   | d d@ d> d@ | d d> d@ | d A d? A | d< | d d@ d	> d@ | d d
> d@ | d A d? A | d< | d
 d@ d> d@ | d
 d> d@ | d
 A d? A | d
< | d | d A | d
 A S )zA fast (pseudo)-random number generator.

    Parameters
    ----------
    state: array of int64, shape (3,)
        The internal state of the rng

    Returns
    -------
    A (pseudo)-random int32 value
    r   l       l             l             l             r   )stater   r   r   tau_rand_int   s    r   z	f4(i8[:])c                 C   s   t | }tt|d S )a  A fast (pseudo)-random number generator for floats in the range [0,1]

    Parameters
    ----------
    state: array of int64, shape (3,)
        The internal state of the rng

    Returns
    -------
    A (pseudo)-random float32 in the interval [0, 1]
    i)r   absfloat)r   integerr   r   r   tau_rand-   s    r   zf4(f4[::1])r   C)readonly)dimi)localsfastmathr   c                 C   s:   d}| j d }t|D ]}|| | | |  7 }qt|S )zCompute the (standard l2) norm of a vector.

    Parameters
    ----------
    vec: array of shape (dim,)

    Returns
    -------
    The l2 norm of vec.
    g        r   )shaperangenpsqrt)vecresultr   r   r   r   r   norm>   s
    
r%   c                 C   sf   t j| t jd}t| D ]H}d}d}|rXt|| }t|D ]}||| kr< q$q<d}q$|||< q|S )aP  Generate n_samples many integers from 0 to pool_size such that no
    integer is selected twice. The duplication constraint is achieved via
    rejection sampling.

    Parameters
    ----------
    n_samples: int
        The number of random samples to select from the pool

    pool_size: int
        The size of the total pool of candidates to sample from

    rng_state: array of int64, shape (3,)
        Internal state of the random number generator

    Returns
    -------
    sample: array of shape(n_samples,)
        The ``n_samples`` randomly selected elements from the pool.
    dtypeTr   F)r!   emptyint64r    r   )	n_samples	pool_sizer   r$   r   Zreject_samplejkr   r   r   rejection_sample_   s    
r.   c                   @   s   e Zd ZdS )HeapTypeN)__name__
__module____qualname__r   r   r   r   r/      s   r/   c                   @   s0   e Zd Zedd Zedd Zedd ZdS )Heapc                 C   s   t | S N)Heap_get_indicesselfr   r   r   indices   s    zHeap.indicesc                 C   s   t | S r4   )Heap_get_distancesr6   r   r   r   	distances   s    zHeap.distancesc                 C   s   t | S r4   )Heap_get_flagsr6   r   r   r   flags   s    z
Heap.flagsN)r0   r1   r2   propertyr8   r:   r<   r   r   r   r   r3      s   

r3   c                 C   s   | j S r4   )r<   r6   r   r   r   r;      s    r;   c                 C   s   | j S r4   )r:   r6   r   r   r   r9      s    r9   c                 C   s   | j S r4   )r8   r6   r   r   r   r5      s    r5   r8   r:   r<   c                 C   sh   t jt| t|fdt jd}t jt| t|ft jt jd}t jt| t|ft jd}|||f}|S )a^  Constructor for the numba enabled heap objects. The heaps are used
    for approximate nearest neighbor search, maintaining a list of potential
    neighbors sorted by their distance. We also flag if potential neighbors
    are newly added to the list or not. Internally this is stored as
    a single ndarray; the first axis determines whether we are looking at the
    array of candidate graph_indices, the array of distances, or the flag array for
    whether elements are new or not. Each of these arrays are of shape
    (``n_points``, ``size``)

    Parameters
    ----------
    n_points: int
        The number of graph_data points to track in the heap.

    size: int
        The number of items to keep on the heap for each graph_data point.

    Returns
    -------
    heap: An ndarray suitable for passing to other numba enabled heap functions.
    r&   )r!   fullintint32inftyfloat32zerosuint8)n_pointssizer8   r:   r<   r$   r   r   r   	make_heap   s
     
rH   c                 C   s   |d d | j d k r|d d }|d }|}| | | | k rB|}|| j d k rd| | | | k rd|}||krpqq | | | |  | |< | |< || ||  ||< ||< |}q dS )zRestore the heap property for a heap with an out of place element
    at position ``elt``. This works with a heap pair where heap1 carries
    the weights and heap2 holds the corresponding elements.r   r   r   Nr   )Zheap1Zheap2elt
left_childright_childswapr   r   r   siftdown   s    rN   F)parallelr   c                 C   s   t | jd D ]}t| jd d ddD ]|}| ||f | |df  | |df< | ||f< |||f ||df  ||df< |||f< t||d|f | |d|f d q*q| |fS )a  Given two arrays representing a heap (indices and distances), reorder the
     arrays by increasing distance. This is effectively just the second half of
     heap sort (the first half not being required since we already have the
     graph_data in a heap).

     Note that this is done in-place.

    Parameters
    ----------
    indices : array of shape (n_samples, n_neighbors)
        The graph indices to sort by distance.
    distances : array of shape (n_samples, n_neighbors)
        The corresponding edge distance.

    Returns
    -------
    indices, distances: arrays of shape (n_samples, n_neighbors)
        The indices and distances sorted by increasing distance.
    r   r   r>   N)numbapranger   r    rN   )r8   r:   r   r,   r   r   r   deheap_sort   s    **(rR   idx)rO   r   r   c                 C   s  | d }| d }|j d }|j d }tj||fdtjd}tj||ftjtjd}	tj||fdtjd}
tj||ftjtjd}t|D ]}|| }t|D ]}t|D ]}|||f }|||f }|dk rqt	|}|r(|| |krt
|	| || || || |krnt
|	| || || q|| |krLt
|| |
| || || |krt
|| |
| || qqq| d }| d }t|D ]V}t|D ]F}|||f }t|D ]*}|||f |krd|||f<  qqqq||
fS )a  Build a heap of candidate neighbors for nearest neighbor descent. For
    each vertex the candidate neighbors are any current neighbors, and any
    vertices that have the vertex as one of their nearest neighbors.

    Parameters
    ----------
    current_graph: heap
        The current state of the graph for nearest neighbor descent.

    max_candidates: int
        The maximum number of new candidate neighbors.

    rng_state: array of int64, shape (3,)
        The internal state of the rng

    Returns
    -------
    candidate_neighbors: A heap with an array of (randomly sorted) candidate
    neighbors for each vertex in the graph.
    r   r   r   r>   r&   )r   r!   r?   rA   infrC   rP   rQ   r    r   checked_heap_push)current_graphmax_candidatesr   	n_threadscurrent_indicesZcurrent_flags
n_verticesn_neighborsZnew_candidate_indicesZnew_candidate_priorityZold_candidate_indicesZold_candidate_prioritynZlocal_rng_stater   r,   rS   Zisndr8   r<   r-   r   r   r   new_build_candidates)  s    

          
r^   zb1(u1[::1],i4)c                 C   s    |d? }d|d@ > }| | |@ S Nr   r      r   table	candidatelocmaskr   r   r   has_been_visited  s    rf   zvoid(u1[::1],i4)c                 C   s(   |d? }d|d@ > }| |  |O  < d S r_   r   ra   r   r   r   mark_visited  s    rg   zi4(f4[::1],i4[::1],f4,i4))rG   r   ic1ic2i_swap)r   r   r   c           	      C   s   || d krdS | j d }|| d< ||d< d}d| d }|d }||krNqnX||krl| | |kr|}qqn:| | | | kr|| | k r|}qqn|| | k r|}nq| | | |< || ||< |}q.|| |< |||< dS Nr   r   r   rI   	
prioritiesr8   pr\   rG   r   rh   ri   rj   r   r   r   simple_heap_push  s6    
ro   c           	      C   s   || d krdS | j d }t|D ]}||| kr" dS q"|| d< ||d< d}d| d }|d }||krnqnX||kr| | |kr|}qqn:| | | | kr|| | k r|}qqn|| | k r|}nq| | | |< || ||< |}qN|| |< |||< dS rk   r   r    rl   r   r   r   rU     s<    
rU   z$i4(f4[::1],i4[::1],u1[::1],f4,i4,u1)c                 C   s  || d krdS | j d }t|D ]}||| kr" dS q"|| d< ||d< ||d< d}d| d }|d }	||krvqnX|	|kr| | |kr|}
qqn:| | | |	 kr|| | k r|}
qqn|| |	 k r|	}
nq| |
 | |< ||
 ||< ||
 ||< |
}qV|| |< |||< |||< dS rk   rp   )rm   r8   r<   rn   r\   frG   r   rh   ri   rj   r   r   r   checked_flagged_heap_push	  sB    
rr   )rn   qr]   addedr\   r   r,   c              
   C   s   d}| d }| d }| d }t |D ]}tt|D ]}tt|| D ]}	|| |	 \}
}}|
dksJ|dkrrqJ|
| |krt||
 ||
 ||
 ||d}||7 }|| |krJt|| || || ||
d}||7 }qJq6q&|S )Nr   r   r   r>   )rP   rQ   r    lenrr   )rV   updatesrX   	n_changesrm   r8   r<   r\   r   r,   rn   rs   r]   rt   r   r   r   apply_graph_updates_low_memoryJ  s>              rx   )rn   rs   )r   r   c           
   	   C   s&  d}t t|D ]}t t|| D ]}|| | \}}}|dks&|dkrNq&||| krj||| krjq&nV||| krxnHt| d | | d | | d | ||d}	|	dkr|| | ||	7 }||ks||| krq&t| d | | d | | d | ||d}	|	dkr&|| | ||	7 }q&q|S )Nr   r>   r   r   )r    ru   rr   add)
rV   rv   in_graphrw   r   r,   rn   rs   r]   rt   r   r   r   apply_graph_updates_high_memoryv  sF    


	


	r{   c              	   C   s|   t |jd D ]h}t |jd D ]T}|||f }|dkr ||| || }t| d | | d | | d | ||d q q| S Nr   r   r   r    r   rr   )heapgraph_indicesdatametricr   rS   r,   r]   r   r   r   !initalize_heap_from_graph_indices  s    .r   c              	   C   sv   t |jd D ]b}t |jd D ]N}|||f }|dkr |||f }t| d | | d | | d | ||d q q| S r|   r}   )r~   r   Zgraph_distancesr   rS   r,   r]   r   r   r   /initalize_heap_from_graph_indices_and_distances  s    .r   c              	   C   s   t |jd D ]}t|jd D ]}|||f }||| ||d   }	||| ||d   }
||| ||d   }||| ||d   }||	|
||}t| d | | d | | d | ||d q"q| S r|   )rP   rQ   r   r    rr   )r~   r   data_indptrdata_indicesZ	data_valsr   r   rS   r,   ind1data1ind2data2r]   r   r   r   (sparse_initalize_heap_from_graph_indices  s    .r   c                   C   s   t t   S r4   )timectimer   r   r   r   ts  s    r   )/r   rP   
numba.corer   Znumba.experimental.structrefexperimentalZ	structrefnumpyr!   njitr   r   r   rC   Arrayintpuint32r%   r.   register	StructRefr/   ZStructRefProxyr3   r;   r9   r5   Zdefine_proxyrH   rN   rR   r)   r^   rf   rg   uint16ro   rU   rr   rA   rE   rx   r{   r   r   r   r   r   r   r   r   <module>   s   





$










F
Y


-
2
5	

0




