def GraphComp(self, PathImg=''): ''' DESCRIPTION: Función para hacer la combinación de gráficos. ''' # Tamaño de la Figura fH = 40 # Largo de la Figura fV = 20 # Ancho de la Figura # Se crea la carpeta para guardar la imágen utl.CrFolder(PathImg + self.Names[0]) for iar, ar in enumerate(self.ArchMap): if self.Names[iar] == self.NamesSeries[iar]: # Se extraen los datos MapImg = mpimg.imread(self.ArchMap[iar]) SeriesImg = mpimg.imread(self.ArchSeries[iar]) f = plt.figure(figsize=utl.cm2inch(fH, fV), facecolor='w', edgecolor='w') a = f.add_subplot(1, 2, 1) a.imshow(SeriesImg) a.axes.get_xaxis().set_visible(False) a.axes.get_yaxis().set_visible(False) a = f.add_subplot(1, 2, 2) a.imshow(MapImg) a.axes.get_xaxis().set_visible(False) a.axes.get_yaxis().set_visible(False) plt.tight_layout() plt.savefig(PathImg + self.Names[0] + '/' + 'Image' + '_%02d.png' % iar, format='png', dpi=200) plt.close('all')
def MapsShape_Raster(Raster, Shape=None, Var='Data', Name='Results', PathImg='', *args): ''' DESCRIPTION: With this function the information of an netCDF type file can be extracted. _______________________________________________________________________ INPUT: :param Raster: A str, File that would be extracted including the path. :param Shape: A dict, List of variables that would be extracted from the netCDF file. Defaulted to None. :param Var: A dict, Range of data that would be extracted :param Name: A dict, Range of data that would be extracted :param PathImg: A dict, Range of data that would be extracted _______________________________________________________________________ OUTPUT: :return Data: A dict, Extracted Data Dictionary. ''' # ------------------ # Error Managment # ------------------ if not (isinstance(Raster, np.ndarray)): raise Exception('Raster must be a ndArray') # ------------------ # Parameters # ------------------ # Graph parameters fH = 30 fV = 20 plt.rcParams.update({'font.size': 15,'font.family': 'sans-serif'\ ,'font.sans-serif': 'Arial'\ ,'xtick.labelsize': 15,'xtick.major.size': 6,'xtick.minor.size': 4\ ,'xtick.major.width': 1,'xtick.minor.width': 1\ ,'ytick.labelsize': 15,'ytick.major.size': 12,'ytick.minor.size': 4\ ,'ytick.major.width': 1,'ytick.minor.width': 1\ ,'axes.linewidth':1\ ,'grid.alpha':0.1,'grid.linestyle':'-'}) fig = plt.figure(figsize=DM.cm2inch(fH, fV)) # Folder to save utl.CrFolder(PathImg) return
def WriteFile(Labels, Values, deli=None, Headers=None, flagHeader=False, Pathout='', Name='', NaNdata=''): ''' DESCRIPTION: This function aims to save data in a csv file from. _______________________________________________________________________ INPUT: :param Labels: A list, String left labels, this acts as the keys. :param Values: A dict, Value dictionary. :param deli: A str, delimeter of the data. :param Headers: A list, Headers of the data, defaulted to None. :param flagHeaders: A boolean, if headers are needed. :param Pathout: a str, Saving directory. :param Name: A str, File Name with extension. :param NaNdata: A str, Manage the NaN type data. _______________________________________________________________________ OUTPUT: ''' # Create the directory utl.CrFolder(Pathout) if deli == None: deli = self.deli try: f = open(Pathout + Name, 'w', encoding='utf-8') except: f = open(Pathout + Name, 'w') for iL, L in enumerate(Labels): # Headers if iL == 0 and flagHeader: wr = deli.join(Headers) + '\r\n' f.write(wr) f.write(L + deli) # Change nan values to empty wr1 = np.array(Values[L]).astype(str) wr1[wr1 == 'nan'] = NaNdata wr = deli.join(wr1) + '\r\n' f.write(wr) f.close() return
def PlotData(self,Time=0): ''' DESCRIPTION: This method plots all the case information. _________________________________________________________________ INPUT: ''' FilesA = [] for it,t in enumerate(self.DatesSt): if it >= Time: print(t) F = t xEv = np.where(self.RadarDatesP == F+timedelta(0,5*60*60))[0] if len(xEv) == 1: FilesA.append(self.ArchRadar[xEv[0]][len(self.PathRadar):]) RadarFile = self.Opengz(FilesA[-1],self.PathRadar,self.PathRadar) # Se verifican los datos de Radar if RadarFile == -1: continue # Se corrige la información de Radar VELH = RadarFile.fields['VELH'] DBZH = RadarFile.fields['DBZH'] NCPH = RadarFile.fields['NCPH'] DBZHC = DBZH masks = [~(np.ma.getmaskarray(VELH['data'])) & (np.ma.getdata(VELH['data'])==0), ~(np.ma.getmaskarray(DBZH['data'])) & (np.ma.getdata(DBZH['data'])<=-20), ~(np.ma.getmaskarray(NCPH['data'])) & (np.ma.getdata(NCPH['data'])<=0.75)] total_mask = masks[0] | masks[1] | masks [2] DBZHC['data'] = np.ma.masked_where(total_mask,DBZHC['data']) RadarFile.add_field('DBZHC', DBZHC) # Attenuation spec_at, cor_z = pyart.correct.calculate_attenuation( RadarFile, 0, refl_field='DBZH', ncp_field='NCPH', rhv_field='SNRHC', phidp_field='PHIDP') RadarFile.add_field('specific_attenuation', spec_at) RadarFile.add_field('corrected_reflectivity_horizontal', cor_z) self.RadarFile = RadarFile # Se genera el mapa self.RadarGraphs(RadarFile,t.strftime('%Y/%m/%d %H:%M'),t,vmin=5) utl.CrFolder(self.PathImg+'DBZH'+'/') plt.savefig(self.PathImg+'DBZH'+'/'+'%04i Image'%(it)+'.png' ,format='png',dpi=200) plt.close('all') return
def SaveMat(self, Name='Results', Pathout=''): ''' DESCRIPTION: This method saves the data in a .mat format file. _______________________________________________________________________ INPUT: :param Name: a str, Name of the file. :param Pathout: a str, Path to save the file. _______________________________________________________________________ OUTPUT: :return: File in .mat format. ''' utl.CrFolder(Pathout) Data = self.Data Data['DatesC'] = self.Dates.str Nameout = Pathout + Name + '.mat' sio.savemat(Nameout, self.Data) return
def SaveDictJson(Data, Pathout='', Name='Dictionary'): ''' DESCRIPTION: This function aims to save data in a csv file from. _______________________________________________________________________ INPUT: :param Data: A dict, Dictionary with the data. :param Pathout: a str, Saving directory. :param Name: A str, File Name with extension. _______________________________________________________________________ OUTPUT: Save a Json file with the dictionary. ''' # Create folder utl.CrFolder(Pathout) with open(Pathout + Name + '.json', 'w') as f: json.dump(Data, f) return
def MALR(self,slope,intercept,Zmax=7000,Zmin=1000,LCLp=1800,FlagGraph=False,PathImg='',NameArch='',Name=''): ''' DESCRIPTION: Script para encontrar la moist adiabatic lapse rate a partir de los datos horarios dados, esta se encontrará para todas las diferentes horas, presentando una gráfica diferente por hora. Este script utilizará las ecuaciones descritas por Del Genio (s.f.) en su curso de termodinámica en la universidad de columbia, estas fueron programas por Daniel Ruiz en eñ archivo 'Claro River Profiles Final Version.xls'. Para mayor información remitirse al documento 'Summary of key equations.docx' el cual contiene un resumen de lo expuesto por Del Genio (s.f.) en las notas de clase, realizado por Daniel Ruiz. El nivel de condensación por elevación (LCL) se supone según estimaciones previas, según Cuevas (2015) el LCL se encuentra entre 2190 -> Secos - 2140 -> Mojados para una región en el PNN Los Nevados. Estimaciones previas de Daniel Ruiz (sugerencia personal) sugieren que el valor se encuentra a 1800 msnm, hace falta un estudio más profundo para ver en donde se encuentra este punto. _________________________________________________________________________ INPUT: + slope: Pendiente para la temperatura _________________________________________________________________________ OUTPUT: - ''' # En esta sección se colacarán y calcularán algunas de las constantes, # estas constantes se encuentran expuestas en el archivo 'Claro River # Profiles Final Version.xls', en la hoja 'Constants' realizado por el # profesor Daniel Ruiz. # Presión de vapor en saturación a 0°C e_s0 = 6.11 # mb e_sp0 = e_s0*100 # Pa # Calor latente, Este valor es a 0°C y puede ser asumido como cte. L = 2.5*10**6 # J/kg H_2O # Constante de gases para vapor de agua R_v = 461 # J/K/kg # Temperatura T_0 = 273.15 # K T = 288.15 # K Tc = T-T_0 # °C # Presión de vapor de agua en saturación a 15°C e_s = e_sp0*np.exp((L/R_v)*((1/T_0)-(1/T))) # Pa e_sh = e_s/100 # hPa # Epsilon (Buscar ¿qué es?) epsilon = 0.622 # R_d/R_v # Presión (¿Qué presión?) p = 80000 # Pa # Saturated Mixing ratio W_s = epsilon*(e_s/p) # Gas constant for dry air R_d = 287 # J/K/kg DivCR = 3.5 # C_p/R_d # Specific heat for dry at constant pressure C_p = R_d*DivCR # J/K/kg # dry adiabatic lapse rate Gamma_d = 9.8 # K/km # Moist adiabatic lapse rate Gamma_m = Gamma_d*((1+((L*W_s)/(R_d*T)))/((1+(((L**2)*W_s)/(C_p*R_v*(T**2)))))) # Deltas PF = 273.15 # K DT = T-PF # K DZ = DT/Gamma_m # km # Datos adicionales p_0 = 1013*100 # Pa H_s = 8631 # m z = -H_s*np.log(p/p_0) # m # Freezing level FL = (DZ*1000)+ z # m # Assumed Freezing level AFL = 4900 # m ADZ = (AFL-z)/1000 # km # Buscar qué es Tao!! Tao = DT/ADZ # K/km # R_d/C_p DivRC = R_d/C_p # Presió 0 P_00 = 1000 # hPa - mb # ------------------------------------------------------------ # Se crea el vecto de alturas Al = np.arange(Zmin,Zmax+50,50) # Vector de alturas cada 50 metros Als = len(Al) # Tamaño del vector Headers = ['Mean Annual T [°C]', 'Mean Annual T [K]'\ , 'e_s (T) [Pa]', 'Atmospheric pressure [mbar]'\ , 'Atmospheric pressure [Pa]', 'W_s', 'Gamma_m [K/km]'\ , 'Gamma_d [K/km]', 'Profile T [K]-LCL='+str(LCLp),'Profile T dry'] Hes = len(Headers) # Se crea la matriz con todos los valores TM = np.zeros((Als,Hes)) # Se calcula la temperatura a partir de una regresión previamente realizada TM[:,0] = slope*Al+intercept # Se encuentra el primer valor para el cual T<=0 x_0 = np.where(TM[:,0] <= 0)[0] Al_0 = Al[x_0[0]] # Se pasa la temperatura Kelvin TM[:,1] = TM[:,0]+273.15 # Se inicializa el vector del perfil vertical de temperatura TM[0,-2] = TM[0,1] TM[0,-1] = TM[0,1] # Se calculan el resto de los valores for ii,i in enumerate(Al): # Presión de vapor e_s [Pa] TM[ii,2] = e_sp0*np.exp((L/R_v)*((1/T_0)-(1/TM[ii,1]))) # Presión atmosférica [mbar] -> Se puede cambiar por datos!! # Se calcula con la ecuación hidroestática p=1009.28 exp(-z/H) # donde H: Scale Height = 8631. TM[ii,3] = 1009.28*np.exp(-i/H_s) # Presión atmosférica [Pa] TM[ii,4] = TM[ii,3]*100 # Rata de mezcla W_s TM[ii,5] = epsilon*(TM[ii,2]/TM[ii,4]) # Moist adiabatic lapse rate Gamma_m TM[ii,6] = Gamma_d*((1+((L*TM[ii,5])/(R_d*TM[ii,1])))/((1+(((L**2)*TM[ii,5])/(C_p*R_v*(TM[ii,1]**2)))))) # Dry adiabatic lapse rate TM[ii,7] = Gamma_d # Se genera el perfil vertical de temperatura if ii > 0: # Perfil de temperatura vertical [k] if i <= LCLp: # Perfil adiabático seco TM[ii,8] = TM[ii-1,8]-TM[ii,7]*((i-Al[ii-1])/1000) else: # Perfil adiabático húmedo TM[ii,8] = TM[ii-1,8]-((TM[ii-1,6]+TM[ii,6])/2)*((i-Al[ii-1])/1000) # Dry adiabatic lapse rate profile TM[ii,9] = TM[ii-1,9]-TM[ii,7]*((i-Al[ii-1])/1000) # Se realiza la gráfica if FlagGraph: # Se crea la carpeta en donde se guarda la información utl.CrFolder(PathImg) # Se organizan los valores para graficarlos x = np.where(Al <= LCLp)[0] xx = np.where(Al > LCLp)[0] # Parámetros de la gráfica fH = 20 fV = fH*(2/3) minorLocatorx = MultipleLocator(1) minorLocatory = MultipleLocator(100) F = plt.figure(figsize=utl.cm2inch(fH,fV)) plt.rcParams.update({'font.size': 14,'font.family': 'sans-serif'\ ,'font.sans-serif': 'Arial'}) plt.plot(TM[:,0],Al,'k-',label='Gradiente Ambiental') plt.plot(TM[x,8]-273.15,Al[x],'r--',label='Gradiente Adiabático Seco') plt.plot(TM[:,9]-273.15,Al,'r--') plt.plot(TM[xx,8]-273.15,Al[xx],'b--',label='Gradiente Adiabático Húmedo') plt.legend(loc=0,fontsize=12) plt.title(Name,fontsize=16 ) # Colocamos el título del gráfico plt.xlabel(u'Temperatura [°C]',fontsize=14) # Colocamos la etiqueta en el eje x plt.ylabel('Altura [msnm]',fontsize=14) # Colocamos la etiqueta en el eje y plt.gca().set_ylim([900,4500]) plt.gca().xaxis.set_minor_locator(minorLocatorx) plt.gca().yaxis.set_minor_locator(minorLocatory) plt.xlim([-5,40]) plt.savefig(PathImg + NameArch +'.png', format='png',dpi=200) plt.close('all') # Se reportan los resultados return Al,TM
def GraphStSeries(self, Var, NameArch='', PathImg=''): ''' DESCRIPTION: Method that load station information for comparation, need to run LoadStations first. _________________________________________________________________________ INPUT: :param Var: A str, Variable to be compared. :param Name: A str, Name of the graph. :param NameArch: A str, Name of the file. :param PathImg: A str, Path to save the file. _________________________________________________________________________ OUTPUT: ''' VarL = {'Pres_F': 'Presión'} VarLL = {'Pres_F': 'Presión [hPa]'} LabelVal = ['DurPrec', 'TotalPrec', 'IntPrec'] LabelValV = ['Max', 'Min', 'Mean', 'Sum'] Oper = { 'Max': np.nanmax, 'Min': np.nanmin, 'Mean': np.nanmean, 'Sum': np.nansum } Values = dict() # Iniziaticed Values for L1 in LabelVal: Values[L1] = [] # Folder Creation fH = 20 fV = fH * (2 / 3) fig = plt.figure(figsize=DM.cm2inch(fH, fV)) plt.rcParams.update({'font.size': 15,'font.family': 'sans-serif'\ ,'font.sans-serif': 'Arial'\ ,'xtick.labelsize': 15,'xtick.major.size': 6,'xtick.minor.size': 4\ ,'xtick.major.width': 1,'xtick.minor.width': 1\ ,'ytick.labelsize': 15,'ytick.major.size': 12,'ytick.minor.size': 4\ ,'ytick.major.width': 1,'ytick.minor.width': 1\ ,'axes.linewidth':1\ ,'grid.alpha':0.1,'grid.linestyle':'-'}) x = 0 xx = 0 for iID, ID in enumerate(self.ID): if xx == 0: self.EvT += 1 xx = 1 PP = int(len(self.DataSt[ID]['Prec']) / 2) if np.nanmax( self.DataSt[ID]['Prec'][PP:PP + int(2 * 60 / self.dt)]) > 0.01: if x == 0: self.EvSiT += 1 x = 1 # Precipitation event parameters PMax = np.nanmax( self.DataSt[ID]['Prec'][PP:PP + int(2 * 60 / self.dt)]) M = np.where(self.DataSt[ID]['Prec'][PP:PP + int(2 * 60 / self.dt)] == PMax)[0][0] + PP self.PrecCount = HyMF.PrecCount(self.DataSt[ID]['Prec'], self.DataSt[ID]['FechaC'], dt=self.dt, M=M) # Label of the parameters Dur = round(self.PrecCount['DurPrec'], 3) TotPrec = round(self.PrecCount['TotalPrec'], 3) if np.isnan(Dur): LabelT = self.St_Info[ID][ 'CodesNames'] + ' (No hay datos suficientes)' else: Datest = self.PrecCount['DatesEvst'][0].strftime('%H:%M') LabelT = self.St_Info[ID][ 'CodesNames'] + ' ({}, {} h, {} mm)'.format( Datest, Dur, TotPrec) for L1 in LabelVal: Values[L1].append(self.PrecCount[L1]) plt.plot(self.DataSt[ID]['FechaCP'], self.DataSt[ID][Var], '--', label=LabelT) else: plt.plot(self.DataSt[ID]['FechaCP'], self.DataSt[ID][Var], '-', label=self.St_Info[ID]['CodesNames']) ax = plt.gca() yTL = ax.yaxis.get_ticklocs() Ver = self.DataSt[ID]['FechaCP'][int( len(self.DataSt[ID]['FechaCP']) / 2)] plt.plot([Ver, Ver], [yTL[0], yTL[-1]], 'k--') plt.ylabel(VarLL[Var]) for tick in plt.gca().get_xticklabels(): tick.set_rotation(45) # plt.title(VarL[Var]) lgd = plt.legend(bbox_to_anchor=(-0.15, 1.02, 1.15, .102), loc=3, ncol=2, mode="expand", borderaxespad=0., fontsize=8.0) # plt.legend(loc=1) plt.grid() yTL = ax.yaxis.get_ticklocs() # List of Ticks in y MyL = (yTL[1] - yTL[0]) / 5 # Minor tick value minorLocatory = MultipleLocator(MyL) plt.gca().yaxis.set_minor_locator(minorLocatory) utl.CrFolder(PathImg + '/') plt.savefig(PathImg + '/' + Var[:-2] + '_' + NameArch + '_' + str(self.Ev) + '.png', format='png', dpi=200, bbox_extra_artists=(lgd, ), bbox_inches='tight') plt.close('all') if len(Values[L1]) > 0: for L1 in LabelValV: for L2 in LabelVal: self.PrecT[L1][L2].append(Oper[L1](np.array(Values[L2]))) return
def FilFFT(self,f,t,FiltHi,FiltHf,dt=1,flag=True,Pathimg='',x1=0,x2=50,V='Pres',tt='minutos',Ett=0,ii=1,ix='pos',DTT='5'): ''' DESCRIPTION: Con esta función se obtiene un filtro cuadrado a partir del espectro de potencias encontrado con la transformada de Fourier. Lo que hace es tomar una hora de comienzo y de finalización y lo que se encuentre por fuera de las horas lo vuelve cero. _________________________________________________________________________ INPUT: + f: Los datos a los que se les va a sacar la transformada de Fourier. + t: La serie temporal utilizada para obtener las de frecuencias. + Filt_Hi: Hora de inicio del filtro (esta asociado al Periodo NO a la frecuencia). + Filt_Hf: Hora final del filtro (esta asociado al Periodo NO a la frecuencia). + dt: el paso de tiempo determinado para la serie de tiempo. + flag: Variable booleana que sirve para indicar si se desean gráficas o no. Las variables que se presentarán a continuación se darán solo si flag == True. + Pathimg: Ruta para guardar las imágenes. + x1: Primer valor del xlim. + x2: Segundo valor del xlim. + V: String de la variable que se está analizando . + tt: Escala de tiempo que se desea graficar. + Ett: Escala de tiempo que se desean que se pasen los datos para la graficación. 0: Se dejan en el tiempo principal. 1: Se pasan a Horas de minutos ó a minutos de segundos. 2: Se pasan a Horas de escala cinco-minutal. 3: Se pasan a Horas de escala quince-minutal. + ii: El número de gráfica que se realizará. + ix: Estación que se está analizando. + DTT: Periodo en qué escala temporal. _________________________________________________________________________ OUTPUT: - Pres_F: Resultado de los datos filtrados completos. - Pres_FF: Resultado de los datos filtrados, solamente los datos reales. - P_amp: La amplitud de los coeficientes. - P_p: la potencia asociada a los coeficientes. - P_t: La suma total de las potencias. - P_var: El porcentaje de varianza explicado por cada potencia. - P_fr: La frecuencia asociada al tiempo. - P_Per: Periodo asociado al tiempo. - P_A: Coeficientes encontrados con la FFT. ''' # Se encuentra la transformada de Fourier P_amp, P_p, P_t, P_var, P_fr, P_Per, P_A = self.FT(f,t,1) # ----------------- # Filtrado # ----------------- # Los periodos de inicio y finalización Filt_Per = FiltHf; Filt_Peri = FiltHi; P_AA = P_A.copy() # Se copia el valor de los ceoficientes. # Se desarrolla el filtro cuadrado. for i in range(len(P_fr)): if P_Per[i]>-Filt_Peri and P_Per[i]<Filt_Peri: P_AA[i]=0 if P_Per[i]<-Filt_Per or P_Per[i]>Filt_Per: P_AA[i]=0 P_AA[0] = P_A[0] p_fil=np.abs(P_AA)**2 # Se realiza la transformada inversa Pres_F = np.fft.ifft(P_AA) Pres_FF = Pres_F.real #Pres_FF = np.sqrt((Pres_F.real**2) + (Pres_F.imag**2)) if flag: # Se crea la carpeta utl.CrFolder(Pathimg+'Comp/') # Se halla el pico máximo x = np.where(P_p[:-1] == max(P_p[:-1])) # Se halla el pico máximo xx = np.where(p_fil[:-1] == max(p_fil[:-1])) if Ett == 0: # Pico máximo PM = round(abs(P_Per[x][0]),2) # Pico máximo asociado a las 4 horas P4 = round(abs(P_Per[xx][0]),2) elif Ett == 1: # Pico máximo PM = round(abs(P_Per[x][0])/60,2) # Pico máximo asociado a las 4 horas P4 = round(abs(P_Per[xx][0])/60,2) elif Ett ==2: # Pico máximo PM = round(abs(P_Per[x][0])*5/60,2) # Pico máximo asociado a las 4 horas P4 = round(abs(P_Per[xx][0])*5/60,2) elif Ett ==3: # Pico máximo PM = round(abs(P_Per[x][0])*15/60,2) # Pico máximo asociado a las 4 horas P4 = round(abs(P_Per[xx][0])*15/60,2) else: utl.ExitError('FiltFFT','AnET','Change in the time scale not available yet') # Tamaño de la Figura fH=20 # Largo de la Figura fV = fH*(2/3) # Ancho de la Figura # Formato de las gráficas AFon = 15; Tit = 15; Axl = 15 F = plt.figure(figsize=utl.cm2inch(fH,fV)) plt.rcParams.update({'font.size': 15,'font.family': 'sans-serif'\ ,'font.sans-serif': 'Arial Narrow'\ ,'xtick.labelsize': 15,'xtick.major.size': 6,'xtick.minor.size': 4\ ,'xtick.major.width': 1,'xtick.minor.width': 1\ ,'ytick.labelsize': 15,'ytick.major.size': 12,'ytick.minor.size': 4\ ,'ytick.major.width': 1,'ytick.minor.width': 1\ ,'axes.linewidth':1\ ,'grid.alpha':0.1,'grid.linestyle':'-'}) plt.tick_params(axis='x',which='both',bottom='on',top='off',\ labelbottom='on',direction='in') plt.tick_params(axis='x',which='major',direction='inout') plt.tick_params(axis='y',which='both',left='on',right='off',\ labelleft='on') plt.tick_params(axis='y',which='major',direction='inout') plt.plot(P_Per[:len(t)/2-1], P_p[:len(t)/2-1], '-', lw = 1.5) plt.plot(abs(P_Per[x]),P_p[x],'ro', ms=10) plt.text(50, P_p[x][0], r'Periodo $\sim$ %s %s' %(PM,tt),fontsize=AFon) plt.title('Potencia espectral',fontsize=Tit ) # Colocamos el título del gráfico plt.xlabel(u'Periodo [cada '+ DTT +' min]',fontsize=AFon) # Colocamos la etiqueta en el eje x plt.ylabel('Potencia espectral',fontsize=AFon) # Colocamos la etiqueta en el eje y plt.savefig(Pathimg + V +'_ET_' + str(ii)+ '_' + ix + '.png',format='png',dpi=300) # gráfica del esprectro filtrado plt.figure(figsize=(15,10)) plt.rcParams.update({'font.size': 15,'font.family': 'sans-serif'\ ,'font.sans-serif': 'Arial Narrow'\ ,'xtick.labelsize': 15,'xtick.major.size': 6,'xtick.minor.size': 4\ ,'xtick.major.width': 1,'xtick.minor.width': 1\ ,'ytick.labelsize': 16,'ytick.major.size': 12,'ytick.minor.size': 4\ ,'ytick.major.width': 1,'ytick.minor.width': 1\ ,'axes.linewidth':1\ ,'grid.alpha':0.1,'grid.linestyle':'-'}) plt.tick_params(axis='x',which='both',bottom='on',top='off',\ labelbottom='on',direction='in') plt.tick_params(axis='x',which='major',direction='inout') plt.tick_params(axis='y',which='both',left='on',right='off',\ labelleft='on') plt.tick_params(axis='y',which='major',direction='inout') plt.plot(P_Per[:len(t)/2-1], p_fil[:len(t)/2-1], '-', lw = 1.5) # Dibujamos los valores de las parejas ordenadas con una línea contínua #plt.plot(P_Per[len(t)/2:], p_fil[len(t)/2:], '-', linewidth = 2) # Dibujamos los valores de las parejas ordenadas con una línea contínua # plt.plot(abs(P_Per[x]),p_fil[x],'ro', ms=10) # #plt.text(abs(P_Per[x][0]-18), p_fil[x][0], r'Periodo \sim %s horas' %(P4)) # plt.text(28, p_fil[x][0], r'Periodo $\sim$ %s horas' %(P4),fontsize=AFon) plt.title('Potencia espectral filtrada',fontsize=Tit ) # Colocamos el título del gráfico plt.xlabel(u'Periodo [cada '+ DTT +' min]',fontsize=AFon) # Colocamos la etiqueta en el eje x plt.ylabel('Potencia espectral',fontsize=AFon) # Colocamos la etiqueta en el eje y # plt.legend(loc='best') plt.xlim(x1, x2) # Guardar la imagen plt.savefig(Pathimg + ix + '_' +V +'_filt(%s_h)_' %(int(FiltHf)) + str(ii) + '.png',format='png',dpi=300 ) plt.close('all') fig, axs = plt.subplots(1,2, figsize=(15, 8), facecolor='w', edgecolor='k') plt.rcParams.update({'font.size': 15,'font.family': 'sans-serif'\ ,'font.sans-serif': 'Arial Narrow'\ ,'xtick.labelsize': 15,'xtick.major.size': 6,'xtick.minor.size': 4\ ,'xtick.major.width': 1,'xtick.minor.width': 1\ ,'ytick.labelsize': 16,'ytick.major.size': 12,'ytick.minor.size': 4\ ,'ytick.major.width': 1,'ytick.minor.width': 1\ ,'axes.linewidth':1\ ,'grid.alpha':0.1,'grid.linestyle':'-'}) axs = axs.ravel() # Para hacer un loop con los subplots axs[0].plot(P_Per[:len(t)/2-1], P_p[:len(t)/2-1], '-', lw = 1.5) axs[0].set_title('Potencia espectral sin filtrar',fontsize=Tit ) axs[0].set_xlabel(u'Periodo [cada '+ DTT +' min]',fontsize=AFon) axs[0].set_ylabel('Potencia espectral',fontsize=AFon) axs[0].set_xlim([x1,x2]) axs[1].plot(P_Per[:len(t)/2-1], p_fil[:len(t)/2-1], '-', lw = 1.5) axs[1].set_title('Potencia espectral filtrada',fontsize=Tit ) axs[1].set_xlabel(u'Periodo [cada '+ DTT +' min]',fontsize=AFon) #axs[1].set_ylabel('Potencia espectral',fontsize=AFon) axs[1].set_xlim([x1,x2]) plt.tight_layout() plt.savefig(Pathimg+'Comp/'+ ix + '_' +V +'_filt(%s-%s_m)_' %(int(FiltHi),int(FiltHf)) + str(ii) + '.png',format='png',dpi=300) plt.close('all') #return Pres_F, P_amp, P_p, P_t, P_var, P_fr, P_Per, P_A return Pres_F, P_amp, p_fil, P_t, P_var, P_fr, P_Per, P_A
def CiclDV(MesesMM, PathImg='', Name='', Name2='', Var='', Var2='', Var3=''): ''' DESCRIPTION: Con esta función se pretende realizar el ciclo diurno de cualquier variable a lo largo del año. Además pueden obtenerse las gráficas si así se desea. _______________________________________________________________________ INPUT: + MesesMM: Variable de los promedios mensuales multianuales. + PathImg: Ruta para guardar las imágenes. + Name: Nombre de los documentos. + Name2: Nombre de la estación. + Var: Nombre corto de la variable. + Var2: Nombre completo de la variable + Var3: Nombre completo de la variable con unidades de medida. _______________________________________________________________________ OUTPUT: Este código saca 1 gráfica teniendo el promedio de todos los meses. ''' # Se crea la ruta en donde se guardarán los archivos utl.CrFolder(PathImg) # Se inicializan las variables MM = ['E', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D', 'E'] ProcP = np.empty((12, 24)) # Ciclo para extraer los promedios for ii, i in enumerate(range(1, 13)): ProcP[ii, :] = MesesMM[i] x = np.arange(0, 24) x3 = np.arange(0, 25) # Se organizan las horas ProcP2 = np.hstack((ProcP[:, 7:], ProcP[:, :7])) x2 = np.hstack((x[7:], x[:7])) for i in range(len(ProcP2)): ProcP22 = 0 ProcP22 = np.hstack((ProcP2[i, :], ProcP2[i, 0])) if i == 0: ProcP3 = ProcP22 else: ProcP3 = np.vstack((ProcP3, ProcP22)) ProcP3 = np.vstack((ProcP3, ProcP3[0, :])) # Datos para las gráficas # v = np.linspace(608, 8, 9, endpoint=True) # bounds=[0,1,2,3,4,5,6,7,8] # ProcP2 = np.hstack((ProcP2,ProcP2[:,0:1])) x2 = np.hstack((x2, x2[0])) F = plt.figure(figsize=(15, 10)) plt.rcParams.update({'font.size': 22}) #plt.contourf(x3,np.arange(1,14),ProcP3,v,vmax=8,vmin=0) plt.contourf(x3, np.arange(1, 14), ProcP3) plt.title('Ciclo diurno de la ' + Var2 + ' en el año en ' + Name2, fontsize=26) # Colocamos el título del gráfico plt.ylabel('Meses', fontsize=24) # Colocamos la etiqueta en el eje x plt.xlabel('Horas', fontsize=24) # Colocamos la etiqueta en el eje y axs = plt.gca() axs.yaxis.set_ticks(np.arange(1, 14, 1)) axs.set_yticklabels(MM) axs.xaxis.set_ticks(np.arange(0, 25, 1)) axs.set_xticklabels(x2) plt.tight_layout() #cbar = plt.colorbar(boundaries=bounds,ticks=v) cbar = plt.colorbar() cbar.set_label(Var3) plt.gca().invert_yaxis() plt.legend(loc=1) plt.grid() plt.savefig(PathImg + 'T' + Var + '_' + Name + '.png') plt.close('all')
def ExtractData(self, Name='Doc', Pathout=''): ''' DESCRIPTION: This method extracts the data to an Excel File with several sheets. _________________________________________________________________ ''' if self.Data['H'] is None: self.Error('Model_AngstromPrescott', 'ExtractData', 'Cannot extract information if Rad is not added') # Parameters Vars = ['Dates', 'H', 'H0', 'n', 'N'] # Create Folder utl.CrFolder(Pathout) # Create document B = xlsxwl.Workbook(Pathout + Name + '.xlsx') # Add Data Sheet S = B.add_worksheet('Data') # Headers S.write(0, 0, 'Dates') S.write(0, 1, 'Julian Day') S.write(0, 2, 'H') S.write(0, 3, 'H0') S.write(0, 4, 'n') S.write(0, 5, 'N') S.write(0, 6, 'RelH') S.write(0, 7, 'RelN') # Fill data for iD, D in enumerate(self.Dates.str): # Dates S.write(iD + 1, 0, D) # Julian Day S.write(iD + 1, 1, self.Julian_Day[iD]) x = 2 for var in Vars[1:]: if np.isnan(self.Data[var][iD]): D = '' else: D = self.Data[var][iD] S.write(iD + 1, x, D) x += 1 # RelH if np.isnan(self.RelRad[iD]): D = '' else: D = self.RelRad[iD] S.write(iD + 1, 6, D) # RelN if np.isnan(self.RelN[iD]): D = '' else: D = self.RelN[iD] S.write(iD + 1, 7, D) # Add Graph Sheet S = B.add_worksheet('Graphs') # --------------- # Create graphs # --------------- # Ranges of the data VarCol = {'Dates': 0, 'H': 2, 'H0': 3, 'n': 4, 'N': 5} VarsRel = ['RelH', 'RelN'] VarsRelCol = {'RelH': 6, 'RelN': 7} Ranges = dict() Names = dict() RangesRel = dict() for ivar, var in enumerate(Vars): Ranges[var] = xl_range_abs(1, VarCol[var], iD + 1, VarCol[var]) Names[var] = xl_range_abs(0, VarCol[var], 0, VarCol[var]) for ivar, var in enumerate(VarsRelCol): RangesRel[var] = xl_range_abs(1, VarsRelCol[var], iD + 1, VarsRelCol[var]) x = 1 xx = 1 for ichart in range(2): chart = B.add_chart({'type': 'line'}) chart.add_series({ 'name': "=Data!" + Names[Vars[x]], 'categories': "=Data!" + Ranges['Dates'], 'values': "=Data!" + Ranges[Vars[x]] }) chart.add_series({ 'name': "=Data!" + Names[Vars[x + 1]], 'categories': "=Data!" + Ranges['Dates'], 'values': "=Data!" + Ranges[Vars[x + 1]] }) S.insert_chart(xx, 1, chart, { 'x_offset': 0, 'y_offset': 0, 'x_scale': 2., 'y_scale': 1.0 }) x += 2 xx += 15 # Scatter Linear chart = B.add_chart({'type': 'scatter'}) chart.add_series({ 'name': "Relación", 'categories': "=Data!" + RangesRel['RelN'], 'values': "=Data!" + RangesRel['RelH'], 'trendline': { 'type': 'linear', 'display_equation': True, 'display_r_squared': True } }) chart.set_title({'name': 'Relación entre índices lineal'}) chart.set_x_axis({'name': 'Fracción de Brillo Solar (n/N)'}) chart.set_y_axis({'name': 'Índice de claridad (H/H0)'}) chart.set_style(1) chart.set_legend({'none': True}) S.insert_chart(32, 1, chart, { 'x_offset': 0, 'y_offset': 0, 'x_scale': 1.5, 'y_scale': 1.5 }) # Scatter Polynomial chart = B.add_chart({'type': 'scatter'}) chart.add_series({ 'name': "Relación", 'categories': "=Data!" + RangesRel['RelN'], 'values': "=Data!" + RangesRel['RelH'], 'trendline': { 'type': 'polynomial', 'display_equation': True, 'display_r_squared': True, 'order': 3 } }) chart.set_title({'name': 'Relación entre índices Polinomica'}) chart.set_x_axis({'name': 'Fracción de Brillo Solar (n/N)'}) chart.set_y_axis({'name': 'Índice de claridad (H/H0)'}) chart.set_style(1) chart.set_legend({'none': True}) S.insert_chart(32 + 25, 1, chart, { 'x_offset': 0, 'y_offset': 0, 'x_scale': 1.5, 'y_scale': 1.5 }) B.close()
def GraphAdj(self, Name='Image', PathImg='', flagConInt=False): ''' DESCRIPTION: This method makes the scatter plot of the given data. _________________________________________________________________ INPUT: :param Name: A str, Name of the document. :param PathImg: A str, path to save the Image. ''' V1 = self.RelN V2 = self.RelRad FitC = self.R # Se realiza el ajuste x = np.linspace(np.nanmin(self.RelN), np.nanmax(self.RelN), 100) VC = FitC['Function'](x, *FitC['Coef']) # Tamaño de la Figura fH = 20 # Largo de la Figura fV = fH * (2 / 3) # Ancho de la Figura # Se crea la carpeta para guardar la imágen utl.CrFolder(PathImg) # Se genera la gráfica F = plt.figure(figsize=DM.cm2inch(fH, fV)) # Parámetros de la Figura plt.rcParams.update({'font.size': 15,'font.family': 'sans-serif'\ ,'font.sans-serif': 'Arial' ,'xtick.labelsize': 15,'xtick.major.size': 6,'xtick.minor.size': 4\ ,'xtick.major.width': 1,'xtick.minor.width': 1\ ,'ytick.labelsize': 16,'ytick.major.size': 12,'ytick.minor.size': 4\ ,'ytick.major.width': 1,'ytick.minor.width': 1\ ,'axes.linewidth':1\ ,'grid.alpha':0.1,'grid.linestyle':'-'}) plt.tick_params(axis='x',which='both',bottom='on',top='off',\ labelbottom='on',direction='out') plt.tick_params(axis='y',which='both',left='on',right='off',\ labelleft='on') plt.tick_params(axis='y', which='major', direction='inout') plt.grid() # Precipitación plt.scatter(V1, V2, color='dodgerblue', alpha=0.7) # plt.title('',fontsize=16) plt.ylabel('Índice de claridad ' + r'($H/H0$)', fontsize=16) plt.xlabel('Fracción de Brillo Solar ' + r'($n/N$)', fontsize=16) # Axes ax = plt.gca() xTL = ax.xaxis.get_ticklocs() # List of Ticks in x MxL = (xTL[1] - xTL[0]) / 5 # minorLocatorx value plt.xlim([0, np.nanmax(V1) + 2 * MxL]) xTL = ax.xaxis.get_ticklocs() # List of Ticks in x MxL = (xTL[1] - xTL[0]) / 5 # minorLocatorx value minorLocatorx = MultipleLocator(MxL) yTL = ax.yaxis.get_ticklocs() # List of Ticks in y MyL = np.abs(np.abs(yTL[1]) - np.abs(yTL[0])) / 5 # minorLocatory value minorLocatory = MultipleLocator(MyL) plt.gca().xaxis.set_minor_locator(minorLocatorx) plt.gca().yaxis.set_minor_locator(minorLocatory) # Se incluye el ajuste Label = FitC['FunctionEq'] + '\n' + r'$R^2=%.3f$' plt.plot(x, VC, 'k--', label=Label % tuple(list(FitC['Coef']) + [FitC['R2']])) plt.legend(loc=1, fontsize=10, framealpha=0.6) if flagConInt: for i in range(2): Coef = [] for j in range(len(FitC['Coef'])): Coef.append(FitC['ConInt'][j][i]) VC = FitC['Function'](x, *Coef) plt.plot(x, VC, 'r--') plt.tight_layout() Nameout = PathImg + Name plt.savefig(Nameout + '.png', format='png', dpi=200) plt.close('all') return
def PlotDataRHI(self,Time=0): ''' DESCRIPTION: This method plots all the case information. _________________________________________________________________ INPUT: ''' FilesA = [] FilesARHI = [] for it,t in enumerate(self.DatesSt): if it >= Time: print(t) F = t xEv = np.where(self.RadarDatesP == F+timedelta(0,5*60*60))[0] if len(xEv) == 1: FilesA.append(self.ArchRadar[xEv[0]][len(self.PathRadar):]) if len(FilesA) == 0: continue RadarFile = self.Opengz(FilesA[-1],self.PathRadar,self.PathRadar) # Se verifican los datos de Radar if RadarFile == -1: continue # Se corrige la información de Radar VELH = RadarFile.fields['VELH'] DBZH = RadarFile.fields['DBZH'] NCPH = RadarFile.fields['NCPH'] DBZHC = DBZH masks = [~(np.ma.getmaskarray(VELH['data'])) & (np.ma.getdata(VELH['data'])==0), ~(np.ma.getmaskarray(DBZH['data'])) & (np.ma.getdata(DBZH['data'])<=-20), ~(np.ma.getmaskarray(NCPH['data'])) & (np.ma.getdata(NCPH['data'])<=0.75)] total_mask = masks[0] | masks[1] | masks [2] DBZHC['data'] = np.ma.masked_where(total_mask,DBZHC['data']) RadarFile.add_field('DBZHC', DBZHC) # Attenuation spec_at, cor_z = pyart.correct.calculate_attenuation( RadarFile, 0, refl_field='DBZH', ncp_field='NCPH', rhv_field='SNRHC', phidp_field='PHIDP') RadarFile.add_field('specific_attenuation', spec_at) RadarFile.add_field('corrected_reflectivity_horizontal', cor_z) self.RadarFile = RadarFile # RHI xEv = np.where(self.RadarRHIDatesP == F+timedelta(0,5*60*60))[0] if len(xEv) == 1: FilesARHI.append(self.ArchRadarRHI[xEv[0]][len(self.PathRadarRHI):]) if len(FilesARHI) == 0: continue RadarRHIFile = self.Opengz(FilesARHI[-1],self.PathRadarRHI,self.PathRadarRHI,flagRHI=False) # Se verifican los datos de Radar if RadarRHIFile == -1: continue # Se corrige la información de Radar VELH = RadarRHIFile.fields['VELH'] DBZH = RadarRHIFile.fields['DBZH'] NCPH = RadarRHIFile.fields['NCPH'] DBZHC = DBZH masks = [~(np.ma.getmaskarray(VELH['data'])) & (np.ma.getdata(VELH['data'])==0), ~(np.ma.getmaskarray(DBZH['data'])) & (np.ma.getdata(DBZH['data'])<=-20), ~(np.ma.getmaskarray(NCPH['data'])) & (np.ma.getdata(NCPH['data'])<=0.75)] total_mask = masks[0] | masks[1] | masks [2] DBZHC['data'] = np.ma.masked_where(total_mask,DBZHC['data']) RadarRHIFile.add_field('DBZHC', DBZHC) # Attenuation spec_at, cor_z = pyart.correct.calculate_attenuation( RadarRHIFile, 0, refl_field='DBZH', ncp_field='NCPH', rhv_field='SNRHC', phidp_field='PHIDP') RadarRHIFile.add_field('specific_attenuation', spec_at) RadarRHIFile.add_field('corrected_reflectivity_horizontal', cor_z) self.RadarRHIFile = RadarRHIFile radar = RadarRHIFile display = pyart.graph.RadarDisplay(radar) fig = plt.figure(figsize=[12, 17]) fig.subplots_adjust(hspace=0.4) xlabel = 'Distance from radar (km)' ylabel = 'Height agl (km)' colorbar_label = 'Hz. Eq. Refl. Fac. (dBZ)' nplots = radar.nsweeps for snum in radar.sweep_number['data']: fixed_angle = radar.fixed_angle['data'][snum] title = 'HSRHI Az=%.3f' % (fixed_angle) ax = fig.add_subplot(nplots, 1, snum+1) display.plot('corrected_reflectivity_horizontal', snum, vmin=-20, vmax=20, mask_outside=False, title=title, axislabels=(xlabel, ylabel), colorbar_label=colorbar_label, ax=ax) display.set_limits(ylim=[0, 15], ax=ax) figure_title = 'Time: ' + t fig.text(0.35, 0.92, figure_title) plt.show() aaa # ------- # Se genera el mapa self.RadarGraphs(RadarFile,t.strftime('%Y/%m/%d %H:%M'),t,vmin=5) utl.CrFolder(self.PathImg+'DBZH_RHI'+'/') plt.savefig(self.PathImg+'DBZH_RHI'+'/'+'%04i Image'%(it)+'.png' ,format='png',dpi=200) plt.close('all') return
def WriteCSVSeries(Dates, Values, Headers, deli=None, flagHeader=True, Pathout='', Name='', NaNdata=''): ''' DESCRIPTION: This function aims to save data in a csv file from. _______________________________________________________________________ INPUT: :param Dates: A list, Dates of the series. :param Values: A Dict or list, Value dictionary. :param deli: a str, delimeter of the data. :param Headers: A list, Headers of the data, Labels of the Dates and Values. :param flagHeaders: a Boolean, if headers are needed. :param Pathout: a str, Saving directory. :param Name: a str, File Name with extension. :param NaNdata: a str, Manage the NaN type data. _______________________________________________________________________ OUTPUT: This function return a .csv file. ''' # Create the directory utl.CrFolder(Pathout) if deli == None: deli = self.deli try: f = open(Pathout + Name + '.csv', 'w', encoding='utf-8') except: f = open(Pathout + Name + '.csv', 'w') for iL, L in enumerate(Dates): # Headers if iL == 0 and flagHeader: wr = deli.join(Headers) + '\n' f.write(wr) f.write(L + deli) # Change nan values to empty Line = [] for Head in Headers[1:]: Line.append(str(Values[Head][iL])) for iL, L in enumerate(Line): if L == 'nan': Line[iL] = NaNdata elif L == '': Line[iL] = NaNdata # Line = np.array(Line).astype('>U4') # Line[Line == 'nan'] = NaNdata # Line[Line == ''] = NaNdata wr = deli.join(Line) + '\n' f.write(wr) f.close() return
def WaveletPlot(time, Data1, period, power, sig95, coi, global_ws, global_signif, Var_LUn='', Un3='', Title1='', Title2='', Title3='', Name='', PathImg='', **args): ''' DESCRIPTION: Esta función permite hacer las gráficas de series temporales parecidas a a las presentadas en Excel para el proyecto. _________________________________________________________________________ INPUT: :param time: a ndarray, Years :param Data1: a ndarray, Vector with the Data :param Var_LUn: A str, Label with units. :param Title1: A str, title of the image. :param Var: Nombre de la imagen. :param flagT: Flag para saber si se incluye el título. :param v: Titulo de la Figura. :param PathImg: Ruta donde se quiere guardar el archivo. :param **args: Argumentos adicionales para la gráfica, como color o ancho de la línea. _________________________________________________________________________ OUTPUT: Esta función arroja una gráfica y la guarda en la ruta desada. ''' font = 'Arial' # Image dimensions fH = 30 fV = fH * (2.0 / 3.0) # Image resolution dpi = 120 # Tamaño de la Figura fH = fH # Largo de la Figura fV = fV # Ancho de la Figura # Se crea la carpeta para guardar la imágen utl.CrFolder(PathImg) # Se genera la gráfica F = plt.figure(figsize=DM.cm2inch(fH, fV)) # Parámetros de la Figura plt.rcParams.update({'font.size': 12,'font.family': 'sans-serif'\ ,'font.sans-serif': font\ ,'xtick.labelsize': 12,'xtick.major.size': 6,'xtick.minor.size': 4\ ,'xtick.major.width': 1,'xtick.minor.width': 1\ ,'ytick.labelsize': 12,'ytick.major.size': 12,'ytick.minor.size': 4\ ,'ytick.major.width': 1,'ytick.minor.width': 1\ ,'axes.linewidth':1\ ,'grid.alpha':0.1,'grid.linestyle':'-'}) plt.rcParams['agg.path.chunksize'] = 20000 plt.subplot(211) plt.plot(time, Data1, **args) plt.xlim(time[0], time[-1]) plt.xlabel('Time [years]') plt.ylabel(Var_LUn) plt.title('a) ' + Title1, fontsize=12) #--- Contour plot wavelet power spectrum plt3 = plt.subplot(223) levels = [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16] CS = plt.contourf(time, period, np.log2(power), len(levels), cmap=plt.get_cmap('jet')) #*** or use 'contour' im = plt.contourf(CS, levels=np.log2(levels), cmap=plt.get_cmap('jet')) plt.xlabel('Time [year]') plt.ylabel('Period [years]') plt.title('b) ' + Title2, fontsize=12) plt.xlim(time[0], time[-1]) # 95# significance contour, levels at -99 (fake) and 1 (95# signif) plt.contour(time, period, sig95, [-99, 1], colors='k') # cone-of-influence, anything "below" is dubious plt.plot(time, coi, 'k') # format y-scale plt3.set_yscale('log', basey=2, subsy=None) plt.ylim([np.min(period), np.max(period)]) ax = plt.gca().yaxis ax.set_major_formatter(matplotlib.ticker.ScalarFormatter()) plt3.ticklabel_format(axis='y', style='plain') plt3.invert_yaxis() # set up the size and location of the colorbar divider = make_axes_locatable(plt3) cax = divider.append_axes("bottom", size="5%", pad=0.5) plt.colorbar(im, cax=cax, orientation='horizontal') #--- Plot global wavelet spectrum plt4 = plt.subplot(224) plt.plot(global_ws, period) plt.plot(global_signif, period, '--') plt.xlabel(r'Power ' + Un3) plt.ylabel('Period [years]') plt.title('c) ' + Title3, fontsize=12) plt.xlim([0, 1.25 * np.max(global_ws)]) # format y-scale plt4.set_yscale('log', basey=2, subsy=None) plt.ylim([np.min(period), np.max(period)]) ax = plt.gca().yaxis ax.set_major_formatter(matplotlib.ticker.ScalarFormatter()) plt4.ticklabel_format(axis='y', style='plain') plt4.invert_yaxis() plt.tight_layout() # Se guarda la figura plt.savefig(PathImg + Name + '.png', format='png', dpi=dpi) plt.close('all')
def GeoTIFFSave(T, geoTrans, Projection=None, Name='Results', Pathout='', pixeltype='float'): ''' DESCRIPTION: This Functions saves one a raster in GeoTIFF format (.tif) in one one band. _________________________________________________________________________ INPUT: :param T: A ndArray, 2x2 Matrix with the values of the raster. :param geoTrans: A tuple, tuple with the following values. (x_min,cellsize_x,0.0,y_max,0.0,cellsize_y) :param Projection: A str, wkt projection. Is set WGS84. :param Name: A str, Name of the file. Is set to 'Results'. :param Pathout: A str, Path to save the file. Is set to ''. _________________________________________________________________________ OUTPUT: Se guarda un archivo GeoTiff. ''' # ------------------ # Values # ------------------ x_pixels = T.shape[1] # number of pixels in x y_pixels = T.shape[0] # number of pixels in y if pixeltype == 'float': Pixel = gdal.GDT_Float32 elif pixeltype == 'int': Pixel = gdal.GDT_Int32 # ------------------ # Save File # ------------------ # Create Folder utl.CrFolder(Pathout) Nameout = Pathout + Name + '.tif' # Pojection if Projection == None: # WGS84 wkt_projection = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]' else: wkt_projection = Projection driver = gdal.GetDriverByName('GTiff') dataset = driver.Create( Nameout, x_pixels, y_pixels, 1, Pixel, ) dataset.SetGeoTransform(geoTrans) dataset.SetProjection(wkt_projection) dataset.GetRasterBand(1).WriteArray(T) Band = dataset.GetRasterBand(1) if pixeltype == 'float': Band.SetNoDataValue(-9999.0) elif pixeltype == 'int': Band.SetNoDataValue(-9999) dataset.FlushCache() # Write to disk. return