Вы находитесь на странице: 1из 10

# -*- coding: utf-8 -*"""

Created on Sat Oct 08 09:30:10 2016


@author: INGPRO2CPPH
"""
#==============================================================================
# Tarea 2
#==============================================================================
#==============================================================================
# Punto 1
#==============================================================================
import numpy as np
import netCDF4 as nc
import matplotlib.pyplot as plt
import pandas as pd
from dateutil.rrule import *
import datetime
from scipy.stats.mstats import pearsonr, spearmanr
import matplotlib.pylab as plb
from mpl_toolkits.basemap import Basemap
#==============================================================================
# Importar datos Mapas 1982- Enero - 2014 Diciembre
#==============================================================================
data = nc.Dataset("C:\Users\INGPRO2CPPH\Downloads\X190.249.138.72.270.16.41.37.n
c")
lat = data.variables["lat"][:]
lon = data.variables["lon"][:]
sst = data.variables["sst"][:]
time = data.variables["time"][:]
t = np.asarray(rrule(MONTHLY, dtstart = dt.datetime(1982,01,01), until = dt.date
time(2014,12,31), interval = 1)[:])
fechast=range(len(time))
for i in range(len(time)):
fechast[i]=datetime.date(1800,1,1)+datetime.timedelta(time[i])
fechas_str=[datetime.datetime.strftime(i,'%Y/%m/%d') for i in fechast]
#==============================================================================
# Serie Caudales 1982- Enero - 2014 Diciembre
#==============================================================================
# Serie caudales ORIGINAL Desde 1982- Enero - 2014 Diciembre
calamarmod=np.genfromtxt('C:\Users\INGPRO2CPPH\Desktop\Python\QmediosmensualesCa
lamar.csv',dtype=None, delimiter=';', skip_header=0)
date=calamarmod[:,0] # Leer columna fechas
caudal=calamarmod[:,1] # Leer columna caudales
q = [float(x.strip(' "')) for x in caudal]
fecha = [float(x.strip('" ')) for x in date] # Convertir fecha a float
for i in range(len(fecha)):
fechas[i]=datetime.date(1900,1,1)+datetime.timedelta(days=fecha[i])
fechas2=pd.to_datetime(fechas)
##########################################################################

#Para utilizar Pandas


qpandas=pd.Series(q,index=fechas2)
##########################################################################
for i in range(len(fecha)):
fechas[i]=datetime.date(1900,1,1)+datetime.timedelta(days=fecha[i])
import matplotlib.patches as mpatches
plt.figure(figsize=[10,5])
plt.plot(fechas,q,'b') # Graficar toda la serie
plt.ylabel("Caudal (m3/s)")
plt.xlabel("Meses")
patch = mpatches.Patch(color='blue', label='Caudal')
plt.legend(handles=[patch])
plt.savefig("Serie Caudales Mensuales.png")
# 2) Serie caudales sin valores negativos
qq=np.copy(q)
for i in range(len(qq)):
if q[i]<0:
qq[i]=np.NaN
else:
qq[i]=q[i]
qq
plt.figure(figsize=[10,5])
plt.plot(fechas,qq)
plt.ylabel("Caudal (m3/s)")
patch = mpatches.Patch(color='blue', label='Caudal')
plt.legend(handles=[patch])
plt.savefig("Serie Q mensuales sin valor negativos v2.png")
# 2) Normalizar serie de caudales
caudal1=qq
mesesq=12
qestn=np.ones(caudal.shape) #Crear un vector de 1. Inicializar el vector de esta
ndarizado
qm=np.ones(12) #Crear vector qm de Caudales Medios
qd=np.ones(12) #Crear vector qd de Desviaciones estndar de Caudales
for m in range(mesesq): # 12 meses
qm[m]=np.nanmean(caudal1[m::12]) # Media de cada mes, segn el t ------ [m::12
, para ir desde el mes m de 12 en 12 hasta el final, es decir, utilizar enero me
s 1, enero del mes 2, etc.
qd[m]=np.nanstd(caudal1[m::12]) # Desviacin estndar de cada mes
for k in range(len(caudal1)):
qestn[k]=(caudal1[k]-qm[np.mod(k,mesesq)])/qd[np.mod(k,mesesq)] # Caudal nor
malizado
plt.subplots_adjust(hspace=3)
plt.figure(figsize=[8,8])
plt.subplot(211)

plt.plot(fechas,qestn)
plt.grid()
plt.ylabel("Caudal medio normalizado (m3/s)")
plt.subplot(212)
plt.plot(fechas,q)
plt.grid()
plt.ylabel("Caudal medio mensual (m3/s)")
===============================================================================
# Pasar serie diaria a mensual con Pandas
===============================================================================
qmedio=qpandas.resample('M').mean()
===============================================================================
#
===============================================================================

#==============================================================================
#Normalizar pxeles, para quitar el ciclo anual de cada pxel
#==============================================================================
meses=12 # Perodos en un ao
sstestn=np.ones(sst.shape) # Matriz serie temperatura mensual Normalizada
M=np.ones((12,len(lat),len(lon))) #Crear matriz M de Medias
D=np.ones((12,len(lat),len(lon))) #Crear matriz D de Desviaciones estndar
for i in range(len(lat)): # Leer filas de -90, 90
for j in range(len(lon)): # Leer columnas de -180, 180
for m in range(meses): # 12 meses
M[m,i,j]=np.mean(sst[m::12,i,j]) # Media de cada mes, segn el t ----- [m::12,i,j para ir desde el mes m de 12 en 12 hasta el final, es decir, utiliz
ar enero mes 1, enero del mes 2, etc.
D[m,i,j]=np.std(sst[m::12,i,j]) # Desviacin estndar de cada mes, segn e
l t
for k in range(len(time)): #Recorrer toda la serie temporal en cada pxel
sstestn[k,i,j]=(sst[k,i,j]-M[np.mod(k,meses),i,j])/D[np.mod(k,meses)
,i,j] # Pxel normalizado
plt.subplots_adjust(hspace=0.4)
#Graficar todos los meses
for g in range(len(time)):
plt.imshow(sstestn[g,:,:],extent=[lon[0]-180,lon[-1]-180,lat[-1],lat[0]])
plt.colorbar()
plt.savefig("C:\Users\INGPRO2CPPH\Desktop\Python\SSTNORM MES %d .png" %(g))
plt.close()
# Figure 1
plt.subplot(221)
plt.plot(fechas,sstestn[:,30,30])
plt.title('Serie Estandarizada')
plt.grid(True)
# Figure 2

plt.subplot(222)
plt.plot(fechas,sst[:,30,30])
plt.title('Serie Original')
plt.grid(True)
plt.subplots_adjust(hspace=3)
plt.figure(figsize=[8,8])
plt.subplot(211)
plt.plot(fechas,sst[:,30,30])
plt.grid()
plt.ylabel('Temperatura Serie Original')
plt.subplot(212)
plt.plot(fechas,sstestn[:,30,30])
plt.grid()
plt.ylabel('Temperatura Serie Estandarizada')
mes = 2 # Corresponde al primer mapa a generar conforme la numeracin inicial (0 e
l primer mapa).
fig = plt.figure(figsize=(18,10)) #Establezco el tamao de la figura
ax = fig.add_subplot(121)
ax.set_title(u'Temperatura (C) '+fechas_str[mapa][0:7], size=12) #Determino el ttu
lo
m = Basemap(llcrnrlat=-88.75,urcrnrlat=88.75, llcrnrlon=1.25,urcrnrlon=358.75,
rsphere=6371200.,resolution='l',area_thresh=10000)
ny = lat.shape[0]; nx = lon.shape[0]
lons, lats = m.makegrid(nx, ny)
x,y = m(lons, lats)
cs = m.contourf(x,y,np.flipud(M[mes]))
m.colorbar(location='bottom',pad="10%")
m.drawparallels(np.arange(-90.,90,30.),labels=[1,0,0,0], size=11,linewidth=0.1)
m.drawmeridians(np.arange(0, 360, 30.),labels=[0,0,0,1], size=11, linewidth=0.1)
m.drawcoastlines()
m.drawmapboundary()
#==============================================================================
#Estandarizar pxeles, para quitar el ciclo anual de cada pxel
#==============================================================================
meses=12 # Perodos en un ao
sstest=np.ones(sst.shape)
M1=np.ones((12,len(lat),len(lon))) #Crear matriz M
for i in range(len(lat)): # Leer filas de -90, 90
for j in range(len(lon)): # Leer columnas de -180, 180
for m in range(meses): # 12 meses
M1[m,i,j]=np.mean(sst[m::12,i,j]) # Media de cada mes, segn el t ----- [m::12,i,j para ir desde el mes m de 12 en 12 hasta el final, es decir, utili
zar enero mes 1, enero del mes 2, etc.
for k in range(len(time)): #Recorrer toda la serie temporal en cada pxel
sstest[k,i,j]=sst[k,i,j]/M[np.mod(k,meses),i,j] # Pxel estandarizado
plt.subplots_adjust(hspace=0.4)
plt.figure(figsize=[15,10])
plt.imshow(sstest[5,:,:]) #Mostrar en algn mes todo el mapa estandarizado
plt.colorbar()
plt.savefig("C:\Users\INGPRO2CPPH\Desktop\Python\Mapa estandarizado 10.png")

plt.subplots_adjust(hspace=0.4)
plt.figure(figsize=[15,10])
plt.imshow(M[0,:,:]) #Mostrar la media del Mes m (0-12)
plt.colorbar()
plt.savefig("C:\Users\INGPRO2CPPH\Desktop\Python\Mapa estandarizado Enero.png")
mes = 0 # Corresponde al primer mapa a generar conforme la numeracin inicial (0 e
l primer mapa).
fig = plt.figure(figsize=(18,10)) #Establezco el tamao de la figura
ax = fig.add_subplot(121)
ax.set_title(u'Temperatura (C) '+fechas_str[mapa][0:7], size=12) #Determino el ttu
lo
m = Basemap(llcrnrlat=-88.75,urcrnrlat=88.75, llcrnrlon=1.25,urcrnrlon=358.75,
rsphere=6371200.,resolution='l',area_thresh=10000)
ny = lat.shape[0]; nx = lon.shape[0]
lons, lats = m.makegrid(nx, ny)
x,y = m(lons, lats)
cs = m.contourf(x,y,np.flipud(M1[mes]))
m.colorbar(location='bottom',pad="10%")
m.drawparallels(np.arange(-90.,90,30.),labels=[1,0,0,0], size=11,linewidth=0.1)
m.drawmeridians(np.arange(0, 360, 30.),labels=[0,0,0,1], size=11, linewidth=0.1)
m.drawcoastlines()
m.drawmapboundary()
for g in range(len(time)):
#for g in ((range(len(time[0]))),len(range(time[100]))):
plt.imshow(sstest[g,:,:],extent=[lon[0]-180,lon[-1]-180,lat[-1],lat[0]])
plt.colorbar()
plt.savefig("C:\Users\INGPRO2CPPH\Desktop\Python\SSTESTAND MES %d .png" %(g)
)
plt.close()
#Prueba para un pxel
# Figure 1
plt.subplot(221)
plt.plot(sstest[:,30,30])
plt.title('Serie Estandarizada')
plt.grid(True)
# Figure 2
plt.subplot(222)
plt.plot(sst[:,30,30])
plt.title('Serie Original')
plt.grid(True)
===============================================================================
#Graficar mapas del SST
===============================================================================
mapa = 0 # Corresponde al primer mapa a generar conforme la numeracin inicial (0
el primer mapa).
fig = plt.figure(figsize=(18,10)) #Establezco el tamao de la figura
ax = fig.add_subplot(121)
ax.set_title(u'Temperatura (C) '+fechas_str[mapa][0:7], size=12) #Determino el ttu
lo
m = Basemap(llcrnrlat=-88.75,urcrnrlat=88.75, llcrnrlon=1.25,urcrnrlon=358.75,
rsphere=6371200.,resolution='l',area_thresh=10000)
ny = lat.shape[0]; nx = lon.shape[0]

lons, lats = m.makegrid(nx, ny)


x,y = m(lons, lats)
cs = m.contourf(x,y,np.flipud(sst[mapa]))
m.colorbar(location='bottom',pad="10%")
m.drawparallels(np.arange(-90.,90,30.),labels=[1,0,0,0], size=11,linewidth=0.1)
m.drawmeridians(np.arange(0, 360, 30.),labels=[0,0,0,1], size=11, linewidth=0.1)
m.drawcoastlines()
m.drawmapboundary()
plt.savefig("C:\Users\INGPRO2CPPH\Desktop\Python\"Temperatura %d .png" %(fechas_
str[mapa][0:7]))
# Correlaciones con Rezago
#Generacin de Rezagos
Rezago=1 # Defino el rezago a evaluar
CorrRez=[] #Vector donde guardar las correlaciones
It=(len(lon)*len(lat)) #Nmero de pixeles
caudal_copy=np.reshape(caudal,(len(caudal))) #Cambiar caudal a una dimensin
caudal_copy=caudal_copy[Rezago:] #Recortar la serie de caudal teniendo en cuenta
el rezago
#Generacin de correlaciones entre la serie de caudal recortada y un tramo de sst
(Yst) menos es rezago
for yc in range(It):
CorrRez.append(spearmanr(Yst[(len(caudal)*yc):((len(caudal)*(yc+1))-(Rezago)
)],caudal_copy))
#Transformacin de forma del vector de correlaciones a la forma matricial del netC
DF
CorrRez=np.asarray(CorrRez) #Transformo el vector C en un array
CorrRez1=np.zeros(len(CorrRez)) #Creo un array para guardar las correlaciones de
l mismo tamao de C
for nix in range(len(CorrRez)): #Loop para guardar en el valor de correlacin en e
l vector "Correlacin"
CorrRez1[nix]=CorrRez[nix,0]
VecCorrRez1=np.reshape(CorrRez1,(180,360)) #Cambio la forma del vector original
de modo que se adaptea la latitud y longitud
VecCorrRez1=np.nan_to_num(VecCorrRez1) #Cambio los valores de "nan" a ceros asum
iendo que los valores son continentales.
#Generacin mapa de correlaciones (con rezago)
fig = plt.figure(figsize=(30,10)) #Establezco el tamao de la figura
ax = fig.add_subplot(121)
ax.set_title(u'CORRELACION SST/CAUDAL ESTACIN CALAMAR \n 1981-2014'+ ' Rezago: %s
meses'%(Rezago), size=14, ) #Determino el ttulo
m = Basemap(llcrnrlat=-88.75,urcrnrlat=88.75, llcrnrlon=1.25,urcrnrlon=358.75,
rsphere=6371200.,resolution='l',area_thresh=10000)
ny = lat_values.shape[0]; nx = lon_values.shape[0]
lons, lats = m.makegrid(nx, ny)
x,y = m(lons, lats)
cs = m.contourf(x,y,np.flipud(VecCorrRez1))
m.colorbar(location='bottom',pad="10%")
m.drawparallels(np.arange(-90.,90,30.),labels=[1,0,0,0], size=11,linewidth=0.1)
m.drawmeridians(np.arange(0, 360, 30.),labels=[0,0,0,1], size=11, linewidth=0.1)

m.drawcoastlines()
m.drawmapboundary()
plt.savefig('Correlacin_rezago.pdf', bbox_inches='tight') #Determino el nombre de
l archivo y la extensin
#==============================================================================
# -------Mapa de correlaciones entre Qestn y SSTest .NORMALIZADOS V2
#==============================================================================
caudal1=qestn
spearman5 = np.ones((len(lat),len(lon)))
pearson5=np.ones((len(lat),len(lon)))
i=0
for la in range(len(lat)):
j=0
for lo in range(len(lon)):
sp = spearmanr(caudal1,sstestn[:,la,lo])[0]
pe = pearsonr(caudal1,sstestn[:,la,lo])[0]
spearman5[i][j]=sp
pearson5[i][j]=pe
j=j+1
i=i+1
===============================================================================
plt.imshow(spearman5)
plt.colorbar()
plt.savefig("C:\Users\INGPRO2CPPH\Desktop\Python\Mapa de Correlacion entre Q y S
ST.png")
===============================================================================
#Grfica Spearman
Graficar=spearman5 #Variable para graficar
fig = plt.figure(figsize=(30,10)) #Establezco el tamao de la figura
ax = fig.add_subplot(121)
ax.set_title(u'CORRELACION SPEARMAN SST/CAUDAL ESTACIN CALAMAR \n 1/1981-12/2014'
, size=14, ) #Determino el ttulo
m = Basemap(llcrnrlat=-88.75,urcrnrlat=88.75, llcrnrlon=1.25,urcrnrlon=358.75,
rsphere=6371200.,resolution='l',area_thresh=10000)
ny = lat.shape[0]; nx = lon.shape[0]
lons, lats = m.makegrid(nx, ny)
x,y = m(lons, lats)
cs = m.contourf(x,y,np.flipud(Graficar))
m.colorbar(location='bottom',pad="10%")
m.drawparallels(np.arange(-90.,90,30.),labels=[1,0,0,0], size=11,linewidth=0.1)
m.drawmeridians(np.arange(0, 360, 30.),labels=[0,0,0,1], size=11, linewidth=0.1)
m.drawcoastlines()
m.drawmapboundary()
plt.savefig("C:\Users\INGPRO2CPPH\Desktop\Python\Correlacion Spearman sin rezago
v2.png",bbox_inches='tight')
#Grfica Pearson
Graficar=pearson5 #Variable para graficar
fig = plt.figure(figsize=(30,10)) #Establezco el tamao de la figura
ax = fig.add_subplot(121)
ax.set_title(u'CORRELACION PEARSON SST/CAUDAL ESTACIN CALAMAR \n 1/1981-12/2014',

size=14, ) #Determino el ttulo


= Basemap(llcrnrlat=-88.75,urcrnrlat=88.75, llcrnrlon=1.25,urcrnrlon=358.75,
rsphere=6371200.,resolution='l',area_thresh=10000)
ny = lat.shape[0]; nx = lon.shape[0]
lons, lats = m.makegrid(nx, ny)
x,y = m(lons, lats)
cs = m.contourf(x,y,np.flipud(Graficar))
m.colorbar(location='bottom',pad="10%")
m.drawparallels(np.arange(-90.,90,30.),labels=[1,0,0,0], size=11,linewidth=0.1)
m.drawmeridians(np.arange(0, 360, 30.),labels=[0,0,0,1], size=11, linewidth=0.1)
m.drawcoastlines()
m.drawmapboundary()
plt.savefig("C:\Users\INGPRO2CPPH\Desktop\Python\Correlacion Pearson sin rezago
v2.png",bbox_inches='tight')
m

===============================================================================
# Correlacin con rezago entre Q y SST
===============================================================================
caudal2=qestn
meses=1
spearcor3 = np.ones((len(lat),len(lon)))
for r in range(meses):
i=0
for la in range(len(lat)):
j=0
for lo in range(len(lon)):
spcor3 = spearmanr(caudal2[r+1:],sstestn[0:-(r+1),la,lo])[0]
pe = pearsonr(caudal,sstestn[:,la,lo])[0]
spearcor3[i][j]=spcor3
#pearson[i][j]=pearcor
j=j+1
i=i+1
#-------caudal2=qestn
meses=2
spearcor4 = np.ones((meses,len(lat),len(lon)))
for r in range(meses):
i=0
for la in range(len(lat)):
j=0
for lo in range(len(lon)):
spcor3 = spearmanr(caudal2[r+1:],sstestn[0:-(r+1),la,lo])[0]
#pe = pearsonr(caudal,sstestn[:,la,lo])[0]
spearcor4[r][i][j]=spcor3
#pearson[r][i][j]=pearcor
j=j+1
i=i+1
#-------# Figure 1
plt.subplot(221)
plt.imshow(sstestn[:,30,30])
plt.title('Serie Estandarizada')
plt.grid(True)
Graficar=spearcor4[1,:,:] #Variable para graficar
rezago=2

fig = plt.figure(figsize=(30,10)) #Establezco el tamao de la figura


ax = fig.add_subplot(121)
ax.set_title(u'CORRELACION PEARSON SST/CAUDAL ESTACIN CALAMAR \n Rezago %s meses'
%(rezago), size=14) #Determino el ttulo
m = Basemap(llcrnrlat=-88.75,urcrnrlat=88.75, llcrnrlon=1.25,urcrnrlon=358.75,
rsphere=6371200.,resolution='l',area_thresh=10000)
ny = lat.shape[0]; nx = lon.shape[0]
lons, lats = m.makegrid(nx, ny)
x,y = m(lons, lats)
cs = m.contourf(x,y,np.flipud(Graficar))
m.colorbar(location='bottom',pad="10%")
m.drawparallels(np.arange(-90.,90,30.),labels=[1,0,0,0], size=11,linewidth=0.1)
m.drawmeridians(np.arange(0, 360, 30.),labels=[0,0,0,1], size=11, linewidth=0.1)
m.drawcoastlines()
m.drawmapboundary()
plt.savefig("C:\Users\INGPRO2CPPH\Desktop\Python\Correlacion Pearson con rezago
2 v2.png",bbox_inches='tight')
===============================================================================
# Significancia Montecarlo
===============================================================================
meses=
v1 = np.copy(qq) # Serie caudales
v2 = np.ones((meses,len(lat),len(lon))) #Series temperaturas
k=2
n1=len(qq)
s=2
#Nmero de veces que voy a desordenar el vector
d=0
#Contador para Pearson
S=np.zeros(k) #Vectores que guaradan las correlaciones para cada rezago
S1=np.zeros(s) #Vectores que guardan las correlaciones de los vectores desordena
dos
#Vectores que me guardan los percentiles
S95=np.zeros(k) # Vector de los percentiles 95 de Spearman
S5=np.zeros(k) # Vector de los percentiles 5 de Spearman
for t in range(0,k):
d=0 #Actualizar los contadores
X=(v1[:n1-t]) #Series que se van rezagando
Y=(v2[t:])
cs=spearmanr(X,Y)
S[t]=cs[0]
A=np.copy(X)
#Crea las copias
Z=np.copy(Y)
for f in range(0,s): #Ciclo para hallar correlacin de un mismo rezago en s v
eces
np.random.shuffle(Z) #Desordena el vector
cs1=spearmanr(A,Z)
S1[f]=cs1[0]
v2 = np.ones((len(lat),len(lon)))
for r in range(meses):
i=0
for la in range(len(lat)):
j=0
for lo in range(len(lon)):

spcor3 = spearmanr(caudal2[r+1:],sstestn[0:-(r+1),la,lo])[0]
pe = pearsonr(caudal,sstestn[:,la,lo])[0]
spearcor3[i][j]=spcor3
#pearson[i][j]=pearcor
j=j+1
i=i+1
#Vectores que me almacenan los percentiles
S95[t]=np.percentile(S1,95)
S5[t]=np.percentile(S1,5)

Вам также может понравиться