CoolFace
Apppublic

nakas/NWPS_SWAN

sourceHugging Facegpl-3.0updated 1y agoView on Hugging Face
0likes
test_pygrib_setup.py136 linesDownload Raw Back to root
1#!/usr/bin/env python32"""3Test script to verify pygrib installation and Arctic GRIB file processing4"""5import sys6import os7 8def test_pygrib_import():9    """Test if pygrib can be imported successfully"""10    print("πŸ” Testing pygrib import...")11    try:12        import pygrib13        print(f"βœ… pygrib imported successfully, version: {pygrib.__version__}")14        return True15    except ImportError as e:16        print(f"❌ pygrib import failed: {e}")17        return False18 19def test_eccodes_import():20    """Test if eccodes can be imported successfully"""21    print("πŸ” Testing eccodes import...")22    try:23        import eccodes24        print(f"βœ… eccodes imported successfully")25        return True26    except ImportError as e:27        print(f"❌ eccodes import failed: {e}")28        return False29 30def test_arctic_grib_processing():31    """Test Arctic GRIB file processing with pygrib"""32    arctic_file = "arctic_manual_20250828_12z.grib2"33    34    if not os.path.exists(arctic_file):35        print(f"⚠️ Arctic test file not found: {arctic_file}")36        return False37    38    print(f"πŸ§ͺ Testing Arctic GRIB processing with pygrib...")39    40    try:41        import pygrib42        43        # Open GRIB file44        grbs = pygrib.open(arctic_file)45        print(f"πŸ“‚ Successfully opened Arctic GRIB file")46        47        # Count messages48        msg_count = grbs.messages49        print(f"πŸ“Š Total messages in file: {msg_count}")50        51        # Test reading first few messages52        grbs.rewind()53        wave_params_found = 054        55        for i, grb in enumerate(grbs):56            if i >= 10:  # Test first 10 messages57                break58                59            param_name = grb.name60            short_name = grb.shortName if hasattr(grb, 'shortName') else 'unknown'61            62            print(f"  Message {i+1}: {param_name} ({short_name})")63            64            # Look for wave parameters65            if any(keyword in param_name.lower() for keyword in ['wave', 'swell', 'height', 'period']):66                wave_params_found += 167                print(f"    🌊 Found wave parameter!")68                69                try:70                    # Test coordinate extraction71                    lats, lons = grb.latlons()72                    values = grb.values73                    74                    print(f"    πŸ“ Grid shape: {values.shape}")75                    print(f"    πŸ“ˆ Value range: {values.min():.3f} to {values.max():.3f}")76                    print(f"    πŸ—ΊοΈ Lat range: {lats.min():.2f}Β° to {lats.max():.2f}Β°")77                    print(f"    πŸ—ΊοΈ Lon range: {lons.min():.2f}Β° to {lons.max():.2f}Β°")78                    79                    # Check for Arctic coverage80                    arctic_points = (lats >= 50.0).sum()81                    print(f"    🧊 Arctic points (β‰₯50Β°N): {arctic_points:,}")82                    83                except Exception as coord_error:84                    print(f"    ❌ Coordinate extraction failed: {coord_error}")85                    continue86        87        grbs.close()88        print(f"βœ… Arctic GRIB processing test completed")89        print(f"🌊 Wave parameters found: {wave_params_found}")90        91        return wave_params_found > 092        93    except Exception as e:94        print(f"❌ Arctic GRIB processing failed: {e}")95        import traceback96        traceback.print_exc()97        return False98 99def main():100    """Run all pygrib tests"""101    print("πŸ§ͺ PyGRIB Setup Test Suite")102    print("=" * 50)103    104    tests_passed = 0105    total_tests = 3106    107    # Test 1: Import pygrib108    if test_pygrib_import():109        tests_passed += 1110    111    print()112    113    # Test 2: Import eccodes114    if test_eccodes_import():115        tests_passed += 1116    117    print()118    119    # Test 3: Arctic GRIB processing (if file exists)120    if test_arctic_grib_processing():121        tests_passed += 1122    123    print()124    print("=" * 50)125    print(f"βœ… Tests passed: {tests_passed}/{total_tests}")126    127    if tests_passed == total_tests:128        print("πŸŽ‰ All tests passed! pygrib is working correctly.")129    else:130        print("⚠️ Some tests failed. Check error messages above.")131    132    return tests_passed == total_tests133 134if __name__ == "__main__":135    success = main()136    sys.exit(0 if success else 1)