scahpy 0.0.10__tar.gz → 0.0.11__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of scahpy might be problematic. Click here for more details.

Files changed (38) hide show
  1. {scahpy-0.0.10/scahpy.egg-info → scahpy-0.0.11}/PKG-INFO +2 -1
  2. {scahpy-0.0.10 → scahpy-0.0.11}/pyproject.toml +2 -1
  3. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/__init__.py +1 -1
  4. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/in_out.py +74 -34
  5. scahpy-0.0.11/scahpy/map_plots.py +279 -0
  6. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/met_diag.py +50 -17
  7. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/spatial_scales.py +1 -1
  8. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/temp_scales.py +18 -7
  9. {scahpy-0.0.10 → scahpy-0.0.11/scahpy.egg-info}/PKG-INFO +2 -1
  10. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy.egg-info/requires.txt +1 -0
  11. scahpy-0.0.10/scahpy/map_plots.py +0 -73
  12. {scahpy-0.0.10 → scahpy-0.0.11}/LICENSE +0 -0
  13. {scahpy-0.0.10 → scahpy-0.0.11}/MANIFEST.in +0 -0
  14. {scahpy-0.0.10 → scahpy-0.0.11}/README.md +0 -0
  15. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/colors_scales.py +0 -0
  16. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/SA_paises.dbf +0 -0
  17. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/SA_paises.prj +0 -0
  18. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/SA_paises.shp +0 -0
  19. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/SA_paises.shp.xml +0 -0
  20. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/SA_paises.shx +0 -0
  21. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/Z12.cpg +0 -0
  22. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/Z12.dbf +0 -0
  23. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/Z12.prj +0 -0
  24. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/Z12.shp +0 -0
  25. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/Z12.shx +0 -0
  26. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/__init__.py +0 -0
  27. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/estaciones_test.cpg +0 -0
  28. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/estaciones_test.dbf +0 -0
  29. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/estaciones_test.prj +0 -0
  30. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/estaciones_test.qmd +0 -0
  31. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/estaciones_test.shp +0 -0
  32. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/estaciones_test.shx +0 -0
  33. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/geo_em.d01.nc +0 -0
  34. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy/data/geo_em.d02.nc +0 -0
  35. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy.egg-info/SOURCES.txt +0 -0
  36. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy.egg-info/dependency_links.txt +0 -0
  37. {scahpy-0.0.10 → scahpy-0.0.11}/scahpy.egg-info/top_level.txt +0 -0
  38. {scahpy-0.0.10 → scahpy-0.0.11}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: scahpy
3
- Version: 0.0.10
3
+ Version: 0.0.11
4
4
  Summary: Package to process and analyze outputs from IGP-RESM-COW model
5
5
  Author-email: Fiorela Castillón <fv.castillon@gmail.com>
6
6
  License: GNU GENERAL PUBLIC LICENSE
@@ -689,6 +689,7 @@ License-File: LICENSE
689
689
  Requires-Dist: wrf-python
690
690
  Requires-Dist: netCDF4
691
691
  Requires-Dist: xarray
692
+ Requires-Dist: dask
692
693
  Requires-Dist: numpy
693
694
  Requires-Dist: pandas
694
695
  Requires-Dist: matplotlib
@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
6
6
 
7
7
  [project]
8
8
  name = "scahpy"
9
- version = "0.0.10"
9
+ version = "0.0.11"
10
10
  description = "Package to process and analyze outputs from IGP-RESM-COW model"
11
11
  readme = "README.md"
12
12
  authors = [{ name = "Fiorela Castillón", email = "fv.castillon@gmail.com" }]
@@ -22,6 +22,7 @@ dependencies = [
22
22
  'wrf-python',
23
23
  'netCDF4',
24
24
  'xarray',
25
+ 'dask',
25
26
  'numpy',
26
27
  'pandas',
27
28
  'matplotlib',
@@ -9,4 +9,4 @@ __all__ = [
9
9
  ]
10
10
 
11
11
  # Version of scahpy package
12
- __version__ = "0.0.10"
12
+ __version__ = "0.0.11"
@@ -127,50 +127,90 @@ def _select_time(x,difHor,sign):
127
127
  d=d.assign_coords({'time':time2})
128
128
  return d
129
129
 
130
- def ds_wrf_multi(files,list_no_vars,difHor=0,sign=1):
131
- """Read a list of wrfout files for the variables selected.
132
- ES: Lee una lista de archivos wrfout para las variables seleccionadas.
130
+ def ds_wrf_multi(files, list_no_vars, difHor=0, sign=1, save_path=None):
131
+ """
132
+ Read a list of wrfout files for the selected variables and optionally save the resulting netCDF file.
133
133
 
134
- Parameters/Parametros:
135
- ----------------------
136
- files : List of wrfout files / Lista de archivos wrfout
137
- list_no_vars : List of variables to be delated / Lista de variables a ignorar
138
- difHor : String with the hours t / Lista de variables a mantener
139
- sign: -1 or 1 according to the difference / +1 o -1 dependiendo de
140
- la diferencia horaria respecto a la UTC
134
+ Parameters:
135
+ -----------
136
+ files : list of str
137
+ List of paths to wrfout files.
138
+ list_no_vars : list
139
+ List of variables to be excluded.
140
+ difHor : str, optional
141
+ String with the hour difference.
142
+ sign : int, optional
143
+ -1 or 1 according to the difference.
144
+ save_path : str, optional
145
+ Path to save the resulting netCDF file.
146
+
147
+ Returns:
148
+ --------
149
+ ds1 : xarray.Dataset
150
+ Dataset containing the selected variables.
141
151
  """
142
- ds = xr.open_mfdataset(files, combine='nested', concat_dim='time', parallel= True ,engine='netcdf4',
143
- drop_variables=list_no_vars, preprocess = partial(_select_time,difHor=difHor,sign=sign))
144
- ds.attrs = []
152
+ # Read the wrfout files and drop specified variables
153
+ ds = xr.open_mfdataset(files, combine='nested', concat_dim='time', parallel=True, engine='netcdf4',
154
+ drop_variables=list_no_vars, preprocess=partial(_select_time, difHor=difHor, sign=sign))
155
+
156
+ # Remove duplicate times
145
157
  _, index = np.unique(ds['time'], return_index=True)
146
158
  ds = ds.isel(time=index)
147
- ds1 = _new_coords(files[0],ds)
148
- ds1.encoding['unlimited_dims']=('time',)
149
-
150
- return ds1
151
159
 
152
- def ds_wrf_single(file,list_no_vars,difHor=0,sign=1):
153
- """Read a list of wrfout files for the variables selected.
154
- ES: Lee una lista de archivos wrfout para las variables seleccionadas.
160
+ # Update coordinates and encoding
161
+ ds1 = _new_coords(files[0], ds)
162
+ ds1.encoding['unlimited_dims'] = ('time',)
155
163
 
156
- Parameters/Parametros:
157
- ----------------------
158
- files : wrfout file / archivo wrfout
159
- list_no_vars : List of variables to be delated / Lista de variables a ignorar
160
- difHor : String with the hours t / Lista de variables a mantener
161
- sign: -1 or 1 according to the difference / +1 o -1 dependiendo de
162
- la diferencia horaria respecto a la UTC
164
+ # Optionally save the resulting netCDF file
165
+ if save_path is not None:
166
+ ds1.to_netcdf(save_path)
167
+
168
+ return ds1
169
+
170
+
171
+ def ds_wrf_single(file, list_no_vars, difHor=0, sign=1, save_path=None):
172
+ """
173
+ Read a list of wrfout files for the selected variables and optionally save the resulting netCDF file.
174
+
175
+ Parameters:
176
+ -----------
177
+ file : str
178
+ Path to the wrfout file.
179
+ list_no_vars : list
180
+ List of variables to be excluded.
181
+ difHor : str, optional
182
+ String with the hour difference.
183
+ sign : int, optional
184
+ -1 or 1 according to the difference.
185
+ save_path : str, optional
186
+ Path to save the resulting netCDF file.
187
+
188
+ Returns:
189
+ --------
190
+ ds2 : xarray.Dataset
191
+ Dataset containing the selected variables.
163
192
  """
164
- ds = xr.open_dataset(file,engine='netcdf4', drop_variables=list_no_vars)
165
- ds1 = ds.rename({'XTIME':'time'}).swap_dims({'Time':'time'})
166
- time2=pd.to_datetime(ds1.time.values) + (sign*pd.Timedelta(difHor))
167
- ds1=ds1.assign_coords({'time':time2})
193
+ # Read the wrfout file(s) and drop specified variables
194
+ ds = xr.open_dataset(file, engine='netcdf4', drop_variables=list_no_vars)
195
+
196
+ # Rename and manipulate time coordinate
197
+ ds1 = ds.rename({'XTIME': 'time'}).swap_dims({'Time': 'time'})
198
+ time2 = pd.to_datetime(ds1.time.values) + (sign * pd.Timedelta(difHor))
199
+ ds1 = ds1.assign_coords({'time': time2})
168
200
  ds1.attrs = []
201
+
202
+ # Remove duplicate times
169
203
  _, index = np.unique(ds1['time'], return_index=True)
170
204
  ds1 = ds1.isel(time=index)
171
- ds2 = _new_coords(file,ds1)
172
- ds2.encoding['unlimited_dims']=('time',)
173
-
205
+
206
+ # Update coordinates and encoding
207
+ ds2 = _new_coords(file, ds1)
208
+ ds2.encoding['unlimited_dims'] = ('time',)
209
+
210
+ # Optionally save the resulting netCDF file
211
+ if save_path is not None:
212
+ ds2.to_netcdf(save_path)
213
+
174
214
  return ds2
175
215
 
176
216
 
@@ -0,0 +1,279 @@
1
+ import matplotlib.pyplot as plt
2
+ import numpy as np
3
+ import cartopy.crs as ccrs
4
+ import cartopy.feature as cfe
5
+ from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
6
+ from cartopy.io.shapereader import Reader
7
+ import cmocean
8
+ import matplotlib.colors
9
+ import importlib.resources
10
+ from pathlib import Path
11
+
12
+ def map_pp_uv10_sst(pp, sfc, levs, levs2, shapefile=None, output_path=None, save_maps=True, freq=None,
13
+ quiverkey_speed=5,extent=None):
14
+ """
15
+ Plots precipitation maps for specified months.
16
+
17
+ Parameters:
18
+ - pp (xarray.Dataset): Precipitation data.
19
+ - sfc (xarray.Dataset): Surface data with SST and UV10 data.
20
+ - levs (list): Contour levels for precipitation.
21
+ - levs2 (list): Contour levels for SSTSK.
22
+ - shapefile (str): Path to the shapefile for South America countries (could be any other).
23
+ - output_path (str, optional): Path to save the maps. If None, maps will be displayed but not saved. Defaults to None.
24
+ - freq (str): Could be 'H' , 'D', 'M', 'Y'. Defaults to Hourly ('H').
25
+ - save_maps (bool, optional): If True, saves the maps. If False, only displays them. Defaults to True.
26
+ - quiverkey_speed (int, optional): Speed parameter for quiverkey. Defaults to 5.
27
+ - extent: [x1,x2,y1,y2] spatial extension
28
+ """
29
+ if shapefile is None:
30
+ data_dir = importlib.resources.files('scahpy.data')
31
+ data_path = Path(data_dir , 'SA_paises.shp')
32
+ sa = cfe.ShapelyFeature(Reader(data_path).geometries(), ccrs.PlateCarree(), edgecolor='k', facecolor='none')
33
+ else:
34
+ sa = cfe.ShapelyFeature(Reader(shapefile).geometries(), ccrs.PlateCarree(), edgecolor='k', facecolor='none')
35
+
36
+ if extent is None:
37
+ extent = [-93.8, -68, -21.9, 4.1]
38
+
39
+ cmaps = cmocean.tools.lighten(cmocean.cm.rain, 0.85)
40
+ norm = matplotlib.colors.BoundaryNorm(levs, cmaps.N)
41
+
42
+ lons = pp.lon.values
43
+ lats = pp.lat.values
44
+ times = np.datetime_as_string(sfc.time.values,unit='m')
45
+
46
+ for i in range(len(times)):
47
+ if freq == 'H' or freq is None:
48
+ timess = times[i][0:13]
49
+ elif freq == 'D':
50
+ timess = times[i][0:10]
51
+ elif freq == 'M':
52
+ timess = times[i][0:7]
53
+ elif freq == 'Y':
54
+ timess = times[i][0:4]
55
+
56
+ fig, axs = plt.subplots(figsize=(13, 12), ncols=1, nrows=1, sharex=True, sharey=True,
57
+ subplot_kw=dict(projection=ccrs.PlateCarree()))
58
+
59
+ pcm = axs.contourf(lons, lats, pp.sel(time=timess), levels=levs,
60
+ cmap=cmaps, norm=norm, extend='both', transform=ccrs.PlateCarree())
61
+ fig.colorbar(pcm, ax=axs, label='mm', orientation='vertical', shrink=.7, pad=0.07, aspect=20, format='%3.0f')
62
+ c = axs.contour(lons, lats, sfc.get('SSTSK').sel(time=timess),
63
+ levels=levs2, colors=['#F29727', '#C70039', '#511F73'],
64
+ linewidths=[1.5, 1.6, 1.8], linestyles='solid',
65
+ alpha=0.45, transform=ccrs.PlateCarree(), zorder=7)
66
+ axs.clabel(c, levels=levs2, inline=False, colors='#000000', fontsize=12, zorder=9)
67
+ Q = axs.quiver(lons[::7], lats[::7],
68
+ sfc.U10.sel(time=timess)[::7, ::7], sfc.V10.sel(time=timess)[::7, ::7],
69
+ headwidth=5, headlength=7)
70
+ axs.quiverkey(Q, 0.87, 1.02, quiverkey_speed, f'{quiverkey_speed} m/s', labelpos='E', coordinates='axes', labelsep=0.05)
71
+
72
+ axs.add_feature(sa, linewidth=0.7, zorder=7)
73
+ lon_formatter = LongitudeFormatter()
74
+ lat_formatter = LatitudeFormatter()
75
+ axs.yaxis.set_major_formatter(lat_formatter)
76
+ axs.xaxis.set_major_formatter(lon_formatter)
77
+ axs.set_extent(extent)
78
+
79
+ plt.title(f'Map of Precipitation : {timess}')
80
+
81
+ if save_maps:
82
+ if output_path is None:
83
+ raise ValueError("Output path cannot be None when saving maps.")
84
+ plt.savefig(f'{output_path}/m_TSM_UV_PP_{timess}.png',
85
+ bbox_inches='tight', dpi=300, facecolor='white', transparent=False)
86
+ else:
87
+ plt.show()
88
+
89
+ plt.close()
90
+
91
+ def map_clim_pp_uv10_sst(pp, sfc, levs, levs2, shapefile, output_path=None, month_list=None,
92
+ save_maps=True, quiverkey_speed=5,extent=None):
93
+ """
94
+ Plots precipitation maps for specified months.
95
+
96
+ Parameters:
97
+ - pp (xarray.Dataset): Precipitation data.
98
+ - sfc (xarray.Dataset): Surface data with SST and UV10 data.
99
+ - levs (list): Contour levels for precipitation.
100
+ - levs2 (list): Contour levels for SSTSK.
101
+ - shapefile (str): Path to the shapefile for South America countries (could be any other).
102
+ - output_path (str, optional): Path to save the maps. If None, maps will be displayed but not saved. Defaults to None.
103
+ - month_list (list, optional): List of months to plot. Defaults to None (all months).
104
+ - save_maps (bool, optional): If True, saves the maps. If False, only displays them. Defaults to True.
105
+ - quiverkey_speed (int, optional): Speed parameter for quiverkey. Defaults to 5.
106
+ - extent: [x1,x2,y1,y2] spatial extension
107
+ """
108
+ if shapefile is None:
109
+ data_dir = importlib.resources.files('scahpy.data')
110
+ data_path = Path(data_dir , 'SA_paises.shp')
111
+ sa = cfe.ShapelyFeature(Reader(data_path).geometries(), ccrs.PlateCarree(), edgecolor='k', facecolor='none')
112
+ else:
113
+ sa = cfe.ShapelyFeature(Reader(shapefile).geometries(), ccrs.PlateCarree(), edgecolor='k', facecolor='none')
114
+
115
+ if extent is None:
116
+ extent = [-93.8, -68, -21.9, 4.1]
117
+
118
+ cmaps = cmocean.tools.lighten(cmocean.cm.rain, 0.85)
119
+ norm = matplotlib.colors.BoundaryNorm(levs, cmaps.N)
120
+
121
+ lons = pp.lon.values
122
+ lats = pp.lat.values
123
+
124
+
125
+
126
+ if month_list is None:
127
+ month_list = range(1, 13)
128
+
129
+ for month in month_list:
130
+ fig, axs = plt.subplots(figsize=(13, 12), ncols=1, nrows=1, sharex=True, sharey=True,
131
+ subplot_kw=dict(projection=ccrs.PlateCarree()))
132
+
133
+ pcm = axs.contourf(lons, lats, pp.sel(month=month), levels=levs,
134
+ cmap=cmaps, norm=norm, extend='both', transform=ccrs.PlateCarree())
135
+ fig.colorbar(pcm, ax=axs, label='mm/month', orientation='vertical', shrink=.7, pad=0.07, aspect=20, format='%3.0f')
136
+ c = axs.contour(lons, lats, sfc.get('SSTSK').sel(month=month),
137
+ levels=levs2, colors=['#F29727', '#C70039', '#511F73'],
138
+ linewidths=[1.5, 1.6, 1.8], linestyles='solid',
139
+ alpha=0.45, transform=ccrs.PlateCarree(), zorder=7)
140
+ axs.clabel(c, levels=levs2, inline=False, colors='#000000', fontsize=12, zorder=9)
141
+ Q = axs.quiver(lons[::7], lats[::7],
142
+ sfc.U10.sel(month=month)[::7, ::7], sfc.V10.sel(month=month)[::7, ::7],
143
+ headwidth=5, headlength=7)
144
+ axs.quiverkey(Q, 0.87, 1.02, quiverkey_speed, f'{quiverkey_speed} m/s', labelpos='E', coordinates='axes', labelsep=0.05)
145
+
146
+ axs.add_feature(sa, linewidth=0.7, zorder=7)
147
+ lon_formatter = LongitudeFormatter()
148
+ lat_formatter = LatitudeFormatter()
149
+ axs.yaxis.set_major_formatter(lat_formatter)
150
+ axs.xaxis.set_major_formatter(lon_formatter)
151
+ axs.set_extent(extent)
152
+
153
+ plt.title(f'Map of Precipitation Month: {month:02d}')
154
+
155
+ if save_maps:
156
+ if output_path is None:
157
+ raise ValueError("Output path cannot be None when saving maps.")
158
+ plt.savefig(f'{output_path}/m_TSM_UV_PP_{month}.png',
159
+ bbox_inches='tight', dpi=300, facecolor='white', transparent=False)
160
+ else:
161
+ plt.show()
162
+
163
+ plt.close()
164
+
165
+ def cross_section_yz(ds,vari,levs,cmaps,title,quiverkey_speed=5,
166
+ output_path=None, freq=None, save_maps=True):
167
+ """
168
+ Plots Cross Sections of Pressure level variables in YZ direction.
169
+
170
+ Parameters:
171
+ - ds (xarray.Dataset): wrfout data already interpolated to pressure levels (output from spatial_scales.vert_levs()).
172
+ - vari (list): List of variables to plot including V and W.
173
+ - levs (list): Contour levels for variable.
174
+ - title (str): Title to display in the graph.
175
+ - output_path (str, optional): Path to save the maps. If None, maps will be displayed but not saved. Defaults to None.
176
+ - freq (str): Could be 'H' , 'D', 'M', 'Y'. Defaults to Hourly ('H').
177
+ - save_maps (bool, optional): If True, saves the maps. If False, only displays them. Defaults to True.
178
+ - quiverkey_speed (int, optional): Speed parameter for quiverkey. Defaults to 5.
179
+ """
180
+
181
+ lats = ds.lat.values
182
+ times = np.datetime_as_string(ds.time.values,unit='m')
183
+ Y=ds.level.values
184
+
185
+ norms = matplotlib.colors.BoundaryNorm(levs, cmaps.N)
186
+ plt.rcParams['font.family'] = 'Monospace'
187
+
188
+ if freq == 'H' or freq is None:
189
+ j=13
190
+ elif freq == 'D':
191
+ j=10
192
+ elif freq == 'M':
193
+ j=7
194
+ elif freq == 'Y':
195
+ j=4
196
+
197
+ for i in range(len(times)):
198
+
199
+ timess = times[i][0:j]
200
+
201
+ vv=ds.get('V').sel(time=timess)
202
+ ww=ds.get('W').sel(time=timess)*1000
203
+ var=ds.get(vari).sel(time=timess) #(g/kg)
204
+
205
+ fig,axs = plt.subplots(figsize=(6,10),ncols=1,nrows=1)
206
+ pcm=axs.contourf(lats, Y, var,levels=levs,cmap=cmaps,norm=norms,extend='both')
207
+ fig.colorbar(pcm,ax=axs,label='', orientation='horizontal', shrink=.9,pad=0.04,aspect=25,format='%3.1f')
208
+ Q=axs.quiver(lats[::4],Y,vv[::,::4],ww[::,::4],scale=170,headwidth=4,headlength=4)
209
+ axs.invert_yaxis()
210
+ axs.quiverkey(Q,0.87,0.98,quiverkey_speed, f'{quiverkey_speed} m/s',labelpos='E',coordinates='axes',labelsep=0.05)
211
+ plt.title(f'{title} {timess}',loc='center')
212
+
213
+ if save_maps:
214
+ if output_path is None:
215
+ raise ValueError("Output path cannot be None when saving maps.")
216
+ plt.savefig(f'{output_path}/Cross_Section_YZ_{var}_{timess}.png',
217
+ bbox_inches='tight', dpi=300, facecolor='white', transparent=False)
218
+ else:
219
+ plt.show()
220
+
221
+ plt.close()
222
+
223
+ def cross_section_xz(ds,vari,levs,cmaps,title,quiverkey_speed=5,
224
+ output_path=None, freq=None, save_maps=True):
225
+ """
226
+ Plots Cross Sections of Pressure level variables in XZ direction.
227
+
228
+ Parameters:
229
+ - ds (xarray.Dataset): wrfout data already interpolated to pressure levels (output from spatial_scales.vert_levs()).
230
+ - vari (list): List of variables to plot including V and W.
231
+ - levs (list): Contour levels for variable.
232
+ - title (str): Title to display in the graph.
233
+ - output_path (str, optional): Path to save the maps. If None, maps will be displayed but not saved. Defaults to None.
234
+ - freq (str): Could be 'H' , 'D', 'M', 'Y'. Defaults to Hourly ('H').
235
+ - save_maps (bool, optional): If True, saves the maps. If False, only displays them. Defaults to True.
236
+ - quiverkey_speed (int, optional): Speed parameter for quiverkey. Defaults to 5.
237
+ """
238
+
239
+ lons = ds.lon.values
240
+ times = np.datetime_as_string(ds.time.values,unit='m')
241
+ Y=ds.level.values
242
+
243
+ norms = matplotlib.colors.BoundaryNorm(levs, cmaps.N)
244
+ plt.rcParams['font.family'] = 'Monospace'
245
+
246
+ if freq == 'H' or freq is None:
247
+ j=13
248
+ elif freq == 'D':
249
+ j=10
250
+ elif freq == 'M':
251
+ j=7
252
+ elif freq == 'Y':
253
+ j=4
254
+
255
+ for i in range(len(times)):
256
+
257
+ timess = times[i][0:j]
258
+
259
+ uu=ds.get('U').sel(time=timess)
260
+ ww=ds.get('W').sel(time=timess)*1000
261
+ var=ds.get(vari).sel(time=timess) #(g/kg)
262
+
263
+ fig,axs = plt.subplots(figsize=(6,10),ncols=1,nrows=1)
264
+ pcm=axs.contourf(lons, Y, var,levels=levs,cmap=cmaps,norm=norms,extend='both')
265
+ fig.colorbar(pcm,ax=axs,label='', orientation='horizontal', shrink=.9,pad=0.04,aspect=25,format='%3.1f')
266
+ Q=axs.quiver(lons[::4],Y,uu[::,::4],ww[::,::4],scale=170,headwidth=4,headlength=4)
267
+ axs.invert_yaxis()
268
+ axs.quiverkey(Q,0.87,0.98,quiverkey_speed, f'{quiverkey_speed} m/s',labelpos='E',coordinates='axes',labelsep=0.05)
269
+ plt.title(f'{title} {timess}',loc='center')
270
+
271
+ if save_maps:
272
+ if output_path is None:
273
+ raise ValueError("Output path cannot be None when saving maps.")
274
+ plt.savefig(f'{output_path}/Cross_Section_XZ_{var}_{timess}.png',
275
+ bbox_inches='tight', dpi=300, facecolor='white', transparent=False)
276
+ else:
277
+ plt.show()
278
+
279
+ plt.close()
@@ -1,29 +1,47 @@
1
1
  import numpy as np
2
2
  import xarray as xr
3
3
 
4
- def calc_pp(ds,elim=False):
5
- """ de-acumulate the rainfall and save it as PP.
6
- ES: Calcula la precipitación nominal en el tiempo de salida (ej. 3hr, etc),
7
- es decir desacumula la precipitación líquida y la guarda como 'PP'.
8
-
9
- Parameters/Parámetros:
10
- ----------------------
11
- ds : dataset with the variables RAINC, RAINNC and RAINSH already loaded with
12
- coordinates already processed / dataset con las variables RAINC, RAINNC and RAINSH
13
- ya cargado con las coordenadas apropiadas.
4
+ def calc_pp(ds, vars_to_sum=['RAINC', 'RAINNC', 'RAINSH'], elim=False):
5
+ """Calculate precipitation nominal at the output time (e.g., 3hr, etc).
6
+ De-accumulate liquid precipitation and save it as 'PP'.
7
+
8
+ Parameters:
9
+ -----------
10
+ ds : xarray.Dataset
11
+ Dataset with the variables RAINC, RAINNC, and RAINSH already loaded and processed coordinates.
12
+
13
+ vars_to_sum : list of str, optional
14
+ List of variables to be summed for precipitation calculation (default is ['RAINC', 'RAINNC', 'RAINSH']).
15
+
16
+ elim : bool, optional
17
+ If True, eliminates intermediate variables after calculation (default is False).
18
+
19
+ Returns:
20
+ --------
21
+ ds : xarray.Dataset
22
+ Dataset with calculated precipitation 'PP'.
23
+
24
+ Example:
25
+ ---------
26
+ # Calculate precipitation with default settings (sum of RAINC, RAINNC, and RAINSH)
27
+ ds = calc_pp(ds)
28
+
29
+ # Calculate precipitation using only RAINC and RAINNC
30
+ ds = calc_pp(ds, vars_to_sum=['RAINC', 'RAINNC'])
14
31
  """
15
32
  ntime = ds.time[0:-1]
16
- ds['PP2'] = ds['RAINC'] + ds['RAINNC'] + ds['RAINSH']
33
+ # Calculate precipitation based on the sum of specified variables
34
+ ds['PP2'] = sum(ds[var] for var in vars_to_sum)
17
35
 
18
- dd=ds['PP2'].diff('time')
36
+ # De-accumulate precipitation and save it as 'PP'
37
+ dd = ds['PP2'].diff('time')
19
38
  dd['time'] = ntime
20
39
 
21
- ds['PP'] = dd
22
-
23
- if elim==True:
24
- ds=ds.drop_vars(['PP2','RAINC','RAINNC','RAINSH'])
40
+ # Drop intermediate variables if elim is True
41
+ if elim:
42
+ ds = ds.drop_vars(['PP2'] + vars_to_sum)
25
43
  else:
26
- ds=ds.drop_vars(['PP2'])
44
+ ds = ds.drop_vars(['PP2'])
27
45
 
28
46
  return ds
29
47
 
@@ -98,4 +116,19 @@ def calc_qe(ds,elim=False):
98
116
  ds=ds.drop_vars(['QVAPOR'])
99
117
 
100
118
  return ds
119
+
120
+ def calc_celsius(ds,var):
121
+ """ Calculate de conversion from Kelvin to Celsius'
122
+
123
+ K-273.15 = C
124
+
125
+ Parameters/Parámetros:
126
+ ----------------------
127
+ ds : dataset with the SSTSK variable/ dataset con las variables U10 and V10
128
+ ya cargado con las coordenadas apropiadas.
129
+ """
130
+
131
+ ds[var]=ds[var]-273.15
132
+
133
+ return ds
101
134
 
@@ -29,7 +29,7 @@ def vert_levs(ds,varis,lvls=None):
29
29
  dlvl[var].attrs['vert_units'] = ''
30
30
  dlvl[var].encoding['coordinates'] = 'time lat lon'
31
31
  datasets.append(dlvl)
32
- ds_lvl = xr.concat(datasets,dim='time')
32
+ ds_lvl = xr.merge(datasets)
33
33
  ds_lvl.encoding['unlimited_dims']=('time',)
34
34
  ds_lvl['lat'].attrs = {"units": 'degrees_north', 'axis': 'Y','long_name':'Latitude','standard_name':'latitude'}
35
35
  ds_lvl['lon'].attrs = {"units": 'degrees_east', 'axis': 'X','long_name':'Longitude','standard_name':'longitude'}
@@ -1,7 +1,7 @@
1
1
  import xarray as xr
2
2
  import numpy as np
3
3
 
4
- def dmy_var(ds,tiempo=None ,accum=None, avg=None, mediana=None):
4
+ def dmy_var(ds, tiempo=None, accum=None, avg=None, mediana=None):
5
5
  """Convert hourly (default wrf out) time to any acceptable by resample function.
6
6
  ES: Convierte los datos horarios (por defecto wrfout) a otra escala de tiempo
7
7
  aceptada por la función resample (ejm. 'D' diario, 'M' mensual, etc)
@@ -15,19 +15,30 @@ def dmy_var(ds,tiempo=None ,accum=None, avg=None, mediana=None):
15
15
  mediana : if True use the median function / Si es True, emplea la función mediana
16
16
  """
17
17
 
18
+ datasets = []
19
+
18
20
  if accum is not None:
19
- ds_ac = ds[accum].resample(time = tiempo).sum()
21
+ ds_ac = ds[accum].resample(time=tiempo).sum()
22
+ datasets.append(ds_ac)
23
+
20
24
  if avg is not None:
21
- ds_avg = ds[avg].resample(time = tiempo).mean()
25
+ ds_avg = ds[avg].resample(time=tiempo).mean()
26
+ datasets.append(ds_avg)
27
+
22
28
  if mediana is not None:
23
- ds_med = ds[mediana].resample(time = tiempo).median()
29
+ ds_med = ds[mediana].resample(time=tiempo).median()
30
+ datasets.append(ds_med)
31
+
32
+ if not datasets: # If no datasets were created
33
+ print('Ingrese al menos una variable para operar.')
34
+ return None
24
35
 
25
36
  try:
26
- datasets = [ds_ac, ds_avg, ds_med]
27
37
  ds_all = xr.concat(datasets, dim='time')
28
- except:
38
+ except ValueError:
39
+ print('Coloque una escala temporal apropiada')
40
+ return None
29
41
 
30
- print('coloque una escala temporal apropiada')
31
42
  return ds_all
32
43
 
33
44
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: scahpy
3
- Version: 0.0.10
3
+ Version: 0.0.11
4
4
  Summary: Package to process and analyze outputs from IGP-RESM-COW model
5
5
  Author-email: Fiorela Castillón <fv.castillon@gmail.com>
6
6
  License: GNU GENERAL PUBLIC LICENSE
@@ -689,6 +689,7 @@ License-File: LICENSE
689
689
  Requires-Dist: wrf-python
690
690
  Requires-Dist: netCDF4
691
691
  Requires-Dist: xarray
692
+ Requires-Dist: dask
692
693
  Requires-Dist: numpy
693
694
  Requires-Dist: pandas
694
695
  Requires-Dist: matplotlib
@@ -1,6 +1,7 @@
1
1
  wrf-python
2
2
  netCDF4
3
3
  xarray
4
+ dask
4
5
  numpy
5
6
  pandas
6
7
  matplotlib
@@ -1,73 +0,0 @@
1
- import matplotlib.pyplot as plt
2
- import numpy as np
3
- import cartopy.crs as ccrs
4
- import cartopy.feature as cfe
5
- from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
6
- from cartopy.io.shapereader import Reader
7
- import cmocean
8
- import matplotlib.colors
9
-
10
- def m_pp_uv10_sst(pp, sfc, levs, levs2, sa_shapefile, output_path=None, month_list=None,
11
- save_maps=True, quiverkey_speed=5,extent=None):
12
- """
13
- Plots precipitation maps for specified months.
14
-
15
- Parameters:
16
- - pp (xarray.Dataset): Precipitation data.
17
- - sfc (xarray.Dataset): Surface data with SST and UV10 data.
18
- - levs (list): Contour levels for precipitation.
19
- - levs2 (list): Contour levels for SSTSK.
20
- - sa_shapefile (str): Path to the shapefile for South America countries (could be any other).
21
- - output_path (str, optional): Path to save the maps. If None, maps will be displayed but not saved. Defaults to None.
22
- - month_list (list, optional): List of months to plot. Defaults to None (all months).
23
- - save_maps (bool, optional): If True, saves the maps. If False, only displays them. Defaults to True.
24
- - quiverkey_speed (int, optional): Speed parameter for quiverkey. Defaults to 5.
25
- - extent: [x1,x2,y1,y2] spatial extension
26
- """
27
- cmaps = cmocean.tools.lighten(cmocean.cm.rain, 0.85)
28
- norm = matplotlib.colors.BoundaryNorm(levs, cmaps.N)
29
-
30
- lons = pp.lon.values
31
- lats = pp.lat.values
32
-
33
- sa = cfe.ShapelyFeature(Reader(sa_shapefile).geometries(), ccrs.PlateCarree(), edgecolor='k', facecolor='none')
34
-
35
- if month_list is None:
36
- month_list = range(1, 13)
37
-
38
- for month in month_list:
39
- fig, axs = plt.subplots(figsize=(13, 12), ncols=1, nrows=1, sharex=True, sharey=True,
40
- subplot_kw=dict(projection=ccrs.PlateCarree()))
41
-
42
- pcm = axs.contourf(lons, lats, pp.sel(month=month), levels=levs,
43
- cmap=cmaps, norm=norm, extend='both', transform=ccrs.PlateCarree())
44
- fig.colorbar(pcm, ax=axs, label='mm/month', orientation='vertical', shrink=.7, pad=0.07, aspect=20, format='%3.0f')
45
- c = axs.contour(lons, lats, sfc.get('SSTSK').sel(month=month),
46
- levels=levs2, colors=['#F29727', '#C70039', '#511F73'],
47
- linewidths=[1.5, 1.6, 1.8], linestyles='solid',
48
- alpha=0.45, transform=ccrs.PlateCarree(), zorder=7)
49
- axs.clabel(c, levels=levs2, inline=False, colors='#000000', fontsize=12, zorder=9)
50
- Q = axs.quiver(lons[::7], lats[::7],
51
- sfc.U10.sel(month=month)[::7, ::7], sfc.V10.sel(month=month)[::7, ::7],
52
- headwidth=5, headlength=7)
53
- axs.quiverkey(Q, 0.87, 1.02, quiverkey_speed, f'{quiverkey_speed} m/s', labelpos='E', coordinates='axes', labelsep=0.05)
54
-
55
- axs.add_feature(sa, linewidth=0.7, zorder=7)
56
- lon_formatter = LongitudeFormatter()
57
- lat_formatter = LatitudeFormatter()
58
- axs.yaxis.set_major_formatter(lat_formatter)
59
- axs.xaxis.set_major_formatter(lon_formatter)
60
- axs.set_extent(extent)
61
-
62
- plt.title(f'Map of Precipitation Month: {month:02d}')
63
-
64
- if save_maps:
65
- if output_path is None:
66
- raise ValueError("Output path cannot be None when saving maps.")
67
- plt.savefig(f'{output_path}/m_TSM_UV_PP_{month}.png',
68
- bbox_inches='tight', dpi=300, facecolor='white', transparent=False)
69
- else:
70
- plt.show()
71
-
72
- plt.close()
73
-
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes