-
Notifications
You must be signed in to change notification settings - Fork 4
Semiparametric Mu Estimation for NMV mixtures #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
andreev-sergej
merged 14 commits into
PySATL:main
from
andreev-sergej:Semiparametric-NMV-Mu-Estimation
Jul 23, 2024
Merged
Changes from 13 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
4145d3d
Init: Implement Mu Estimation Algorithm for NVM mixtures.
andreev-sergej fa52cbe
Fix: add mpmath to requirements.dev.txt and requirements.txt
andreev-sergej 89745ab
Fix:
andreev-sergej 01cee12
Fix: Fix tests because of new __init__ methods for mixtures
andreev-sergej 21915a1
Add: Tests for _set_default_params in SemiParametricMuEstimation class
andreev-sergej 894d4d2
Add: Tests for algorithm in SemiParametricMuEstimation class
andreev-sergej 15886ba
Fix: Make test more reliable
andreev-sergej 048d88b
Fix: Parameters type changed from list to dict
andreev-sergej c3fda52
Fix: Parameters type changed from list to dict. New validation method…
andreev-sergej 0e5f1dc
Fix: Fix tests for new parameters type. Add test for new parameter: m…
andreev-sergej 6bd6d03
Fix: Fix tests for new validation method
andreev-sergej ce5c26d
Fix: Add docstrings
andreev-sergej d415a3b
Fix: Style fix
andreev-sergej 7265b3d
Fix: Validation method. Add constant for parameter keys.
andreev-sergej File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
mypy~=1.10.0 | ||
black~=24.4.2 | ||
isort~=5.13.2 | ||
mpmath~=1.3.0 | ||
pytest~=7.4.4 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
numpy~=1.26.4 | ||
scipy~=1.13.1 | ||
matplotlib~=3.8.4 | ||
mpmath~=1.3.0 |
120 changes: 120 additions & 0 deletions
120
src/algorithms/nvm_semi_param_algorithms/mu_estimation.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
import math | ||
from typing import Callable, TypedDict, Unpack | ||
|
||
import mpmath | ||
import numpy as np | ||
from numpy import _typing | ||
|
||
M_DEFAULT_VALUE = 1000 | ||
TOLERANCE_DEFAULT_VALUE = 10**-5 | ||
OMEGA_DEFAULT_VALUE = lambda x: -1 * math.sin(x) if abs(x) <= math.pi else 0 | ||
MAX_ITERATIONS_DEFAULT_VALUE = 10**9 | ||
|
||
|
||
class SemiParametricMuEstimation: | ||
"""Estimation of mu parameter of NVM mixture represented in canonical form Y = alpha + mu*xi + sqrt(xi)*N, | ||
where alpha = 0 | ||
|
||
Args: | ||
sample: sample of the analysed distribution | ||
params: parameters of the algorithm | ||
m - search area, | ||
tolerance - defines where to stop binary search, | ||
omega - Lipschitz continuous odd function on R with compact support | ||
|
||
""" | ||
|
||
class ParamsAnnotation(TypedDict, total=False): | ||
"""Class for parameters annotation""" | ||
|
||
m: float | ||
tolerance: float | ||
omega: Callable[[float], float] | ||
max_iterations: float | ||
|
||
def __init__(self, sample: _typing.ArrayLike = None, **kwargs: Unpack[ParamsAnnotation]): | ||
self.sample = np.array([]) if sample is None else sample | ||
self.m, self.tolerance, self.omega, self.max_iterations = self._validate_kwargs(**kwargs) | ||
|
||
def _validate_kwargs( | ||
self, **kwargs: Unpack[ParamsAnnotation] | ||
) -> tuple[float, float, Callable[[float], float], float]: | ||
"""Parameters validation function | ||
|
||
Args: | ||
kwargs: Parameters of Algorithm | ||
|
||
Returns: Parameters of Algorithm | ||
|
||
""" | ||
if any([i not in self.ParamsAnnotation.__annotations__ for i in kwargs]): | ||
raise ValueError("Got unexpected parameter") | ||
if "m" in kwargs and (not isinstance(kwargs.get("m"), int) or kwargs.get("m", -1) <= 0): | ||
raise ValueError("Expected positive integer as parameter m") | ||
if "tolerance" in kwargs and ( | ||
not isinstance(kwargs.get("tolerance"), (int, float)) or kwargs.get("tolerance", -1) <= 0 | ||
): | ||
raise ValueError("Expected positive float as parameter tolerance") | ||
if "omega" in kwargs and not callable(kwargs.get("omega")): | ||
raise ValueError("Expected callable object as parameter omega") | ||
if "max_iterations" in kwargs and ( | ||
not isinstance(kwargs.get("max_iterations"), int) or kwargs.get("max_iterations", -1) <= 0 | ||
): | ||
raise ValueError("Expected positive integer as parameter max_iterations") | ||
return ( | ||
kwargs.get("m", M_DEFAULT_VALUE), | ||
kwargs.get("tolerance", TOLERANCE_DEFAULT_VALUE), | ||
kwargs.get("omega", OMEGA_DEFAULT_VALUE), | ||
kwargs.get("max_iterations", MAX_ITERATIONS_DEFAULT_VALUE), | ||
) | ||
|
||
def __w(self, p: float, sample: np._typing.NDArray) -> float: | ||
"""Root of this function is an estimation of mu | ||
|
||
Args: | ||
p: float | ||
sample: sample of the analysed distribution | ||
|
||
Returns: function value | ||
|
||
""" | ||
y = 0.0 | ||
for x in sample: | ||
try: | ||
e = math.exp(-p * x) | ||
except OverflowError: | ||
e = mpmath.exp(-p * x) | ||
y += e * self.omega(x) | ||
return y | ||
|
||
def algorithm(self, sample: np._typing.NDArray) -> float: | ||
"""Root of this function is an estimation of mu | ||
|
||
Args: | ||
sample: sample of the analysed distribution | ||
|
||
Returns: estimated mu value | ||
|
||
""" | ||
|
||
if self.__w(0, sample) == 0: | ||
return 0 | ||
if self.__w(0, sample) > 0: | ||
return -1 * self.algorithm(-1 * sample) | ||
if self.__w(self.m, sample) < 0: | ||
return self.m | ||
|
||
left, right = 0.0, self.m | ||
iteration = 0 | ||
while left <= right: | ||
mid = (right + left) / 2 | ||
if iteration > self.max_iterations: | ||
return mid | ||
iteration += 1 | ||
if abs(self.__w(mid, sample)) < self.tolerance: | ||
return mid | ||
elif self.__w(mid, sample) < 0: | ||
left = mid | ||
else: | ||
right = mid | ||
return -1 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Empty file.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Мне кажется, так попроще
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А ещё можно ключи, по которым получаются параметры, тоже в константы вынести