### Basic Skyborn Usage in Python Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/quickstart.rst Demonstrates importing the Skyborn library and utilizing its functions for statistical calculations. It shows examples for computing Gaussian probability density function (PDF) values and performing Pearson correlation analysis. ```python import skyborn as skb # Example: Gaussian PDF calculation pdf_values = skb.gaussian_pdf(mu=0, sigma=1, x=x_values) # Example: Correlation analysis correlation = skb.pearson_correlation(x_data, y_data) ``` -------------------------------- ### Install Skyborn with Optional Dependencies Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/installation.rst Installs Skyborn along with specific groups of optional dependencies to enable full functionality or development features. Use '[all]' for all optional dependencies, or specify groups like '[plotting]', '[dev]', or '[docs]'. ```bash # Install with all optional dependencies pip install skyborn[all] # Install with specific dependency groups pip install skyborn[plotting] pip install skyborn[dev] pip install skyborn[docs] ``` -------------------------------- ### Install Skyborn from Git Repository Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/installation.rst Installs the Skyborn package directly from its GitHub repository. This is useful for installing the latest development version or a specific branch. It clones the repository and installs it in editable mode. ```bash # Clone the repository git clone https://github.com/QianyeSu/skyborn.git cd skyborn # Install in development mode pip install -e . ``` -------------------------------- ### Install Skyborn for Development Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/notebooks/index.rst Installs Skyborn with development dependencies and launches Jupyter Lab in the docs/source/notebooks directory. This is a prerequisite for running the provided notebooks locally. ```bash pip install skyborn[dev] jupyter lab docs/source/notebooks/ ``` -------------------------------- ### Verify Skyborn Installation Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/installation.rst Verifies a successful installation of the Skyborn package by importing the library and printing its version. It also runs a basic function to ensure core functionalities are working as expected. ```python import skyborn as skb import numpy as np print(skb.__version__) x = np.linspace(-3, 3, 100) pdf = skb.gaussian_pdf(0, 1, x) print("Installation successful!") ``` -------------------------------- ### JavaScript: Graphics Setup Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_ro.html Prepares the graphics for rendering by calling `setDiscs` to initialize the disc elements and `setDots` to populate the particle dots. ```javascript setGraphics () { this.setDiscs() this.setDots() } ``` -------------------------------- ### Python: Example usage of GridFill with new initialization options Source: https://github.com/qianyesu/skyborn/blob/main/src/skyborn/gridfill/GRIDFILL_UPGRADE_INTEGRATION_REPORT.md Provides example Python code snippets demonstrating how to utilize the new initialization features of the GridFill module. It shows how to enable zonal linear interpolation by setting `initzonal_linear=True` and how to specify a custom initial value using `initial_value=999.0`. These examples illustrate the practical application of the upgraded functionalities for improved Poisson equation solver initialization. ```python import numpy as np import skyborn.gridfill as gf # Assuming 'data', 'xdim', 'ydim', 'eps' are defined elsewhere # Using linear interpolation initialization result, converged = gf.fill(data, xdim=1, ydim=0, eps=1e-4, initzonal_linear=True) # Using custom initial value result, converged = gf.fill(data, xdim=1, ydim=0, eps=1e-4, initial_value=999.0) ``` -------------------------------- ### Import Libraries and Setup Environment Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/notebooks/gridfill_tutorial.ipynb Imports necessary Python libraries including NumPy, XArray, Matplotlib, Cartopy, and Skyborn's gridfill modules. It also configures Matplotlib for publication-quality plots and provides feedback on successful setup and available colormaps. ```python import numpy as np import xarray as xr import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature from cartopy.util import add_cyclic_point import time # For timing measurements import warnings warnings.filterwarnings('ignore') # Import high-quality colormaps try: import cmaps print("✅ Advanced colormaps available (cmaps)") except ImportError: print("ℹ️ Using standard matplotlib colormaps") # Define fallback colormap import matplotlib.cm as cm cmaps = type('obj', (object,), {'BlueWhiteOrangeRed': cm.RdYlBu_r}) # Import GridFill modules - the star of this tutorial! 🌟 from skyborn.gridfill.xarray import fill as xr_fill from skyborn.gridfill.xarray import validate_grid_coverage, fill_multiple from skyborn.plot import add_equal_axes # Configure matplotlib for publication-quality plots plt.rcParams.update({ 'figure.figsize': (16, 12), 'font.size': 12, 'axes.titlesize': 14, 'axes.labelsize': 12, 'font.family': 'DejaVu Sans', 'font.weight': 'normal', 'axes.labelweight': 'bold', 'mathtext.fontset': 'stix', 'axes.unicode_minus': False, 'figure.dpi': 100, 'savefig.dpi': 300, 'savefig.bbox': 'tight', 'savefig.facecolor': 'white' }) print("🚀 GridFill Tutorial Environment Setup Complete!") print("📦 Libraries imported successfully:") print(" • NumPy & XArray for data handling") print(" • Matplotlib & Cartopy for beautiful visualizations") print(" • Skyborn GridFill for advanced interpolation") print(f" • XArray interface: {xr_fill.__module__}") print("\n🎯 Ready to demonstrate advanced data interpolation with GridFill!") ``` -------------------------------- ### Install Skyborn Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/index.rst Installs the Skyborn Python package using pip. This is the first step to using the library for climate data analysis. ```bash pip install skyborn ``` -------------------------------- ### Skyborn AHole Component: Line Setup Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_ro.html Initializes the grid lines for the 'black hole' effect. This method calculates and prepares the data structure for drawing the lines based on the component's dimensions. ```javascript class AHole extends HTMLElement { /** * Set lines */ setLines() { const { width, height } = this.rect; this.lines = []; // ... (code to calculate and populate this.lines) } // ... other methods ... ``` -------------------------------- ### Skyborn AHole Component: Initialization and Setup Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_ro.html Handles the initialization of the AHole web component, including setting up the canvas context, defining dimensions, and calling methods to set initial states for discs, lines, and particles. It also sets up event listeners for resizing. ```javascript class AHole extends HTMLElement { /** * Init */ connectedCallback() { // Elements this.canvas = this.querySelector(".js-canvas"); this.ctx = this.canvas.getContext("2d"); this.discs = []; this.lines = []; // Init this.setSize(); this.setDiscs(); this.setLines(); this.setParticles(); this.bindEvents(); // RAF requestAnimationFrame(this.tick.bind(this)); } /** * Bind events */ bindEvents() { window.addEventListener("resize", this.onResize.bind(this)); } /** * Resize handler */ onResize() { this.setSize(); this.setDiscs(); this.setLines(); this.setParticles(); } /** * Set size */ setSize() { this.rect = this.getBoundingClientRect(); this.render = { width: this.rect.width, height: this.rect.height, dpi: window.devicePixelRatio, }; this.canvas.width = this.render.width * this.render.dpi; this.canvas.height = this.render.height * this.render.dpi; } // ... other methods ... ``` -------------------------------- ### Import pyMannKendall and Check Availability Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/notebooks/mann_kendall_tutorial.ipynb This snippet attempts to import the pyMannKendall library and sets a flag indicating its availability. If the import fails, it prints an informative message and instructions for installation. ```python try: import pymannkendall as pmk HAS_PYMANNKENDALL = True print("✅ pyMannKendall available for validation") except ImportError: HAS_PYMANNKENDALL = False print("⚠️ pyMannKendall not available. Install with: pip install pymannkendall") print(" Proceeding with Skyborn validation only") ``` -------------------------------- ### Initialize Black Hole Particle System - JavaScript Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_backup.html Initializes the BlackHoleParticleSystem by getting the canvas element and creating an instance of the system. This is the entry point for the particle simulation. It requires a canvas element with the ID 'particles-canvas'. ```javascript const canvas = document.getElementById('particles-canvas'); const blackHoleSystem = new BlackHoleParticleSystem(canvas); ``` -------------------------------- ### Skyborn Climate Data Analysis Examples (Python) Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/index.rst Demonstrates basic usage of the Skyborn package in Python, including Gaussian PDF calculation, atmospheric data interpolation with GridFill, GRIB to NetCDF conversion, and Pearson correlation calculation. ```python import skyborn as skb from skyborn.gridfill.xarray import gridfill_xarray # Use emergent constraint methods pdf = skb.gaussian_pdf(mu=0, sigma=1, x=x_values) # Advanced atmospheric data interpolation (NEW in v0.3.10) filled_data = gridfill_xarray(atmospheric_data, eps=1e-4) # Convert GRIB to NetCDF skb.grib_to_netcdf('input.grib', 'output.nc') # Statistical analysis correlation = skb.pearson_correlation(x_data, y_data) ``` -------------------------------- ### JavaScript: Disc Initialization Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_ro.html Initializes an array of discs, defining their starting position and dimensions. It then tweens these discs based on a progress factor (`p`) to create an animation effect, storing the tweened state. ```javascript setDiscs () { this.discs = [] this.startDisc = { x: this.render.width * 0.5, y: this.render.height * 0.45, w: this.render.width * PERSPECTIVE_CONFIG.ELLIPSE_WIDTH, h: this.render.height * PERSPECTIVE_CONFIG.ELLIPSE_HEIGHT } const totalDiscs = 150 for (let i = 0; i < totalDiscs; i++) { const p = i / totalDiscs const disc = this.tweenDisc({ p }) this.discs.push(disc) } } ``` -------------------------------- ### Install Skyborn using Conda Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/installation.rst Installs the Skyborn package using the Conda package manager from the conda-forge channel. This method is an alternative to pip and is useful for users who prefer or rely on the Conda ecosystem. ```bash conda install -c conda-forge skyborn ``` -------------------------------- ### JavaScript: BlackHole Class Initialization Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_ro.html Initializes the BlackHole custom element. It sets up the canvas context, sizes the canvas, binds event listeners for resizing, and starts the animation loop using requestAnimationFrame. ```javascript connectedCallback() { // Elements this.canvas = this.querySelector(".js-canvas"); this.ctx = this.canvas.getContext("2d"); // Init this.setSizes(); this.bindEvents(); // RAF requestAnimationFrame(this.tick.bind(this)); } ``` -------------------------------- ### Display Package Versions and Functionality Summary (Python) Source: https://github.com/qianyesu/skyborn/blob/main/examples/Emergent_Constraints.ipynb Prints the versions of key packages (pandas, numpy, matplotlib, xarray) and provides a summary of available Skyborn emergent constraint functions and data visualization setup. It also includes a basic test for the gaussian_pdf function. ```python print("📦 Package Versions:") print(f" pandas: {pd.__version__}") print(f" numpy: {np.__version__}") print(f" matplotlib: {plt.matplotlib.__version__}") print(f" xarray: {xr.__version__}") print("\n🧮 Skyborn Emergent Constraint Functions:") print(" ✅ gaussian_pdf - Calculate Gaussian PDF") print(" ✅ emergent_constraint_posterior - Apply emergent constraints") print(" ✅ emergent_constraint_prior - Calculate prior distributions") print("\n📊 Data Visualization Setup:") print(" ✅ High-resolution figures (300 DPI)") print(" ✅ Seaborn styling enabled") print(" ✅ Color palette optimized") print("\n🔗 Reference Implementation:") print(" https://github.com/blackcata/Emergent_Constraints/tree/master") # Test basic functionality test_x = np.linspace(-3, 3, 100) test_pdf = gaussian_pdf(mu=0, sigma=1, x=test_x) print(f"\n✅ Function test successful - PDF max: {test_pdf.max():.4f}") ``` -------------------------------- ### Python: GRIB to NetCDF Conversion with Skyborn Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/api/conversion.rst Demonstrates how to perform GRIB to NetCDF conversions using the Skyborn library. This includes single file conversion, batch processing of multiple GRIB files, and converting data within a specified longitude range. Ensure the Skyborn library is installed. ```python import skyborn as skb # Convert single GRIB file to NetCDF skb.grib_to_netcdf('input.grib', 'output.nc') # Batch convert multiple files input_files = ['file1.grib', 'file2.grib', 'file3.grib'] output_files = ['file1.nc', 'file2.nc', 'file3.nc'] skb.conversion.batch_convert_grib_to_nc(input_files, output_files) # Convert longitude range data = skb.conversion.convert_longitude_range(dataset, '180') # Basic GRIB to NetCDF conversion success = skb.conversion.grib_to_netcdf('input.grib', 'output.nc') # Convert longitude range data_converted = skb.conversion.convert_longitude_range(data, '180') ``` -------------------------------- ### Project Documentation Structure Source: https://github.com/qianyesu/skyborn/blob/main/src/skyborn/spharm/html/help.html Explains the content and purpose of the Trees and Index pages for project-level documentation. ```APIDOC ## Project Documentation ### Trees Page - Module hierarchy: Lists all packages and modules, grouped by package. - Class hierarchy: Lists all classes, grouped by base class. ### Index Page - Term index: Lists all indexed terms with links to their documentation. - Identifier index: Lists all package, module, class, method, function, variable, and parameter names with descriptions and links. ``` -------------------------------- ### Example: Regridding Data with Skyborn ConservativeRegridder (Python) Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/api/interpolation.rst This example demonstrates how to use the Skyborn ConservativeRegridder to regrid data. It involves loading data using xarray, initializing the regridder with source and target grids, and then applying the regridder to transform the data. The ConservativeRegridder is suitable for preserving mass or other conserved quantities during regridding. ```python import skyborn as skb import xarray as xr # Load data data = xr.open_dataset('input_data.nc') # Create regridder regridder = skb.interp.ConservativeRegridder( source_grid=data, target_grid=target_grid ) # Regrid data regridded_data = regridder.regrid_array(data['temperature']) ``` -------------------------------- ### Run Emergent Constraint Demonstration Python Source: https://github.com/qianyesu/skyborn/blob/main/examples/Emergent_Constraints.ipynb Executes a demonstration for emergent constraints, displays results, and prints analysis completion with uncertainty reduction and constrained projection. ```python print("🚀 Running emergent constraint demonstration...") results = create_emergent_constraint_demo() plt.show() print(f"\n✅ Analysis complete!") print(f"📊 Uncertainty reduced by {results['uncertainty_reduction']:.1f}%") print(f"🎯 Constrained projection: {results['posterior_mean']:.2f} ± {results['posterior_std']:.2f}") ``` -------------------------------- ### GridFill Initialization Parameters Source: https://github.com/qianyesu/skyborn/blob/main/src/skyborn/gridfill/GRIDFILL_UPGRADE_INTEGRATION_REPORT.md Documentation for the new initialization parameters available in the GridFill `fill` and `fill_cube` functions. ```APIDOC ## POST /api/gridfill/fill ### Description This endpoint (or function within the library) allows filling missing values in grid data using various initialization strategies, including advanced interpolation methods. ### Method POST (or function call) ### Endpoint `/api/gridfill/fill` (conceptual) ### Parameters #### Query Parameters - **initzonal_linear** (boolean) - Optional - If `True`, uses zonal linear interpolation for initial guesses of missing values. Defaults to `False`. - **initial_value** (float) - Optional - Specifies a custom initial value to use when the zero initialization mode is active. Defaults to `0.0`. #### Request Body (This would typically be the data to be filled, e.g., a masked array, along with other configuration parameters like `xdim`, `ydim`, `eps`, `relax`, `itermax`, `cyclic`, `verbose`) ```json { "grids": "[masked_array_data]", "xdim": 1, "ydim": 0, "eps": 1e-4, "relax": 0.6, "itermax": 100, "initzonal": false, "initzonal_linear": true, "cyclic": false, "initial_value": 0.0, "verbose": false } ``` ### Request Example ```python import skyborn.gridfill as gf import numpy as np # Example data (replace with actual masked array) data = np.ma.array([[1, 2, np.nan], [4, np.nan, 6]]) # Using linear interpolation initialization result, converged = gf.fill(data, xdim=1, ydim=0, eps=1e-4, initzonal_linear=True) # Using custom initial value result, converged = gf.fill(data, xdim=1, ydim=0, eps=1e-4, initial_value=999.0) ``` ### Response #### Success Response (200) - **result** (numpy.ndarray) - The grid with missing values filled. - **converged** (boolean) - Indicates whether the filling process converged. #### Response Example ```json { "result": "[filled_array_data]", "converged": true } ``` ``` -------------------------------- ### Create Realistic Missing Data Regions (Python) Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/notebooks/gridfill_tutorial.ipynb Demonstrates the creation of artificial missing data regions in wind data (u, v components, and wind speed) to simulate real-world scenarios like satellite swath gaps, storm centers, or coastal boundary issues. This aids in quantitatively assessing interpolation accuracy. ```python # Create backup copies of original data for comparison u_original = u_wind.copy() v_original = v_wind.copy() speed_original = wind_speed.copy() # Create working copies that will have missing data u_missing = u_wind.copy() v_missing = v_wind.copy() speed_missing = wind_speed.copy() print("🎭 Creating realistic missing data scenarios...") # Get coordinate arrays for geometric calculations lats = u_wind.latitude.values lons = u_wind.longitude.values lat_mesh, lon_mesh = np.meshgrid(lats, lons, indexing='ij') # Initialize missing data mask missing_mask = np.zeros_like(lat_mesh, dtype=bool) # 🟥 Region 1: Large rectangular gap (simulating satellite swath gap) print(" Creating large rectangular gap (satellite swath simulation)...") lat_mask1 = (lat_mesh >= 20) & (lat_mesh <= 40) lon_mask1 = (lon_mesh >= 120) & (lon_mesh <= 160) gap1_mask = lat_mask1 & lon_mask1 missing_mask |= gap1_mask ``` -------------------------------- ### Skyborn Plotting Utilities: Create Figure Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/api/plotting.rst Creates a matplotlib figure and axes object with specified dimensions and layout. It returns the figure and axes objects, which can then be used for plotting. Requires matplotlib to be installed. ```python import skyborn as skb import matplotlib.pyplot as plt # Create figure fig, ax = skb.plot.createFigure((12, 8), 1, 1) ``` -------------------------------- ### Initialize Single Particle Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_blackhole.html Initializes a single particle with random properties for position, velocity, and appearance. The 'start' parameter determines if the particle should be initialized at the top of its movement area. This function is used to create new particles during the animation. ```javascript initParticle(start = false) { const sx = this.particleArea.sx + this.particleArea.sw * Math.random(); const ex = this.particleArea.ex + this.particleArea.ew * Math.random(); const dx = ex - sx; const vx = 0.1 + Math.random() * 0.5; const y = start ? this.particleArea.h * Math.random() : this.particleArea.h; const r = 0.5 + Math.random() * 4; const vy = 0.5 + Math.random(); return { x: sx, sx, dx, y, vy, p: 0, r, c: `rgba(255, 255, 255, ${Math.random()})` }; } ``` -------------------------------- ### Skyborn Python Module Imports and Basic Usage Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/modules/skyborn.rst Demonstrates how to import the Skyborn package and access its core modules for statistical calculations, data conversion, and visualization. Shows basic function calls for Gaussian PDF, GRIB to NetCDF conversion, and figure creation. ```python import skyborn as skb # Use calculation functions x_values = [1, 2, 3, 4, 5] pdf = skb.calc.gaussian_pdf(mu=0, sigma=1, x=x_values) # Convert data formats skb.conversion.grib_to_netcdf('input.grib', 'output.nc') # Create visualizations fig, ax = skb.plot.createFigure((10, 6), 1, 1) ``` -------------------------------- ### Python: Emergent Constraint Analysis with Skyborn Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/gallery.rst Demonstrates the core steps for applying emergent constraints using the Skyborn package. It covers loading climate data, performing calculations like Gaussian PDF and Pearson correlation, and visualizing the results. This snippet assumes the existence of helper functions like `load_your_ecs_data` and `plot_constraint_analysis`. ```python import skyborn as skb import numpy as np # Load your climate data ecs_data = load_your_ecs_data() constraint_data = load_constraint_data() # Apply emergent constraint pdf = skb.gaussian_pdf(obs_mean, obs_std, x_grid) correlation = skb.pearson_correlation(constraint_data, ecs_data) # Visualize results plot_constraint_analysis(ecs_data, constraint_data, obs_pdf) ``` -------------------------------- ### JavaScript: Disc Tweening Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_ro.html Tweens the properties of a disc based on a progress factor (`p`). It calculates scaled width and height using cubic and exponential easing functions, respectively, and sets the disc's position to match the starting position. ```javascript tweenDisc (disc) { const { startDisc } = this const scaleX = this.tweenValue(1, 0, disc.p, 'outCubic') const scaleY = this.tweenValue(1, 0, disc.p, 'outExpo') disc.sx = scaleX disc.sy = scaleY disc.w = startDisc.w * scaleX disc.h = startDisc.h * scaleY disc.x = startDisc.x disc.y = startDisc.y + disc.p * startDisc.h * PERSPECTIVE_CONFIG.DEPTH_FACTOR return disc } ``` -------------------------------- ### Save Plot to PDF in Python Source: https://github.com/qianyesu/skyborn/blob/main/examples/Emergent_Constraints.ipynb This Python snippet demonstrates how to save a matplotlib plot to a PDF file. It defines the directory and filename for the output PDF, incorporating latitude information into the filename. Ensure matplotlib is installed and the output directory exists. ```python dir_name = "./RESULT/" file_name = "Scat_PDF_CMIP5_CHL_NO3_LAT_"+str(latS)+str(latN)+".pdf" plt.savefig(dir_name+file_name) ``` -------------------------------- ### Python GridFill Performance Analysis and Reporting Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/notebooks/gridfill_tutorial.ipynb This Python script calculates and prints a comprehensive performance analysis for various GridFill interpolation methods. It computes RMSE, MAE, Max Error, and Correlation for filled regions, comparing different initialization strategies and marking new or recommended methods. Dependencies include numpy for numerical operations. ```python methods_detailed = { 'Basic': speed_filled_basic, 'High-Precision': speed_filled_precise, 'Modified Relax': speed_filled_relax, 'Zonal Init': speed_filled_zonal, 'Linear Zonal Init (NEW)': speed_filled_linear, 'Custom Initial Value (NEW)': speed_filled_custom, 'Combined New Features (NEW)': speed_filled_combined, 'Direct Speed (Not Recommended)': speed_direct_fill } print("\n" + "="*90) print("COMPREHENSIVE GRIDFILL PERFORMANCE ANALYSIS (Including NEW Features)") print("="*90) print(f"\nAccuracy assessment for filled regions ({missing_mask.sum():,} grid points):") print(f"{ 'Method':<32} {'RMSE':<10} {'MAE':<10} {'Max Error':<12} {'Correlation':<12}") print("-" * 85) for method_name, filled_data in methods_detailed.items(): # Calculate errors in missing regions only original_vals = speed_original.values[missing_mask] filled_vals = filled_data.values[missing_mask] rmse = np.sqrt(np.mean((filled_vals - original_vals)**2)) mae = np.mean(np.abs(filled_vals - original_vals)) max_err = np.max(np.abs(filled_vals - original_vals)) correlation = np.corrcoef(original_vals, filled_vals)[0, 1] # Mark recommended and new methods marker = " ✅" if "Zonal Init" in method_name and "NEW" not in method_name else "" marker += " 🆕" if "NEW" in method_name else "" marker += " ❌" if "Direct" in method_name else "" print(f"{method_name:<32} {rmse:<10.3f} {mae:<10.3f} {max_err:<12.3f} {correlation:<12.3f}{marker}") print(f"\n🎯 Key Findings:") print(f"• Zonal initialization shows excellent performance for atmospheric data") print(f"• 🆕 Linear zonal initialization may improve performance for data with strong gradients") print(f"• 🆕 Custom initial values allow fine-tuning for specific datasets") print(f"• 🆕 Combined features offer maximum flexibility for challenging scenarios") print(f"• Component-wise filling (u,v→speed) preserves vector field relationships") print(f"• Direct speed filling loses important directional information") print(f"• All methods successfully filled {missing_percent:.1f}% missing data") print(f"\n🆕 NEW FEATURES SUMMARY:") print(f"• initzonal_linear: Use linear zonal mean instead of constant") print(f"• initial_value: Set custom initial guess for missing regions") print(f"• Combined usage: Enhanced initialization for complex datasets") ``` -------------------------------- ### JavaScript: Value Tweening Utility Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_ro.html Provides a utility function to tween a value between a start and end point based on a progress factor (`p`) and an easing function. Supports linear easing by default or specified easing functions like 'easeOutCubic' and 'easeOutExpo'. ```javascript tweenValue (start, end, p, ease = false) { const delta = end - start const easeFn = easingUtils[ ease ? "ease" + ease.charAt(0).toUpperCase() + ease.slice(1) : "linear" ]; return start + delta * easeFn(p); } ``` -------------------------------- ### Load Wind Data from NetCDF Files (Python) Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/notebooks/gridfill_tutorial.ipynb Loads atmospheric u and v wind components from NetCDF files. Handles FileNotFoundError by generating synthetic wind data if files are not found. Calculates wind speed and displays data statistics and quality. ```python import xarray as xr import numpy as np # Assume validate_grid_coverage is defined elsewhere def validate_grid_coverage(data_array): # Dummy implementation for example return {'coverage': 1.0, 'total_points': data_array.size, 'valid': True, 'messages': []} data_path = '../../../src/skyborn/windspharm/examples/example_data/' print("🔄 Loading atmospheric wind data...") try: # Load datasets ds_u = xr.open_dataset(data_path + 'uwnd_mean.nc') ds_v = xr.open_dataset(data_path + 'vwnd_mean.nc') # Extract wind components as DataArrays (select January for seasonal focus) u_wind = ds_u.uwnd.isel(time=0) # January 850 hPa level v_wind = ds_v.vwnd.isel(time=0) print("✅ Wind data loaded successfully!") except FileNotFoundError: print("⚠️ Example data not found. Creating synthetic wind field...") # Create synthetic realistic wind field lons = np.linspace(0, 360, 144, endpoint=False) lats = np.linspace(-90, 90, 73) # Create realistic wind patterns lon_grid, lat_grid = np.meshgrid(lons, lats) u_wind = xr.DataArray( 10 * np.sin(np.radians(2 * lon_grid)) * np.cos(np.radians(lat_grid)), coords={'latitude': lats, 'longitude': lons}, dims=['latitude', 'longitude'] ) v_wind = xr.DataArray( -5 * np.cos(np.radians(3 * lon_grid)) * np.sin(np.radians(lat_grid)), coords={'latitude': lats, 'longitude': lons}, dims=['latitude', 'longitude'] ) # Calculate wind speed for visualization and analysis wind_speed = np.sqrt(u_wind**2 + v_wind**2) # Display comprehensive data information print("\n📐 Dataset Specifications:") print(f" Grid dimensions: {u_wind.shape}") print(f" Spatial resolution: {u_wind.dims}") print(f" Latitude range: {u_wind.latitude.min().values:.1f}° to {u_wind.latitude.max().values:.1f}°") print(f" Longitude range: {u_wind.longitude.min().values:.1f}° to {u_wind.longitude.max().values:.1f}°") print(f"\n🌪️ Wind Field Statistics:") print(f" U-component range: {u_wind.min().values:.2f} to {u_wind.max().values:.2f} m/s") print(f" V-component range: {v_wind.min().values:.2f} to {v_wind.max().values:.2f} m/s") print(f" Wind speed range: {wind_speed.min().values:.2f} to {wind_speed.max().values:.2f} m/s") print(f" Mean wind speed: {wind_speed.mean().values:.2f} m/s") # Validate data quality validation = validate_grid_coverage(u_wind) print(f"\n🔍 Data Quality Assessment:") print(f" Data completeness: {validation['coverage']*100:.1f}%") print(f" Grid points: {validation['total_points']:,}") if validation['valid']: print(" ✅ Data quality: Excellent for GridFill analysis") else: print(" ⚠️ Data quality issues detected:") for msg in validation['messages']: print(f" • {msg}") ``` -------------------------------- ### Initialize Matplotlib Figure and Axes for Plotting Source: https://github.com/qianyesu/skyborn/blob/main/examples/Emergent_Constraints.ipynb Initializes a Matplotlib figure with two subplots arranged in a single row and two columns. This setup is used for creating comparative visualizations of the oceanographic data. The `constrained_layout=True` argument helps in optimizing subplot spacing. ```python fig, axes = plt.subplots(1,2,figsize=(11,5),constrained_layout=True) ``` -------------------------------- ### Create VectorWind Instance Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/notebooks/windspharm_tutorial.ipynb Initializes a VectorWind instance using January's zonal (u) and meridional (v) wind components. This step is crucial for subsequent analyses. It automatically configures the grid type and reports the data shape. ```python import xarray as xr import matplotlib.pyplot as plt import matplotlib.cm as cmaps import cartopy.crs as ccrs import cartopy.feature as cfeature import numpy as np from windspharm.standard import VectorWind from windspharm.tools import add_cyclic_point, add_equal_axes, save_gallery_figure # Assume u_jan and v_jan are xarray DataArrays representing wind components # Example dummy data (replace with your actual data) u_jan = xr.DataArray(np.random.rand(73, 144), dims=['latitude', 'longitude'], coords={'latitude': np.linspace(-90, 90, 73), 'longitude': np.linspace(-180, 180, 144)}) v_jan = xr.DataArray(np.random.rand(73, 144), dims=['latitude', 'longitude'], coords={'latitude': np.linspace(-90, 90, 73), 'longitude': np.linspace(-180, 180, 144)}) # Create VectorWind instance for January vw = VectorWind(u_jan, v_jan) print("VectorWind instance created successfully!") print(f"Grid type automatically detected and configured") print(f"Data shape: {u_jan.shape}") print(f"Ready for spherical harmonic analysis!") ``` -------------------------------- ### Formatting Main Wind Speed Colorbar (Python) Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/notebooks/gridfill_tutorial.ipynb Applies integer formatting and bold labels to the main colorbar representing wind speed. It uses the `format_colorbar_integers` helper function or similar logic to ensure ticks and labels are clear and appropriately styled for the wind speed data. ```Python # Add colorbars with integer formatting and bold labels fig.subplots_adjust(bottom=0.12, hspace=0.05, wspace=0.08) # Shared colorbar for wind speed (rows 1-2) with integer formatting cbar_ax_main = fig.add_axes([0.1, 0.08, 0.8, 0.015]) cbar_main = plt.colorbar(im1, cax=cbar_ax_main, orientation='horizontal') cbar_main.set_label('Wind Speed (m/s)', fontsize=12, fontweight='bold') # Set integer ticks for main colorbar speed_ticks = np.arange(0, int(speed_original.max().values)+1, 10) cbar_main.set_ticks(speed_ticks) cbar_main.set_ticklabels([f'{int(tick)}' for tick in speed_ticks]) cbar_main.ax.tick_params(labelsize=10) # Apply bold formatting for label in cbar_main.ax.get_xticklabels(): label.set_fontweight('bold') ``` -------------------------------- ### Memory-Efficient VectorWind Initialization Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/notebooks/windspharm_tutorial.ipynb This Python code demonstrates how to initialize the VectorWind class in a memory-efficient manner using `legfunc='computed'`. This is recommended for large datasets as it computes Legendre functions on-the-fly, reducing memory footprint at the cost of slightly increased computation time. It also highlights other memory-saving tips. ```python # Assume VectorWind class and wind data (u_jan, v_jan) are defined elsewhere. # Demonstrate memory-efficient processing print("Memory usage tips:") print("1. Use 'legfunc='computed'' for large datasets to save memory") print("2. Process data in chunks for very large time series") print("3. Use appropriate truncation levels to reduce computational cost") # Example of memory-efficient initialization vw_memory_efficient = VectorWind(u_jan, v_jan, legfunc='computed') vrt_efficient = vw_memory_efficient.vorticity() print("\nMemory-efficient VectorWind instance created successfully!") print("This approach computes Legendre functions on-the-fly, using less memory") print("but taking slightly more time for calculations.") ``` -------------------------------- ### Skyborn AHole Component: Disc Geometry Calculation Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_ro.html Calculates the geometry for the discs that form the 'black hole' effect. It defines start and end disc properties and determines clipping paths based on disc dimensions and positions, ensuring the effect is rendered within bounds. ```javascript class AHole extends HTMLElement { /** * Set discs */ setDiscs() { const { width, height } = this.rect; this.discs = []; this.startDisc = { x: width * 0.5, y: height * 0.45, w: width * PERSPECTIVE_CONFIG.ELLIPSE_WIDTH, h: height * PERSPECTIVE_CONFIG.ELLIPSE_HEIGHT, }; this.endDisc = { x: width * 0.5, y: height * 0.95, w: 0, h: 0, }; const totalDiscs = 100; let prevBottom = height; this.clip = {}; for (let i = 0; i < totalDiscs; i++) { const p = i / totalDiscs; const disc = this.tweenDisc({ p }); const bottom = disc.y + disc.h; if (bottom <= prevBottom) { this.clip = { disc: { ...disc }, i }; } prevBottom = bottom; this.discs.push(disc); } this.clip.path = new Path2D(); this.clip.path.ellipse( this.clip.disc.x, this.clip.disc.y, this.clip.disc.w, this.clip.disc.h, 0, 0, Math.PI * 2 ); this.clip.path.rect( this.clip.disc.x - this.clip.disc.w, 0, this.clip.disc.w * 2, this.clip.disc.y ); } // ... other methods ... ``` -------------------------------- ### Tween Disc Properties Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_blackhole.html Applies tweening to the disc's properties (x, y, w, h) based on its progress ('p'). It uses the 'tweenValue' function to interpolate between start and end values, with 'inExpo' easing applied to the 'y' and 'h' properties for a specific animation feel. ```javascript tweenDisc(disc) { disc.x = this.tweenValue(this.startDisc.x, this.endDisc.x, disc.p); disc.y = this.tweenValue( this.startDisc.y, this.endDisc.y, disc.p, "inExpo" ); disc.w = this.tweenValue(this.startDisc.w, this.endDisc.w, disc.p); disc.h = this.tweenValue(this.startDisc.h, this.endDisc.h, disc.p); return disc; } ``` -------------------------------- ### WebGL Shader Initialization and Rendering Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_logo.html This JavaScript code initializes a WebGL rendering context, compiles and links GLSL shaders, sets up vertex data, and defines the main drawing loop. It handles viewport configuration, clearing, and uniform updates. ```javascript const vert = `#version 300 es precision highp float; layout(location = 0) in vec2 a_position; out vec2 vUv; void main() { gl_Position = vec4(a_position, 0.0, 1.0); vUv = a_position * 0.5 + 0.5; }`; const frag = `precision highp float; uniform float u_time; uniform vec3 u_resolution; uniform float u_mix; out vec4 fragColor; void main() { vec2 uv = gl_FragCoord.xy / u_resolution.xy; float channel = u_time * 0.5; vec3 O = vec3( 0.1 + 0.5 * sin(channel + 0.0), // Dominant green component 0.6 + 0.4 * sin(channel + 1.0), // Deep blue background 0.0 // No red component ); // Example of additional color calculations (commented out) // vec3 O = vec3( // 0.7 + 0.5 * sin(channel + 0.0), // Strong cyan // 0.9 + 0.4 * sin(channel + 0.5) // Strong blue // ); float glow = sin(u_time * 0.1) * 0.5 + 0.5; float edgeBrightness = 1.0 - length(uv - 0.5) * 1.5; O *= glow * edgeBrightness; fragColor = vec4(O, 1.0); }`; const shader = new ShaderBuilder(gl, vert, frag); shader.build(); const quadVerts = new Float32Array([ -1, -1, 1, -1, -1, 1, 1, 1, ]); shader.createVAO('quad'); shader.bindVAO('quad'); shader.createVBO('quad', quadVerts); shader.setAttribute('a_position', 2, gl.FLOAT); let desiredFPS = 60; const draw = (time) => { const isLowEnd = document.documentElement.classList.contains('low-end'); const target = isLowEnd ? 25 : desiredFPS; gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT); shader.use(); shader.setUniform3f('u_resolution', gl.canvas.width, gl.canvas.height, 1); shader.setUniform1f('u_time', time * 0.001); shader.setUniform1f('u_mix', 0.5); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); if (isLowEnd) { setTimeout(() => requestAnimationFrame(draw), 1000 / target); } else { requestAnimationFrame(draw); } }; requestAnimationFrame(draw); ``` -------------------------------- ### Tween Value with Easing Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/backup/entrance_blackhole.html Calculates an intermediate value between a start and end point based on a progress percentage 'p'. It supports different easing functions from 'easingUtils' to control the animation's acceleration and deceleration. Defaults to linear easing if no easing function is specified. ```javascript tweenValue(start, end, p, ease = false) { const delta = end - start; const easeFn = easingUtils[ ease ? "ease" + ease.charAt(0).toUpperCase() + ease.slice(1) : "linear" ]; return start + delta * easeFn(p); } ``` -------------------------------- ### Visualize U and V Wind Component GridFill Results (Python) Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/notebooks/gridfill_tutorial.ipynb Generates detailed visualizations of U and V wind component gridfill results using matplotlib and cartopy. It plots original, missing, filled (zonal initialization), and error components, incorporating coastal features and cyclic points for accurate representation. ```python # Create detailed visualization of U and V component gridfill results fig, axes = plt.subplots(3, 4, figsize=(24, 16), subplot_kw={'projection': ccrs.Robinson(central_longitude=180)}) # Define levels for u and v components u_levels = np.linspace(u_original.min().values, u_original.max().values, 20) v_levels = np.linspace(v_original.min().values, v_original.max().values, 20) def plot_component_elegant(ax, data, title, levels, cmap='RdBu_r'): """Plot wind component with elegant styling""" ax.add_feature(cfeature.COASTLINE, alpha=0.8, linewidth=1.2) ax.add_feature(cfeature.OCEAN, color='#f0f8ff', alpha=0.3) ax.add_feature(cfeature.LAND, color='#f5f5dc', alpha=0.4) # Add cyclic point for smooth visualization data_cyclic, lon_cyclic = add_cyclic_point(data.values, coord=data.longitude.values) # Create contour plot im = ax.contourf(lon_cyclic, data.latitude.values, data_cyclic, levels=levels, cmap=cmap, transform=ccrs.PlateCarree(), extend='both') ax.set_title(title, fontsize=14, fontweight='bold', pad=15) ax.set_global() ax.gridlines(alpha=0.3) return im # Row 1: U Component Analysis # Original U im1 = plot_component_elegant(axes[0,0], u_original, 'Original U Component', u_levels) # U with missing data im2 = plot_component_elegant(axes[0,1], u_missing, 'U Component with Missing Data', u_levels) # Filled U (zonal method) im3 = plot_component_elegant(axes[0,2], u_filled_zonal, 'GridFill U Component (Zonal Init)', u_levels) # U Component Error u_error = np.abs(u_filled_zonal.values - u_original.values) u_error_data = xr.DataArray(u_error, coords=u_original.coords, dims=u_original.dims) u_error_data = u_error_data.where(missing_mask, np.nan) u_error_levels = np.linspace(0, np.nanmax(u_error[missing_mask]), 15) im4 = plot_component_elegant(axes[0,3], u_error_data, 'U Component Error (Filled Regions)', u_error_levels, 'Reds') # Row 2: V Component Analysis # Original V im5 = plot_component_elegant(axes[1,0], v_original, 'Original V Component', v_levels) # V with missing data im6 = plot_component_elegant(axes[1,1], v_missing, 'V Component with Missing Data', v_levels) # Filled V (zonal method) im7 = plot_component_elegant(axes[1,2], v_filled_zonal, 'GridFill V Component (Zonal Init)', v_levels) ``` -------------------------------- ### Skyborn Plotting Utilities: Add Equal Axes Source: https://github.com/qianyesu/skyborn/blob/main/docs/source/api/plotting.rst Adds an axes object to a figure with equal aspect ratio, useful for scientific visualizations. It takes an existing axes object, a position string, and offsets as input. Ensure matplotlib is installed for figure and axes manipulation. ```python import skyborn as skb import matplotlib.pyplot as plt import numpy as np # Create figure with equal axes fig, ax = plt.subplots() ax_new = skb.plot.add_equal_axes(ax, 'right', 0.1, 0.2) ```