0
# Data Input/Output
1
2
MetPy provides robust I/O support for major meteorological file formats including GEMPAK surface/sounding/grid data, NEXRAD radar data, GINI satellite imagery, and METAR observations. All readers provide automatic format detection, metadata preservation, and seamless integration with the scientific Python ecosystem.
3
4
## Capabilities
5
6
### GEMPAK Data Formats
7
8
Complete support for GEMPAK surface, upper-air, and grid data formats used widely in meteorological operations and research.
9
10
```python { .api }
11
class GempakSurface:
12
"""
13
Read GEMPAK surface data files.
14
15
Provides access to surface meteorological observations stored in GEMPAK format
16
including station metadata, parameter definitions, and observation data.
17
"""
18
19
def __init__(self, file):
20
"""
21
Initialize GEMPAK surface data reader.
22
23
Parameters:
24
- file: path to GEMPAK surface file
25
"""
26
27
@property
28
def parameters(self):
29
"""Available parameters in the file."""
30
31
@property
32
def stations(self):
33
"""Station information and metadata."""
34
35
def gdxarray(self, parameter=None, station_id=None, date_time=None):
36
"""
37
Read data as xarray Dataset.
38
39
Parameters:
40
- parameter: parameter name to read
41
- station_id: specific station ID
42
- date_time: specific date/time
43
44
Returns:
45
xarray Dataset with observation data
46
"""
47
48
class GempakSounding:
49
"""
50
Read GEMPAK upper-air sounding data files.
51
52
Provides access to atmospheric profile data including mandatory and significant
53
levels, with support for multiple sounding types and station locations.
54
"""
55
56
def __init__(self, file):
57
"""
58
Initialize GEMPAK sounding data reader.
59
60
Parameters:
61
- file: path to GEMPAK sounding file
62
"""
63
64
@property
65
def parameters(self):
66
"""Available parameters in sounding data."""
67
68
@property
69
def stations(self):
70
"""Sounding station information."""
71
72
def gdxarray(self, station_id=None, date_time=None):
73
"""
74
Read sounding data as xarray Dataset.
75
76
Parameters:
77
- station_id: specific station ID
78
- date_time: specific date/time
79
80
Returns:
81
xarray Dataset with sounding profile data
82
"""
83
84
class GempakGrid:
85
"""
86
Read GEMPAK gridded data files.
87
88
Provides access to gridded meteorological analysis and forecast data
89
with full coordinate system and metadata support.
90
"""
91
92
def __init__(self, file):
93
"""
94
Initialize GEMPAK grid data reader.
95
96
Parameters:
97
- file: path to GEMPAK grid file
98
"""
99
100
@property
101
def parameters(self):
102
"""Available grid parameters."""
103
104
@property
105
def grid_info(self):
106
"""Grid coordinate system information."""
107
108
def gdxarray(self, parameter=None, date_time=None, level=None):
109
"""
110
Read grid data as xarray DataArray.
111
112
Parameters:
113
- parameter: parameter name to read
114
- date_time: specific date/time
115
- level: specific vertical level
116
117
Returns:
118
xarray DataArray with gridded data and coordinates
119
"""
120
```
121
122
### NEXRAD Radar Data
123
124
Support for NEXRAD Level 2 (base data) and Level 3 (derived products) radar data formats.
125
126
```python { .api }
127
class Level2File:
128
"""
129
Read NEXRAD Level 2 radar data files.
130
131
Provides access to base radar moments including reflectivity, velocity,
132
and spectrum width with full sweep and radial structure preservation.
133
"""
134
135
def __init__(self, file):
136
"""
137
Initialize Level 2 radar file reader.
138
139
Parameters:
140
- file: path to Level 2 radar file
141
"""
142
143
@property
144
def sweeps(self):
145
"""Available radar sweeps and their parameters."""
146
147
@property
148
def site_info(self):
149
"""Radar site location and configuration."""
150
151
def get_data(self, moment, sweep=0):
152
"""
153
Get radar moment data for specific sweep.
154
155
Parameters:
156
- moment: radar moment ('REF', 'VEL', 'SW', etc.)
157
- sweep: sweep number
158
159
Returns:
160
Radar data array with range/azimuth coordinates
161
"""
162
163
class Level3File:
164
"""
165
Read NEXRAD Level 3 radar product files.
166
167
Provides access to derived radar products including composite reflectivity,
168
precipitation estimates, and storm-relative products.
169
"""
170
171
def __init__(self, file):
172
"""
173
Initialize Level 3 radar file reader.
174
175
Parameters:
176
- file: path to Level 3 product file
177
"""
178
179
@property
180
def product_info(self):
181
"""Product metadata and specifications."""
182
183
@property
184
def site_info(self):
185
"""Radar site information."""
186
187
def get_data(self):
188
"""
189
Get product data.
190
191
Returns:
192
Product data array with appropriate coordinates
193
"""
194
```
195
196
### GINI Satellite Data
197
198
Support for GINI (GOES Ingest and NOAAPORT Interface) satellite data format.
199
200
```python { .api }
201
class GiniFile:
202
"""
203
Read GINI satellite data files.
204
205
Provides access to GOES satellite imagery and derived products with
206
full coordinate system and calibration information.
207
"""
208
209
def __init__(self, file):
210
"""
211
Initialize GINI file reader.
212
213
Parameters:
214
- file: path to GINI file
215
"""
216
217
@property
218
def metadata(self):
219
"""Satellite and product metadata."""
220
221
@property
222
def proj_info(self):
223
"""Map projection information."""
224
225
def get_data(self):
226
"""
227
Get satellite data.
228
229
Returns:
230
Satellite data array with geographic coordinates
231
"""
232
```
233
234
### METAR Observations
235
236
Parsing and processing of METAR (Meteorological Aerodrome Report) surface observations.
237
238
```python { .api }
239
def parse_metar_file(filename, year=None, month=None):
240
"""
241
Parse a file containing METAR observations.
242
243
Parameters:
244
- filename: path to METAR file
245
- year: year for date parsing (if not in METAR)
246
- month: month for date parsing (if not in METAR)
247
248
Returns:
249
List of parsed METAR observation dictionaries
250
"""
251
252
def parse_metar_to_dataframe(filename, year=None, month=None):
253
"""
254
Parse METAR file and return as pandas DataFrame.
255
256
Parameters:
257
- filename: path to METAR file
258
- year: year for date parsing
259
- month: month for date parsing
260
261
Returns:
262
pandas DataFrame with METAR observations and metadata
263
"""
264
```
265
266
## Usage Examples
267
268
### Reading GEMPAK Surface Data
269
270
```python
271
from metpy.io import GempakSurface
272
273
# Open GEMPAK surface file
274
sf = GempakSurface('surface_data.gem')
275
276
# Examine available parameters and stations
277
print("Parameters:", sf.parameters)
278
print("Stations:", sf.stations[:5]) # First 5 stations
279
280
# Read specific parameter as xarray Dataset
281
temp_data = sf.gdxarray(parameter='TMPF')
282
print(temp_data)
283
284
# Read data for specific station and time
285
denver_data = sf.gdxarray(station_id='KDEN', date_time='2023-01-15/12:00')
286
print(denver_data)
287
```
288
289
### Working with NEXRAD Level 2 Data
290
291
```python
292
from metpy.io import Level2File
293
import matplotlib.pyplot as plt
294
295
# Open Level 2 radar file
296
radar = Level2File('KFTG20230115_120000_V06')
297
298
# Get radar site information
299
print("Site:", radar.site_info)
300
print("Available sweeps:", radar.sweeps)
301
302
# Read reflectivity data for first sweep
303
ref_data = radar.get_data('REF', sweep=0)
304
print("Reflectivity shape:", ref_data.shape)
305
306
# Basic radar plot
307
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
308
ax.pcolormesh(ref_data.azimuth, ref_data.range, ref_data)
309
ax.set_title('Radar Reflectivity')
310
plt.show()
311
```
312
313
### Processing METAR Data
314
315
```python
316
from metpy.io import parse_metar_to_dataframe
317
import pandas as pd
318
319
# Parse METAR file to DataFrame
320
df = parse_metar_to_dataframe('metar_data.txt', year=2023, month=1)
321
322
# Examine the data structure
323
print(df.columns)
324
print(df.head())
325
326
# Filter and analyze
327
denver_obs = df[df['station_id'] == 'KDEN']
328
print(f"Denver observations: {len(denver_obs)}")
329
330
# Basic statistics
331
print("Temperature statistics:")
332
print(denver_obs['air_temperature'].describe())
333
```
334
335
### Reading Satellite Data
336
337
```python
338
from metpy.io import GiniFile
339
import matplotlib.pyplot as plt
340
341
# Open GINI satellite file
342
gini = GiniFile('goes_visible.gini')
343
344
# Get metadata and projection information
345
print("Metadata:", gini.metadata)
346
print("Projection:", gini.proj_info)
347
348
# Read satellite data
349
sat_data = gini.get_data()
350
print("Data shape:", sat_data.shape)
351
352
# Display satellite image
353
plt.figure(figsize=(10, 8))
354
plt.imshow(sat_data, origin='upper', cmap='gray')
355
plt.title('GOES Visible Imagery')
356
plt.colorbar(label='Digital Counts')
357
plt.show()
358
```
359
360
### Reading GEMPAK Grid Data
361
362
```python
363
from metpy.io import GempakGrid
364
import metpy.calc as mpcalc
365
366
# Open GEMPAK grid file
367
grid = GempakGrid('nam_analysis.gem')
368
369
# Check available parameters
370
print("Available parameters:", grid.parameters)
371
372
# Read 500 hPa geopotential height
373
hght_500 = grid.gdxarray(parameter='HGHT', level=500)
374
print(hght_500)
375
376
# Read temperature and calculate potential temperature
377
temp_500 = grid.gdxarray(parameter='TMPK', level=500)
378
theta = mpcalc.potential_temperature(500 * units.hPa, temp_500)
379
print("Potential temperature calculated")
380
```
381
382
## Integration with Scientific Python
383
384
### XArray Integration
385
386
All MetPy I/O classes provide native xarray output with proper coordinate systems and metadata.
387
388
```python
389
# GEMPAK data as xarray Dataset
390
sf = GempakSurface('surface.gem')
391
ds = sf.gdxarray()
392
393
# Automatic coordinate parsing with MetPy
394
ds = ds.metpy.parse_cf()
395
print("CRS:", ds.metpy.crs)
396
397
# Access coordinates by type
398
print("Time coordinate:", ds.metpy.time)
399
print("Spatial coordinates:", ds.metpy.x, ds.metpy.y)
400
```
401
402
### Units Integration
403
404
Data readers automatically apply appropriate units to meteorological variables.
405
406
```python
407
# Temperature data with units
408
temp_data = sf.gdxarray(parameter='TMPF')
409
print("Temperature units:", temp_data.metpy.units)
410
411
# Unit conversion
412
temp_celsius = temp_data.metpy.convert_units('celsius')
413
print("Converted to Celsius:", temp_celsius.metpy.units)
414
```
415
416
## Error Handling
417
418
```python
419
try:
420
sf = GempakSurface('nonexistent.gem')
421
except FileNotFoundError:
422
print("GEMPAK file not found")
423
except Exception as e:
424
print(f"Error reading GEMPAK file: {e}")
425
426
# Check for valid radar moments
427
radar = Level2File('radar.dat')
428
try:
429
ref_data = radar.get_data('REF', sweep=0)
430
except ValueError as e:
431
print(f"Reflectivity not available: {e}")
432
```
433
434
## Types
435
436
```python { .api }
437
from typing import Dict, List, Optional, Union
438
import xarray as xr
439
import pandas as pd
440
import numpy as np
441
442
# File path types
443
FilePath = Union[str, Path]
444
445
# Data return types
446
GempakData = xr.Dataset
447
RadarData = np.ndarray
448
SatelliteData = np.ndarray
449
MetarData = Union[List[Dict], pd.DataFrame]
450
451
# Metadata types
452
StationInfo = Dict[str, Union[str, float]]
453
ProductInfo = Dict[str, Union[str, int, float]]
454
```