예제 #1
0
 def density(self, j, estimator="linear"):
     """
     Compute the signal's density
     :param j:               scaling parameter [int]
     :param estimator:       estimator type [str]
     :return:                density function estimation values [1D array]
     """
     [c, d] = self._scaling_coefficients(j)
     lowest_value = round(min(self.signal), 3)
     highest_value = round(max(self.signal), 3)
     density_x = np.linspace(lowest_value, highest_value, self.len_signal)
     density_y = np.linspace(lowest_value, highest_value, self.len_signal)
     density_z = np.empty(shape=(len(density_x), len(density_y)))
     print(
         "[INFO] {} - Computing the signal's density using the wavelet {} estimator (resolution level: {})"
         .format(functions.get_now(), estimator, j))
     if estimator == "donoho" or estimator == "thresholded":
         density_z = self._density_donoho(j, c, d, density_x, density_y)
     elif estimator == "linear":
         density_z = self._density_linear(j, c, density_x, density_y)
     else:
         print('\n[ERROR] {} - Undefined estimator)'.format(
             functions.get_now()))
         quit()
     density_x, density_y = np.meshgrid(density_x, density_y)
     return [density_x, density_y, density_z]
예제 #2
0
 def dwt(self, j):
     """
     Compute the Discrete Wavelet Transform
     :param j:           scaling parameter [int]
     :return:            approximation coefficients cA, and details coefficients cD [2D array]
     """
     print(
         '\n[INFO] {} - Computing the Discrete Wavelet Transformation (resolution level: {})'
         .format(functions.get_now(), j))
     cA = self._dwtA(j)
     cD = self._dwtD(j)
     return [cA, cD]
예제 #3
0
 def idwt(self, cA, cD, j):
     """
     Compute the Inverse Discrete Wavelet Transform
     :param cA:          approximation coefficients [1D array]
     :param cD:          details coefficients [1D array]
     :param j:           scaling parameter [int]
     :return:            approximation values yA, and details values yD [2D array]
     """
     print(
         '[INFO] {} - Computing the Inverse Discrete Wavelet Transformation (resolution level: {})'
         .format(functions.get_now(), j))
     yA = self._idwtA(cA, j)
     yD = self._idwtD(cD, j)
     return [yA, yD]
예제 #4
0
 def denoise(self, cD, threshold="universal", threshold_type="soft"):
     """
     Denoise the signal
     :param cD:                  details coefficients [1D array]
     :param threshold:           method to compute the threshold value: either "universal" or "SURE" [str]
     :param threshold_type:      either "soft" or "hard" [str]
     :return:                    denoised details coefficients [1D array]
     """
     # Computing the threshold
     if threshold == "universal":
         print(
             "[INFO] {} - Denoising the wavelets coefficients (threshold: universal {})"
             .format(functions.get_now(), threshold_type))
         threshold_value = self._universal_threshold(cD)
     elif threshold == "SURE":
         print(
             "[INFO] {} - Denoising the wavelets coefficients (threshold: SURE {})"
             .format(functions.get_now(), threshold_type))
         threshold_value = self._sureshrink_threshold(cD)
     else:
         threshold_value = 0
         print('\n[ERROR] {} - Undefined threshold)'.format(
             functions.get_now()))
         quit()
     # User indication
     print('[INFO] {} - Threshold value: {}'.format(functions.get_now(),
                                                    threshold_value))
     # Applying the threshold
     if threshold_type == "soft":
         cD = self._soft_thresholding(cD, threshold_value)
     elif threshold_type == "hard":
         cD = self._hard_thresholding(cD, threshold_value)
     else:
         print('\n[ERROR] {} - Undefined threshold type)'.format(
             functions.get_now()))
         quit()
     return cD
예제 #5
0
 def _build_father_wavelet(self):
     """
     Build the father wavelet
     :return:        father wavelet matrix [2D array]
     """
     # Display indication to user
     if self.nb_moments == 1:
         nb_iterations = 10
         wavelet_name = "haar"
     else:
         nb_iterations = 6
         wavelet_name = "daubechie_{}".format(self.nb_moments)
     print('\n[INFO] {} - Building the {} father wavelet ({} iterations)'.
           format(functions.get_now(), wavelet_name, nb_iterations))
     # Define support
     if self.nb_moments == 1:
         support = [0, 2]
     else:
         support = [0, 20]
     # Initialization
     step = 1
     t = np.zeros(support[1] - support[0] + 1)
     phi_t = np.zeros(support[1] - support[0] + 1)
     for i in range(0, len(t)):
         t[i] = support[0] + i
         if t[i] == 1:
             phi_t[i] = 1
     # Cascade algorithm
     for j in range(2, nb_iterations + 1):
         step = step / 2
         t_tampon = t
         phi_t_tampon = phi_t
         t = np.zeros(2 * len(t_tampon) - 1)
         phi_t = np.zeros(2 * len(t_tampon) - 1)
         for i in range(0, len(t), 2):
             t[i] = t_tampon[int(i / 2)]
             phi_t[i] = phi_t_tampon[int(i / 2)]
         for i in range(1, len(t) - 1, 2):
             t[i] = (t_tampon[int(i / 2)] + t_tampon[int(i / 2) + 1]) / 2
             sum_ = 0
             for k in range(0, 2 * self.nb_moments):
                 sum_ = sum_ + coefficients_dict[self.nb_moments][k] * \
                                 self._support_value(2 * t[i] - k, t_tampon, phi_t_tampon)
             phi_t[i] = sum_
     # Interpolate Daubechie Wavelet to smoothen the function
     if self.nb_moments != 1:
         for i in range(0, nb_iterations + 1):
             for int_index in range(0, support[1]):
                 if i == 0:
                     index = self._support_index(int_index, t)
                     phi_t[index] = (phi_t[index - 1] +
                                     phi_t[index + 1]) / 2
                 else:
                     for j in range(1, pow(2, i), 2):
                         index = self._support_index(
                             int_index + j / pow(2, i), t)
                         phi_t[index] = (phi_t[index - 1] +
                                         phi_t[index + 1]) / 2
     # Find last used index
     check = False
     index = len(t) - 1
     for i in range(0, len(t)):
         if phi_t[i] == 0 and check is False:
             index = i
             check = True
         if phi_t[i] != 0 and check is True:
             check = False
     # Remove useless indexes
     t = t[0:index]
     phi_t = phi_t[0:index]
     return [t, phi_t]
예제 #6
0
density_normal_x = np.linspace(min(simulated_returns)*100, max(simulated_returns)*100, len(simulated_returns))
density_normal_y = np.empty(len(density_normal_x))
for i in range(0, len(density_normal_x)):
    density_normal_y[i] = math.exp(-(density_normal_x[i] ** 2) / 2) / math.sqrt(2 * math.pi)
    density_normal_y[i] = functions.normal_pdf(density_normal_x[i], 0, 1)
density_normal_y = density_normal_y / sum(density_normal_y)
density_normal_x = density_normal_x/100

# Initializing Graph Params
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)
fig.set_size_inches(16, 7.6)
fig.set_tight_layout(True)
fig.suptitle(str("Returns Density Estimation"), fontsize=16)

# Simulated Data - Non Parametric Density Estimation (Gaussian Kernel)
print("\n[INFO] {} - Computing the simulated returns density using the gaussian kernel estimator".format(functions.get_now()))
ax1.plot(density_normal_x, density_normal_y, label="Normal Density", linestyle='dashed')
for smoothing in smoothing_array:
    [density_kernel_x, density_kernel_y] = functions.compute_kernel_density(simulated_returns, smoothing=smoothing)
    functions.initialize_subplot(ax=ax1, title='Simulated Returns - Gaussian Kernel Estimator', xlabel="Returns")
    ax1.plot(density_kernel_x, density_kernel_y, label="Smoothing h={}".format(smoothing))
    ax1.legend(loc="upper right")

# Simulated Data - Wavelet Parameters
nb_moments = 6
j = 7
# Simulated Data - Wavelet Density Estimations (Wavelet Kernel & Thresholded)
wavelet = Wavelets.Daubechie(signal=simulated_returns, nb_vanishing_moments=nb_moments)
[density_wav_x, density_wav_linear_y] = wavelet.density(j, "linear")
[density_wav_x, density_wav_donoho_y] = wavelet.density(j, "donoho")
functions.initialize_subplot(ax=ax2, title='Simulated Returns - Wavelet Estimators (db_{} / j={})'.format(nb_moments, j), xlabel="Returns")
예제 #7
0
density_normal_y = np.empty(len(density_normal_x))
for i in range(0, len(density_normal_x)):
    density_normal_y[i] = functions.normal_pdf(density_normal_x[i], 0, 1)
density_normal_y = density_normal_y / sum(density_normal_y)
density_normal_x = density_normal_x / 100

# Initializing Graph Params
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)
fig.set_size_inches(16, 7.6)
fig.set_tight_layout(True)
fig.suptitle(str("Returns Density Estimation"), fontsize=16)

# Simulated Data - Non Parametric Density Estimation (Gaussian Kernel)
print(
    "\n[INFO] {} - Computing the simulated returns density using the gaussian kernel estimator"
    .format(functions.get_now()))
ax1.plot(density_normal_x,
         density_normal_y,
         label="Normal Density",
         linestyle='dashed')
for smoothing in smoothing_array:
    [density_kernel_x,
     density_kernel_y] = functions.compute_kernel_density(simulated_returns,
                                                          smoothing=smoothing)
    functions.initialize_subplot(
        ax=ax1,
        title='Simulated Returns - Gaussian Kernel Estimator',
        xlabel="Returns")
    ax1.plot(density_kernel_x,
             density_kernel_y,
             label="Smoothing h={}".format(smoothing))