| 1 |
''' This module contains functions necessary to fit a negative binomial |
| 2 |
using the maximum likelihood estimator and some numerical analysis |
| 3 |
@author: Peter Xenopoulos |
| 4 |
@website: http://www.peterxeno.com |
| 5 |
@downloaded 17 oct 2019 from https://github.com/pnxenopoulos/negative_binomial/blob/master/negative_binomial/core.py |
| 6 |
''' |
| 7 |
|
| 8 |
import math |
| 9 |
import numpy as np |
| 10 |
|
| 11 |
from scipy.optimize import newton |
| 12 |
from scipy.special import digamma |
| 13 |
|
| 14 |
def r_derv(r_var, vec): |
| 15 |
''' Function that represents the derivative of the neg bin likelihood wrt r |
| 16 |
@param r: The value of r in the derivative of the likelihood wrt r |
| 17 |
@param vec: The data vector used in the likelihood |
| 18 |
''' |
| 19 |
if not r_var or not vec: |
| 20 |
raise ValueError("r parameter and data must be specified") |
| 21 |
|
| 22 |
if r_var <= 0: |
| 23 |
raise ValueError("r must be strictly greater than 0") |
| 24 |
|
| 25 |
total_sum = 0 |
| 26 |
obs_mean = np.mean(vec) |
| 27 |
n_pop = float(len(vec)) |
| 28 |
|
| 29 |
for obs in vec: |
| 30 |
total_sum += digamma(obs + r_var) |
| 31 |
|
| 32 |
total_sum -= n_pop*digamma(r_var) |
| 33 |
total_sum += n_pop*math.log(r_var / (r_var + obs_mean)) |
| 34 |
|
| 35 |
return total_sum |
| 36 |
|
| 37 |
def p_equa(r_var, vec): |
| 38 |
''' Function that represents the equation for p in the neg bin likelihood wrt p |
| 39 |
@param r: The value of r in the derivative of the likelihood wrt p |
| 40 |
@param vec: Te data vector used in the likelihood |
| 41 |
''' |
| 42 |
if not r_var or not vec: |
| 43 |
raise ValueError("r parameter and data must be specified") |
| 44 |
|
| 45 |
if r_var <= 0: |
| 46 |
raise ValueError("r must be strictly greater than 0") |
| 47 |
|
| 48 |
data_sum = np.sum(vec) |
| 49 |
n_pop = float(len(vec)) |
| 50 |
p_var = 1 - (data_sum / (n_pop * r_var + data_sum)) |
| 51 |
return p_var |
| 52 |
|
| 53 |
def neg_bin_fit(vec, init=0.0001): |
| 54 |
''' Function to fit negative binomial to data |
| 55 |
@param vec: The data vector used to fit the negative binomial distribution |
| 56 |
@param init: Set init to a number close to 0, and you will always converge |
| 57 |
''' |
| 58 |
if not vec: |
| 59 |
raise ValueError("Data must be specified") |
| 60 |
|
| 61 |
est_r = newton(r_derv, init, args=(vec,)) |
| 62 |
est_p = p_equa(est_r, vec) |
| 63 |
return est_r, est_p |
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|