o
    Rŀg                     @   s8   d Z ddlmZ ddlmZ dd Zdd Zdd	 Zd
S )zpMethods to calculate p-values from a Chi-squared cumulative distribution function.

for likelihood ratio tests.
    )exp)logc                 C   sB   | dk rt d|dk rt dd| }| d }dt|| }|S )z@Compute p-value, from distribution function and test statistics.   zdf must be at least 1r   z#The test statistic must be positive      ?g       @)
ValueError_incomplete_gamma)dfstatxalphaprob r   G/var/www/html/myenv/lib/python3.10/site-packages/Bio/Phylo/PAML/chi2.pycdf_chi2   s   r   c                 C   s   | dkrt | }d}|dk r)d}|}|dk r"||9 }|d7 }|dk s|}t| }d||  }||d t|  | d d| d | d | d	 |  S )
a  Compute the log of the gamma function for a given alpha (PRIVATE).

    Comments from Z. Yang:
    Returns ln(gamma(alpha)) for alpha>0, accurate to 10 decimal places.
    Stirling's formula is used for the central polynomial part of the procedure.
    Pike MC & Hill ID (1966) Algorithm 291: Logarithm of the gamma function.
    Communications of the Association for Computing Machinery, 9:684
    r      r   r   gdg?g48CgJ?gnlf?g=UUUUU?)r   r   )r   r
   fzr   r   r   _ln_gamma_function!   s8   	
r   c                 C   s  |}t |}d}d}d}d}d}d}	d}
d}d}| dkrdS | dk s&|dkr(dS t|t|  |  | }| dkr]| |kr]d| }||  d }	d}d| | d | |	 ddg}|d |d  }n$d}d}|}||kry|d7 }|| | 9 }||7 }||ksg||| 9 }|S 	 |d7 }|	d7 }	|d7 }|| }
tdD ]}|	||d   |
||   ||d
 < q|d dkr|d
 |d  }t|| }||kr|}n||| krn(td
D ]
}||d  ||< qt|d
 |k rqtd
D ]
}||  |  < qqd||  }|S )a/  Compute an incomplete gamma ratio (PRIVATE).

    Comments from Z. Yang::

        Returns the incomplete gamma ratio I(x,alpha) where x is the upper
               limit of the integration and alpha is the shape parameter.
        returns (-1) if in error
        ln_gamma_alpha = ln(Gamma(alpha)), is almost redundant.
        (1) series expansion     if alpha>x or x<=1
        (2) continued fraction   otherwise
        RATNEST FORTRAN by
        Bhattacharjee GP (1970) The incomplete gamma integral.  Applied Statistics,
        19: 285-287 (AS32)

    g:0yE>gꌠ9Y>)Fr   r   N      T      )r   r   r   rangeabs)r
   r   pgaccurateoverflowginrnabandiftermfactorpnir   r   r   r   D   sn   &r   N)__doc__mathr   r   r   r   r   r   r   r   r   <module>   s   #