Skip to content

Commit 5f43be2

Browse files
committed
Adding missing MLE file
1 parent bc2e6b4 commit 5f43be2

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/pydefm/defm_mle.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
from scipy.optimize import minimize
2+
import numpy as np
3+
4+
# Function to print an array using two digits
5+
def print_array(arr):
6+
return "[" + ", ".join([f"{'' if x < 0 else ' '}{x:.2f}" for x in arr]) + "]"
7+
8+
class defm_mle_fit:
9+
"""
10+
Represents the result of a Maximum Likelihood Estimation (MLE) fit in the DEFM model.
11+
12+
Attributes:
13+
par (list): The estimated parameter values.
14+
or_ (list): The odds ratios corresponding to the estimated parameter values.
15+
se (list): The standard errors of the estimated parameter values.
16+
ll (float): The log-likelihood value of the fit.
17+
optimres (object): The optimization result object containing additional information.
18+
"""
19+
20+
def __init__(self, par, or_, se, ll, optimres):
21+
self.par = par
22+
self.or_ = or_
23+
self.se = se
24+
self.ll = ll
25+
self.optimres = optimres
26+
27+
def __str__(self):
28+
return f"defm_mle_fit\n\tpar =" + \
29+
print_array(self.par) + \
30+
",\n\tor =" + \
31+
print_array(self.or_) + \
32+
",\n\tse ="+ \
33+
print_array(self.se) + \
34+
f"\n\tll ={self.ll: .2f}"
35+
36+
def defm_mle(obj, par):
37+
"""
38+
Maximum Likelihood Estimation using the defm method.
39+
40+
Parameters:
41+
obj (object): The object containing the likelihood function.
42+
par (array-like): The initial parameter values.
43+
44+
Returns:
45+
defm_mle_fit: An instance of the defm_mle_fit class containing the estimated parameters, odds ratios, standard errors, log-likelihood value, and optimization results.
46+
"""
47+
def ll(par):
48+
return -obj.likelihood(par, as_log=True)
49+
50+
res = minimize(ll, par)
51+
return defm_mle_fit(
52+
par=res.x,
53+
or_=np.exp(res.x),
54+
se=np.sqrt(np.diag(res.hess_inv)),
55+
ll=-res.fun,
56+
optimres=res
57+
)

0 commit comments

Comments
 (0)