
    uki (                        d dl mZ d dlmZ d dl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mZ d dlmZ e edd       G d d                    Zd Z e	j0                  d       d        Zy)    )	dataclass)partial)AnyN)api)dtypes)lax)numpy)random)check_arraylikepromote_dtypes_inexact)linalgspecial)register_pytree_node_classTF)frozeninitc                       e Zd ZU dZeed<   eed<   eed<   eed<   eed<   ddZd	 Zd
 Ze	d        Z
ed        Zed        Zd Zd Zd Zd Zd ZddZd Zd ZddZddZd Zy)gaussian_kdea  Gaussian Kernel Density Estimator

  JAX implementation of :class:`scipy.stats.gaussian_kde`.

  Parameters:
    dataset: arraylike, real-valued. Data from which to estimate the distribution.
      If 1D, shape is (n_data,). If 2D, shape is (n_dimensions, n_data).
    bw_method: string, scalar, or callable. Either "scott", "silverman", a scalar
      value, or a callable function which takes ``self`` as a parameter.
    weights: arraylike, optional. Weights of the same shape as the dataset.
  neffdatasetweights
covarianceinv_covNc                 J   t        d|       t        j                  |      }t        j                  t        j                  |      t        j                        rt        d      |j                  dkD  st        d      |j                  \  }}|{t        d|       t        ||      \  }}t        j                  |      }|t        j                  |      z  }|j                   dk7  rt        d      t#        |      |k7  r=t        d      t        |      \  }t        j$                  |d|z  |j                        }| j'                  d	|       | j'                  d
|       | j'                  ddt        j                  |dz        z        }|dn|}|dk(  rt        j(                  |d|dz   z        }nr|dk(  r&t        j(                  ||dz   z  dz  d|dz   z        }nGt        j*                  |      rt-        |t.              s|}nt1        |      r	 ||       }nt        d      t        j                  t        j2                  |dd|            }t        j4                  j7                  |      }	||dz  z  }
|	|dz  z  }| j'                  d|
       | j'                  d|       y )Nr   z*gaussian_kde does not support complex data   z.`dataset` input should have multiple elements.z*`weights` input should be one-dimensional.z%`weights` input should be of length n      ?)dtyper   r   r      scottg         	silvermang      @zD`bw_method` should be 'scott', 'silverman', a scalar, or a callable.F)rowvarbiasaweightsr   r   )r   jnp
atleast_2dr   
issubdtyper   r   npcomplexfloatingNotImplementedErrorsize
ValueErrorshaper   
atleast_1dsumndimlenfull_setattrpowerisscalar
isinstancestrcallablecovr   inv)selfr   	bw_methodr   dnr   factordata_covariancedata_inv_covr   r   s               S/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/scipy/stats/kde.py__init__zgaussian_kde.__init__3   sA   NG,nnW%G7+R-?-?@ LMM<<!GHH==DAqng./Agww'g!!g		EFF	W	@AA'0hgC!G7==9gMM)W%MM)W%==SWWWaZ%8!89D$,)IGyysa!e}-f	k	!yyQ#-sa!e}=f	i	 Is)Cf	)	f
P  nn@BO::>>/2L 619,JVQY&GMM,
+MM)W%    c                 4    t         j                  | ||       |S N)object__setattr__)r:   namevalues      rA   r2   zgaussian_kde._setattrc   s     tT5)LrC   c                 x    | j                   | j                  | j                  | j                  | j                  fd fS rE   )r   r   r   r   r   r:   s    rA   tree_flattenzgaussian_kde.tree_flatteni   s4    YYdllDOO\\ " "rC   c                     ~| j                  |       }|j                  d|d          |j                  d|d          |j                  d|d          |j                  d|d          |j                  d	|d
          |S )Nr   r   r   r   r   r   r      r   r   )__new__r2   )clsaux_datachildrenkdes       rA   tree_unflattenzgaussian_kde.tree_unflattenm   sr    
++c
CLL!%LLHQK(LLHQK(LLx{+LLHQK(JrC   c                 4    | j                   j                  d   S )Nr   r   r,   rK   s    rA   r<   zgaussian_kde.dx       <<a  rC   c                 4    | j                   j                  d   S )Nr   rV   rK   s    rA   r=   zgaussian_kde.n|   rW   rC   c                     t        d|       | j                  |      }t        d| j                  j                  | j
                  dddf   |j                  | j                        }|dddf   S )z.Evaluate the Gaussian KDE on the given points.evaluateFNr   r   _reshape_points_gaussian_kernel_evalr   Tr   r   )r:   pointsresults      rA   rZ   zgaussian_kde.evaluate   s\    J'!!&)F"5$,,..$,,q$w:O#)88T\\;F!Q$<rC   c                 $    | j                  |      S rE   rZ   )r:   r_   s     rA   __call__zgaussian_kde.__call__   s    ==  rC   c                    t        j                  t        j                  |            }t        j                  |      }|j                  | j
                  fk7  rt        d| j
                         |j                  | j
                  | j
                  fk7  rt        d| j
                         t        j                  | j                  |z         }t        j                  dt        j                  z        | j
                  z  t        j                  t        j                  |d               z  }d|z  }t        ||| j                   | j"                  |      S )z2Integrate the distribution weighted by a Gaussian.zmean does not have dimension z#covariance does not have dimension r   r   r   )r$   r-   squeezer%   r,   r<   r+   r   
cho_factorr   sqrtr'   piproddiag_gaussian_kernel_convolver   r   )r:   meanr8   cholnorms        rA   integrate_gaussianzgaussian_kde.integrate_gaussian   s    >>#++d+,D
..
CzzdffY6tvvh?@@
yyTVVTVV$$<TVVHEFFT__s23D88AI&#((472C)DDD:D$T4t||%)+ +rC   c                 :   | j                   dk7  rt        d      t        j                  |      dk7  st        j                  |      dk7  rt        d      t	        j
                  t	        j                  | j                              }t	        j
                  || j                  z
  |z        }t	        j
                  || j                  z
  |z        }t	        j                  | j                  t        j                  |      t        j                  |      z
  z        S )z1Integrate the distribution over the given limits.r   z'integrate_box_1d() only handles 1D pdfsr   z=the limits of integration in integrate_box_1d must be scalars)r<   r+   r'   r/   r$   re   rg   r   r   r.   r   r   ndtr)r:   lowhighsigmas       rA   integrate_box_1dzgaussian_kde.integrate_box_1d   s    vv{@AA	wws|qBGGDMQ.
IK KKK12E
++sT\\)U2
3C;;t||+u45D774<<7<<#5S8I#IJKKrC   c           
         |j                   | j                   k7  rt        d      t        j                  | j                  |j                  z         }t        j                  dt        j                  z        | j                   z  t        j                  t        j                  |d               z  }d|z  }| j                  |j                  k  r| |fn|| f\  }} t        j                  t        t        |||j                   |j"                        d      |j                         }t        j$                  ||j"                  z        S )z8Integrate the product of two Gaussian KDE distributions.z$KDEs are not the same dimensionalityr   r   r   r   in_axes)r<   r+   r   rf   r   r$   rg   r'   rh   ri   rj   r=   r   vmapr   rk   r   r   r.   )r:   otherrm   rn   smlgr`   s          rA   integrate_kdezgaussian_kde.integrate_kde   s    ww$&&=>>T__u/?/??@D88AI&#((472C)DDD:D"ffuww.dE]UDMFB!SXXg7tRZZ jj*!!#-F 776BJJ&''rC   c                    t        j                  |      \  }}t        j                  || j                  || j                        }t        j
                  |t        j                  | j                  | j                  j                        | j                  || j                  j                        j                  }| j                  dd|f   |z   S )aj  Randomly sample a dataset from the estimated pdf

    Args:
      key: a PRNG key used as the random key.
      shape: optional, a tuple of nonnegative integers specifying the result
        batch shape; that is, the prefix of the result shape excluding the last
        axis.

    Returns:
      The resampled dataset as an array with shape `(d,) + shape`.
    )r,   p)r,   r   N)r
   splitchoicer=   r   multivariate_normalr$   zerosr<   r   r   r   r^   )r:   keyr,   ind_keyeps_keyindepss          rA   resamplezgaussian_kde.resample   s     ||C(GW
--u
EC

$
$W%(YYtvvt7L7L%M%)__+0+/<<+=+=	? @Aq	 
 <<3#%%rC   c                 $    | j                  |      S )zProbability density functionrb   )r:   xs     rA   pdfzgaussian_kde.pdf   s    ==rC   c                     t        d|       | j                  |      }t        d| j                  j                  | j
                  dddf   |j                  | j                        }|dddf   S )z Log probability density functionlogpdfTNr   r[   )r:   r   r`   s      rA   r   zgaussian_kde.logpdf   s\    Ha QA"4ag9N#$336F!Q$<rC   c                     ~~~t        d      )4This method is not implemented in the JAX interface.z>only 1D box integrations are supported; use `integrate_box_1d`r)   )r:   
low_boundshigh_boundsmaxptss       rA   integrate_boxzgaussian_kde.integrate_box   s    K
HJ JrC   c                     ~t        d      )r   z:dynamically changing the bandwidth method is not supportedr   )r:   r;   s     rA   set_bandwidthzgaussian_kde.set_bandwidth   s    
DF FrC   c                    t        j                  t        j                  |      t        j
                        rt        d      t        j                  |      }|j                  \  }}|| j                  k7  r]|dk(  r3|| j                  k(  r$t        j                  || j                  df      }|S t        dj                  || j                              |S )Nz1gaussian_kde does not support complex coordinatesr   z2points have dimension {}, dataset has dimension {})r   r&   r   r   r'   r(   r)   r$   r%   r,   r<   reshaper+   format)r:   r_   r<   ms       rA   r\   zgaussian_kde._reshape_points   s    6*B,>,>?
=? ?^^F#F<<DAqDFF{	
aAKVdffa[1
 M @GG466 	 MrC   )NN) rE   )__name__
__module____qualname____doc__r   __annotations__rB   r2   rL   classmethodrT   propertyr<   r=   rZ   rc   ro   ru   r}   r   r   r   r   r   r\   r   rC   rA   r   r      s    
 	),,/,.&`"   ! ! ! !!+ 
L(&*JFrC   r   c                     ||d d d f   z
  }t        j                  | |      }dt        j                  ||z  d      z  }|t        j                  t        j                  |       |z        z  S )N      ?r   axis)r   	cho_solver$   r.   exp)rm   rn   targetr   rl   diffalphaargs           rA   rk   rk      sb    	$q$w-	$


4
&%cggdUl++#	/0	00rC   )static_argnumsc                    	
 t        ||      \  }}j                  d   }|j                  d   |k7  rt        d      |j                  ||fk7  rt        d      t        j                  |d      }t        j                  |      t        j                  ||      }t        j                  t        j                  t        j                  |                  d|z  t        j                  dt        j                  z        z  z
  
 
fd	 rt        j                  nt
        j                  	fd	}t        j                  |      } ||      S )
Nr   z)points and xi must have same trailing dimz%precision matrix must match data dimsT)lowerr   r   c                     dt        j                  t        j                  || z
              z  z
  }rt        j                  |      |z   S |t        j                  |      z  S )Nr   )r$   r.   squarelogr   )x_testx_trainy_trainr   in_loglog_norms       rA   kernelz%_gaussian_kernel_eval.<locals>.kernel  sS    
S3773::g.>#?@@
@CWWW##swws|##rC   c                 R      t        j                  d      |       d      S )N)Nr   r   rw   r   r   )r   ry   )r   r   r_   reducevaluess    rA   <lambda>z'_gaussian_kernel_eval.<locals>.<lambda>  s+    V$JCHHV\$J%&%8)*, rC   )r   r,   r+   r   choleskyr$   dotr.   r   rj   r'   rh   r   	logsumexpr   ry   )r   r_   r   xi	precisionr<   	whiteningreduced_kernelmapped_kernelr   r   r   s   ```      @@@rA   r]   r]      s   "8fb)#%&&"ill1o!XXa[A
@
AA__A
<
==ooit4)7769%&
wwr9"WWSWW	hhy !AgBEE	(::;($ !'7CGG&,. ((>*-	r	rC   )dataclassesr   	functoolsr   typingr   r	   r'   jax._srcr   r   r   r$   r
   jax._src.numpy.utilr   r   jax._src.scipyr   r   jax._src.tree_utilr   r   rk   jitr]   r   rC   rA   <module>r      s{    "       !  G * 9 
$U#O O $ Od1 	 rC   