def plot_files(fname, **args):
    # Converts the CPT file to be used in Python
    cpt = loadCPT('IR4AVHRR6.cpt')
    # Makes a linear interpolation with the CPT file
    cpt_convert = LinearSegmentedColormap('cpt', cpt)

    # Search for the Scan Start in the file name
    time = (fname[fname.find("MG_")+3:fname.find(".nc")])
    # Format the "Observation Start" string
    date = datetime.strptime(time,'%Y%m%d%H%M%S')

    # Check if we already created the image
    image_string = folder+'images/%s_%s.png' % (channel, datetime.strftime(date,'%Y%m%d%H%M%S'))
    if os.path.isfile(image_string):
        print('Skipping '+fname)
        return None

    # print('Using '+fname)
    # Open the file using the NetCDF4 library
    nc = Dataset(fname)
    # Extract the Brightness Temperature values from the NetCDF
    temp_b = brigthness_temp(nc.variables[channel])
    hrv =  nc.variables[channel_hrv][:]

    if (hrv.std() > 0.9):
        args['bmap'].pcolormesh(args['x_hrv'], args['y_hrv'], hrv, vmin=0, vmax=20, cmap='gray')
        args['bmap'].pcolormesh(args['x'], args['y'], np.ma.masked_array(temp_b, temp_b > -38),
                        vmin=-80, vmax=50, cmap=cpt_convert,
                        alpha=0.3, linewidth=0, antialiased=True)
    else:
        args['bmap'].pcolormesh(args['x'], args['y'], temp_b, vmin=-80, vmax=50, cmap=cpt_convert,
            antialiased=True)

    args['bmap'].drawcoastlines(linewidth=0.5, linestyle='solid', color='white')
    args['bmap'].drawcountries(linewidth=0.5, linestyle='solid', color='white')
    args['bmap'].drawparallels(np.arange(-90.0, 90.0, 5.), linewidth=0.2,
             color='white', labels=[True, False, False, True], fontsize=7)
    args['bmap'].drawmeridians(np.arange(0.0, 360.0, 5.), linewidth=0.2, 
            color='white', labels=[True, False, False, True], fontsize=7)

    # Insert the legend
    args['bmap'].colorbar(location='right', label='Brightness Temperature [C] / HRV radiance',
                     size='2%', pad='1%')

    date_formatted = datetime.strftime(date,'%a %d %b %Y, %H:%MZ')
    annotation(plt.gca(), date_formatted,
                    loc='upper center',fontsize=9)
    annotation(plt.gca(), "SEVIRI %s,%s High Rate data" %(channel, channel_hrv) + u"\N{COPYRIGHT SIGN}"+'EUMETSAT - prepared by Guido Cioni (www.guidocioni.it)' ,
                    loc='lower left', fontsize=7)
    #print('Saving file %s' % image_string)
    plt.savefig(image_string, bbox_inches='tight', dpi=200)
    plt.clf()
Exemple #2
0
                   dashes=[4, 4],
                   color='white',
                   labels=[True, False, False, True],
                   fmt='%g',
                   labelstyle="+/-",
                   size=8)

dataAboveLimit = masked_array(dataArray,
                              dataArray < -20)  #TIRA OS MENORES QUE -20
dataBelowLimit = masked_array(dataArray,
                              dataArray >= -20)  #TIRA OS MAIORES QUE -20

if int(Band) <= 7 or int(Band) == 15:
    # Converts a CPT file to be used in Python
    cpt = loadCPT(
        '/home/cendas/GOES16_WS_Rodrigo/CloudTopTemperature/Colortables/Square Root Visible Enhancement.cpt'
    )
    # Makes a linear interpolation
    cpt_convert = LinearSegmentedColormap('cpt', cpt)
    # Plot the GOES-16 channel with the converted CPT colors (you may alter the min and max to match your preference)
    bmap.imshow(dataArray, origin='upper', cmap=cpt_convert, vmin=0, vmax=1)

elif int(Band) > 7 and int(Band) <= 10:
    # Converts a CPT file to be used in Python
    cptHot = loadCPT(
        '/home/cendas/GOES16_WS_Rodrigo/CloudTopTemperature/Colortables/GMT_hot.cpt'
    )
    cptGray = loadCPT(
        '/home/cendas/GOES16_WS_Rodrigo/CloudTopTemperature/Colortables/Square Root Visible Enhancement.cpt'
    )
    # Makes a linear interpolation
Exemple #3
0
def plot(sistemas_convectivos_nc, glm_nc, local, extent, resolution=2):

    if (local == 'Brasil'):
        degrees = 10
        label_fontsize = 50
    elif (local == 'Sudeste'):
        degrees = 5
        label_fontsize = 8
    else:
        degrees = 2
        resolution = 0.8
        label_fontsize = 8

    g16glm = Dataset(glm_nc, 'r')
    nc = Dataset(sistemas_convectivos_nc)

    # Get the latitude and longitude image bounds
    geo_extent = nc.variables['geospatial_lat_lon_extent']
    min_lon = float(geo_extent.geospatial_westbound_longitude)
    max_lon = float(geo_extent.geospatial_eastbound_longitude)
    min_lat = float(geo_extent.geospatial_southbound_latitude)
    max_lat = float(geo_extent.geospatial_northbound_latitude)

    # Choose the visualization extent (min lon, min lat, max lon, max lat)
    #extent = [-45.0, -24.5, -39.0, -20.7]

    # Choose the image resolution (the higher the number the faster the processing is)
    #resolution = 0.8 #2

    # Calculate the image extent required for the reprojection
    H = nc.variables['goes_imager_projection'].perspective_point_height
    x1 = nc.variables['x_image_bounds'][0] * H
    x2 = nc.variables['x_image_bounds'][1] * H
    y1 = nc.variables['y_image_bounds'][1] * H
    y2 = nc.variables['y_image_bounds'][0] * H

    # Call the reprojection funcion
    grid = remap(sistemas_convectivos_nc, extent, resolution, x1, y1, x2, y2)
    tipos = ["todos", "event", "group", "flash"]
    for formato in range(4):
        glm_variables = [False, False, False, False]
        glm_variables[formato] = True
        #print(glm_variables)
        # Read the data returned by the function ==============================================================
        # If it is an IR channel subtract 273.15 to convert to ° Celsius
        data = grid.ReadAsArray() - 273.15

        # Make pixels outside the footprint invisible
        data[data <= -180] = np.nan

        # Define the size of the saved picture =================================================================
        DPI = 150
        fig = plt.figure(figsize=(data.shape[1] / float(DPI),
                                  data.shape[0] / float(DPI)),
                         frameon=False,
                         dpi=DPI)
        ax = plt.Axes(fig, [0., 0., 1., 1.])
        ax.set_axis_off()
        fig.add_axes(ax)
        ax = plt.axis('off')

        # Plot the Data =======================================================================================

        # Create the basemap reference for the Rectangular Projection
        bmap = Basemap(llcrnrlon=extent[0],
                       llcrnrlat=extent[1],
                       urcrnrlon=extent[2],
                       urcrnrlat=extent[3],
                       epsg=4326)

        # Draw the countries and Brazilian states shapefiles
        bmap.readshapefile('/home/cendas/GOES16_WS_Rodrigo/GLM/src/BRA_adm1',
                           'BRA_adm1',
                           linewidth=0.50,
                           color='#000000')

        if (local == 'Brasil'):
            bmap.readshapefile(
                '/home/cendas/GOES16_WS_Rodrigo/GLM/src/ne_10m_coastline',
                'ne_10m_coastline',
                linewidth=0.50,
                color='#000000')

        #ne_10m_coastline
        # Draw parallels and meridians
        if (not (local == 'Brasil')):
            bmap.drawparallels(np.arange(-90.0, 90.0, degrees),
                               linewidth=0.3,
                               dashes=[4, 4],
                               color='white',
                               labels=[True, False, False, True],
                               fmt='%g',
                               labelstyle="+/-",
                               size=8)
            bmap.drawmeridians(np.arange(0.0, 360.0, degrees),
                               linewidth=0.3,
                               dashes=[4, 4],
                               color='white',
                               labels=[True, False, False, True],
                               fmt='%g',
                               labelstyle="+/-",
                               size=8)
        else:
            bmap.drawparallels(np.arange(-90.0, 90.0, degrees),
                               linewidth=0.3,
                               dashes=[4, 4],
                               color='white',
                               labels=[True, False, False, True],
                               fmt='%g',
                               labelstyle="+/-",
                               size=30)
            bmap.drawmeridians(np.arange(0.0, 360.0, degrees),
                               linewidth=0.3,
                               dashes=[4, 4],
                               color='white',
                               labels=[True, False, False, True],
                               fmt='%g',
                               labelstyle="+/-",
                               size=30)
        #Split the dataset with temperatures above and below -20°C
        temp = -80
        tempAbove = masked_array(data, data < temp)
        tempBelow = masked_array(data, data >= temp)

        # Converts a CPT file to be used in Python

        cptSquareRoot = loadCPT(
            '/home/cendas/GOES16_WS_Rodrigo/GLM/src/Square Root Visible Enhancement.cpt'
        )
        # Makes a linear interpolation
        cpt_convert_SquareRoot = LinearSegmentedColormap('cpt', cptSquareRoot)

        # Plot the GOES-16 channel with the converted CPT colors (you may alter the min and max to match your preference)
        plot_SquareRoot = bmap.imshow(tempAbove,
                                      origin='upper',
                                      cmap=cpt_convert_SquareRoot,
                                      vmin=-80,
                                      vmax=100)

        # ===================== LEGENDA ==========================

        # Get the unit based on the channel. If channels 1 trough 6 is Albedo. If channels 7 to 16 is BT.
        Unit = "Cloud Top Temperature [°C]"

        # Choose a title for the plot
        Title = " Geostationary Lightning Mapper (GLM) - GOES Satellite"
        Latitude = "Latitude"
        Longitude = "Longitude"

        # Add a black rectangle in the bottom to insert the image description
        lon_difference = (extent[2] - extent[0])  # Max Lon - Min Lon
        # Add the image description inside the black rectangle
        lat_difference = (extent[3] - extent[1])  # Max lat - Min lat
        if (not (local == 'Brasil')):
            #Labels and its positions #
            plt.text(extent[0] + lon_difference * 0.5,
                     extent[3] + lat_difference * 0.035,
                     Title,
                     horizontalalignment='center',
                     color='black',
                     size=9)

            plt.text(extent[0] + lon_difference * 0.5,
                     extent[3] + lat_difference * 0.065,
                     " ",
                     horizontalalignment='center',
                     color='black',
                     size=10)

            plt.text(extent[0] + lon_difference * 0.5,
                     extent[1] - lat_difference * 0.11,
                     Longitude,
                     horizontalalignment='center',
                     color='black',
                     size=10)

            plt.text(extent[0] + lon_difference * 0.5,
                     extent[1] - lat_difference * 0.15,
                     " ",
                     horizontalalignment='center',
                     color='black',
                     size=18)

            plt.text(extent[0] - lon_difference * 0.15,
                     extent[1] + lat_difference * 0.5,
                     Latitude,
                     verticalalignment='center',
                     rotation="vertical",
                     color='black',
                     size=10)

        else:
            plt.text(extent[0] + lon_difference * 0.5,
                     extent[3] + lat_difference * 0.035,
                     Title,
                     horizontalalignment='center',
                     color='black',
                     size=40)

            plt.text(extent[0] + lon_difference * 0.5,
                     extent[3] + lat_difference * 0.065,
                     " ",
                     horizontalalignment='center',
                     color='black',
                     size=10)

            plt.text(extent[0] + lon_difference * 0.5,
                     extent[1] - lat_difference * 0.11,
                     Longitude,
                     horizontalalignment='center',
                     color='black',
                     size=40)

            plt.text(extent[0] + lon_difference * 0.5,
                     extent[1] - lat_difference * 0.15,
                     " ",
                     horizontalalignment='center',
                     color='black',
                     size=18)

            plt.text(extent[0] - lon_difference * 0.15,
                     extent[1] + lat_difference * 0.5,
                     Latitude,
                     verticalalignment='center',
                     rotation="vertical",
                     color='black',
                     size=40)

        # ========================================
        if (glm_variables[0]):  #Todos
            # Get Events, Group and flash from Glm file
            event_lat = g16glm.variables['event_lat'][:]
            event_lon = g16glm.variables['event_lon'][:]

            group_lat = g16glm.variables['group_lat'][:]
            group_lon = g16glm.variables['group_lon'][:]

            flash_lat = g16glm.variables['flash_lat'][:]
            flash_lon = g16glm.variables['flash_lon'][:]

            # Plot events as large blue dots
            event_x, event_y = bmap(event_lon, event_lat)
            bmap.plot(event_x, event_y, 'bo', markersize=7, label='Events')

            # Plot groups as medium green dots
            group_x, group_y = bmap(group_lon, group_lat)
            bmap.plot(group_x, group_y, 'go', markersize=3, label='Group')

            # Plot flashes as small red dots
            flash_x, flash_y = bmap(flash_lon, flash_lat)
            bmap.plot(flash_x, flash_y, 'ro', markersize=1, label='Flash')
            plt.legend(fontsize=label_fontsize, loc=4)
        else:
            if (glm_variables[1]):
                # Get Events from Glm file
                event_lat = g16glm.variables['event_lat'][:]
                event_lon = g16glm.variables['event_lon'][:]
                # Plot events as large blue dots
                event_x, event_y = bmap(event_lon, event_lat)
                bmap.plot(event_x, event_y, 'bo', markersize=7, label='Events')
            if (glm_variables[2]):
                # Get Group from Glm file
                group_lat = g16glm.variables['group_lat'][:]
                group_lon = g16glm.variables['group_lon'][:]
                # Plot groups as medium green dots
                group_x, group_y = bmap(group_lon, group_lat)
                bmap.plot(group_x, group_y, 'go', markersize=3, label='Group')
            if (glm_variables[3]):
                # Get Flash from Glm file
                flash_lat = g16glm.variables['flash_lat'][:]
                flash_lon = g16glm.variables['flash_lon'][:]
                # Plot flashes as small red dots
                flash_x, flash_y = bmap(flash_lon, flash_lat)
                bmap.plot(flash_x, flash_y, 'ro', markersize=1, label='Flash')
            plt.legend(fontsize=label_fontsize, loc=4)
            #plt.show()
        Start = glm_nc[glm_nc.find('_s') + 1:glm_nc.find("_e") - 3]
        year = int(Start[1:5])
        dayjulian = int(
            Start[5:8]) - 1  # Subtract 1 because the year starts at "0"
        dayconventional = datetime.datetime(year, 1, 1) + datetime.timedelta(
            dayjulian)  # Convert from julian to conventional
        month = dayconventional.strftime('%m')
        day = dayconventional.strftime('%d')
        hour = int(Start[8:12])

        plt.savefig('/home/cendas/GOES16_WS_Rodrigo/GLM/Output/' + local +
                    '/glm_' + str(year) + str(month) + str(day) + '_' +
                    str(hour) + '_' + tipos[formato] + '.png',
                    dpi=DPI,
                    pad_inches=0,
                    transparent=True,
                    bbox_inches='tight')
        plt.close()
# Required libraries
from mpl_toolkits.basemap import Basemap  # Import the Basemap toolkit
import matplotlib.pyplot as plt
from netCDF4 import Dataset
import numpy as np  # Import the Numpy package
from cpt_convert import loadCPT  # Import the CPT convert function
from matplotlib.colors import LinearSegmentedColormap  # Linear interpolation for color maps
from datetime import datetime
from glob import glob
import os
from utils import brigthness_temp

# Converts the CPT file to be used in Python
cpt = loadCPT('IR4AVHRR6.cpt')
# Makes a linear interpolation with the CPT file
cpt_convert = LinearSegmentedColormap('cpt', cpt)

path = '/work/mh0731/m300382/sat/ilona/'

fnames = sorted(glob(path + "*.nc"))
first = True
coords = []
dates = []

# for fname in fnames[35:340]:
for fname in fnames[35:340]:
    # Search for the Scan Start in the file name
    time = (fname[fname.find("MG_") + 3:fname.find(".nc")])
    # Format the "Observation Start" string
    date = datetime.strptime(time, '%Y%m%d%H%M%S')
Exemple #5
0
    print ('\n4. Ploteando datos')
    
    # Obtiene las coordenadas extremas de la ventana
    coorven = coordenadasVentana(x,y,offset)
    
    # Plotea los datos
    plotDatos(x,y,offset,var,path,coorven,dataVen,dataMin,dataMax,dataMean,varBus,varName,stdName,unidades,varCal,paleta,logoPath,muestraDatos)
    
    # Muestra la información del proceso           
    print ('Region Mapeada en:', round(t.time() - start,4), 'segundos')
    print ('Latitud :',y)
    print ('Longitud :',x)
    print (var+' :',varBus)
        
# TEST DE LA FUNCIÓN 
cpt = loadCPT('temperature.cpt')
cpt_convert = LinearSegmentedColormap('cpt', cpt)

# Parametros requeridos
path = 'OR_ABI-L2-SSTF-M3_G16_s20180661300403_e20180661356170_c20180661400158.nc'
var = 'SST'
x = -112
y = 22
offset = 15
paleta = 'Spectral'
logoPath = 'LANOT.png'
muestraDatos = True

# Función plot buscador Goes16
plotBuscador(path,var,x,y,offset,paleta,logoPath,muestraDatos)
Exemple #6
0
def dataproc(ruta, path, paleta):

    #    path="OR_ABI-L2-CMIPM1-M3C14_G16_s20190280235234_e20190280235291_c20190280235337.nc"

    # Open NC file
    nc = Dataset(path)

    # Load data
    data_subset = nc.variables['CMI'][:][:, :]

    # Create the projection variables
    ori_proj = nc.variables['goes_imager_projection']
    sat_h = ori_proj.perspective_point_height
    sat_lon = ori_proj.longitude_of_projection_origin
    sat_sweep = ori_proj.sweep_angle_axis
    # The projection x and y coordinates equals
    # the scanning angle (in radians) multiplied by the satellite height (http://proj4.org/projections/geos.html)
    X = nc.variables['x'][:] * sat_h
    Y = nc.variables['y'][:] * sat_h
    p = Proj(proj='geos', h=sat_h, lon_0=sat_lon, sweep=sat_sweep)
    # Convert map points to latitude and longitude with the magic provided by Pyproj
    XX, YY = np.meshgrid(X, Y)
    lons, lats = p(XX, YY, inverse=True)

    ii = []
    jj = []
    for i in range(lons.shape[1]):
        for j in range(lats.shape[0]):
            if lons[-1, i] >= -83.2 and lats[j, -1] >= 22.3 and lons[
                    -1, i] <= -81.4 and lats[j, -1] <= 23.7:
                ii.append(i)
                jj.append(j)

    jmin, jmax = (int(np.min(ii)), int(np.max(ii)))
    imin, imax = (int(np.min(jj)), int(np.max(jj)))

    # Create map
    DPI = 150
    ax = plt.figure(figsize=(2000 / float(DPI), 2000 / float(DPI)),
                    frameon=True,
                    dpi=DPI)
    bmap = Basemap(projection='cyl',
                   llcrnrlon=lons[-1, jmin],
                   llcrnrlat=lats[imax, -1],
                   urcrnrlon=lons[-1, jmax],
                   urcrnrlat=lats[imin, -1],
                   resolution='h')

    bmap.drawparallels(np.arange(-90.0, 90.0, 10.0),
                       linewidth=0.1,
                       color='black',
                       labels=[True, False, False, True])
    bmap.drawmeridians(np.arange(0.0, 360.0, 10.0),
                       linewidth=0.1,
                       color='black',
                       labels=[True, False, False, True])

    # Load Shapefile
    #    bmap.readshapefile('Nueva_DPA','Nueva_DPA',linewidth=0.90,color='darkslategray')
    bmap.drawstates(color='gray', linewidth=0.25)
    bmap.drawcoastlines(color='k', linewidth=0.9)
    bmap.drawcountries(color='k', linewidth=0.9)

    # Converts a CPT file to be used in Python
    cpt = loadCPT(paleta)
    # Makes a linear interpolation
    cpt_convert = LinearSegmentedColormap('cpt', cpt)

    # Plot the GOES-16 channel with the converted CPT colors
    #bmap.pcolormesh(lons[imin:imax,jmin:jmax],lats[imin:imax,jmin:jmax],data_subset[imin:imax,jmin:jmax], cmap=cpt_convert, vmin=170, vmax=378)
    bmap.pcolormesh(lons[imin:imax, jmin:jmax],
                    lats[imin:imax, jmin:jmax],
                    data_subset[imin:imax, jmin:jmax] - 273.15,
                    cmap=cpt_convert,
                    vmin=-103,
                    vmax=104)

    # Search for the GOES-16 channel in the file name
    Band = (path[path.find("M3C") + 3:path.find("_G16")])
    # Search for the Scan start in the file name
    Start = (path[path.find("_s") + 2:path.find("_e")])
    Start_Formatted = Start[0:4] + " Day " + Start[4:7] + " - " + Start[
        7:9] + ":" + Start[9:11] + ":" + Start[11:13] + "." + Start[
            13:14] + " UTC"
    # Search for the Scan end in the file name
    End = (path[path.find("_e") + 2:path.find("_c")])
    End_Formatted = End[0:4] + " Day " + End[4:7] + " - " + End[
        7:9] + ":" + End[9:11] + ":" + End[11:13] + "." + End[13:14] + " UTC"

    # Add a title to the plot
    plt.title("GOES-16 ABI Band " + Band + "\n Scan from " + Start_Formatted +
              " to " + End_Formatted,
              fontsize=10)

    #bmap.colorbar(location='right', label='Brightness Temperature [K]')
    bmap.colorbar(location='right', label='Brightness Temperature [C]')

    # Save the result
    # Converting from julian day to dd-mm-yyyy
    year = int(Start[0:4])
    dayjulian = int(
        Start[4:7]) - 1  # Subtract 1 because the year starts at "0"
    dayconventional = datetime.datetime(year, 1, 1) + datetime.timedelta(
        dayjulian)  # Convert from julian to conventional
    date = dayconventional.strftime(
        '%d-%b-%Y')  # Format the date according to the strftime directives
    date_save = dayconventional.strftime('%d%m%Y')
    time_save = Start[7:9] + Start[9:11] + Start[11:13]
    plt.savefig('G16_C' + str(Band) + '_' + date_save + '_' + time_save +
                '_meso.png',
                dpi=DPI,
                bbox_inches='tight',
                pad_inches=0)
    plt.clf()
    plt.cla()
Exemple #7
0
bmap.drawmeridians(np.arange(0.0, 360.0, 5),
                   linewidth=0.3,
                   dashes=[4, 4],
                   color='white',
                   labels=[True, False, False, True],
                   fmt='%g',
                   labelstyle="+/-",
                   size=10)

#Split the dataset with temperatures above and below -20°C
temp = -20
tempAbove = masked_array(data, data < temp)
tempBelow = masked_array(data, data >= temp)

# Converts a CPT file to be used in Python
cptRainbow = loadCPT('..\\colortable\\Rainbow.cpt')
cptSquareRoot = loadCPT('..\\colortable\\Square Root Visible Enhancement.cpt')

# Makes a linear interpolation
cpt_convert_SquareRoot = LinearSegmentedColormap('cpt', cptSquareRoot)
cpt_convert_Rainbow = LinearSegmentedColormap('cpt', cptRainbow)

# Plot the GOES-16 channel with the converted CPT colors (you may alter the min and max to match your preference)
plot_SquareRoot = bmap.imshow(tempAbove,
                              origin='upper',
                              cmap=cpt_convert_SquareRoot,
                              vmin=-20,
                              vmax=100)
plot_Rainbow = bmap.imshow(tempBelow,
                           origin='upper',
                           cmap=cpt_convert_Rainbow,
def extract_band_info(Band):
    '''
    Create strings with:
    - Central wavelength (Center_WL)
    - Variable units (Unit)
    - Conversion (K to Celsius) (Conversion)
    - Colortable (CPT)
    - Min and max values in imshow (Min, Max)
    according to the selected band.
    '''

    if Band == '01':
        Center_WL = '(0.47 µm)'
    elif Band == '02':
        Center_WL = '(0.64 µm)'
    elif Band == '03':
        Center_WL = '(0.865 µm)'
    elif Band == '04':
        Center_WL = '(1.378 µm)'
    elif Band == '05':
        Center_WL = '(1.61 µm)'
    elif Band == '06':
        Center_WL = '(2.25 µm)'
    elif Band == '07':
        Center_WL = '(3.90 µm)'
    elif Band == '08':
        Center_WL = '(6.19 µm)'
    elif Band == '09':
        Center_WL = '(6.95 µm)'
    elif Band == '10':
        Center_WL = '(7.34 µm)'
    elif Band == '11':
        Center_WL = '(8.50 µm)'
    elif Band == '12':
        Center_WL = '(9.61 µm)'
    elif Band == '13':
        Center_WL = '(10.35 µm)'
    elif Band == '14':
        Center_WL = '(11.20 µm)'
    elif Band == '15':
        Center_WL = '(12.30 µm)'
    elif Band == '16':
        Center_WL = '(13.30 µm)'

    if int(Band) <= 6:
        # Unit = "Reflectance"
        Unit = "Refletância"  # pt-br
        Conversion = 0.
    else:
        # Unit = "Brightness Temperature (°C)"
        Unit = "Temperatura de Brilho (°C)"  # pt-br
        Conversion = -273.15

    if int(Band) <= 6:
        CPT = loadCPT(
            '../Data/GENERAL/colortables/Square Root Visible Enhancement.cpt')
        Min, Max = 0, 1
    elif int(Band) == 7:
        CPT = loadCPT('../Data/GENERAL/colortables/SVGAIR2_TEMP.cpt')
        Min, Max = -112.15, 56.85
    elif int(Band) > 7 and int(Band) < 11:
        CPT = loadCPT('../Data/GENERAL/colortables/SVGAWVX_TEMP.cpt')
        Min, Max = -112.15, 56.85
    elif int(Band) > 10:
        CPT = loadCPT('../Data/GENERAL/colortables/IR4AVHRR6.cpt')
        Min, Max = -103, 84

    return Center_WL, Unit, Conversion, CPT, Min, Max
Exemple #9
0
fig.add_axes(ax)
ax = plt.axis('off')
#=====================================================================================================    


# Plot the Data =======================================================================================
# Create the basemap reference for the Rectangular Projection
bmap = Basemap(llcrnrlon=extent[0], llcrnrlat=extent[1], urcrnrlon=extent[2], urcrnrlat=extent[3], epsg=4326)
# Draw the countries 
bmap.readshapefile('/home/usuario/Escritorio/BELEN/geonet/Countries_Shape/ne_10m_admin_0_countries','ne_10m_admin_0_countries',linewidth=0.70,color='black')    
# Draw parallels and meridians
bmap.drawparallels(np.arange(-90.0, 90.0, 5.0), linewidth=0.2, dashes=[4, 4], color='white', labels=[False,False,False,False], fmt='%g', labelstyle="+/-", xoffset=-0.80, yoffset=-1.00, size=7)
bmap.drawmeridians(np.arange(0.0, 360.0, 5.0), linewidth=0.2, dashes=[4, 4], color='white', labels=[False,False,False,False], fmt='%g', labelstyle="+/-", xoffset=-0.80, yoffset=-1.00, size=7)

if Band <= 6:
    cpt = loadCPT('/home/usuario/Escritorio/BELEN/geonet/Colortables/Square_Root_Visible_Enhancement.cpt')
    cpt_convert = LinearSegmentedColormap('cpt', cpt)
    bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=0, vmax=1)
    #cb = bmap.colorbar(location='bottom', size = '1%', pad = '-4%', ticks=[0.2, 0.4, 0.6, 0.8])
    #cb.ax.set_xticklabels(['20', '40', '60', '80'])
elif Band == 7:
    cpt = loadCPT('/home/usuario/Escritorio/BELEN/geonet/Colortables/SVGAIR2_TEMP.cpt')
    cpt_convert = LinearSegmentedColormap('cpt', cpt)
    bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=-112.15, vmax=56.85)
    #cb = bmap.colorbar(location='bottom', size = '1%', pad = '-4%')
elif Band > 7 and Band < 11:
    cpt = loadCPT('/home/usuario/Escritorio/BELEN/geonet/Colortables/SVGAWVX_TEMP.cpt')
    cpt_convert = LinearSegmentedColormap('cpt', cpt)
    bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=-112.15, vmax=56.85)
    #cb = bmap.colorbar(location='bottom', size = '1%', pad = '-4%')
elif Band > 10:
Exemple #10
0
def ploteador(nombre):
    # archi=dire+nombre+'.nc'
    # archiM=dire+nombre+'.txt'
    archi = dataPATH + nombre  # archi=dire+nombre+'.nc'
    archiM = dataPATH + nombre[0:73] + '.txt'

    if (nombre[8] == '1'):
        VAR = nombre[11:14]
    elif (archi[8] == '2'):
        VAR = nombre[10:13]
    VAR = 'CMI'

    start = t.time()

    # %% Lectura de Metadatos

    arch = open(archiM, 'r')
    lines = arch.readlines()
    #icanal = int(lines[3].split('#')[0])
    icanal = 10
    cols = int(lines[4].split('#')[0])
    rows = int(lines[5].split('#')[0])
    t_0 = float(lines[10].split('#')[0])
    t_start = lines[11][14:33]  # Fecha correspondiente a 0s

    # Parametross de calibracion
    offset = 0  # float(lines[25].split('#')[0])  # DN->L
    scale = 1  # float(lines[26].split('#')[0])

    #esun = float(lines[28].split('#')[0])
    #kapa0 = float(lines[30].split('#')[0])  # L->reflectancia
    #ukapa0 = lines[31].split('#')[0]  # unidades

    #fk1 = float(lines[34].split('#')[0])  # DN->K
    #fk2 = float(lines[36].split('#')[0])
    #bc1 = float(lines[38].split('#')[0])
    #bc2 = float(lines[40].split('#')[0])

    # Parametros de proyeccion
    #proj = lines[14].split('#')[0]
    lat_0 = lines[13].split('#')[0]
    lon_0 = lines[14].split('#')[0]
    h = lines[15].split('#')[0]
    a = lines[16].split('#')[0]
    b = lines[17].split('#')[0]
    f = 1 / float(lines[18].split('#')[0])

    arch.close

    # %%Configuraciones espec'ificas para cada banda

    canal = ('%02d' % icanal)
    if icanal > 11:
        cptfile = 'IR4AVHRR6.cpt'
    elif icanal > 7:
        cptfile = 'SVGAWVX_TEMP.cpt'
    else:
        cptfile = 'SVGAIR2_TEMP.cpt'

    print(cptfile)

    # %% lectura y extraccion de informacion de la pasada
    connectionInfo = 'HDF5:\"' + archi + '\"://' + VAR

    raw = gdal.Open(connectionInfo, gdal.GA_ReadOnly)

    driver = raw.GetDriver().LongName

    band = raw.GetRasterBand(1)
    bandtype = gdal.GetDataTypeName(band.DataType)
    print(bandtype)
    # data = band.ReadAsArray(0, 0, cols, rows)
    data = band.ReadAsArray()

    #  %% Proyecciones

    # GOES-16 Spatial Reference System
    sourcePrj = osr.SpatialReference()
    # sourcePrj.ImportFromProj4('+proj='+proj+' +h='+h+' +a='+a+' +b='+b+' +
    # f='+str(f)#no es valida proj+'geostationary'
    #             +'lat_0='+lat_0+' +lon_0='+lon_0+' +sweep=x +no_defs')

    sourcePrj.ImportFromProj4('+proj=geos +h=' + h + ' +a=' + a + ' +b=' + b +
                              '  +f=' + str(f) + 'lat_0=' + lat_0 +
                              ' +lon_0=' + lon_0 + ' +sweep=x +no_defs')

    # Lat/lon WSG84 Spatial Reference System
    targetPrj = osr.SpatialReference()
    targetPrj.ImportFromProj4('+proj=longlat +ellps=WGS84 \
                               +datum=WGS84 + no_defs')

    # Setup projection and geo-transformation
    raw.SetProjection(sourcePrj.ExportToWkt())
    raw.SetGeoTransform(
        getGeoT(GOES16_EXTENT, raw.RasterYSize, raw.RasterXSize))

    # Compute grid dimension
    sizex = int(((extent[2] - extent[0]) * KM_PER_DEGREE) / resolution)
    sizey = int(((extent[3] - extent[1]) * KM_PER_DEGREE) / resolution)

    # Get memory driver
    memDriver = gdal.GetDriverByName('MEM')

    # Create grid
    grid = memDriver.Create('grid', sizex, sizey, 1, gdal.GDT_Float32)

    # Setup projection and geo-transformation
    grid.SetProjection(targetPrj.ExportToWkt())
    grid.SetGeoTransform(getGeoT(extent, grid.RasterYSize, grid.RasterXSize))

    # Perform the projection/resampling
    gdal.ReprojectImage(raw,
                        grid,
                        sourcePrj.ExportToWkt(),
                        targetPrj.ExportToWkt(),
                        gdal.GRA_NearestNeighbour,
                        options=['NUM_THREADS=ALL_CPUS'])

    # Read grid data
    array1 = grid.ReadAsArray()

    # Mask fill values (i.e. invalid values)
    np.ma.masked_where(array1, array1 == -1, False)

    # %% Calibracion
    array = array1 * scale + offset  # DN ->mW m-2 sr-1 mum-1
    # if icanal>=7:#DN ->C
    #    Temp=(fk2 / (np.log((fk1 / array) + 1)) - bc1 ) /
    #    bc2-273.15#mW m-2 sr-1 mum-1 ->C
    # else:
    #    Temp=kapa0*array#REVISAR!!!
    Temp = array - 273.15
    # Temp=array

    grid.GetRasterBand(1).SetNoDataValue(-1)
    grid.GetRasterBand(1).WriteArray(array)

    # %% Plot the Data ========================================================
    # Create the basemap reference for the Rectangular Projection

    t_ini = t_0 + float(
        calendar.timegm(t.strptime(t_start, '%Y-%m-%d %H:%M:%S')))
    fechaT, fechaN = fecha(t_ini)  # Fechas para titulos y nombre de archivo

    fig = plt.figure(num=1, clear='True')
    # frameon es para NO desplegar la figura
    fig = plt.figure(num=1, figsize=[20, 16], dpi=300, frameon='False')
    # 4326 es WGS84 (LatLOn)
    bmap = Basemap(resolution='h',
                   llcrnrlon=extent[0],
                   llcrnrlat=extent[1],
                   urcrnrlon=extent[2],
                   urcrnrlat=extent[3],
                   epsg=4326)

    # Draw the shapefiles
    bmap.readshapefile(dires + '008_limites_provinciales_LL',
                       '008_limites_provinciales_LL',
                       linewidth=0.3,
                       color='w')
    bmap.readshapefile(dires + 'DEPARTAMENTOS_linea',
                       'DEPARTAMENTOS_linea',
                       linewidth=0.1,
                       color='gray')
    # bmap.readshapefile(dires3+'Límites_internacionales','Límites_internacionales',linewidth=0.3,color='w')
    # bmap.readshapefile(dires+'Ejidos_urbanos_linea','Ejidos_urbanos_linea',linewidth=0.1,color='yellow')#bmap.readshapefile(dires3+'Límites_internacionales','Límites_internacionales',linewidth=0.3,color='w')
    # bmap.readshapefile(dires+'Lago_San_Roque','Lago_San_Roque',linewidth=0.5,color='blue')#bmap.readshapefile(dires3+'Límites_internacionales','Límites_internacionales',linewidth=0.3,color='w')
    # bmap.readshapefile(dires+'Ejidos_afectados_linea','Ejidos_afectados_linea',linewidth=0.7,color='w')#bmap.readshapefile(dires3+'Límites_internacionales','Límites_internacionales',linewidth=0.3,color='w')
    # bmap.readshapefile(dires+'Zona_Afectada_EPSG4326_linea','Zona_Afectada_EPSG4326_linea',linewidth=0.7,color='w')#bmap.readshapefile(dires3+'Límites_internacionales','Límites_internacionales',linewidth=0.3,color='w')
    # bmap.readshapefile(dires+'ne_10m_admin_0_map_units/ne_10m_admin_0_map_units','ne_10m_admin_0_map_units',linewidth=0.3,color='w')
    # bmap.readshapefile(dires+'limite_interprovincial/Límites_interprovinciales','Límites_interprovinciales',linewidth=0.3,color='w')
    # bmap.readshapefile(dires3+'Límites_internacionales','Límites_internacionales',linewidth=0.3,color='w')

    # Draw parallels and meridians
    bmap.drawparallels(np.arange(-90.0, 90.0, 3.),
                       linewidth=0.3,
                       dashes=[4, 4],
                       color='white',
                       labels=[True, True, False, False],
                       fmt='%g',
                       labelstyle="+/-",
                       xoffset=0.10,
                       yoffset=-1.00,
                       size=5)
    bmap.drawmeridians(np.arange(0.0, 360.0, 3.),
                       linewidth=0.3,
                       dashes=[4, 4],
                       color='white',
                       labels=[False, False, True, False],
                       fmt='%g',
                       labelstyle="+/-",
                       xoffset=-0.80,
                       yoffset=0.20,
                       size=5)

    # Converts a CPT file to be used in Python
    # cptfile = "crisp_ice.cpt"
    cpt = loadCPT(direcpt + cptfile)

    # Makes a linear interpolation
    cpt_convert = LinearSegmentedColormap('cpt', cpt)

    # Plot the GOES-16 channel with the converted CPT colors (you may alter
    # the min and max to match your preference)
    if icanal >= 7:
        img_plot = bmap.imshow(Temp,
                               origin='upper',
                               cmap=cpt_convert,
                               vmin=-90,
                               vmax=50)
    else:
        img_plot = bmap.imshow(Temp,
                               origin='upper',
                               cmap='Greys',
                               vmin=0.001,
                               vmax=0.1)  # 'Greys'

    # Add a black rectangle in the bottom to insert the image description
    lon_difference = (extent[2] - extent[0])  # Max Lon - Min Lon
    currentAxis = plt.gca()
    currentAxis.add_patch(
        Rectangle((extent[0], extent[1]),
                  lon_difference, (lon_difference) * 0.040,
                  alpha=1,
                  zorder=3,
                  facecolor='black'))

    if icanal >= 7:
        Unit = "Temperatura de Brillo [°C]"
    else:
        Unit = "Reflectancia"

    t_ini = raw.GetMetadata()['date_created']
    date = str(t_ini[0:10])
    time = str(nombre[34:36]) + ":" + str(nombre[36:38])
    Title = " GOES-16 ABI Canal " + canal + " " + date + " " + time + " UTC"

    # Title = " GOES-16 ABI Canal "+ canal +" "+ fechaT
    Institution = "CONAE-Argentina"

    # Add the image description inside the black rectangle
    lat_difference = (extent[3] - extent[1])  # Max lat - Min lat
    plt.text(extent[0],
             extent[1] + lat_difference * 0.005,
             Title,
             horizontalalignment='left',
             color='white',
             size=5)
    plt.text(extent[2],
             extent[1] + lat_difference * 0.005,
             Institution,
             horizontalalignment='right',
             color='white',
             size=5)

    # Insert the colorbar at the right
    cb = bmap.colorbar(location='bottom', size='2%', pad='1%')
    cb.outline.set_visible(True)  # Remove the colorbar outline
    cb.ax.tick_params(width=0)  # Remove the colorbar ticks
    cb.ax.xaxis.set_tick_params(pad=-2)  # Put the colobar labels inside
    # the colorbar
    cb.ax.tick_params(axis='x', colors='black', labelsize=6)  # Change the
    # color and size of the colorbar labels

    cb.set_label(Unit)

    # Export the result to GeoTIFF
    # driver = gdal.GetDriverByName('GTiff')
    # driver.CreateCopy(dire+'Channel_'+ canal+'_'+
    # Region+fechaN+'_WGS84.tif', grid, 0)

    # grabar a png

    # Volver este
    # plt.savefig(dire_out+'Channel_'+ canal+'_'+Region+'_'+
    # date+'_'+time+'_WGS84.png',
    # dpi=300,bbox_inches='tight', pad_inches=0)
    # dire_out2='/media/andres/Elements/GOES16/BTCH13/ANTARTIDA/'
    plt.savefig(dire_out + 'Channel_' + canal + '_' + Region + '_' + date +
                '_' + time + '_WGS84.png',
                dpi=300,
                bbox_inches='tight',
                pad_inches=0)

    # plt.savefig(dire+'Channel_'+ canal+'_'+Region+'_'+date+'_'+time+
    # '_WGS84.png', dpi=500,figsize=[20,16])

    # Close file
    raw = None
    print('- finished! Time:', t.time() - start, 'seconds')
    # ##############################################################GEOTIFF
    grid.GetRasterBand(1).WriteArray(array)
    driver = gdal.GetDriverByName('GTiff')
    driver.CreateCopy(
        dire_out + 'Channel_' + canal + '_' + Region + '_' + date + '_' +
        time + '_WGS84.tif', grid, 0)
Exemple #11
0
 def _generate_cmap(self):
     self._cmap_convert_cpt = loadCPT(self._cmap_to_goes_plot)
     self._cmap = LinearSegmentedColormap('cpt', self._cmap_convert_cpt)
Exemple #12
0
def plotRGB(data, extension, imagen, fechaInicio, fechaFinal, fecha, anio,
            region, numEvento, nomEvento, tipoCiclon, productoNom,
            productoMapa, pathOutputPNG, pathOutputMap, pathOutputTrack):
    import os
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    #import matplotlib.image as image
    from cpt_convert import loadCPT  # Import the CPT convert function
    from matplotlib.colors import LinearSegmentedColormap  # Linear interpolation for color maps
    #import matplotlib.ticker as mticker
    import cartopy.crs as crrs
    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
    import geopandas as gpd
    from glob import glob
    from PIL import Image
    #import cartopy.feature as cfeature
    #from matplotlib.lines import Line2D
    #from mpl_toolkits.axes_grid1 import make_axes_locatable

    # Es X
    dimMapY = (extension[2] - extension[0]) / 445000
    #print("AQUIIIIIX",dimMapY)
    #dimMapX = (extension[1]-extension[3])/445000
    #print("AQUIIIIIX",dimMapY)
    #print("AQUII2",dimMapX)

    #print('EXTENCION',dimMapX,dimMapY)

    fechaNom = fecha.split(' ')[0].replace(
        '/', '') + '_' + fecha.split(' ')[1].replace(':', '')

    if 'EDL_CT_' + anio + '_' + numEvento + '_' + nomEvento + '_' + productoNom + '_' + fecha + ".png" in os.listdir(
            pathOutputPNG + region + '/EDL_CT_' + anio + '_' + numEvento +
            '_' + nomEvento + '_' + productoNom + '/'):
        print('Archivo EDL_CT_' + anio + '_' + numEvento + '_' + nomEvento +
              '_' + productoNom + '_' + fecha + ".png" + ' ya esta creado')
    else:

        cpt = loadCPT('./paletas/IR4AVHRR6.cpt')
        cpt_convert = LinearSegmentedColormap('cpt', cpt)

        fig = plt.figure(figsize=((extension[2] - extension[0]) / 445000,
                                  (extension[1] - extension[3]) / 445000))
        ax = plt.axes([0, 0, 1, 1], projection=crrs.Mercator(), frameon=False)

        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        plt.autoscale(tight=True)
        plt.gca().outline_patch.set_visible(False)

        ax.set_extent([extension[0], extension[2], extension[3], extension[1]],
                      crs=crrs.Mercator())
        plt.imshow(
            data,
            extent=[extension[0], extension[2], extension[3], extension[1]],
            vmin=-103.15,
            vmax=104.85,
            cmap=cpt_convert)

        plt.savefig(pathOutputPNG + region + '/EDL_CT_' + anio + '_' +
                    numEvento + '_' + nomEvento + '_' + productoNom +
                    '/EDL_CT_' + anio + '_' + numEvento + '_' + nomEvento +
                    '_' + productoNom + '_' + fechaNom + ".png",
                    dpi=300,
                    bbox_inches='tight',
                    pad_inches=0)

        # =========================================================
        # Ploteo de mapa de trayectoria
        #plt.suptitle(tipoCiclon+' '+nomEvento, y=dimMapY/5)
        plt.title(
            fechaInicio.strftime(tipoCiclon.upper() + ' ' + nomEvento.upper() +
                                 '\n' + '%Y/%m/%dT%H:%M:%SZ') + '  -  ' +
            fechaFinal.strftime('%Y/%m/%dT%H:%M:%SZ') + '\n' + productoMapa,
            fontsize=dimMapY * 1.4,
            color="black")
        #grids
        gl = ax.gridlines(crs=crrs.PlateCarree(),
                          draw_labels=True,
                          linewidth=dimMapY / 10,
                          color='black',
                          alpha=0.5,
                          linestyle='--')
        gl.xlabels_top = False
        gl.xformatter = LONGITUDE_FORMATTER
        gl.yformatter = LATITUDE_FORMATTER
        gl.xlabel_style = {'size': dimMapY, 'color': 'black'}
        gl.ylabel_style = {'size': dimMapY, 'color': 'black'}
        #elemnts
        file = glob(pathOutputTrack + region + '/' + anio + '_' + numEvento +
                    '_' + nomEvento + '/*_lin.shp')
        shp_track = file[0].split('/')[-1]
        df_track = gpd.read_file(pathOutputTrack + region + '/' + anio + '_' +
                                 numEvento + '_' + nomEvento + '/' + shp_track)
        df_track = df_track.to_crs({'init': 'epsg:3857'})
        df_track.plot(ax=ax,
                      column='STORMTYPE',
                      linewidth=dimMapY / 5,
                      cmap='tab20',
                      legend=True,
                      legend_kwds={
                          'loc': 'lower right',
                          'fontsize': dimMapY,
                          'title': 'Estado',
                          'title_fontsize': dimMapY,
                          'borderpad': 0.1,
                          'handletextpad': 0.1,
                          'markerscale': dimMapY / 10,
                          'shadow': False,
                          'edgecolor': 'none'
                      })
        #for i in range(len(df_track)):
        #if df_track.iloc(i)['STORMTYPE'] == 'Baja Presión':
        #df_track.plot(ax=ax,column='STORMTYPE', linewidth = dimMapY/5, color=['#FF0000', '#FF6C00', '#FFEC00', '#B6FF00', '#64FF00', '#14BC00', '#4AFFB2', '#00FFE4', '#00AEFF', '#00AEFF','#0065EE','#5A49FF','#AF49FF','#FF00E0'],legend = True,legend_kwds={'loc': 'lower right','fontsize':dimMapY,'title':'Estado','title_fontsize':dimMapY,'borderpad':0.1,'handletextpad':0.1,'markerscale':dimMapY/10,'shadow':False,'edgecolor':'none'})

        file = glob(pathOutputTrack + region + '/' + anio + '_' + numEvento +
                    '_' + nomEvento + '/*_pts.shp')
        shp_pts = file[0].split('/')[-1]
        df_pts = gpd.read_file(pathOutputTrack + region + '/' + anio + '_' +
                               numEvento + '_' + nomEvento + '/' + shp_pts)
        df_pts = df_pts.to_crs({'init': 'epsg:3857'})
        df_pts.plot(ax=ax, color='black', markersize=dimMapY / 11, zorder=2)
        props = dict(boxstyle='round',
                     facecolor='white',
                     edgecolor='none',
                     alpha=0.7)
        for x, y, label, label1 in zip(df_pts.geometry.x, df_pts.geometry.y,
                                       df_pts.HHMM, df_pts.DAY):
            if label == '1200':
                ax.annotate(label,
                            xy=(x, y),
                            xytext=(dimMapY * 0.6, dimMapY * 0.6),
                            textcoords="offset points",
                            fontsize=dimMapY / 1.5,
                            bbox=props)
            if label == '0000':
                ax.annotate(int(label1),
                            xy=(x, y),
                            xytext=(dimMapY * 0.6, dimMapY * 1.4),
                            textcoords="offset points",
                            fontsize=dimMapY * 0.9,
                            color='r',
                            bbox=props)

        #ax.add_feature(cfeature.LAND)
        #ax.coastlines(linewidth=dimMapY/16,resolution='10m')
        df_enti = gpd.read_file(
            './shapefiles/coastlines_mexicoMer/coastlines_mexicoMer.shp')
        #df_enti = df_enti.to_crs({'init':'epsg:3857'})
        #plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        df_enti.plot(ax=ax, color='black', linewidth=0.3)
        #props = dict(boxstyle='round', facecolor='white',edgecolor='none', alpha=0.7)
        plt.text(extension[0] + dimMapY * 5500,
                 extension[3] + dimMapY * 8000,
                 fecha,
                 color='black',
                 fontsize=dimMapY * 1.6,
                 bbox=props)
        #ax.imshow(logo,extent=[extension[0],extension[2],extension[3],extension[1]])

        plt.imshow(
            data,
            extent=[extension[0], extension[2], extension[3], extension[1]],
            vmin=-103.15,
            vmax=104.85,
            cmap=cpt_convert)
        #cax = fig.add_axes([0.001,0.99, 0.998, 0.01])
        #if dimMapY > dimMapX:
        #   dimcb = dimMapX
        #else:
        #   dimcb = dimMapY
        # dimcb*0.0019097747932542944
        cax = fig.add_axes([0.001, 0.99, 0.998, 0.01])
        cbar = plt.colorbar(cax=cax, orientation='horizontal')
        cbar.ax.tick_params(labelsize=dimMapY, grid_alpha=0.5)
        cbar.outline.set_linewidth(dimMapY / 15)
        #cbar.outline.set_linewidth(0)
        plt.savefig(pathOutputMap + region + '/EDL_CT_' + anio + '_' +
                    numEvento + '_' + nomEvento + '_' + productoNom +
                    '/EDL_CT_' + anio + '_' + numEvento + '_' + nomEvento +
                    '_' + productoNom + '_' + fechaNom + ".png",
                    dpi=300,
                    bbox_inches='tight',
                    pad_inches=0)

        logo = Image.open('./logos/lanot_logo.png')
        logo = logo.resize((int(dimMapY * 37), int(dimMapY * 11)),
                           Image.ANTIALIAS)
        mapa = Image.open(pathOutputMap + region + '/EDL_CT_' + anio + '_' +
                          numEvento + '_' + nomEvento + '_' + productoNom +
                          '/EDL_CT_' + anio + '_' + numEvento + '_' +
                          nomEvento + '_' + productoNom + '_' + fechaNom +
                          ".png")
        mapa.paste(logo, (int(mapa.width) - int(
            (dimMapY * 40)), int(dimMapY * 3)), logo)
        mapa.save(pathOutputMap + region + '/EDL_CT_' + anio + '_' +
                  numEvento + '_' + nomEvento + '_' + productoNom +
                  '/EDL_CT_' + anio + '_' + numEvento + '_' + nomEvento + '_' +
                  productoNom + '_' + fechaNom + ".png")

        fig.clear()
        ax.clear()
        plt.close(fig)
Exemple #13
0
#Sahpes - Furnas:
bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/138kV_2D','138kV',linewidth=1.0,color='#FF0000')
bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/230kV_2D','230kV',linewidth=1.0,color='#00FF09')
bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/345kV_2D','345kV',linewidth=1.0,color='#FFC400')
bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/500kV_2D','500kV',linewidth=1.0,color='#001AFF')
bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/600kV_2D','600kV',linewidth=1.0,color='#FF00EF')
bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/750kV_2D','750kV',linewidth=1.0,color='#00FFFF')

# Draw parallels and meridians
#bmap.drawparallels(np.arange(-90.0, 90.0, 5.0), linewidth=0.2, dashes=[4, 4], color='white', labels=[False,False,False,False], fmt='%g', labelstyle="+/-", xoffset=-0.80, yoffset=-1.00, size=7)
#bmap.drawmeridians(np.arange(0.0, 360.0, 5.0), linewidth=0.2, dashes=[4, 4], color='white', labels=[False,False,False,False], fmt='%g', labelstyle="+/-", xoffset=-0.80, yoffset=-1.00, size=7)
#if Band = 7 and Band = 10:
# Converts a CPT file to be used in Python
if Band == 2:
  cpt = loadCPT('/dados/backup_homefazzt/download/GMT_grey.cpt')
  cpt_convert = LinearSegmentedColormap('cpt', cpt)
  bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=0, vmax=1)
elif Band==8 or Band==9: #WV
  cpt= loadCPT('/dados/backup_homefazzt/download/WVCOLOR35.cpt')
  cpt_convert = LinearSegmentedColormap('cpt', cpt)
  bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=-105,vmax=105)
else:
  cpt = loadCPT('/dados/backup_homefazzt/download/IR4AVHRR6.cpt')
  cpt_convert = LinearSegmentedColormap('cpt', cpt)
  bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=-103, vmax=84)
# Makes a linear interpolation
#cpt_convert = LinearSegmentedColormap('cpt', cpt)
# Plot the GOES-16 channel with the converted CPT colors (you may alter the min and max to match your preference)
#bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=-103, vmax=84)
# Insert the colorbar at the bottom
Exemple #14
0
def plot_field_panel(
    grid,
    field,
    level,
    fmin,
    fmax,
    lat_index=None,
    lon_index=None,
    date="",
    name_multi="",
    shp_name="",
    hailpad_pos=None,
    zero_height=3.0,
    minusforty_height=10.0,
    grid_spc=0.25,
    cmap=None,
    reverse_cmap=False,
    norm=None,
    xlim=(-48, -46),
    ylim=(-24, -22),
    save_path="./",
):
    """
    Using gridded multidoppler processed data, plot horizontal and vertical
    views:
    - In a specific height (defined by index)
    - In a specific cross-section (defined by lat_index and lon_index)

    Parameters
    ----------
    grid: gridded multidoppler processed data
    field: field to be plotted
    level: level of horizontal plot
    fmin, fmax: field min and max values
    lat_index: tuple of latitude indexes for cross section
        (end, start) in degrees
    lon_index: tuple of longitude indexes for cross section
        (end, start) in degrees
    date: date to be shown on main title
    name_multi: acronym with all radar names
    shp_name: path of shapefiles
    hailpad_pos: tuple of hailpad position
        (lon, lat)
    zero_height: 0 degrees height
    grid_spc: grid spacing for horizontal plot
    cmap: define colorbar. None will use Py-ART defauts
    reverse_cmap: If cmap is defined and this is True, the colormap will be
        reversed
    norm: normalization of the colormap
    xlim, ylim: plot limits in lon, lat for horizontal view
        (min, max) in degrees
    save_path: path to save the figures
    """

    # Getting lat-lon-z points
    lons, lats = grid.get_point_longitude_latitude(level)
    xz, z = np.meshgrid(grid.get_point_longitude_latitude()[0], grid.z["data"])

    # Opening colortables
    if field != "FH":
        if cmap:
            cpt = loadCPT(cmap)
            if reverse_cmap:
                cmap = LinearSegmentedColormap("cpt_r", revcmap(cpt))
            else:
                cmap = LinearSegmentedColormap("cpt", cpt)

    # Main figure
    display = pyart.graph.GridMapDisplay(grid)
    fig = plt.figure(figsize=(10, 3.25), constrained_layout=True)
    if field == "FH":
        gs = GridSpec(nrows=1, ncols=8, figure=fig)
    else:
        gs = GridSpec(nrows=1, ncols=7, figure=fig)

    # - Horizontal view
    print("-- Plotting horizontal view --")
    ax1 = fig.add_subplot(gs[0, :3])
    display.plot_basemap(
        min_lon=xlim[0],
        max_lon=xlim[1],
        min_lat=ylim[0],
        max_lat=ylim[1],
        lon_lines=np.arange(xlim[0], xlim[1], grid_spc),
        lat_lines=np.arange(ylim[0], ylim[1], grid_spc),
        auto_range=False,
    )
    display.basemap.readshapefile(shp_name, "sao_paulo", color="gray")
    # -- Reflectivity (shaded)
    display.plot_grid(
        field,
        level,
        vmin=fmin,
        vmax=fmax,
        cmap=cmap,
        colorbar_flag=False,
        norm=norm,
    )

    # -- Hailpad position
    display.basemap.plot(
        hailpad_pos[0],
        hailpad_pos[1],
        "kX",
        markersize=15,
        markerfacecolor="None",
        latlon=True,
    )
    # -- Cross section position
    display.basemap.plot(lon_index, lat_index, "k--", latlon=True)

    # - Vertical view
    print("-- Plotting vertical view --")
    ax2 = fig.add_subplot(gs[0, 3:])
    # -- Reflectivity (shaded)
    display.plot_latlon_slice(
        field,
        vmin=fmin,
        vmax=fmax,
        coord1=(lon_index[0], lat_index[0]),
        coord2=(lon_index[1], lat_index[1]),
        zerodeg_height=zero_height,
        minusfortydeg_height=minusforty_height,
        zdh_col="k",
        cmap=cmap,
        dot_pos=hailpad_pos,
        colorbar_flag=False,
        norm=norm,
    )
    cb = display.plot_colorbar(
        orientation="vertical", label=grid.fields[field]["units"]
    )
    if field == "FH":
        cb = adjust_fhc_colorbar_for_pyart(cb)

    # - General aspects
    plt.suptitle(
        name_multi + " " + date,
        weight="bold",
        stretch="condensed",
        size="x-large",
    )
    ax1.set_title(
        str(level + 1) + " km " + grid.fields[field]["standard_name"].title()
    )
    ax2.set_title(
        "Cross Section " + grid.fields[field]["standard_name"].title()
    )
    ax2.set_xlabel("")
    ax2.set_ylabel("Distance above Ground (km)")
    ax2.grid(linestyle="-", linewidth=0.25)
    plt.savefig(
        save_path
        + name_multi
        + " "
        + grid.fields[field]["standard_name"].title()
        + " "
        + date
        + ".png",
        dpi=300,
        bbox_inches="tight",
        transparent=True,
    )
Exemple #15
0
    #ax.add_feature(ccrs.cartopy.feature.STATES)

    #plt.title('GOES-16 Day Snow-Fog', loc='left', fontweight='semibold', fontsize=15)
    #plt.title('%s' % scan_start.strftime('%d %B %Y %H:%M UTC '), loc='right');

    globe = ccrs.Globe(semimajor_axis=semi_major, semiminor_axis=semi_minor)
    geos = ccrs.Geostationary(central_longitude=sat_lon, 
                             satellite_height=sat_h, globe=globe)

    dtext = ('%s' % scan_start.strftime('%d %B %Y %H:%M UTC '))

    fig = plt.figure(1, figsize=(15, 12), dpi=300)

    ax1 = fig.add_subplot(1, 1, 1, projection=geos)

    cpt = loadCPT('SVGAWVX_TEMP.cpt')
    # Makes a linear interpolation
    cpt_convert = LinearSegmentedColormap('cpt', cpt) 
     # Plot the GOES-16 channel with the converted CPT colors (you may alter the min and max to match your preference)
#    ax1.imshow(data, origin='upper', cmap=cpt_convert, vmin=-112.15, vmax=56.85)

    print(RGB-273.15)
    cf=ax1.imshow(RGB-273.15, origin='upper', cmap=cpt_convert,
                       extent=(x.min(), x.max(), y.min(), y.max()),
                       transform=geos,
                       interpolation='nearest', vmin=-112.15, vmax=56.85)


    cb = plt.colorbar(cf, orientation='horizontal', pad=0, aspect=50, extendrect=True)
    cb.set_label('Abs. Vorticity ($s^{-1}$)')
Exemple #16
0
def plot_files(fnames):
    # Converts the CPT file to be used in Python
    cpt = loadCPT('IR4AVHRR6.cpt')
    # Makes a linear interpolation with the CPT file
    cpt_convert = LinearSegmentedColormap('cpt', cpt)

    first = True

    for fname in fnames:
        # Search for the Scan Start in the file name
        time = (fname[fname.find("MG_") + 3:fname.find(".nc")])
        # Format the "Observation Start" string
        date = datetime.strptime(time, '%Y%m%d%H%M%S')

        # Check if we already created the image
        image_string = folder + 'images/%s_%s.png' % (
            channel, datetime.strftime(date, '%Y%m%d%H%M%S'))
        if os.path.isfile(image_string):
            #print('Skipping '+fname)
            continue

        print('Using ' + fname)
        # Open the file using the NetCDF4 library
        nc = Dataset(fname)
        # Extract the Brightness Temperature values from the NetCDF
        temp_b = brigthness_temp(nc.variables[channel])
        hrv = nc.variables[channel_hrv][:]

        fig = plt.figure(figsize=(15, 15))

        if first:
            lons = np.ma.masked_less(np.array(nc.variables['lon']), -180)
            lats = np.ma.masked_less(np.array(nc.variables['lat']), -90)

            lats_hrv, lons_hrv = create_coord_hrv(lats, lons)

            bmap = Basemap(projection='cyl',
                           llcrnrlon=4,
                           llcrnrlat=31,
                           urcrnrlon=26,
                           urcrnrlat=45,
                           resolution='i')

            x, y = bmap(lons, lats)
            x_hrv, y_hrv = bmap(lons_hrv, lats_hrv)

            first = False

        if (hrv.std() > 0.9):
            bmap.pcolormesh(x_hrv, y_hrv, hrv, vmin=0, vmax=20, cmap='gray')
            bmap.pcolormesh(x,
                            y,
                            np.ma.masked_array(temp_b, temp_b > -38),
                            vmin=-80,
                            vmax=50,
                            cmap=cpt_convert,
                            alpha=0.3,
                            linewidth=0,
                            antialiased=True)
        else:
            bmap.pcolormesh(x,
                            y,
                            temp_b,
                            vmin=-80,
                            vmax=50,
                            cmap=cpt_convert,
                            antialiased=True)

        bmap.drawcoastlines(linewidth=0.5, linestyle='solid', color='white')
        bmap.drawcountries(linewidth=0.5, linestyle='solid', color='white')
        bmap.drawparallels(np.arange(-90.0, 90.0, 5.),
                           linewidth=0.2,
                           color='white',
                           labels=[True, False, False, True],
                           fontsize=7)
        bmap.drawmeridians(np.arange(0.0, 360.0, 5.),
                           linewidth=0.2,
                           color='white',
                           labels=[True, False, False, True],
                           fontsize=7)

        # Insert the legend
        bmap.colorbar(location='right',
                      label='Brightness Temperature [C] / HRV radiance',
                      size='2%',
                      pad='1%')

        date_formatted = datetime.strftime(date, '%a %d %b %Y, %H:%MZ')
        annotation(plt.gca(), date_formatted, loc='upper center', fontsize=9)
        annotation(plt.gca(),
                   "SEVIRI %s,%s High Rate data" % (channel, channel_hrv) +
                   u"\N{COPYRIGHT SIGN}" +
                   'EUMETSAT - prepared by Guido Cioni (www.guidocioni.it)',
                   loc='lower left',
                   fontsize=7)
        #print('Saving file %s' % image_string)
        plt.savefig(image_string, bbox_inches='tight', dpi=200)
        plt.clf()

    plt.close('all')