Ejemplo n.º 1
0
"""
-------------------------------------------------
      LIBRERÍA CREADA PARA LA GENERACIÓN DEL
            HISTÓRICO DE FASE TEÓRICO
-------------------------------------------------
@author: LUIS
"""
import numpy as np
import sarPrm as sp
import drawFigures as dF

#------------------LECTURA Y DEFINICIÓN DE PARÁMETROS--------------------
prm = sp.get_parameters()
c,fc,BW,Nf = prm['c'],prm['fc'],prm['BW'],prm['Nf']
Ls,Np,Ro,theta = prm['Ls'],prm['Np'],prm['Ro'],prm['theta']
Lx,Ly,dx,dy = prm['w'],prm['h'],prm['dw'],prm['dh'] # Dimensiones de la imagen

# Funcion para mostrar el historico de fase y varios parametros
def get_SAR_data():
    """ Obtiene el histórico de fase ya sea simulado o real"""
    # Cálculo de parámetros
    It, Rt = sp.get_matrix_data1() # Coordenadas(m) y magnitud del target respectivamente
    dp=Ls/(Np-1) # Paso del riel(m)
    df=BW/(Nf-1) # Paso en frecuencia del BW
    fi=fc-BW/2 # Frecuencia inferior(GHz)
    fs=fc+BW/2 # Frecuencia superior(GHz)

    # Cálculo de las resoluciones
    rr_r=c/(2*BW) # Resolución en rango
    rr_a=c/(2*Ls*fc) # Resolución en azimuth
Ejemplo n.º 2
0
import matplotlib.pyplot as plt
import time
import sarPrm as sp  # Created Library to define sistem parameters
import drawFigures as dF  # Created Library to draw FFT functions
from angles import normalize
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.mplot3d import Axes3D

#########################################################
#     GENERACIÓN DE LOS DATOS (SIMULACIÓN DIRECTA)      #
#########################################################

# N° de puntos: 1

#--------------PARAMETERS DEFINITION---------------------
c, fc, BW, Nf, Ls, Np, Ro = sp.get_parameters()  # Parametros
Rt_x, Rt_y = sp.get_scalar_target()  # Coordendas del target(m)
Ru_m, dx_a_m = sp.verify_conditions()  # Verificar rango y paso del riel maximo
rr_r, rr_x = sp.get_resolutions(Ru_m)  # Resoluciones en rango y azimuth
#Ru_m, dx_a_m = sp.verify_conditions() # Verificar rango y paso del riel maximo

df = BW / (Nf - 1)  # Paso de frecuencia(GHz)
dp = Ls / (Np - 1)  # Paso del riel(m)
fi = fc - BW / 2  # Frecuencia inferior(GHz)
fs = fc + BW / 2  # Frecuencia superior(GHz)

print("--------INFORMACIÓN IMPORTANTE--------------")
print("Range_resolution: ", rr_r)
print("Cross_range_resolution: ", rr_x)
print("--------------------------------------------")
print("Rango máximo (m): ", Ru_m)
def make_interferometry(data, algorithm=None):
    """ Esta funcion se encarga de obtener los  mapas de desplazamientos, o los 
        interferogramas, esto lo realiza usando 2 imagenes consecutivas para obtener
        una imagen de mapa de desplazamientos.
        Para ello pasa por las siguientes etapas:
        1) Obtencion de mapa de coherencia: Esto se realiza para todo el set de imagenes,
                                            con ello se obtiene la mascara.
        2) Obtencion de los interferogramas usando la mascara
        3) Obtencion de los mapas de desplazamientos
        4) Se divide el mapa en zonas 
        5) Se obtiene el promedio de cada zona por interferograma 
        6) Finalmente se guarda los promedios por cada zona y por cada interferograma 
           en una matriz.
    """
    # Obteniendo el mapa de coherencia
    Im = np.load(os.getcwd() + "/Results/Output_" + algorithm +
                 "/Im_10.npy")  # Se carga la imagen 10
    f1 = np.zeros((len(Im), len(Im.T)), dtype=complex)
    f2 = np.zeros((len(Im), len(Im.T)), dtype=complex)
    coh = np.zeros((len(Im), len(Im.T)), dtype=complex)

    for i in range(n_im - 1):
        i += i_o  # Valor inicial
        Im1 = np.load(os.getcwd() + "/Results/Output_" + algorithm + "/Im_" +
                      str(i) + ".npy")
        Im2 = np.load(os.getcwd() + "/Results/Output_" + algorithm + "/Im_" +
                      str(i + 1) + ".npy")
        f1 += Im1 * Im2.conjugate()
        f2 += np.sqrt((abs(Im1)**2) * (abs(Im2)**2))

    coh = abs(f1 / f2)

    # Graficando la coherencia
    if show:
        plt.close('all')
        cmap = "plasma"
        if algorithm == "BP":
            title_name = 'Mapa de coherencia(BP)\n[dset' + str(
                i_o) + '-' + str(i_o + n_im - 1) + ']'
            direction = 'Coherencia_BP_dset' + str(i_o) + '-' + str(
                i_o + n_im - 1) + '].png'

        elif algorithm == "RMA":
            title_name = 'Mapa de coherencia(RMA)\n[dset' + str(
                i_o) + '-' + str(i_o + n_im - 1) + ']'
            direction = 'Coherencia_RMA_dset' + str(i_o) + '-' + str(
                i_o + n_im - 1) + '].png'
        #vmin = np.amin(20*np.log10(abs(Sf_n)))+55 #dB
        #vmax = np.amax(20*np.log10(abs(Sf_n)))#-20

        fig, ax = plt.subplots()
        im = ax.imshow(coh,
                       cmap,
                       origin='lower',
                       aspect='equal',
                       extent=[
                           data['x_min'], data['x_max'], data['y_min'],
                           data['y_max']
                       ])  #, vmin=vmin, vmax=vmax)
        ax.set(xlabel='Azimut(m)', ylabel='Rango(m)', title=title_name)
        ax.grid()
        divider = make_axes_locatable(ax)
        cax = divider.append_axes(
            "right", size="5%",
            pad=0.1)  # pad es el espaciado con la grafica principal
        plt.colorbar(im, cax=cax, label='', extend='both')
        fig.savefig(os.getcwd() +
                    "/Results/Interferograms_BP/Coherence_maps/" + direction,
                    orientation='landscape')

    # Sacando una mascara de [0.7,1] para la coherencia
    mask = coh <= 0.7
    coh[mask] = np.nan

    # Graficando con la mascara
    if show:
        cmap = "plasma"
        if algorithm == "BP":
            title_name = 'Mapa de coherencia recortada(BP)\n[dset' + str(
                i_o) + '-' + str(i_o + n_im - 1) + ']'
            direction = 'CoherenciaCut_BP_dset' + str(i_o) + '-' + str(
                i_o + n_im - 1) + '].png'

        elif algorithm == "RMA":
            title_name = 'Mapa de coherencia recortada(RMA)\n[dset' + str(
                i_o) + '-' + str(i_o + n_im - 1) + ']'
            direction = 'CoherenciaCut_RMA_dset' + str(i_o) + '-' + str(
                i_o + n_im - 1) + '].png'
        #vmin = np.amin(20*np.log10(abs(Sf_n)))+55 #dB
        #vmax = np.amax(20*np.log10(abs(Sf_n)))#-20
        fig, ax = plt.subplots()
        im = ax.imshow(coh,
                       cmap,
                       origin='lower',
                       aspect='equal',
                       extent=[
                           data['x_min'], data['x_max'], data['y_min'],
                           data['y_max']
                       ])  #, vmin=vmin, vmax=vmax)
        ax.set(xlabel='Azimut(m)', ylabel='Rango(m)', title=title_name)
        ax.grid()
        divider = make_axes_locatable(ax)
        cax = divider.append_axes(
            "right", size="5%",
            pad=0.1)  # pad es el espaciado con la grafica principal
        plt.colorbar(im, cax=cax, label='', extend='both')
        fig.savefig(os.getcwd() +
                    "/Results/Interferograms_BP/Coherence_maps/" + direction,
                    orientation='landscape')

    # Obteniendo el mapa de desplazamientos, aka, Interferograma
    par = sp.get_parameters()
    global c, fc
    c, fc = par['c'], par['fc']

    if show:
        for i in range(n_im - 1):
            # Hallando el interferograma 'i'-esimo
            i1 = i + 10
            Im1 = np.load(os.getcwd() + "/Results/Output_" + algorithm +
                          "/Im_" + str(i1) + ".npy")
            Im2 = np.load(os.getcwd() + "/Results/Output_" + algorithm +
                          "/Im_" + str(i1 + 1) + ".npy")
            disp = np.angle(Im1 * Im2.conjugate()) * 1000 * c / (
                4 * np.pi * fc)  # Distancias en mm
            disp[mask] = np.nan
            # Graficando y guardando
            if algorithm == "BP":
                title_name = 'Interferograma (BP) \ndset' + '[' + str(
                    i1) + ']-[' + str(i1 + 1) + ']'
                #direction ='Interferogramas_BP/'+'Itf_BP_dset'+'['+str(i+10)+']-['+str(i+11)+'].png'
                direction = 'Itf_BP_dset' + str(i) + '.png'

            elif algorithm == "RMA":
                title_name = 'Interferograma (RMA) \ndset' + '[' + str(
                    i1) + ']-[' + str(i1 + 1) + ']'
                #direction ='Interferogramas_RMA/'+'Itf_RMA_dset'+'['+str(i+10)+']-['+str(i+11)+'].png'
                direction = 'Itf_RMA_dset' + str(i) + '.png'
            cmap = plt.cm.plasma  #brg
            cmap.set_bad('black', 1.)
            #vmin = np.amin(20*np.log10(abs(Sf_n)))+55 #dB
            #vmax = np.amax(20*np.log10(abs(Sf_n)))#-20
            fig, ax = plt.subplots()
            im = ax.imshow(disp,
                           cmap,
                           origin='lower',
                           aspect='equal',
                           extent=[
                               data['x_min'], data['x_max'], data['y_min'],
                               data['y_max']
                           ])  #, vmin=vmin, vmax=vmax)
            ax.set(xlabel='Azimut(m)', ylabel='Rango(m)', title=title_name)
            ax.grid()
            divider = make_axes_locatable(ax)
            cax = divider.append_axes(
                "right", size="5%",
                pad=0.1)  # pad es el espaciado con la grafica principal
            plt.colorbar(im,
                         cax=cax,
                         label='desplazamiento(mm)',
                         extend='both')
            fig.savefig(
                os.getcwd() +
                "/Results/Interferograms_BP/Interferograms_complete/Images/" +
                direction,
                orientation='landscape')
            plt.close()

    # Hallando la curva de distancias vs tiempo
    #-------Definiendo las zonas--------------
    zone0 = np.array([0, 650, 0, 400])
    zone1 = np.array([0, 100, 100, 200])
    zone2 = np.array([0, 100, 200, 300])
    zone3 = np.array([100, 200, 100, 200])
    zone4 = np.array([100, 200, 200, 300])
    zone5 = np.array([200, 300, 100, 200])
    zone6 = np.array([200, 300, 200, 300])
    zone_indexes = {
        0: zone0,
        1: zone1,
        2: zone2,
        3: zone3,
        4: zone4,
        5: zone5,
        6: zone6
    }

    desp = np.zeros(
        (len(zone_indexes), n_im - 1))  # Variable y: desplazamiento

    for z in range(len(
            zone_indexes)):  # Hallando los desplazamientos promedios por zona
        idc = zone_indexes[z]
        for i in range(n_im - 1):
            i1 = i + 10  # 10 es el valor inicial de las imagenes
            Im1 = np.load(os.getcwd() + "/Results/Output_" + algorithm +
                          "/Im_" + str(i1) + ".npy")
            Im2 = np.load(os.getcwd() + "/Results/Output_" + algorithm +
                          "/Im_" + str(i1 + 1) + ".npy")
            d_i = np.angle(Im1 * Im2.conjugate()) * 1000 * c / (4 * np.pi * fc)
            # ----- Grafica ------
            d_i2 = d_i.copy()
            d_i2[mask] = np.nan
            d_i2 = d_i2[idc[0]:idc[1], idc[2]:idc[3]]
            # -----   end --------
            d_i[mask] = 0
            d_i = d_i[idc[0]:idc[1], idc[2]:idc[3]]
            if i == 0: desp[z, i] = d_i.mean()
            else: desp[z, i] = d_i.mean() + desp[z, i - 1]

            # Graficando la zona z-esima
            if show and i == 0:  #
                if algorithm == "BP":
                    title_name = 'Interferograma recortado(BP) \nZona ' + str(
                        z) + ' - dset' + '[' + str(i1) + ']-[' + str(i1 +
                                                                     1) + ']'
                    direction = 'Itf_BP_rec_zona_' + str(
                        z) + '_dset' + '[' + str(i1) + ']-[' + str(i1 +
                                                                   1) + '].png'
                    #direction ='Interferogramas_BP/'+'Itf_BP_dset'+str(i)+'.png'

                elif algorithm == "RMA":
                    title_name = 'Interferograma recortado(RMA) \nZona ' + str(
                        z) + ' - dset' + '[' + str(i1) + ']-[' + str(i1 +
                                                                     1) + ']'
                    direction = 'Itf_RMA_rec_zona_' + str(
                        z) + '_dset' + '[' + str(i1) + ']-[' + str(i1 +
                                                                   1) + '].png'
                    #direction ='Interferogramas_RMA/'+'Itf_RMA_dset'+str(i)+'.png'
                cmap = plt.cm.plasma  #brg
                cmap.set_bad('black', 1.)
                #vmin = np.amin(20*np.log10(abs(Sf_n)))+55 #dB
                #vmax = np.amax(20*np.log10(abs(Sf_n)))#-20
                fig, ax = plt.subplots()
                im = ax.imshow(d_i2,
                               cmap,
                               origin='lower',
                               aspect='equal',
                               extent=[
                                   idc[2] - 200, idc[3] - 200, idc[0] + 300,
                                   idc[1] + 300
                               ])  #, vmin=vmin, vmax=vmax)
                ax.set(xlabel='Azimut(m)', ylabel='Rango(m)', title=title_name)
                ax.grid()
                divider = make_axes_locatable(ax)
                cax = divider.append_axes(
                    "right", size="5%",
                    pad=0.1)  # pad es el espaciado con la grafica principal
                plt.colorbar(im,
                             cax=cax,
                             label='desplazamiento(mm)',
                             extend='both')
                fig.savefig(
                    os.getcwd() +
                    "/Results/Interferograms_BP/Interferograms_complete/Images/"
                    + direction,
                    orientation='landscape')

    #t = np.arange(len(Ims)-1)+10 # Variable x, tiempo
    time_dset = np.load("Dates_BP.npy")
    time_dset = time_dset[:-1]
    time_dset2 = np.array([
        datetime.datetime.strptime(idx, "%d-%m-%y %H:%M:%S")
        for idx in time_dset
    ])

    # Grafica de desplazamiento vs tiempo por cada algoritmo
    """if show:
        if algorithm == "BP":
            title_name ='Desplazamiento promedio(BP)'
            direction ='desplazamientoPromedio_BP_dset10-100.png'

            fig, ax= plt.subplots()
            ax.plot(t,desp,'b',marker='o',markerfacecolor='b',markeredgecolor='b')
            ax.set(xlabel='Tiempo(unidades)',ylabel='Desplazamiento(mm)', title=title_name)
            #ax.set_xlim([R.min(),R.max()])
            ax.set_ylim([-c*100/(4*fc),c*100/(4*fc)])
            ax.grid()
            plt.show()
            fig.savefig(os.getcwd()+"/Results/Desplazamientos/"+direction,orientation='landscape')

        elif algorithm == "RMA":
            title_name ='Desplazamiento promedio(RMA)'
            direction ='desplazamientoPromedio_RMA_dset10-100.png'

            fig, ax= plt.subplots()
            ax.plot(t,desp,'r',marker='o',markerfacecolor='r',markeredgecolor='r')
            ax.set(xlabel='Tiempo(unidades)',ylabel='Desplazamiento(mm)', title=title_name)
            #ax.set_xlim([R.min(),R.max()])
            ax.set_ylim([-c*50/(4*fc),c*50/(4*fc)])
            ax.grid()
            plt.show()
            fig.savefig(os.getcwd()+"/Results/Desplazamientos/"+direction,orientation='landscape')
      """
    return {'d_t': desp, 't': time_dset2}