Esempio n. 1
0
# os 'keys' do dicionario hs_copa sao ordenados em ordem crescente
lista_crescente = sorted(hs_copa.keys())
del lista_crescente[0]

# direcao de ondas
dir_copa = sio.loadmat(path + '/dir_copa.mat')
del dir_copa['__header__'], dir_copa['__globals__'], dir_copa[
    '__version__']  #, dir_copa['DIR_20160216_210000'] # generalizar esta data!

# converte as variaveis de direcao de graus para componentes u - v
u_componente = {}
v_componente = {}

for keys, values in dir_copa.items():
    U, V = intdir2uv(values)
    u_componente["u_{0}".format(keys[4:])] = U * (-1)
    v_componente["v_{0}".format(keys[4:])] = V * (-1)

u_componente = collections.OrderedDict(sorted(u_componente.items()))
v_componente = collections.OrderedDict(sorted(v_componente.items()))
hs_copa = collections.OrderedDict(sorted(hs_copa.items()))

# gera e salva as imagens no diretorio
for x in range(40):
    hs = hs_copa.values()[x]
    u = u_componente.values()[x]
    v = v_componente.values()[x]
    fig = plt.figure()
    plt.contourf(lon_bg_laje, lat_bg_laje, hs)
    plt.quiver(lon_bg_laje, lat_bg_laje, u, v)
Esempio n. 2
0
def plot(dst=False, filename=localpath + 'static/tmp_files/Data_month.csv_corrected'):

    # dst=True
    # filename = localpath + 'static/tmp_files/Data_month.csv_corrected'

    window_len = 12
    decmag = -22.3

    # READING DATA
    columns = defaultdict(list) 
    with open(filename,'rU') as f:
        reader = csv.DictReader(f) 
        for row in reader: 
            for (k,v) in row.items(): 
                columns[k].append(v) 

    varlist = ["gust", "wspd", "wdir", "cspd", "cdir", "sst"]

    date_window = 7
    tlim = -24 * date_window   # put date_window as function argument

    gust = np.array(map(float, columns.values()[7][tlim:])) 
    wspd = np.array(map(float, columns.values()[3][tlim:]))
    wdir = np.array(map(float, columns.values()[19][tlim:]))
    cspd = np.array(map(float, columns.values()[32][tlim:]))/100
    cdir = np.array(map(float, columns.values()[6][tlim:]))
    sst  = np.array(map(float, columns.values()[9][tlim:]))

    # loading full temperature measurements

    depths = [0, 10, 15, 20, 25, 45]

    f = open(filename)
    lines = f.readlines()
    SST = np.zeros((len(depths), sst.size-1))

    c = 0
    for t in range(tlim, -1):
        SST[0,c] = float(lines[t].split(",")[-11])
        SST[1,c] = float(lines[t].split(",")[-10])
        SST[2,c] = float(lines[t].split(",")[-9])
        SST[3,c] = float(lines[t].split(",")[-8])
        SST[4,c] = float(lines[t].split(",")[-7])
        SST[5,c] = float(lines[t].split(",")[-5])
        c += 1 

    SST = remove_zeros(SST)

    for k in range(len(depths)):
        SST[k,:] = smooth(SST[k,:], 5)


    # loading full current measurements

    depths_c = [2, 10, 16, 20, 26, 30, 36]

    f = open(filename)
    lines = f.readlines()
    CSPD = np.zeros((len(depths_c), cspd.size-1))
    CDIR = np.zeros((len(depths_c), cspd.size-1))


    c = 0
    for t in range(tlim, -1):
        CSPD[0,c] = float(lines[t].split(",")[21])
        CSPD[1,c] = float(lines[t].split(",")[13])
        CSPD[2,c] = float(lines[t].split(",")[14])
        CSPD[3,c] = float(lines[t].split(",")[15])
        CSPD[4,c] = float(lines[t].split(",")[16])
        CSPD[5,c] = float(lines[t].split(",")[17])
        CSPD[6,c] = float(lines[t].split(",")[18])

        CDIR[0,c] = float(lines[t].split(",")[4])
        CDIR[1,c] = float(lines[t].split(",")[5])
        CDIR[2,c] = float(lines[t].split(",")[6])
        CDIR[3,c] = float(lines[t].split(",")[7])
        CDIR[4,c] = float(lines[t].split(",")[8])
        CDIR[5,c] = float(lines[t].split(",")[9])
        CDIR[6,c] = float(lines[t].split(",")[10])

        c += 1 

    # CSPD = remove_zeros(CSPD)
    # for k in range(len(depths_c)):
    #     CSPD[k,:] = smooth(CSPD[k,:], 5)

    # CDIR = remove_zeros(CDIR)
    # for k in range(len(depths_c)):
    #     CDIR[k,:] = smooth(CDIR[k,:], 5)

    CU, CV = intdir2uv(CSPD, CDIR, decmag, 0)

    time = columns.values()[44][tlim:]
    year = dt.datetime.now().year
    days, months, hours, minutes = [], [], [], []
    datetime = []

    for d in range(len(time)):
        days.append(int(time[d].split()[0].replace('.','')[0:2]))
        months.append(int(time[d].split()[0].replace('.','')[2:4]))    
        hours.append(int(time[d].split()[1].replace(':','')[0:2]))   
        minutes.append(int(time[d].split()[1].replace(':','')[2:4]))
        datetime.append(dt.datetime(year, months[d], days[d], hours[d], minutes[d]))

    years = list(np.array(days)*0 + year); del year
    dates, datesnum = [], []

    for year, month, day, hour, minute in zip(years, months, days, hours, minutes):
        d = dt.datetime(year, month, day, hour)
        dates.append( d )
        datesnum.append( date2num(d) )

    datetime = np.array(datetime)
    datesnum = np.array(datesnum)

    # PRE-PROCESSING DATA


    for var in varlist:
        if var != "sst":
            exec('%s = remove_zeros(%s)' %(var, var))
            exec('%s = smooth(%s, window_len)' %(var, var) )
        else:
            exec('%s = remove_zeros(%s)' %(var, var))
            exec('%s = smooth(%s, 5)' %(var, var) )


    # PLOTTING

    fig = plt.figure(facecolor='w', figsize=(17,10))
    plt.suptitle(u'Meteoceanographic Buoy ( SIODOC/IEAPM )\
                     \n$(lon: -42.18 \ \  lat: -22.99)$', fontsize='large')

    #### PLOT WIND & GUST  
    ax = fig.add_subplot(311)
    # print ax.get_position().bounds
    plt.title(u'Wind & Gust (m/s)', fontsize='smaller')
    # preparing arrays for colorfill
    ymin = 0
    ymax = 15
    gy = np.linspace(ymin, ymax, 100)
    gx, gy = np.meshgrid(datesnum, gy)
    xlimit = np.linspace(0, gust.size, gust.size )
    up = np.linspace(ymax+10, ymax+10, gust.size )

    ax.contourf(gx, gy, gy, 100, alpha=1, cmap=plt.cm.hot_r)
    ax.plot(datesnum, gust, 'w-')
    ax.fill_between(datesnum, up, gust, color='w')
    ax.plot(datesnum, wspd, 'k-', linewidth=2)
    ax.set_axis_off()
    ax.fill_between(datesnum, up, wspd, color='w', alpha=0.6)
    # preparing arrays
    wu, wv   = intdir2uv(wspd, wdir, decmag, 0)
    wu2, wv2 = intdir2uv(wspd * 0 + 5, wdir, decmag, 0)
    wu2, wv2 = wu2 * -1, wv2 * -1
    gust_label, wind_label = map(int,gust), map(int,wspd)
    d = 5
    for r, gl in enumerate(gust_label[::d]):
        ax.annotate(gl, (datesnum[::d][r], gust[::d][r] + 0.5), 
                         fontsize=10, fontstyle='italic', alpha=0.5, ha='center')
    for i, wl in enumerate(wind_label[::d]):
        ax.annotate(wl, (datesnum[::d][i], wspd[::d][i] - 1.2), 
                         fontsize=10, fontstyle='italic', ha='center')
    ax.quiver(datesnum[::5], wspd[::5] - 1.8, wu2[::5], wv2[::5],
              width=0.0015, scale=400, pivot='middle')
    plt.axis([datesnum.min(), datesnum.max(), 0, ymax])

    ####### PLOT SURFACE CURRENT
    ax = fig.add_subplot(312)
    # print ax.get_position().bounds
    plt.title(u'Along-shelf surface flow (cm/s)', fontsize='smaller')
    # preparing arrays for colorfill
    cu, cv   = intdir2uv(cspd, cdir, decmag, 0)
    ymax = 0.5  
    cy = np.linspace(ymax*-1, ymax, 100)
    x = np.linspace(0, cu.size, cu.size)
    zr =  np.linspace(0, 0, cu.size)
    cx, cy = np.meshgrid(datesnum, cy)
    down = np.linspace(ymax*-1 -1, ymax*-1 -1, cu.size)
    up  = np.linspace(ymax+1, ymax+1, cu.size)

    plt.contourf(cx, cy, cy, 100, cmap=plt.cm.PRGn)       
    plt.plot(datesnum, cu, 'k-', linewidth=2)
    uplim, downlim = fill_polygons(cu)
    plt.fill_between(datesnum, down, uplim, color='w')
    plt.fill_between(datesnum, up, downlim, color='w')
    ax.set_axis_off()

    yoffset = ymax*0.1
    curr_label = []
    uan = np.abs(cu*100)

    for l in range(len(cu)):
      curr_label.append("%2d" %uan[l])

    d = 5
    for r, cl in enumerate(curr_label[::d]):
        if cu[::d][r] >= 0:
            off = yoffset
        else:
            off = yoffset*-2
        ax.annotate(cl, (datesnum[::d][r], cu[::d][r]+off), 
                  fontsize=10, fontstyle='italic', ha='center')
    # preparing arrays
    ux = cu*0
    ux[np.where(ux > 0)] = 1
    ux[np.where(ux < 0)] = -1
    cu2, cv2 = intdir2uv(cspd*0 + 0.5, cdir, decmag, 0)

    for r in np.arange(0, cu.size, d):
        if cu[r] <= 0:
            off = yoffset*2
        else:
            off = yoffset*-2
        plt.quiver(datesnum[r], cu[r]+off, cu2[r], cv2[r], 
               width=0.0015, scale=40, pivot='middle')   
    plt.axis([datesnum.min(), datesnum.max(), ymax*-1, ymax])


    ######## PLOT TEMP
    ax = fig.add_subplot(313)
    # print ax.get_position().bounds
    plt.title(u'Sea surface temperature ($^\circ$C)', fontsize='smaller')
    # preparing arrays for colorfill
    ymin = 12
    ymax = 28   
    tempy = np.linspace(ymin, ymax, 100)
    tempx, tempy = np.meshgrid(datesnum, tempy)
    uplim = np.linspace(ymax+2, ymax+2, sst.size)

    ax.contourf(tempx, tempy, tempy, 60, cmap=plt.cm.RdBu_r)
    plt.plot(datesnum, sst, 'k-', linewidth=2)
    plt.fill_between(datesnum, uplim, sst, color= 'w')
    d = 5
    yoffset = ymax*0.03
    temp_label = map(int, sst)
    for i, tl in enumerate(temp_label[::d]):
        ax.annotate(tl, (datesnum[::d][i], sst[::d][i]+yoffset), 
                  fontsize=10, fontstyle='italic', ha='center')
    ax.set_axis_off()

    # plotting dates
    ax = fig.add_axes([0.125, 0.04, 0.775, 0.05])
    ax.plot(datesnum, sst*0, 'w')
    ax.set_axis_off()

    for d in np.arange(0, datesnum.size, 24):
        label = dates[d].strftime('%d/%b')
        ax.annotate(label, (datesnum[d], -0.8), 
                    fontweight='bold', ha='center')
    for d in np.arange(0, datesnum.size, 4):
        label = dates[d].strftime('%Hh')
        ax.annotate(label, (datesnum[d], 0.6), ha='center', fontsize=8)
    plt.axis([datesnum[0], datesnum[-1], -1, 1])


    # plotting rise and set shades
    rise_and_set = []

    for i in np.arange(0, datesnum.size, 24):
        day = dt.date(years[i], months[i], days[i])
        rise, sett = get_rise_set(day, dst)
        rise, sett = date2num(rise), date2num(sett)
        rise_and_set.append([rise, sett])

    ax = fig.add_axes([0.125, 0.07, 0.781, 0.8])
    night_fill(ax, rise_and_set, datesnum, ymin, ymax)
    ax.set_axis_off()



    plt.savefig(localpath + 'static/images/siodoc_tmp.png', dpi=96)
    



    ########################################################################

    fig = plt.figure(facecolor='w', figsize=(17,10))
    plt.suptitle(u'Meteoceanographic Buoy ( SIODOC/IEAPM )\
                     \n$(lon: -42.18 \ \  lat: -22.99)$', fontsize='large')

    # preparing arrays
    x, z = np.meshgrid(datesnum[:-1], np.array(depths))

    ax = fig.add_subplot(311)  
    plt.plot_date(datesnum[:-1], wspd[:-1]*0 + 17, 'w') 
    plt.title(u'Temperature ($^\circ$C)', fontsize='smaller')
    plt.contourf(x, -z, SST, np.arange(10, 25, 0.1))
    plt.colorbar(orientation='horizontal', aspect=40, shrink=0.5)
    plt.contour(x, -z, SST, [20, 20], colors='k')
    plt.ylabel("Depth [m]")
    plt.axis([datesnum[0], datesnum[-1], -45, 0])


    ax = fig.add_axes([0.125, 0.1, 0.775, 0.5]) 
    plt.title(u'Velocity (cm/s)', fontsize='smaller')
    plt.ylabel("Depth [m]")
    c = 0
    j = 2
    for d in depths_c:
        plt.quiver(datesnum[::j], datesnum[::j]*0-d,
                   CU[c,::j], CV[c,::j], width=0.001, scale=1200)
        c += 1
    plt.quiver(datesnum[-10], -5, -50, 0, width=0.003, scale=1200)
    plt.text(datesnum[-19], -7, "50 cm/s")
    plt.axis([datesnum[0], datesnum[-1], -45, 5])
    # ax.set_axis_off()
    ax.set_xticklabels([])

    ax = fig.add_axes([0.125, 0.07, 0.781, 0.83])
    night_fill(ax, rise_and_set, datesnum, ymin, ymax)
    ax.set_axis_off()

    # plotting dates
    ax = fig.add_axes([0.125, 0.04, 0.775, 0.05])
    ax.plot(datesnum, sst*0, 'w')
    ax.set_axis_off()

    for d in np.arange(0, datesnum.size, 24):
        label = dates[d].strftime('%d/%b')
        ax.annotate(label, (datesnum[d], -0.8), 
                    fontweight='bold', ha='center')
    for d in np.arange(0, datesnum.size, 4):
        label = dates[d].strftime('%Hh')
        ax.annotate(label, (datesnum[d], 0.6), ha='center', fontsize=8)
    plt.axis([datesnum[0], datesnum[-1], -1, 1])

    plt.savefig(localpath + 'static/images/siodoc_full.png', dpi=96)

    plt.close('all')
Esempio n. 3
0
def plot(filename=localpath + 'static/tmp_files/Data_month.csv_corrected'):
    columns = defaultdict(list) 
    with open(filename,'rU') as f:
        reader = csv.DictReader(f) 
        for row in reader: 
            for (k,v) in row.items(): 
                columns[k].append(v) 

    varlist = ["gust", "wspd", "wdir", "cspd", "cdir", "sst"]
    
    
    date_window = 7
    tlim = -24 * date_window   # put date_window as function argument

    gust = np.array(map(float, columns.values()[7][tlim:])) 
    wspd = np.array(map(float, columns.values()[3][tlim:]))
    wdir = np.array(map(float, columns.values()[19][tlim:]))
    cspd = np.array(map(float, columns.values()[32][tlim:]))/100
    cdir = np.array(map(float, columns.values()[6][tlim:]))
    sst  = np.array(map(float, columns.values()[9][tlim:]))
    
    time = columns.values()[44][tlim:]
    year = dt.datetime.now().year
    days, months, hours, minutes = [], [], [], []
    datetime = []
    
    for d in range(len(time)):
        days.append(int(time[d].split()[0].replace('.','')[0:2]))
        months.append(int(time[d].split()[0].replace('.','')[2:4]))    
        hours.append(int(time[d].split()[1].replace(':','')[0:2]))   
        minutes.append(int(time[d].split()[1].replace(':','')[2:4]))
        datetime.append(dt.datetime(year, months[d], days[d], hours[d], minutes[d]))

    datetime = np.array(datetime)

    window_len = 12
    decmag = -22.3

    for var in varlist:
        if var != "sst":
            exec('%s = remove_zeros(%s)' %(var, var))
            exec('%s = smooth(%s, window_len)' %(var, var) )
        else:
            exec('%s = remove_zeros(%s)' %(var, var))
            exec('%s = smooth(%s, 5)' %(var, var) )


#### PLOT WIND & GUST  

    fig = plt.figure(facecolor='w', figsize=(17,10))
    plt.suptitle(u'Meteoceanographic Buoy ( SIODOC/IEAPM )\
                     \n$(lon: -42.18 \ \  lat: -22.99)$', fontsize='large')

    ax = fig.add_subplot(311)
    plt.title(u'Wind & Gust (m/s)', fontsize='smaller')

    gx = np.linspace(min(gust), max(gust), len(gust))
    gy = np.linspace(min(gust), max(gust), round(max(gust) + 2 ))
    gx, gy = np.meshgrid(gx, gy)
    xlimit = np.linspace(0, len(gust), len(gust) )
    ylimit = gx[0,-1]
    up = np.linspace(ylimit, ylimit, len(gust))

    ax.contourf(gy, 100, alpha=1, cmap=plt.cm.hot_r)
    ax.plot(xlimit, gust, 'w-')

    ax.set_axis_off()
    ax.fill_between(xlimit, up, gust, color='w')

    ax.plot(xlimit, wspd, 'k-', linewidth=2)
    ax.set_axis_off()
    ax.fill_between(xlimit, up, wspd, color='w', alpha=0.6)

    wu, wv   = intdir2uv(wspd, wdir, decmag, 0)
    wu2, wv2 = intdir2uv(wspd * 0 + 5, wdir, decmag, 0)
    wu2, wv2 = wu2 * -1, wv2 * -1

    gust_label, wind_label = map(int,gust), map(int,wspd)

    for r, gust_txt in enumerate(gust_label[::5]):
        ax.annotate(gust_txt, (xlimit[::5][r] - 0.4, gust[::5][r] + 0.5), 
                            fontsize=10, fontstyle='italic', alpha=0.5, ha='center')

    for i, wind_txt in enumerate(wind_label[::5]):
        ax.annotate(wind_txt, (xlimit[::5][i] - 0.6, wspd[::5][i] - 1.2), 
                            fontsize=10, fontstyle='italic', ha='center')

    ax.quiver(xlimit[::5], wspd[::5] - 2.2, wu2[::5], wv2[::5],width=0.0015, scale=400)

    plt.axis([xlimit.min(), xlimit.max(), 0, gust.max()])



####### PLOT CORRENTE

    ax = fig.add_subplot(312)
    plt.title(u'Along-shelf surface flow (cm/s)', fontsize='smaller')
    
    cu, cv   = intdir2uv(cspd, cdir, decmag, 0)

    cx = np.linspace(min(cu), max(cu), len(cu))     
    cy = np.linspace(round(min(cu))-0.1, round(max(cu))+0.1, 2)
    x = np.linspace(0, len(cu), len(cu))
    zr =  np.linspace(0, 0, len(cu))
    curr_cf = np.meshgrid(cx, cy)
    
    down = np.linspace(min(cu)-0.5, min(cu)-0.5, len(cu))
    up  = np.linspace(max(cu)+1, max(cu)+1, len(cu))

    if np.all([cu > 0]):
        plt.contourf(x, cy, curr_cf[1],100,alpha=0.5, cmap=plt.cm.Greens)
    elif np.all([cu < 0]):
        plt.contourf(x, cy, curr_cf[1],100,alpha=0.5, cmap=plt.cm.Purples_r)
    else:
        plt.contourf(x, cy, curr_cf[1],100,alpha=0.5, cmap=plt.cm.PRGn)       
    
    plt.plot_date(x, cu, 'k-', linewidth=2)
    
    uplim, downlim = fill_polygons(cu)
    plt.fill_between(x, down, uplim,color='w')
    plt.fill_between(x, up, downlim,color='w')
    ax.set_axis_off()

    curr_label = []
    uan = np.abs(cu*100)
    
    for l in range(len(cu)):
      curr_label.append("%2d" %uan[l])

    for r, txt_curr in enumerate(curr_label[::10]):
        ax.annotate(txt_curr, (x[::10][r], cu[::10][r] + 0.15), 
                  fontsize=10, fontstyle='italic', ha='center')

    ux = cu*0
    ux[np.where(ux > 0)] = 1
    ux[np.where(ux < 0)] = -1
    cu2, cv2 = intdir2uv(cspd*0 + 0.5, cdir, decmag, 0)
    
    plt.quiver(x[::5], cu[::5]-0.2, cu2[::5], cv2[::5], width=0.0015, scale=40)    


######## PLOT TEMP

    ax = fig.add_subplot(313)
    plt.title(u'Sea surface temperature ($^\circ$C)', fontsize='smaller')

    tempx = np.linspace(min(sst), max(sst), len(sst))   
    tempy = np.linspace(round(min(sst))-0.5, round(max(sst)) + 0.5, 24) #round(min(sst))
    x = np.linspace(0, len(sst), len(sst))
    temp_cf = np.meshgrid(tempx, tempy)

    uplim = np.linspace(round(max(sst)) + 1, round(max(sst)) + 1, len(sst))

    if np.all([ sst > 20]):
        plt.contourf(x, tempy, temp_cf[1], 60, alpha=0.8, cmap=plt.cm.Reds)
    elif np.all([sst <= 20]):
        plt.contourf(x, tempy, temp_cf[1], 60, alpha=0.8, cmap=plt.cm.Blues_r)
    else:    
        plt.contourf(x, tempy, temp_cf[1], 60, alpha=0.8, cmap=plt.cm.RdBu_r)
    
    plt.plot(x, sst,'k-', linewidth=2)
    plt.fill_between(x, uplim, sst, color= 'w')

    temp_label = map(int, sst)
    for i, txt_temp in enumerate(temp_label[::10]):
        ax.annotate(txt_temp, (x[::10][i]-0.4, sst[::10][i]+0.5), 
                  fontsize=10, fontstyle='italic', ha='center')

    nbs = 60
    plt.locator_params(axis='x', nbins=nbs)

    fig.canvas.draw()
    # index = [item.get_text() for item in ax.get_xticklabels()]
    # index = map(int, index)
    # index[-1] = index[-1]-1

    # lab = [datetime[i] for i in index]
    # label = [l.strftime('%d') for l in lab]
    # labels = map(int, np.ones((61)))

    # for c in np.arange(0,61,3):
    #   labels[c] = label[c]
    #   try: 
    #     labels[c+1] = ''
    #     labels[c+2] = ''
    #   except:
    #      'IndexError'

    # ax.set_yticklabels("")
    # ax.set_xticklabels(labels, fontsize='smaller', fontweight='bold')
    # ax.set_xlabel('\nNov/Dez 2013', fontsize='smaller', fontweight='semibold')
    ax.set_frame_on(False)


    plt.savefig(localpath + 'static/images/siodoc_tmp.png', dpi=96)
    plt.close('all')