-
Notifications
You must be signed in to change notification settings - Fork 3
/
__init__.py
executable file
·211 lines (162 loc) · 6.76 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
"""
FABADA is a non-parametric noise reduction technique based on Bayesian
inference that iteratively evaluates possibles moothed models of
the data introduced, obtaining an estimation of the underlying
signal that is statistically compatible with the noisy measurements.
based on P.M. Sanchez-Alarcon, Y. Ascasibar, 2022
"Fully Adaptive Bayesian Algorithm for Data Analysis. FABADA"
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
"""
from __future__ import print_function, division
import numpy as np
from typing import Union
from time import time as time
from scipy import ndimage
import scipy.stats as stats
import sys
def fabada(
data: Union[np.array, list],
data_variance: Union[np.array, list, float],
max_iter: int = 3000,
verbose: bool = False,
**kwargs
) -> np.array:
"""
FABADA for any kind of data (1D or 2D). Performs noise reduction in input.
FABADA is a non-parametric noise reduction technique based on Bayesian
inference that iteratively evaluates possibles smoothed models of
the data introduced, obtaining an estimation of the underlying
signal that is statistically compatible with the noisy measurements.
based on Sanchez-Alarcon, P.M. & Ascasibar, Y. 2022
"Fully Adaptive Bayesian Algorithm for Data Analysis. FABADA"
arXiv:2201.05145
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
:param data: Noisy measurements, either 1 dimension (M) or 2 dimensions (MxN)
:param data_variance: Estimated variance of the input, either MxN array, list
or float assuming all point have same variance.
:param max_iter: 3000 (default). Maximum of iterations to converge in solution.
:param verbose: False (default) or True. Spits some informations about process.
:param **kwargs: Future Work.
:return bayes: denoised estimation of the data with same size as input.
"""
data = np.array(data / 1.0)
data_variance = np.array(data_variance / 1.0)
data[np.where(np.isnan(data))] = 0
if not kwargs:
kwargs = {}
kwargs["debug"] = False
if verbose:
if len(data.shape) == 1:
print("FABADA 1-D initialize")
elif len(data.shape) == 2:
print("FABADA 2-D initialize")
else:
print("Warning: Size of array not supported")
if data_variance.size != data.size:
data_variance = data_variance * np.ones_like(data)
data_variance[np.where(np.isnan(data))] = 1e-15
# INITIALIZING ALGORITMH ITERATION ZERO
t = time()
posterior_mean = data
posterior_variance = data_variance
evidence = Evidence(0, np.sqrt(data_variance), 0, data_variance)
initial_evidence = evidence
chi2_pdf, chi2_data, iteration = 0, data.size, 0
chi2_pdf_derivative, chi2_data_min = 0, data.size
bayesian_weight = 0
bayesian_model = 0
evidence_previous = np.mean(evidence)
converged = False
try:
while not converged:
if verbose:
print('\rIteration = %5d ;'%iteration +
'<E> = %4.2f ; '% evidence_previous +
'Chi^2 = %3.4e/%3.3e '%(chi2_data,data.size),end='')
chi2_pdf_previous = chi2_pdf
chi2_pdf_derivative_previous = chi2_pdf_derivative
evidence_previous = np.mean(evidence)
iteration += 1 # Check number of iterartions done
# GENERATES PRIORS
prior_mean = running_mean(posterior_mean)
prior_variance = posterior_variance
# APPLY BAYES' THEOREM
posterior_variance = 1 / (1 / prior_variance + 1 / data_variance)
posterior_mean = (
prior_mean / prior_variance + data / data_variance
) * posterior_variance
# EVALUATE EVIDENCE
evidence = Evidence(prior_mean, data, prior_variance, data_variance)
evidence_derivative = np.mean(evidence) - evidence_previous
# EVALUATE CHI2
chi2_data = np.sum((data - posterior_mean) ** 2 / data_variance)
chi2_pdf = stats.chi2.pdf(chi2_data, df=data.size)
chi2_pdf_derivative = chi2_pdf - chi2_pdf_previous
chi2_pdf_snd_derivative = chi2_pdf_derivative - chi2_pdf_derivative_previous
# COMBINE MODELS FOR THE ESTIMATION
model_weight = evidence * chi2_data
bayesian_weight += model_weight
bayesian_model += model_weight * posterior_mean
if iteration == 1:
chi2_data_min = chi2_data
# CHECK CONVERGENCE
if (
(chi2_data > data.size and chi2_pdf_snd_derivative >= 0)
and (evidence_derivative < 0)
or (iteration > max_iter)
):
converged = True
# COMBINE ITERATION ZERO
model_weight = initial_evidence * chi2_data_min
bayesian_weight += model_weight
bayesian_model += model_weight * data
except:
print("Unexpected error:", sys.exc_info()[0])
raise
bayes = bayesian_model / bayesian_weight
if verbose:
print('\rIteration = %5d ; '%iteration +
'<E> = %4.2f ; '% np.mean(evidence) +
'Chi^2 = %3.4e/%3.3e '%(chi2_data,data.size),end='')
print(
"\nFinish at {} iterations".format(iteration),
" and with an execute time of {:3.2f} seconds.".format(time() - t),
)
return bayes
def running_mean(dat):
mean = np.array(dat)
dim = len(mean.shape)
if dim == 1:
mean[:-1] += dat[1:]
mean[1:] += dat[:-1]
mean[1:-1] /= 3
mean[0] /= 2
mean[-1] /= 2
elif dim == 2:
mean[:-1, :] += dat[1:, :]
mean[1:, :] += dat[:-1, :]
mean[:, :-1] += dat[:, 1:]
mean[:, 1:] += dat[:, :-1]
mean[1:-1, 1:-1] /= 5
mean[0, 1:-1] /= 4
mean[-1, 1:-1] /= 4
mean[1:-1, 0] /= 4
mean[1:-1, -1] /= 4
mean[0, 0] /= 3
mean[-1, -1] /= 3
mean[0, -1] /= 3
mean[-1, 0] /= 3
else:
print("Warning: Size of array not supported")
return mean
def Evidence(mu1, mu2, var1, var2):
return np.exp(-((mu1 - mu2) ** 2) / (2 * (var1 + var2))) / np.sqrt(
2 * np.pi * (var1 + var2)
)
def PSNR(recover, signal, L=255):
MSE = np.sum((recover - signal) ** 2) / (recover.size)
return 10 * np.log10((L) ** 2 / MSE)