示例#1
0
import matplotlib.pyplot as plt


def load_data(path):
    f = open(path, 'rb')
    d = pickle.load(f)
    f.close()
    return d


def mag2db(mag):
    return 20 * np.log(mag)


d_noise = np.array(load_data("./data/data_clip_noise.dat"))
d_true = np.array(load_data("./data/data_clip_true.dat"))

N_noise = len(d_noise)
N_true = len(d_true)
Fs = 25.2

xf_noise = fftshift(fftfreq(N_noise, 1 / Fs))
yf_noise = fftshift(fft(d_noise))
xf_true = fftshift(fftfreq(N_true, 1 / Fs))
yf_true = fftshift(fft(d_true))

plt.plot(xf_noise, mag2db(abs(yf_noise)), label="noise")
plt.plot(xf_true, mag2db(abs(yf_true)), label="detected data")
plt.legend()

plt.show()
示例#2
0
######################################################################
# Denoise image and reduce shadows
# ================================

import matplotlib.pyplot as plt
import numpy as np
from skimage.data import gravel
from skimage.filters import difference_of_gaussians, window
from scipy.fft import fftn, fftshift

image = gravel()
wimage = image * window('hann', image.shape)  # window image to improve FFT
filtered_image = difference_of_gaussians(image, 1, 12)
filtered_wimage = filtered_image * window('hann', image.shape)
im_f_mag = fftshift(np.abs(fftn(wimage)))
fim_f_mag = fftshift(np.abs(fftn(filtered_wimage)))

fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(8, 8))
ax[0, 0].imshow(image, cmap='gray')
ax[0, 0].set_title('Original Image')
ax[0, 1].imshow(np.log(im_f_mag), cmap='magma')
ax[0, 1].set_title('Original FFT Magnitude (log)')
ax[1, 0].imshow(filtered_image, cmap='gray')
ax[1, 0].set_title('Filtered Image')
ax[1, 1].imshow(np.log(fim_f_mag), cmap='magma')
ax[1, 1].set_title('Filtered FFT Magnitude (log)')
plt.show()

######################################################################
# Enhance edges in an image
示例#3
0
window = signal.hann(51)

plt.plot(window)

plt.title("Hann window")

plt.ylabel("Amplitude")

plt.xlabel("Sample")

plt.figure()

A = fft(window, 2048) / (len(window)/2.0)

freq = np.linspace(-0.5, 0.5, len(A))

response = np.abs(fftshift(A / abs(A).max()))

response = 20 * np.log10(np.maximum(response, 1e-10))

plt.plot(freq, response)

plt.axis([-0.5, 0.5, -120, 0])

plt.title("Frequency response of the Hann window")

plt.ylabel("Normalized magnitude [dB]")

plt.xlabel("Normalized frequency [cycles per sample]")
plt.show()
示例#4
0
#Gráfico de ambas funciones respecto al tiempo
plt.plot(t, f, color="red", label="f(t)")
plt.plot(t, g, color="blue", label="g(t)")
plt.title("Función f(t) y g(t)")
plt.xlabel('tiempo (s)')
plt.ylabel('f(t) y g(t)')
plt.grid()
plt.legend()
plt.savefig("funciones.png")

plt.show()

#Calculo de la transformada de fourier de ambas funciones
Fw = fourier.fft(f, norm="ortho")
Fw = fourier.fftshift(Fw)

Gw = fourier.fft(g, norm="ortho")
Gw = fourier.fftshift(Gw)

#Calculo de las frencuencias de ambas funciones
freq_F = fourier.fftfreq(len(f), 2)
freq_F = fourier.fftshift(freq_F)

freq_G = fourier.fftfreq(len(g), 3)
freq_G = fourier.fftshift(freq_G)

#Gráfico de ambas transformadas
plt.plot(freq_F, abs(Fw))
plt.title("Transformada de f(t)")
plt.xlabel('Frecuencia (Hz)')
import numpy as np

window = signal.kaiser(51, beta=14)

plt.plot(window)

plt.title(r"Kaiser window ($\beta$=14)")

plt.ylabel("Amplitude")

plt.xlabel("Sample")

plt.figure()

A = fft(window, 2048) / (len(window) / 2.0)

freq = np.linspace(-0.5, 0.5, len(A))

response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))

plt.plot(freq, response)

plt.axis([-0.5, 0.5, -120, 0])

plt.title(r"Frequency response of the Kaiser window ($\beta$=14)")

plt.ylabel("Normalized magnitude [dB]")

plt.xlabel("Normalized frequency [cycles per sample]")
plt.show()
示例#6
0
    def test_kmat(self):
        """
        Test that the real-space and Fourier-space pattern generation models agree.

        i.e. that D_i(x) = amp * (1 + m * cos(2*pi*f + phi_i)) * S(r)
        matches the result given using the fourier space matrix
        [[D_1(k)], [D_2(k)], [D_3(k)]] = M * [[S(k)], [S(k-p)], [S(k+p)]]

        :return:
        """

        # set options
        dx = 0.065
        sim_options = {'pixel_size': 0.065, 'wavelength': 0.5, 'na': 1.3}

        # set values for SIM images
        frqs = np.array([[3.5785512, 2.59801082]])
        phases = np.array([[0, 2 * np.pi / 3, 3 * np.pi / 3]])
        mods = np.array([[0.85, 0.26, 0.19]])
        amps = np.array([[1.11, 1.23, 0.87]])

        nangles, nphases = phases.shape

        # ground truth image
        ny = 512
        nx = ny
        gt = np.random.rand(ny, nx)

        # calculate sim patterns using real space method
        x = tools.get_fft_pos(nx, dx)
        y = tools.get_fft_pos(ny, dx)
        xx, yy = np.meshgrid(x, y)

        sim_rs = np.zeros((nangles, nphases, ny, nx))
        sim_rs_ft = np.zeros((nangles, nphases, ny, nx), dtype=np.complex)
        for ii in range(nangles):
            for jj in range(nphases):
                pattern = amps[ii, jj] * (1 + mods[ii, jj] * np.cos(
                    2 * np.pi *
                    (xx * frqs[ii, 0] + yy * frqs[ii, 1]) + phases[ii, jj]))
                sim_rs[ii, jj] = gt * pattern
                sim_rs_ft[ii, jj] = fft.fftshift(
                    fft.fft2(fft.ifftshift(sim_rs[ii, jj])))

        # calculate SIM patterns using Fourier space method
        # frq shifted gt images
        gt_ft_shifted = np.zeros((nangles, nphases, ny, nx), dtype=np.complex)
        for ii in range(nangles):
            gt_ft_shifted[ii, 0] = fft.fftshift(fft.fft2(fft.ifftshift(gt)))
            gt_ft_shifted[ii, 1] = tools.translate_ft(gt_ft_shifted[ii, 0],
                                                      -frqs[ii], dx)
            gt_ft_shifted[ii, 2] = tools.translate_ft(gt_ft_shifted[ii, 0],
                                                      frqs[ii], dx)

        sim_fs_ft = np.zeros(gt_ft_shifted.shape, dtype=np.complex)
        for ii in range(nangles):
            kmat = sim.get_kmat(phases[ii], mods[ii], amps[ii])
            sim_fs_ft[ii] = sim.mult_img_matrix(gt_ft_shifted[ii], kmat)

        sim_fs_rs = np.zeros(gt_ft_shifted.shape)
        for ii in range(nangles):
            for jj in range(nphases):
                sim_fs_rs[ii, jj] = fft.fftshift(
                    fft.ifft2(fft.ifftshift(sim_fs_ft[ii, jj]))).real

        # fx = tools.get_fft_frqs(nx, dx)
        # dfx = fx[1] - fx[0]
        # fy = tools.get_fft_frqs(ny, dx)
        # extent = sim.get_extent(fy, fx)
        #
        # fig, fig_ax = plt.subplots(ncols=2, nrows=2, constrained_layout=True)
        # ii = 0
        # jj = 1
        #
        # fig_ax[0][0].imshow(np.abs(sim_rs_ft[ii, jj])**2, norm=PowerNorm(gamma=0.1), extent=extent)
        # plt.title('calculated in real space')
        #
        # fig_ax[0][1].imshow(np.abs(sim_fs_ft[ii, jj])**2, norm=PowerNorm(gamma=0.1), extent=extent)
        # plt.title('calculated in fourier space')
        #
        # fig_ax[1][0].imshow(sim_rs[ii, jj])
        # plt.title('real space')
        #
        # fig_ax[1][1].imshow(sim_fs_rs[ii, jj])
        # plt.title('real space (calculated in Fourier space)')

        np.testing.assert_allclose(sim_fs_ft, sim_rs_ft, atol=1e-10)
        np.testing.assert_allclose(sim_fs_rs, sim_rs, atol=1e-12)
示例#7
0
w = 1
N = 100

Bx = 2 * 3 * np.sqrt(2) * w
Δx = Bx / N
x = np.linspace(-Bx / 2, Bx / 2, N)  # Espacio real

Bf = 1 / Δx  # Ancho de banda en frecuencia
Δf = Bf / N  # Muestreo en frecuencia
f = np.linspace(-Bf / 2, Bf / 2, N)  # Espacio de Fourier

# In[3]:

g = np.exp(-x**2 / w**2) / np.sqrt(np.pi * w)  # Función en el espacio real
Ga = np.sqrt(w) * np.exp(-(np.pi * w * f)**2)  # Transformada analítica
Gn = abs(fftshift(fft(g))) * Δx  # Transformada numérica

# In[4]:

plt.plot(x, g)

# In[5]:

plt.plot(f, Ga, '.', color='red')
plt.plot(f, Gn, color='orange')

# In[6]:

Gn = abs(fft(g)) * Δx  # Transformada numérica sin fftshift

# In[7]:
示例#8
0
    def save(self, results_dir: str) -> None:
        """averages out the stored statistics from all the drops and store them in a matlab file.

        Theoretical values (if available) are stored as well. If 'plot' is True,
        then plot results.

        Args:
            results_dir (str): the desired directory to save matlab file in.
        """

        filename = os.path.join(results_dir, "statistics.mat")
        """for rx_modem_idx in range(self.__scenario.num_transmitters):
            print(f"\n\tResults for Rx {rx_modem_idx}")

            for snr, ber, fer in zip(
                self.snr_loop, self.bit_error_sum[rx_modem_idx], self.block_error_sum[rx_modem_idx]
            ):
                print(f"\t{self.snr_type.value} = {snr}dB\tBER = {ber:e}, \tfer = {fer:e}")"""

        mat_dict = {
            "snr_type": self.snr_type.name,
            "snr_vector": self.snr_loop,
            "ber_mean": self.average_bit_error_rate,
            "fer_mean": self.average_block_error_rate,
            "ber_lower": self.bit_error_min,
            "ber_upper": self.bit_error_max,
            "fer_lower": self.block_error_min,
            "fer_upper": self.block_error_max,
        }

        if self.__calc_transmit_spectrum:
            for idx, (periodogram, frequency) in enumerate(
                    zip(self._periodogram_tx, self._frequency_range_tx)):
                if periodogram is not None and frequency is not None:
                    mat_dict["frequency_tx_" +
                             str(idx)] = fft.fftshift(frequency)
                    mat_dict["power_spectral_density_tx_" +
                             str(idx)] = fft.fftshift(periodogram) / np.amax(
                                 periodogram)

        if self.__calc_transmit_stft:
            for idx, (time, freq, power) in enumerate(self._stft_tx):
                if time is not None and freq is not None and power is not None:
                    mat_dict["stft_time_tx_" + str(idx)] = time
                    mat_dict["stft_frequency_tx" + str(idx)] = freq
                    mat_dict["stft_power_tx" + str(idx)] = power

        if self.__calc_receive_spectrum:
            for idx, (periodogram, frequency) in enumerate(
                    zip(self._periodogram_rx, self._frequency_range_rx)):

                mat_dict["frequency_rx_" + str(idx)] = fft.fftshift(frequency)
                mat_dict["power_spectral_density_rx_" + str(
                    idx)] = fft.fftshift(periodogram) / np.amax(periodogram)

        if self.__calc_receive_stft:
            for idx, (time, freq, power) in enumerate(self._stft_rx):
                if time is not None and freq is not None and power is not None:
                    mat_dict["stft_time_rx_" + str(idx)] = time
                    mat_dict["stft_frequency_rx_" + str(idx)] = freq
                    mat_dict["stft_power_rx_" + str(idx)] = power

        ber_theory = np.nan * np.ones(
            (self.__scenario.num_transmitters, self.__scenario.num_receivers,
             self.__num_snr_loops),
            dtype=float)
        fer_theory = np.nan * np.ones(
            (self.__scenario.num_transmitters, self.__scenario.num_receivers,
             self.__num_snr_loops),
            dtype=float)
        theory_notes = [[np.nan for _ in self.__scenario.receivers]
                        for _ in self.__scenario.transmitters]

        if self.theoretical_results is not None:

            for tx_idx, rx_idx in zip(range(self.__scenario.num_transmitters),
                                      range(self.__scenario.num_receivers)):

                link_theory = self.theoretical_results[tx_idx, rx_idx]
                if link_theory is not None:

                    if 'ber' in link_theory:
                        ber_theory[tx_idx, rx_idx, :] = link_theory['ber']

                    if 'fer' in link_theory:
                        fer_theory[tx_idx, rx_idx, :] = link_theory['fer']

                    if 'notes' in link_theory:
                        theory_notes[tx_idx][rx_idx] = link_theory['notes']

            mat_dict["ber_theory"] = ber_theory
            mat_dict["fer_theory"] = fer_theory
            mat_dict["theory_notes"] = theory_notes

        # Save results in matlab file
        sio.savemat(filename, mat_dict)
示例#9
0
文件: ploting.py 项目: vimmoos/NN
def log_fft(current, data, data_len, transformer):
    tmp = current[0][transformer][0][
        "output"][:data_len] if current is not None else data[0][0][
            "desired"][:data_len]
    return np.log(np.abs(f.fftshift(f.fftn(tmp)))**2)
    def plot(self,
             title: Optional[str] = None,
             angle: bool = False,
             axes: Optional[np.ndarray] = None,
             space: Union['time', 'frequency', 'both'] = 'both',
             legend: bool = True) -> Optional[plt.figure]:
        """Plot the current signal in time- and frequency-domain.

        Args:

            title (str, optional):
                Figure title.

            angle (bool, optional):
                Plot the angle of complex frequency bins.
                
            axes (Optional[np.ndarray], optional):
                Axes to which the graphs should be plotted to.
                If none are provided, the routine will create a new figure.
                
            space (Union['time', 'frequency', 'both'], optional):
                Signal space to be plotted.
                By default, both spaces are visualized.
                
        Returns:
        
            Optional[plt.figure]:
                The created matplotlib figure.
                `None`, if axes were provided.
        """

        title = "Signal Model" if title is None else title
        figure: Optional[plt.figure] = None
        axes = np.array([[axes]], dtype=object) if isinstance(
            axes, plt.Axes) else axes

        with Executable.style_context():

            # Create a new figure if no axes were provided
            if axes is None:

                num_axes = 2 if space == 'both' else 1

                figure, axes = plt.subplots(self.num_streams,
                                            num_axes,
                                            squeeze=False)
                figure.suptitle(title)

            # Generate timestamps for time-domain plotting
            timestamps = self.timestamps

            # Infer the axis indices to account for different plot
            time_axis_idx = 0
            frequency_axis_idx = 1 if space == 'both' else 0

            for stream_idx, stream_samples in enumerate(self.__samples):

                # Plot time space
                if space in {'both', 'time'}:

                    axes[stream_idx, time_axis_idx].plot(timestamps,
                                                         stream_samples.real,
                                                         label='Real')
                    axes[stream_idx, time_axis_idx].plot(timestamps,
                                                         stream_samples.imag,
                                                         label='Imag')
                    axes[stream_idx,
                         time_axis_idx].set_xlabel('Time-Domain [s]')

                    if legend:
                        axes[stream_idx,
                             time_axis_idx].legend(loc="upper left",
                                                   fancybox=True,
                                                   shadow=True)

                # Plot frequency space
                if space in {'both', 'frequency'}:

                    frequencies = fftshift(
                        fftfreq(self.num_samples, 1 / self.sampling_rate))
                    bins = fftshift(fft(stream_samples))

                    axes[stream_idx,
                         frequency_axis_idx].plot(frequencies, np.abs(bins))
                    axes[stream_idx, frequency_axis_idx].set_ylabel('Abs')
                    axes[stream_idx, frequency_axis_idx].set_xlabel(
                        'Frequency-Domain [Hz]')

                    if angle:

                        phase = axes[stream_idx, frequency_axis_idx].twinx()
                        phase.plot(frequencies, np.angle(bins))
                        phase.set_ylabel('Angle [Rad]')

        return figure
示例#11
0
def FFT(x):
    # return np.abs(np.array([fftshift(fftfreq(FS)),fftshift(fft(x))]))
    return fftshift(fft(x))
示例#12
0
fnames_cal = glob.glob( '/media/apn/datadrive/hydrogen-line/2020-05-16-firstlight/*terminated*.bin')

fs = 5e6 # sampling rate

# offset measured in bytes
# count measured in samples
offset_sec = 0.5 # skip turn on artifacts
sec_to_read = 1
d = [ np.fromfile( fname, dtype = np.complex64, count = int(sec_to_read*fs), offset = int(8* offset_sec* fs )) for fname in fnames_cal ]

psd =  [ welch( _d, fs = fs, nperseg =  2**10, noverlap = None, detrend = 'linear', window = 'hamming', return_onesided = False ) for _d in d ]
# psd is a list each element is f,p
# fftsshift for ease of use
f,p = psd[0]
f = fftshift(f)
p = fftshift(p)

cal_fit_db = spectralBaseline( f, db10(p), band_edge = 1.6e6, band_notches = [[ -0.05e6, 0.05e6 ]] )

#useidx = np.where( np.logical_and( np.abs(f)<1.6e6 , np.abs(f)>0.05e6) )[0]
#poly_fit_order=2
# tried 4 and results didn't work well. 
#cal_fit = polynomial.polyfit( f[useidx]/1e6, db10(p[useidx]), poly_fit_order )
#cal_fit_val = polynomial.polyval( f/1e6, cal_fit)


center_freq_idx = np.argmin( np.abs( f ))
cal = cal_fit_db - cal_fit_db[ center_freq_idx ] 

示例#13
0
def return_shiffetd_fft(Image):
    fft_im = fft.fft2(Image)
    fft_im_sh = fft.fftshift(fft_im)
    return fft_im_sh
示例#14
0
def _fft(image):
    """shifted fft 2D
    """
    return fftshift(fftn(fftshift(image)))
示例#15
0
# Grid in the plane of the aperture

x_in = np.linspace(-2, 2,
                   1000)  # 1000 by 1000 grid to get detail in the pattern
dx = (max(x_in) - min(x_in)) / len(x_in)
y_in = np.linspace(-2, 2, 1000)
dy = (max(y_in) - min(y_in)) / len(y_in)
x_in, y_in = np.meshgrid(x_in, y_in)
grid_in = np.vstack((x_in.flatten(), y_in.flatten())).T

# The Electric field in the plane of the aperture

E_in = np.array([E_0 * double_sq(g[0], g[1]) for g in grid_in
                 ])  # two small square holes in the aperture plane
E_in = np.reshape(E_in, (len(x_in), len(y_in)))

# The output frequencies
X_out = fftshift(fftfreq(len(x_in), dx))
Y_out = fftshift(fftfreq(len(y_in), dy))

X_out *= z / k  # Converting from conjugate units to centimetres
Y_out *= z / k

E_out = fftshift(fft2(E_in))  # reordering the data for better plotting
I_out = np.power(np.abs(E_out), 2)  # Calculating the output intensity

plt.pcolormesh(X_out, Y_out, I_out, shading='nearest', cmap='gray')
plt.colorbar()
plt.show()
示例#16
0
    "E1": 0.15,
    "B2": 0.15,
    "G3": 0.15,
    "D4": 0.08,
    "A5": 0.08,
    "E6": 0.04
}

for record in records:  # one file at a time
    samplerate, data = wavfile.read(record)

    N = len(data)
    T = 1.0 / samplerate
    yf = fft(data)
    xf = fftfreq(N, T)
    xf = fftshift(xf)
    yplot = fftshift(yf)

    size = len(xf)

    # To better visualize the output, only low frequencies are seen
    # because that's the domain of guitar strings, usually.
    start = int(9 * size / 20)
    end = int(11 * size / 20)

    xf = xf[start:end]
    yplot = yplot[start:end]

    yplot = 1.0 / N * np.abs(yplot)
    plt.plot(xf, yplot)
示例#17
0
reduces the spectral leakage, making the "real" frequency information more
visible in the plot of the frequency component of the FFT.
"""

import matplotlib.pyplot as plt
import numpy as np
from scipy.fft import fft2, fftshift
from skimage import img_as_float
from skimage.color import rgb2gray
from skimage.data import astronaut
from skimage.filters import window

image = img_as_float(rgb2gray(astronaut()))

wimage = image * window('hann', image.shape)

image_f = np.abs(fftshift(fft2(image)))
wimage_f = np.abs(fftshift(fft2(wimage)))

fig, axes = plt.subplots(2, 2, figsize=(8, 8))
ax = axes.ravel()
ax[0].set_title("Original image")
ax[0].imshow(image, cmap='gray')
ax[1].set_title("Windowed image")
ax[1].imshow(wimage, cmap='gray')
ax[2].set_title("Original FFT (frequency)")
ax[2].imshow(np.log(image_f), cmap='magma')
ax[3].set_title("Window + FFT (frequency)")
ax[3].imshow(np.log(wimage_f), cmap='magma')
plt.show()
示例#18
0
# We next show how rotation and scaling differences, but not translation
# differences, are apparent in the frequency magnitude spectra of the images.
# These differences can be recovered by treating the magnitude spectra as
# images themselves, and applying the same log-polar + phase correlation
# approach taken above.

# First, band-pass filter both images
image = difference_of_gaussians(image, 5, 20)
rts_image = difference_of_gaussians(rts_image, 5, 20)

# window images
wimage = image * window('hann', image.shape)
rts_wimage = rts_image * window('hann', image.shape)

# work with shifted FFT magnitudes
image_fs = np.abs(fftshift(fft2(wimage)))
rts_fs = np.abs(fftshift(fft2(rts_wimage)))

# Create log-polar transformed FFT mag images and register
shape = image_fs.shape
radius = shape[0] // 8  # only take lower frequencies
warped_image_fs = warp_polar(image_fs, radius=radius, output_shape=shape,
                             scaling='log', order=0)
warped_rts_fs = warp_polar(rts_fs, radius=radius, output_shape=shape,
                           scaling='log', order=0)

warped_image_fs = warped_image_fs[:shape[0] // 2, :]  # only use half of FFT
warped_rts_fs = warped_rts_fs[:shape[0] // 2, :]
shifts, error, phasediff = phase_cross_correlation(warped_image_fs,
                                                   warped_rts_fs,
                                                   upsample_factor=10)
import math
import skimage
from skimage import io, viewer, color, data, filters, feature, morphology
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from scipy.fft import ifft, fft, ifft2, fft2, fftshift
from scipy import signal

scan_gs_bird = np.load('scan_gs_bird.npy')
scan_gs_sample2 = np.load('scan_gs_Sample2.npy')
cropped_sample2 = scan_gs_sample2[0:4000, 0:4000]

scan_gs_sample2_FT = fft2(cropped_sample2)
shifted_FT = fftshift(scan_gs_sample2_FT)

window_width = 100
one_d_window = np.hamming(len(scan_gs_sample2_FT))
window = np.sqrt(np.dot(one_d_window, one_d_window.T))**window_width

low_passed_scan_FrequencyDomain = shifted_FT * window

low_passed_scan = ifft2(low_passed_scan_FrequencyDomain)
plottable_lps = np.abs(low_passed_scan)

fig, ax = plt.subplots(ncols=2, figsize=(8, 2.5))
fig.suptitle('213 time my dudes')

ax[0].imshow(cropped_sample2, cmap='binary')
ax[0].set_title('Original')
ax[0].axis('off')
示例#20
0
#configure pluto
sample_rate = 60e6
center_freq = 2.45e9
exponent = 10
num_samples = 2**exponent

sdr = adi.Pluto("ip:192.168.2.1")

sdr.sample_rate = int(sample_rate)
sdr.rx_rf_bandwidth = int(sample_rate)
sdr.rx_lo = int(center_freq)
sdr.rx_buffer_size = num_samples

for x in range(15):
    data = sdr.rx()
    shifted_spectrum = fftshift(fft(data))
    print(shifted_spectrum)
    spec2 = abs(np.square(np.real(shifted_spectrum))) + abs(
        np.square(np.imag(shifted_spectrum)))
    #plt.figure(0)
    #plt.specgram(abs(shifted_spectrum),scale='dB')
    #plt.figure(1)
    plt.draw()
    plt.pause(0.001)
    time.sleep(0.001)
    plt.specgram(spec2, scale='dB')

print("done")
plt.show()
示例#21
0
def algoritmo_clasifica_cpw(dataset, conjunto, BPFI_cte, BPFO_cte, fs):
    DE, FE, t_DE, t_FE, RPM, samples_s_DE, samples_s_FE = lee_dataset(dataset)
    fr = RPM / 60
    if math.isnan(fr):
        fr = 29.95
    if conjunto == 'DE':
        datos = DE * np.hamming(len(DE))
        dt = t_DE[1] - t_DE[0]
        kurt = kurtosis(datos)
    elif conjunto == 'FE':
        datos = FE * np.hamming(len(FE))
        dt = t_FE[1] - t_FE[0]
        kurt = kurtosis(datos)
    else:
        print('Tipo de conjunto erroneo')

    ceps = complex_cepstrum(datos)
    BPFI = BPFI_cte * fr
    BPFO = BPFO_cte * fr
    title = 'Envelope spectrum'
    fSpecCeps, xSpecCeps, fSpecGCeps, BPFI_coordsCeps, BPFO_coordsCeps = envelope_spectrum(
        ceps, fs, BPFI, BPFO, title, 1)

    fft_envspec = fftshift(fft(detrend(xSpecCeps)))
    fft_envspec_norm = abs(fft_envspec) / np.max(abs(fft_envspec))
    frec_ceps = fftshift(fftfreq(len(xSpecCeps), dt))

    fig = plt.figure(figsize=(20, 10))
    plt.plot(frec_ceps, fft_envspec_norm)
    BPFI_coords = np.arange(BPFI, fs / 8, BPFI)
    for xc in BPFI_coords:
        if xc == BPFI_coords[0]:
            plt.axvline(x=xc,
                        color='r',
                        linestyle='--',
                        lw=1.5,
                        alpha=0.5,
                        label='BPFI')
        else:
            plt.axvline(x=xc, color='r', linestyle='--', lw=1.5, alpha=0.5)
    BPFO_coords = np.arange(BPFO, fs / 8, BPFO)
    for xc2 in BPFO_coords:
        if xc2 == BPFO_coords[0]:
            plt.axvline(x=xc2,
                        color='g',
                        linestyle='--',
                        lw=1.5,
                        alpha=0.5,
                        label='BPFO')
        else:
            plt.axvline(x=xc2, color='g', linestyle='--', lw=1.5, alpha=0.5)

    plt.xlim(0, fs / 2)
    plt.legend(fontsize=12)

    fft_envspec_norm_pos = fft_envspec_norm[len(fft_envspec_norm) //
                                            2:len(fft_envspec_norm)]
    frec_pos = frec_ceps[len(frec_ceps) // 2:len(frec_ceps)]
    maximos, frec_max = busca_maximos_locales(frec_pos, fft_envspec_norm_pos,
                                              BPFI, BPFO, fr, fs)
    por_comunes_BPFI, por_comunes_BPFO = por_comunes_fft(
        frec_max, BPFI_coords, BPFO_coords, fr)
    print(kurt)
    print(por_comunes_BPFI, por_comunes_BPFO)
    # CLASIFICACIÓN
    clasificacion = ''
    if por_comunes_BPFI > 70 and por_comunes_BPFI > 10 + por_comunes_BPFO and kurt > 20:
        clasificacion = 'MUY probable: fallo en inner race'
    elif por_comunes_BPFO > 70 and por_comunes_BPFO > 10 + por_comunes_BPFI and 15 > kurt > 2:
        clasificacion = 'MUY probable: fallo en outer race'
    elif abs(por_comunes_BPFI - por_comunes_BPFO) < 10 and kurt < 3:
        clasificacion = 'MUY probable: sano'
    elif por_comunes_BPFI < 50 and por_comunes_BPFO < 50 and abs(
            por_comunes_BPFO - por_comunes_BPFO) > 10 and kurt < 3:
        clasificacion = 'Probablemente sano'
    elif por_comunes_BPFO > 50 and por_comunes_BPFO > por_comunes_BPFI and 15 > kurt > 2:
        clasificacion = 'Probablemente fallo en outer race'
    elif por_comunes_BPFI > 50 and por_comunes_BPFI > por_comunes_BPFO and kurt > 20:
        clasificacion = 'Probablemente fallo en inner race'
    elif kurt > 20:
        clasificacion = 'No concluyente, posible fallo en inner race'
    elif 15 > kurt > 2:
        clasificacion = 'No concluyente, posible fallo en outer race'
    else:
        clasificacion = 'No concluyente'

    return clasificacion
示例#22
0
r0 = 100
N = 1000
x = np.linspace(-200, 200, N)
Δx = x[1] - x[0]
y = np.linspace(-200, 200, N)
Δy = y[1] - y[0]
X, Y = np.meshgrid(x, y)
circ = X**2 + Y**2 < r0**2  # Función circ

# In[3]:

plt.axes(projection='3d').plot_surface(X, Y, circ, cmap='viridis')

# In[4]:

fftU = fftshift(
    fft2(1 - circ)) * Δx * Δy  # Transformada de Fourier del campo de entrada
fx = fftshift(fftfreq(N, Δx))
Δfx = fx[1] - fx[0]
fy = fftshift(fftfreq(N, Δy))
Δfy = fy[1] - fy[0]
Fx, Fy = np.meshgrid(fx, fy)

# In[5]:

z = 5
α = 2 * np.pi * np.sqrt(abs(1 - (Fx**2 + Fy**2)))
H = np.exp(1j * α * z)  # Función de transferencia
U = (ifft2(fftU * H)) * Δfx * Δfy  # Campo a una distancia z

# In[6]:
示例#23
0
                offset=int(8 * offset_sec * fs)) for fname in fnames_cal
]

psd = [
    welch(_d,
          fs=fs,
          nperseg=2**10,
          noverlap=None,
          detrend='linear',
          window='hamming',
          return_onesided=False) for _d in d
]
# psd is a list each element is f,p
# fftsshift for ease of use
f, p = psd[0]
f = fftshift(f)
p = fftshift(p)

cool_fit_db = spectralBaseline(f,
                               db10(p),
                               band_edge=1.6e6,
                               band_notches=[[-0.05e6, 0.05e6],
                                             [-0.2e6, 0.4e6]])

plt.figure()
plt.plot(f / 1e6, db10(p))
plt.plot(f / 1e6, cool_fit_db)

zero_freq_idx = np.argmin(np.abs(f))
plt.figure()
plt.plot(f / 1e6, db10(p) - cal_fit_db + cal_fit_db[zero_freq_idx])
示例#24
0
def _get_frequency_peaks(time, signal, sfreq, min_peak_height=100):
    sp = fftshift(fft(signal))
    freq = fftshift(fftfreq(time.shape[-1], 1 / sfreq))
    peaks_idx, _ = find_peaks(sp, height=min_peak_height)
    return np.array(list(set(np.abs(freq[peaks_idx]))))
示例#25
0
def fourierTest(mu1, mu2, pos, states_s, states_u, ang, Data):

    import numpy as np
    from scipy.fft import fft, fftfreq, fftshift
    import matplotlib.pyplot as plt

    signal_s = []
    signal_u = []

    fig1, ax1 = plt.subplots()
    fig12, ax12 = plt.subplots()
    fig2, ax2 = plt.subplots()
    fig22, ax22 = plt.subplots()
    fig3, ax3 = plt.subplots()
    fig32, ax32 = plt.subplots()

    if len(states_s):
        for i in states_s:
            if abs(i[-1, 1]) < abs(pos[0] - mu1):
                if len(i[0, :0:-1]) % 2:
                    temp = fft(i[0, :1:-1] - pos[0] + i[1, :1:-1] * 1.j)
                    l = len(i[0, :1:-1])
                    signal_s.append(temp)
                else:
                    temp = fft(i[0, :0:-1] - pos[0] + i[1, :0:-1] * 1.j)
                    l = len(i[0, :0:-1])
                    signal_s.append(temp)
                xf = fftfreq(l, Data['prnt_out_dt'])
                xf = fftshift(xf)
                yf = fftshift(temp)
                ax1.plot(
                    xf[abs(yf) > 0.01 * max(abs(yf))],
                    100.0 / l * np.real(yf[abs(yf) > 0.01 * max(abs(yf))]))
                ax12.plot(
                    xf[abs(yf) > 0.01 * max(abs(yf))],
                    100.0 / l * np.imag(yf[abs(yf) > 0.01 * max(abs(yf))]))

    if len(states_u):
        for i in states_u:
            if abs(i[-1, 1]) < abs(pos[0] - mu1):
                if len(i[0, :-1]) % 2:
                    temp = fft(i[0, :-2] - pos[0] + i[1, :-2] * 1.j)
                    l = len(i[0, :-2])
                    signal_u.append(temp)
                else:
                    temp = fft(i[0, :-1] - pos[0] + i[1, :-1] * 1.j)
                    l = len(i[0, :-1])
                    signal_u.append(temp)
                xf = fftfreq(l, Data['prnt_out_dt'])
                xf = fftshift(xf)
                yf = fftshift(temp)
                ax2.plot(
                    xf[abs(yf) > 0.01 * max(abs(yf))],
                    100.0 / l * np.real(yf[abs(yf) > 0.01 * max(abs(yf))]))
                ax22.plot(
                    xf[abs(yf) > 0.01 * max(abs(yf))],
                    100.0 / l * np.imag(yf[abs(yf) > 0.01 * max(abs(yf))]))

    if len(states_u) and len(states_s) and Data['d'] == 1:
        for i in range(len(states_s)):
            if len(states_s[i][0, :-1]) % 2:
                vecx1 = states_s[i][0, :1:-1]
                vecy1 = states_s[i][1, :1:-1]
            else:
                vecx1 = states_s[i][0, :0:-1]
                vecy1 = states_s[i][1, :0:-1]

            if len(states_u[i][0, :-1]) % 2:
                vecx2 = states_u[i][0, :-2]
                vecy2 = states_u[i][1, :-2]
            else:
                vecx2 = states_u[i][0, :-1]
                vecy2 = states_u[i][1, :-1]

            vecx = np.append(vecx1, vecx2)
            vecy = np.append(vecy1, vecy2)

            temp = fft(vecx - pos[0] + vecy * 1.j)
            l = len(vecx)

            signal_s.append(temp)

            xf = fftfreq(l, Data['prnt_out_dt'])
            xf = fftshift(xf)
            yf = fftshift(temp)
            ax3.plot(xf[abs(yf) > 0.01 * max(abs(yf))],
                     100.0 / l * np.real(yf[abs(yf) > 0.01 * max(abs(yf))]))
            ax32.plot(xf[abs(yf) > 0.01 * max(abs(yf))],
                      100.0 / l * np.imag(yf[abs(yf) > 0.01 * max(abs(yf))]))

    plt.show()
示例#26
0
def digitize(x):
    if bitdepth is 0:
        return x
    a = (2**bitdepth-1)
    return float64(int32(a*x/max(x)))/a

def dB(x):
    return 10*log10(x)
         

def add_detail(x):
    if x =='0':
        return 'non-digitalized'
    return x+' bit'
X = linspace(-7, 7, nsamples)
#plot(X,f(X))
bds = [0, 8, 12, 16]
for bitdepth in bds:
    plot(dB(abs(fft.fftshift(fft.fft(digitize(f(X)))))))
legend(map(lambda x:add_detail(str(x)),bds),loc='upper left')
xlabel('frequency domain (a.u.)')
ylabel('signal (dB)')

#ns = [512, 1024, 2048]
#bitdepth = 8
#for nsamples in ns:
#    X = linspace(-7, 7, nsamples)
#    K = X*nsamples/512.0 
#    plot(K,dB(abs(fft.fftshift(fft.fft(digitize(f(X)))))))
#legend(map(str,ns))
示例#27
0
 def shift(self):
     """This method shifts the image mean (the zero-frequency component)
      towards the center of the image"""
     self._plotting = np.abs(fft.fftshift(self._data))