
    Vpf                       d Z ddlmZ ddlmZ ddlZddlmZmZ ddl	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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dlmZ ddl m!Z!m"Z"m#Z#  ej$        d          Z%de%_&        d2dZ'e%j(        d             Z)e%j*        d             Z+d Z,d Z-d Z.e,ej/        e%<   e-ej0        e%<   e.ej1        e%<    ej2        e% ej3        e)d                     	 	 d3d4d+Z4	 	 d5d6d1Z5dS )7a  JAX primitives related to sparse operations.

This is experimental work to explore sparse support in JAX.

The primitives defined here are deliberately low-level: each primitive implements
a common sparse operation (sparse to dense, dense to sparse, sparse matrix/vector
product, sparse matrix/matrix product) for two common sparse representations
(CSR and COO).

These routines have reference implementations defined via XLA scatter/gather
operations that will work on any backend, although they are not particularly
performant. On GPU runtimes built against CUDA 11.0/ROCm 5.0 or newer, each operation is
computed efficiently via cusparse/hipsparse.

Further down are some examples of potential high-level wrappers for sparse objects.
(API should be considered unstable and subject to change).
    )annotations)partialN)OptionalUnion)	tree_util)	JAXSparse)BCOO)BCSR)COO)CSRCSC)_coo_extract)mlir)core)dtypes)ad)batching)Array	DTypeLikeShapetodenseFarrJAXSparse | Arrayreturnr   c                R    t          j        |           \  }}t          j        |d|iS )zIConvert input to a dense matrix. If input is already dense, pass through.tree)r   tree_flatten	todense_pbind)r   bufsr   s      [/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/jax/experimental/sparse/api.pyr   r   >   s+    %c***$		)D	)	))    c                    t          j        | |          }t          |t                    r|                                n|S N)r   tree_unflatten
isinstancer   r   r   r    r   s      r!   _todense_implr(   C   s5     t,,#$S)44	=#=r"   c                    t          j        | |          }t          |t          j                  r|S t          j        |j        |j        t          j        |j	                            S )N)	weak_type)
r   r%   r&   r   ShapedArrayshapedtyper   is_weakly_typeddatar'   s      r!   _todense_abstract_evalr0   H   sY     t,,#T%&& J		#)SY&:PQTQY:Z:Z	[	[	[[r"   c                   t          |d         t          j                  rJ t          d |dd          D                       sJ t	          j        | d|i}t	          j        |d         g| dd          R d|i}||fS )Nr   c              3  J   K   | ]}t          |t          j                  V  d S r$   )r&   r   Zero).0ts     r!   	<genexpr>z_todense_jvp.<locals>.<genexpr>Q   s.      ::Z27##::::::r"      r   )r&   r   r3   allr   r   )primalstangentsr   primals_outtangents_outs        r!   _todense_jvpr=   O   s    RW-----	::Xabb\:::	:	::::3d33+EgabbkEEEEE,	l	""r"   c               L   t          j        |d                   sJ t          d |dd          D                       rJ t                      }t	          j        ||gt          |          z            }ddlm}m	} ddl
m} ddlm} ||u r| fS t          ||          r|\  }	}
 ||
|           |
fS t          ||          r|\  }	}
} ||
||           |
|fS t          |t                    r|\  }	}}t!          |||           ||fS t#          dt%          |                     )Nr   c              3  >   K   | ]}t          j        |          V  d S r$   )r   is_undefined_primal)r4   bufs     r!   r6   z%_todense_transpose.<locals>.<genexpr>X   s-      AA',,AAAAAAr"   r7   )r	   r
   )_bcoo_extract)bcsr_extractztodense_transpose for )r   r@   anyobjectr   r%   lenjax.experimental.sparser	   r
   jax.experimental.sparse.bcoorB   jax.experimental.sparse.bcsrrC   r&   r   r   NotImplementedErrortype)ctr   r    standinobjr	   r
   rB   rC   _indicesindptrrowcols                 r!   _todense_transposerT   V   s}   		Q	(	((((AAQRRAAAAAAAAHH' y3t99'<==#00000000888888777777G^^5L#t 
DJAw="%%w..#t DAw<,,gv==#s DKAsCS"%%sC//
BtCyyBB
C
CCr"   c               ^     t          j        t          t          |          |          |  dfS )N)r   r   )jaxvmapr   r(   )batched_args
batch_dimsr   s      r!   _todense_batching_rulerZ   m   s.    	@'-d333Z	@	@,	OQR	RRr"   )multiple_resultsint32bcoor,   r   r-   DTypeLike | Noneindex_dtyper   sparse_formatstrr   c           	         t           t          t          t          t          d}||vr4t          d|dt          |                                                     ||         } |j        | f||d|S )a~  Create an empty sparse array.

  Args:
    shape: sequence of integers giving the array shape.
    dtype: (optional) dtype of the array.
    index_dtype: (optional) dtype of the index arrays.
    format: string specifying the matrix format (e.g. ['bcoo']).
    **kwds: additional keywords passed to the format-specific _empty constructor.
  Returns:
    mat: empty sparse matrix.
  )bcsrr]   coocsrcsczsparse_format=z  not recognized; must be one of )r-   r_   )	r
   r	   r   r   r   
ValueErrorlistkeys_empty)r,   r-   r_   r`   kwdsformatsclss          r!   emptyrn   w   s     4CLL''!!
 >m > >'+GLLNN';';> > ? ? ?#	E	HK	H	H4	H	HHr"   NintM
int | Nonekc           	     0   t           t          t          t          d}|| }t	          j        t          j        |           } t	          j        t          j        |          }t	          j        t          j        |          }||         } |j        d|| |||d|S )a  Create 2D sparse identity matrix.

  Args:
    N: int. Number of rows in the output.
    M: int, optional. Number of columns in the output. If None, defaults to `N`.
    k: int, optional. Index of the diagonal: 0 (the default) refers to the main
       diagonal, a positive value refers to an upper diagonal, and a negative value
       to a lower diagonal.
    dtype: data-type, optional. Data-type of the returned array.
    index_dtype: (optional) dtype of the index arrays.
    format: string specifying the matrix format (e.g. ['bcoo']).
    **kwds: additional keywords passed to the format-specific _empty constructor.

  Returns:
    I: two-dimensional sparse matrix with ones along the k-th diagonal.
  )r]   rd   re   rf   N)rq   ro   rs   r-   r_    )	r	   r   r   r   r   concrete_or_erroroperatorindex_eye)	ro   rq   rs   r-   r_   r`   rk   rl   rm   s	            r!   eyerz      s    $ #c#>>'Y	A
X^Q//!
X^Q//!
X^Q//!#		NAau+	N	N	N	NNr"   )r   r   r   r   )Nr\   r]   )
r,   r   r-   r^   r_   r   r`   ra   r   r   )Nr   Nr\   r]   )ro   rp   rq   rr   rs   rp   r-   r^   r_   r   r`   ra   r   r   )6__doc__
__future__r   	functoolsr   rw   typingr   r   rV   r   jax.experimental.sparse._baser   rH   r	   rI   r
   jax.experimental.sparse.coor   jax.experimental.sparse.csrr   r   jax.experimental.sparse.utilr   jax.interpretersr   jax._srcr   r   jax._src.interpretersr   r   jax._src.typingr   r   r   	Primitiver   r[   r   def_implr(   def_abstract_evalr0   r=   rT   rZ   primitive_jvpsprimitive_transposesprimitive_batchersregister_lowering	lower_funrn   rz   ru   r"   r!   <module>r      s   $ # " " " " "        " " " " " " " " 



       3 3 3 3 3 3 - - - - - - - - - - - - + + + + + + 0 0 0 0 0 0 0 0 5 5 5 5 5 5 ! ! ! ! ! !             $ $ $ $ $ $ * * * * * * 3 3 3 3 3 3 3 3 3 3 DN9%%	"	 * * * *
 > > > \ \ \# # #D D D.S S S  , ) %7 	 ")? I &  y.$.E#+ #+ #+ , , , PW%I I I I I* MQ?EO O O O O O Or"   