CoolFace
Apppublic

nakas/NWPS_SWAN

sourceHugging Facegpl-3.0updated 1y agoView on Hugging Face
0likes
read_arctic_data.py115 linesDownload Raw Back to root
1#!/usr/bin/env python32"""3Read and analyze already extracted Arctic GRIB coordinate data4"""5import numpy as np6import os7 8def read_extracted_arctic_data():9    """Read the Arctic coordinate data that was already extracted."""10    11    base_path = "/Users/nakas/Documents/pythonGribExtraction"12    13    # File paths for the extracted data14    data_file = f"{base_path}/wave_data_Significant_height_of_combined_wind_waves_and_swell_data.npy"15    lats_file = f"{base_path}/wave_data_Significant_height_of_combined_wind_waves_and_swell_lats.npy"16    lons_file = f"{base_path}/wave_data_Significant_height_of_combined_wind_waves_and_swell_lons.npy"17    18    print("🧪 Reading extracted Arctic GRIB coordinate data")19    print("=" * 60)20    21    # Check if files exist22    for filepath in [data_file, lats_file, lons_file]:23        if not os.path.exists(filepath):24            print(f"❌ File not found: {filepath}")25            return26        print(f"✅ Found: {os.path.basename(filepath)}")27    28    try:29        # Load the numpy arrays30        print("\n📂 Loading extracted arrays...")31        wave_data = np.load(data_file)32        lats = np.load(lats_file) 33        lons = np.load(lons_file)34        35        print(f"✅ Arrays loaded successfully")36        print(f"📏 Data shape: {wave_data.shape}")37        print(f"📏 Coordinates shape: lats={lats.shape}, lons={lons.shape}")38        39        # Validate data ranges 40        print(f"\n📊 Data validation:")41        print(f"Wave height range: {np.nanmin(wave_data):.3f} to {np.nanmax(wave_data):.3f} m")42        print(f"Latitude range: {np.nanmin(lats):.2f} to {np.nanmax(lats):.2f}°")43        print(f"Longitude range: {np.nanmin(lons):.2f} to {np.nanmax(lons):.2f}°")44        45        # Check for valid data46        valid_mask = ~np.isnan(wave_data) & ~np.isnan(lats) & ~np.isnan(lons)47        valid_count = np.sum(valid_mask)48        total_count = wave_data.size49        50        print(f"\n🔍 Data quality:")51        print(f"Total grid points: {total_count:,}")52        print(f"Valid data points: {valid_count:,}")53        print(f"Valid percentage: {(valid_count/total_count)*100:.1f}%")54        55        # Arctic region filter (lat >= 50°N)56        arctic_mask = (lats >= 50.0) & (lats <= 85.0) & valid_mask57        arctic_count = np.sum(arctic_mask)58        59        print(f"\n🧊 Arctic region (50°-85°N):")60        print(f"Arctic data points: {arctic_count:,}")61        62        if arctic_count > 0:63            arctic_lats = lats[arctic_mask]64            arctic_lons = lons[arctic_mask]65            arctic_waves = wave_data[arctic_mask]66            67            print(f"Arctic lat range: {arctic_lats.min():.2f} to {arctic_lats.max():.2f}°")68            print(f"Arctic lon range: {arctic_lons.min():.2f} to {arctic_lons.max():.2f}°")69            print(f"Arctic wave range: {arctic_waves.min():.3f} to {arctic_waves.max():.3f} m")70            71            # Sample some Arctic points72            print(f"\n🎯 Sample Arctic coordinate points:")73            sample_indices = np.random.choice(len(arctic_lats), min(10, len(arctic_lats)), replace=False)74            75            for i, idx in enumerate(sample_indices):76                print(f"  {i+1:2d}. Lat: {arctic_lats[idx]:7.2f}°, Lon: {arctic_lons[idx]:8.2f}°, Wave: {arctic_waves[idx]:.3f}m")77            78            # Create a sample dataset for your app79            print(f"\n💾 Creating sample dataset...")80            sample_size = min(1000, arctic_count)  # Sample 1000 points81            sample_indices = np.random.choice(arctic_count, sample_size, replace=False)82            83            sample_data = []84            for idx in sample_indices:85                sample_data.append({86                    'latitude': float(arctic_lats[idx]),87                    'longitude': float(arctic_lons[idx]),88                    'value': float(arctic_waves[idx]),89                    'parameter': 'Significant height of combined wind waves and swell',90                    'parameter_type': 'wave_height'91                })92            93            # Save sample as simple text format94            output_file = "/tmp/arctic_sample_coordinates.txt"95            with open(output_file, 'w') as f:96                f.write("latitude,longitude,wave_height\n")97                for point in sample_data:98                    f.write(f"{point['latitude']:.6f},{point['longitude']:.6f},{point['value']:.6f}\n")99            100            print(f"Sample data saved to: {output_file}")101            print(f"\n✅ Arctic coordinate data analysis COMPLETE!")102            print(f"You have {arctic_count:,} real Arctic coordinate points ready to use")103            104            return sample_data105        106        else:107            print("❌ No Arctic data points found")108    109    except Exception as e:110        print(f"❌ Failed to read extracted data: {e}")111        import traceback112        traceback.print_exc()113 114if __name__ == "__main__":115    read_extracted_arctic_data()