File size: 6,186 Bytes
2df9cf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env python3
"""
Test script to demonstrate Arctic GRIB extraction for your specific error case
"""

import os
import sys
from arctic_integration import process_arctic_grib_safe, arctic_grib_handler

def test_arctic_file(grib_file_path):
    """
    Test the Arctic extraction on your specific problematic file
    """
    print("πŸ§ͺ Testing Arctic GRIB Extraction")
    print("=" * 50)
    print(f"File: {grib_file_path}")
    
    if not os.path.exists(grib_file_path):
        print(f"❌ File not found: {grib_file_path}")
        print("Please update the path to your Arctic GRIB file")
        return False
    
    try:
        print("\nπŸ”„ Starting extraction...")
        
        # This should work even with the ECCODES polar stereographic error
        data = process_arctic_grib_safe(grib_file_path, 'dataframe')
        
        print(f"\nβœ… SUCCESS! Extracted {len(data)} data points")
        print("\nπŸ“Š Data Summary:")
        print(f"  Columns: {list(data.columns)}")
        
        if 'latitude' in data.columns:
            print(f"  Latitude range: {data['latitude'].min():.3f}Β° to {data['latitude'].max():.3f}Β°")
        if 'longitude' in data.columns:
            print(f"  Longitude range: {data['longitude'].min():.3f}Β° to {data['longitude'].max():.3f}Β°")
        
        value_col = 'value' if 'value' in data.columns else 'val'
        if value_col in data.columns:
            print(f"  Data range: {data[value_col].min():.6f} to {data[value_col].max():.6f}")
            print(f"  Valid points: {data[value_col].notna().sum()}")
        
        print(f"\nπŸ“‹ First 5 data points:")
        print(data.head())
        
        # Save results
        csv_file = grib_file_path.replace('.grib2', '_EXTRACTED.csv')
        data.to_csv(csv_file, index=False)
        print(f"\nπŸ’Ύ Saved results to: {csv_file}")
        
        return True
        
    except Exception as e:
        print(f"❌ Extraction failed: {e}")
        import traceback
        traceback.print_exc()
        return False

def demonstrate_integration():
    """
    Show how to integrate this with your existing wave puller
    """
    print("\nπŸ”— Integration Example for your grib_wave_puller:")
    print("=" * 60)
    
    integration_code = '''
# Modify your existing Arctic processing code like this:

def process_arctic_region_fixed(grib_file):
    """Enhanced Arctic processing that handles ECCODES errors"""
    
    try:
        # Your existing Arctic processing code
        import xarray as xr
        ds = xr.open_dataset(grib_file, engine='cfgrib')
        # ... rest of your normal processing ...
        
    except Exception as e:
        error_msg = str(e)
        
        # Check if it's the polar stereographic error
        if any(keyword in error_msg.lower() for keyword in 
               ['polar stereographic', 'spherical earth', 'geoiterator']):
            
            print(f"ECCODES polar error detected: {error_msg}")
            print("Switching to alternative Arctic extraction...")
            
            # Use our Arctic extraction instead
            from arctic_integration import arctic_grib_handler
            
            try:
                result = arctic_grib_handler(grib_file)
                print(f"βœ… Successfully extracted {result['total_points']} Arctic points")
                
                # Convert to your expected format
                arctic_data = {
                    'latitudes': [coord[0] for coord in result['coordinates']],
                    'longitudes': [coord[1] for coord in result['coordinates']],
                    'values': result['data'],
                    'region': 'Arctic',
                    'extraction_method': 'polar_bypass'
                }
                
                return arctic_data
                
            except Exception as e2:
                print(f"❌ Arctic extraction also failed: {e2}")
                raise
        else:
            # Different error, re-raise
            raise

# Usage in your main wave puller:
try:
    arctic_data = process_arctic_region_fixed("/tmp/tmp0cvj_act.grib2")
    print("Arctic processing successful!")
    
except Exception as e:
    print(f"Arctic processing failed: {e}")
    # Continue with other regions...
'''
    
    print(integration_code)

def quick_demo():
    """
    Quick demonstration with sample file paths
    """
    # Common Arctic GRIB file paths from your error
    sample_files = [
        "/tmp/tmp0cvj_act.grib2",  # Your specific file
        "/tmp/tmpd7b9xfpo.grib2"   # Your Global file (for comparison)
    ]
    
    print("πŸš€ Quick Demo - Arctic GRIB Extraction")
    print("=" * 50)
    
    for grib_file in sample_files:
        print(f"\nπŸ“ Testing: {grib_file}")
        
        if os.path.exists(grib_file):
            print("File exists - testing extraction...")
            success = test_arctic_file(grib_file)
            if success:
                print("βœ… This file can now be processed successfully!")
            else:
                print("❌ Still having issues with this file")
        else:
            print("❓ File not found (this is expected if temp files are cleaned up)")
    
    # Show the integration approach
    demonstrate_integration()

if __name__ == "__main__":
    if len(sys.argv) > 1:
        # Test specific file provided as argument
        grib_file = sys.argv[1]
        test_arctic_file(grib_file)
    else:
        # Run the quick demo
        quick_demo()
        
        print("\n" + "=" * 60)
        print("🎯 TO USE WITH YOUR SPECIFIC ERROR:")
        print("=" * 60)
        print("1. Run: python test_arctic_extraction.py /tmp/tmp0cvj_act.grib2")
        print("2. Or modify your grib_wave_puller with the integration code above")
        print("3. The extraction will bypass ECCODES and get all lat/lon/data points")
        print("\nπŸ’‘ This solves:")
        print("   β€’ ECCODES ERROR: Polar stereographic Geoiterator")
        print("   β€’ Only supported for spherical earth")
        print("   β€’ Unable to create iterator")
        print("   β€’ Problem with calculation of geographic attributes")