
    IR-eC?                        d Z ddlmZ ddlZddlmZ d Zd 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ed"d            Zd"dZed"d            Zd#dZ	 d$dZ	 d$dZeeeeedZ	 d%dZeeeeedZ	 d&dZdS )'z
Utilities for computing periodogram statistics.

This is an internal module; users should access this functionality via the
``false_alarm_probability`` and ``false_alarm_level`` methods of the
``astropy.timeseries.LombScargle`` API.
    wrapsN)unitsc                 b    || |dz  z                                   S |                                  S N   )sumvaldys     Wlib/python3.11/site-packages/astropy/timeseries/periodograms/lombscargle/_statistics.py_weighted_sumr      s/    	~b!e  """wwyy    c                     ||                                  S t          | |          t          t          j        | j                  |          z  S N)meanr   nponesshaper
   s     r   _weighted_meanr      s@    	zxxzzS"%%bgci6H6H"(M(MMMr   c                 P    t          | dz  |          t          | |          dz  z
  S r   )r   r
   s     r   _weighted_varr      s*    #q&"%%sB(?(?1(DDDr   c                     ddl m} t          j        d| z            t          j         || dz             || dz
  dz            z
            z  S )Nr   )gammalnr      )scipy.specialr   r   sqrtexp)Nr   s     r   _gammar    "   sZ    %%%%%% 71q5>>BF771q5>>GGQUaK4H4H#HIIIIr   c                 <     t                      fd            }|S )Nc                     t          j        |           } t          j        fd| j        D                                           | j                  S )Nc                 (    g | ]} |gR i S  r$   ).0xiargsfunckwargss     r   
<listcomp>z>vectorize_first_argument.<locals>.new_func.<locals>.<listcomp>-   s3    DDDrb24222622DDDr   )r   asarrayarrayflatreshaper   )xr'   r)   r(   s    ``r   new_funcz*vectorize_first_argument.<locals>.new_func*   sO    JqMMxDDDDDDQVDDDEEMMagVVVr   r   )r(   r0   s   ` r   vectorize_first_argumentr1   )   s8    
4[[W W W W [W Or   r      c                 t   t          j        |           } ||z
  dk    rt          d          ||z
  }|dk    rt          j        |            S |dk    rd|z  d| z
  d|z  dz
  z  z  S |dk    rd|z  d| z   d|z  dz
  z  z  S |d	k    r d|z  t          j        d|z  | z            z  S t	          d
| d          )a  Probability density function for Lomb-Scargle periodogram.

    Compute the expected probability density function of the periodogram
    for the null hypothesis - i.e. data consisting of Gaussian noise.

    Parameters
    ----------
    z : array-like
        The periodogram value.
    N : int
        The number of data points from which the periodogram was computed.
    normalization : {'standard', 'model', 'log', 'psd'}
        The periodogram normalization.
    dH, dK : int, optional
        The number of parameters in the null hypothesis and the model.

    Returns
    -------
    pdf : np.ndarray
        The expected probability density function.

    Notes
    -----
    For normalization='psd', the distribution can only be computed for
    periodograms constructed with errors specified.
    All expressions used here are adapted from Table 1 of Baluev 2008 [1]_.

    References
    ----------
    .. [1] Baluev, R.V. MNRAS 385, 1279 (2008)
    r   Degrees of freedom != 2psdstandard      ?r   model      lognormalization='' is not recognizedr   r+   NotImplementedErrorr   
ValueErrorzr   normalizationdHdKNks         r   
pdf_singlerF   2   s    @ 	
1A	Bw!||!";<<<	
RBvqbzz	*	$	$Rx1q5cBhl333	'	!	!Rx1q5dRi!m444	%		Rx"&Q////M=MMMNNNr   c                 D   t          j        |           } ||z
  dk    rt          d          ||z
  }|dk    rt          j        |            S |dk    rd| z
  d|z  z  S |dk    rd| z   d|z  z  S |d	k    rt          j        d|z  | z            S t	          d
| d          )a&  Single-frequency false alarm probability for the Lomb-Scargle periodogram.

    This is equal to 1 - cdf, where cdf is the cumulative distribution.
    The single-frequency false alarm probability should not be confused with
    the false alarm probability for the largest peak.

    Parameters
    ----------
    z : array-like
        The periodogram value.
    N : int
        The number of data points from which the periodogram was computed.
    normalization : {'standard', 'model', 'log', 'psd'}
        The periodogram normalization.
    dH, dK : int, optional
        The number of parameters in the null hypothesis and the model.

    Returns
    -------
    false_alarm_probability : np.ndarray
        The single-frequency false alarm probability.

    Notes
    -----
    For normalization='psd', the distribution can only be computed for
    periodograms constructed with errors specified.
    All expressions used here are adapted from Table 1 of Baluev 2008 [1]_.

    References
    ----------
    .. [1] Baluev, R.V. MNRAS 385, 1279 (2008)
    r   r4   r5   r6   r   r7   r8   r9   r:   r;   r<   r=   r@   s         r   
fap_singlerH   c   s    B 	
1A	Bw!||!";<<<	
RBvqbzz	*	$	$A38$$	'	!	!A4"9%%	%		vdRi!m$$$M=MMMNNNr   c                    t          j        |           } ||z
  dk    rt          d          ||z
  }t          j        d          5  |dk    r!t          j        |            cddd           S |dk    rd| d|z  z  z
  cddd           S |d	k    rd
| d|z  z  z   cddd           S |dk    r&d|z  t          j        |           z  cddd           S t          d| d          # 1 swxY w Y   dS )a+  Single-frequency inverse false alarm probability.

    This function computes the periodogram value associated with the specified
    single-frequency false alarm probability. This should not be confused with
    the false alarm level of the largest peak.

    Parameters
    ----------
    fap : array-like
        The false alarm probability.
    N : int
        The number of data points from which the periodogram was computed.
    normalization : {'standard', 'model', 'log', 'psd'}
        The periodogram normalization.
    dH, dK : int, optional
        The number of parameters in the null hypothesis and the model.

    Returns
    -------
    z : np.ndarray
        The periodogram power corresponding to the single-peak false alarm
        probability.

    Notes
    -----
    For normalization='psd', the distribution can only be computed for
    periodograms constructed with errors specified.
    All expressions used here are adapted from Table 1 of Baluev 2008 [1]_.

    References
    ----------
    .. [1] Baluev, R.V. MNRAS 385, 1279 (2008)
    r   r4   ignoredivider5   Nr6   r   r8   r:   r;   r<   )r   r+   r>   errstater:   r?   )fapr   rB   rC   rD   rE   s         r   inv_fap_singlerQ      s   D *S//C	Bw!||!";<<<	
RB 
H	%	%	% 
S 
SE!!F3KK<
S 
S 
S 
S 
S 
S 
S 
S j((sq2v&	
S 
S 
S 
S 
S 
S 
S 
S
 g%%R((
S 
S 
S 
S 
S 
S 
S 
S e##7RVC[[(
S 
S 
S 
S 
S 
S 
S 
S Q}QQQRRR
S 
S 
S 
S 
S 
S 
S 
S 
S 
Ss*   C(/C(C()C(C((C,/C,c                 0    dt          | ||||          z
  S )a  Cumulative distribution for the Lomb-Scargle periodogram.

    Compute the expected cumulative distribution of the periodogram
    for the null hypothesis - i.e. data consisting of Gaussian noise.

    Parameters
    ----------
    z : array-like
        The periodogram value.
    N : int
        The number of data points from which the periodogram was computed.
    normalization : {'standard', 'model', 'log', 'psd'}
        The periodogram normalization.
    dH, dK : int, optional
        The number of parameters in the null hypothesis and the model.

    Returns
    -------
    cdf : np.ndarray
        The expected cumulative distribution function.

    Notes
    -----
    For normalization='psd', the distribution can only be computed for
    periodograms constructed with errors specified.
    All expressions used here are adapted from Table 1 of Baluev 2008 [1]_.

    References
    ----------
    .. [1] Baluev, R.V. MNRAS 385, 1279 (2008)
    r   )rB   rC   rD   )rH   )rA   r   rB   rC   rD   s        r   
cdf_singlerS      s#    @ z!QmrJJJJJr   r6   c                     t          |          }||z
  }	||z
  }
t          ||          }t          j        dt          j        z  |z            }||z  }t          j        |           } |dk    r-|t          j        |            z  t          j        |           z  S |dk    r<t          |	          |z  d| z
  d|
dz
  z  z  z  t          j        d|	z  | z            z  S |dk    r9t          |
          |z  d| z   d|
z  z  z  t          j        d|
z  | z            z  S |dk    r]t          |
          |z  t          j        d| z  |
dz
  z            z  t          j        |
t          j        d| z            z            z  S t          d	|           )
z>tau factor for estimating Davies bound (Baluev 2008, Table 1).   r5   r6   r   r7   r8   r9   r:   znormalization=)
lenr   r   r   pir+   r   r    sinhr>   )Zfmaxtyr   rB   rC   rD   r   NHNKDtTeffWs                 r   
tau_daviesrb      s   AA	
RB	
RB	q"		B71ru9r>""DtA

1A261"::~

**	*	$	$bzzA~QC26N ;;bgcBhQRl>S>SSS	'	!	!bzzA~QD2I 66rA9N9NNN	%		 2JJfTAXc*++, gb2737+++,,-	
 ""B="B"BCCCr   c                 @   t          |          }t          |          t          |          z
  }||z  }t          | ||          }	t	          j        d          5  t	          j        |t	          j        |	           z             cddd           S # 1 swxY w Y   dS )zGFalse Alarm Probability based on estimated number of indep frequencies.rB   rJ   rK   N)rV   maxminrH   r   rO   expm1log1p)
rY   rZ   r[   r\   r   rB   r   TN_efffap_ss
             r   	fap_naiverl     s    AAAQA1HEq!=999E 
H	%	%	% 3 35&!1!112223 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3s   +BBBc                 f   t          j        |           } t          |          }t          |          t	          |          z
  }||z  }t          j        d          5  t          j        t          j        d| z
            |z             }	ddd           n# 1 swxY w Y   t          |	||          S )z;Inverse FAP based on estimated number of indep frequencies.rJ   rK   r   N)	r   r+   rV   re   rf   rO   rg   r:   rQ   )
rP   rZ   r[   r\   r   rB   r   ri   rj   rk   s
             r   inv_fap_naivern     s    
*S//CAAAQA1HE 
H	%	%	% 3 3"&S//E12223 3 3 3 3 3 3 3 3 3 3 3 3 3 3%M222s   .BBBc                 x    t          |          }t          | ||          }t          | |||||          }||z   S )zSDavies upper-bound to the false alarm probability.

    (Eqn 5 of Baluev 2008)
    rd   )rV   rH   rb   )	rY   rZ   r[   r\   r   rB   r   rk   taus	            r   
fap_daviesrq   %  sG    
 	AAq!=999E
QaBm
D
D
DC3;r   c                      ddl m} |||||f}t           g|R  } fd}	|                    |	||d          }
|
j        st          d            |
j        S )z"Inverse of the davies upper-bound.r   optimizec                 $    t          | g|R  z
  S r   )rq   rA   r'   ps     r   <lambda>z inv_fap_davies.<locals>.<lambda>7      Jq0400014 r   lmr'   method&inv_fap_baluev did not converge for p=scipyrt   rn   rootsuccessr?   r/   rw   rZ   r[   r\   r   rB   rt   r'   z0r(   ress   `          r   inv_fap_daviesr   0       !QM*D	q	 4	 	 	 B4444D
--btD-
9
9C; GE!EEFFF5Lr   c                     t          | t          |          |          }t          | |||||          }t          j        |            |t          j        |           z  z   S )zUAlias-free approximation to false alarm probability.

    (Eqn 6 of Baluev 2008)
    rd   )rH   rV   rb   r   rg   r   )rY   rZ   r[   r\   r   rB   rk   rp   s           r   
fap_baluevr   >  s]    
 q#a&&-00E
QaBm
D
D
DC HcTNN?URVSD\\111r   c                      ddl m} |||||f}t           g|R  } fd}	|                    |	||d          }
|
j        st          d            |
j        S )z/Inverse of the Baluev alias-free approximation.r   rs   c                 $    t          | g|R  z
  S r   )r   rv   s     r   rx   z inv_fap_baluev.<locals>.<lambda>Q  ry   r   rz   r{   r}   r~   r   s   `          r   inv_fap_baluevr   J  r   r     c                    ddl m} t          j                            |          }g }	t          |          D ]}
|                    dt          |          t          |                    } || ||         ||n||         |          }|                    |          \  }}|		                    |
                                           t          j        |	          }	|	                                 |	S )z6Generate a sequence of bootstrap estimates of the max.r   )LombScargler   Nrd   )maximum_frequency)corer   r   randomdefault_rngrangeintegersrV   	autopowerappendre   uQuantitysort)r[   r\   r   rZ   rB   random_seedn_bootstrapr   rng	power_max_sls_bootfreqpowers                  r   _bootstrap_maxr   X  s    !!!!!!
)


,
,CI; & &LLCFFCFF+++qt2:RR2a5
 
 
 ''$'??e%%%%
9%%INNr   c           	      |    t          |||||||          }dt          j        ||           t          |          z  z
  S )z2Bootstrap estimate of the false alarm probability.r   )r   r   searchsortedrV   )	rY   rZ   r[   r\   r   rB   n_bootstrapsr   pmaxs	            r   fap_bootstrapr   l  s?     !QD-lSSDrtQ''#d))333r   c           	      &   t          j        |           } t          |||||||          }|t          j        t          j        d| z
  t          |          z                                t                    dt          |          dz
                     S )z:Bootstrap estimate of the inverse false alarm probability.r   r   )r   r+   r   clipfloorrV   astypeint)	rP   rZ   r[   r\   r   rB   r   r   r   s	            r   inv_fap_bootstrapr   u  su     *S//C!QD-lSSD!c'SYY!677>>sCCQD		TUVVWWr   )singlenaivedaviesbaluev	bootstrapr   c                     |dk    rt          | t          |          |          S |t          vrt          d|           t          |         }|pi } || |||||fi |S )a$  Compute the approximate false alarm probability for periodogram peaks Z.

    This gives an estimate of the false alarm probability for the largest value
    in a periodogram, based on the null hypothesis of non-varying data with
    Gaussian noise. The true probability cannot be computed analytically, so
    each method available here is an approximation to the true value.

    Parameters
    ----------
    Z : array-like
        The periodogram value.
    fmax : float
        The maximum frequency of the periodogram.
    t, y, dy : array-like
        The data times, values, and errors.
    normalization : {'standard', 'model', 'log', 'psd'}, optional
        The periodogram normalization.
    method : {'baluev', 'davies', 'naive', 'bootstrap'}, optional
        The approximation method to use.
    method_kwds : dict, optional
        Additional method-specific keywords.

    Returns
    -------
    false_alarm_probability : np.ndarray
        The false alarm probability.

    Notes
    -----
    For normalization='psd', the distribution can only be computed for
    periodograms constructed with errors specified.

    See Also
    --------
    false_alarm_level : compute the periodogram level for a particular fap

    References
    ----------
    .. [1] Baluev, R.V. MNRAS 385, 1279 (2008)
    r   Unrecognized method: )rH   rV   METHODSr?   )rY   rZ   r[   r\   r   rB   r|   method_kwdss           r   false_alarm_probabilityr     s    V !SVV]333	w		999:::V_F#K6!T1a]BBkBBBr   c                     |dk    rt          | t          |          |          S |t          vrt          d|           t          |         }|pi } || |||||fi |S )a2  Compute the approximate periodogram level given a false alarm probability.

    This gives an estimate of the periodogram level corresponding to a specified
    false alarm probability for the largest peak, assuming a null hypothesis
    of non-varying data with Gaussian noise. The true level cannot be computed
    analytically, so each method available here is an approximation to the true
    value.

    Parameters
    ----------
    p : array-like
        The false alarm probability (0 < p < 1).
    fmax : float
        The maximum frequency of the periodogram.
    t, y, dy : arrays
        The data times, values, and errors.
    normalization : {'standard', 'model', 'log', 'psd'}, optional
        The periodogram normalization.
    method : {'baluev', 'davies', 'naive', 'bootstrap'}, optional
        The approximation method to use.
    method_kwds : dict, optional
        Additional method-specific keywords.

    Returns
    -------
    z : np.ndarray
        The periodogram level.

    Notes
    -----
    For normalization='psd', the distribution can only be computed for
    periodograms constructed with errors specified.

    See Also
    --------
    false_alarm_probability : compute the fap for a given periodogram level

    References
    ----------
    .. [1] Baluev, R.V. MNRAS 385, 1279 (2008)
    r   r   )rQ   rV   INV_METHODSr?   )rw   rZ   r[   r\   r   rB   r|   r   s           r   false_alarm_levelr     s    X aQ777	{	"	"999::: F#K6!T1a]BBkBBBr   )r   r2   )r6   r   r2   )r6   )r   )r6   r   N)r6   r   N)r   N)__doc__	functoolsr   numpyr   astropyr   r   r   r   r   r    r1   rF   rH   rQ   rS   rb   rl   rn   rq   r   r   r   r   r   r   r   r   r   r   r$   r   r   <module>r      sv                     N N NE E EJ J J  .O .O .O .Ob/O /O /O /Od2S 2S 2S 2Sj K  K  K  KFD D D D<
3 
3 
3 
3
3 
3 
3 
3    
 
 
 
	2 	2 	2 	2 
 
 
 
   * QU4 4 4 4 SWX X X X   OS2C 2C 2C 2Cl "  DH3C 3C 3C 3C 3C 3Cr   