Add awesome NetCDF Explorer Gradio app
Browse files- Interactive NetCDF file visualization with multiple plot types
- 2D heatmaps with customizable colormaps and dimension slicing
- Time series analysis with spatial aggregation options
- Vertical profile plots for atmospheric/oceanic data
- Comprehensive metadata analysis and variable exploration
- Modern Gradio interface with responsive controls
- Support for complex multi-dimensional NetCDF datasets
π€ Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
Files changed (2)
- app.pyAdded+445
- requirements.txtAdded+10
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445import gradio as grimport xarray as xrimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.patches as patchesimport plotly.express as pximport plotly.graph_objects as gofrom plotly.subplots import make_subplotsimport pandas as pdimport tempfileimport osfrom typing import Optional, Tuple, Dict, Any
# Set matplotlib backendplt.switch_backend('Agg')
def analyze_netcdf(file_path: str) -> Tuple[str, Dict[str, Any]]: """Analyze NetCDF file and extract metadata.""" try: ds = xr.open_dataset(file_path) # Basic info info = { 'dimensions': dict(ds.dims), 'variables': list(ds.data_vars.keys()), 'coordinates': list(ds.coords.keys()), 'attrs': dict(ds.attrs), 'data_vars_info': {} } # Detailed variable information for var in ds.data_vars: var_info = { 'shape': ds[var].shape, 'dtype': str(ds[var].dtype), 'dims': ds[var].dims, 'attrs': dict(ds[var].attrs), 'min': float(ds[var].min().values) if ds[var].size > 0 else None, 'max': float(ds[var].max().values) if ds[var].size > 0 else None, 'mean': float(ds[var].mean().values) if ds[var].size > 0 else None } info['data_vars_info'][var] = var_info # Generate summary text summary = f"""## Dataset Overview- **Dimensions**: {len(ds.dims)} ({', '.join([f"{k}: {v}" for k, v in ds.dims.items()])})- **Variables**: {len(ds.data_vars)} data variables, {len(ds.coords)} coordinates- **Global Attributes**: {len(ds.attrs)} attributes
### Variables:""" for var, var_info in info['data_vars_info'].items(): summary += f"- **{var}**: {var_info['shape']} ({var_info['dtype']})" if var_info['min'] is not None: summary += f" [{var_info['min']:.2f} to {var_info['max']:.2f}]" summary += "\n" ds.close() return summary, info except Exception as e: return f"Error analyzing file: {str(e)}", {}
def create_2d_plot(file_path: str, variable: str, time_idx: int = 0, level_idx: int = 0, colormap: str = "viridis") -> go.Figure: """Create 2D visualization of NetCDF data.""" try: ds = xr.open_dataset(file_path) if variable not in ds.data_vars: raise ValueError(f"Variable '{variable}' not found in dataset") data_var = ds[variable] # Handle different dimensional data if len(data_var.dims) >= 2: # Find spatial dimensions (usually lat/lon or x/y) spatial_dims = [] for dim in data_var.dims: if any(name in dim.lower() for name in ['lat', 'lon', 'x', 'y']): spatial_dims.append(dim) if len(spatial_dims) >= 2: # Use the last two spatial dimensions dim1, dim2 = spatial_dims[-2:] # Select subset based on other dimensions data_subset = data_var for dim in data_var.dims: if dim not in [dim1, dim2]: if 'time' in dim.lower(): data_subset = data_subset.isel({dim: min(time_idx, data_var.sizes[dim]-1)}) elif any(name in dim.lower() for name in ['level', 'depth', 'height']): data_subset = data_subset.isel({dim: min(level_idx, data_var.sizes[dim]-1)}) else: data_subset = data_subset.isel({dim: 0}) else: # Use first two dimensions dims = list(data_var.dims) if len(dims) >= 2: data_subset = data_var.isel({dim: 0 for dim in dims[2:]}) else: data_subset = data_var dim1, dim2 = dims[:2] else: raise ValueError("Data must have at least 2 dimensions for 2D plotting") # Create the plot fig = go.Figure(data=go.Heatmap( z=data_subset.values, x=data_subset.coords[dim2].values if dim2 in data_subset.coords else None, y=data_subset.coords[dim1].values if dim1 in data_subset.coords else None, colorscale=colormap, colorbar=dict(title=data_var.attrs.get('units', 'Value')) )) fig.update_layout( title=f"{variable} - {data_var.attrs.get('long_name', variable)}", xaxis_title=dim2, yaxis_title=dim1, height=600, width=800 ) ds.close() return fig except Exception as e: # Return empty figure with error message fig = go.Figure() fig.add_annotation( text=f"Error creating plot: {str(e)}", x=0.5, y=0.5, xref="paper", yref="paper", showarrow=False, font=dict(size=16, color="red") ) return fig
def create_time_series(file_path: str, variable: str, method: str = "mean") -> go.Figure: """Create time series plot by aggregating spatial dimensions.""" try: ds = xr.open_dataset(file_path) if variable not in ds.data_vars: raise ValueError(f"Variable '{variable}' not found in dataset") data_var = ds[variable] # Find time dimension time_dim = None for dim in data_var.dims: if 'time' in dim.lower(): time_dim = dim break if time_dim is None: raise ValueError("No time dimension found in the data") # Aggregate spatial dimensions spatial_dims = [dim for dim in data_var.dims if dim != time_dim] if method == "mean": time_series = data_var.mean(dim=spatial_dims) elif method == "max": time_series = data_var.max(dim=spatial_dims) elif method == "min": time_series = data_var.min(dim=spatial_dims) else: time_series = data_var.mean(dim=spatial_dims) fig = go.Figure(data=go.Scatter( x=time_series.coords[time_dim].values, y=time_series.values, mode='lines+markers', name=f"{method.title()} {variable}" )) fig.update_layout( title=f"Time Series: {method.title()} {variable}", xaxis_title="Time", yaxis_title=f"{variable} ({data_var.attrs.get('units', 'Value')})", height=400 ) ds.close() return fig except Exception as e: fig = go.Figure() fig.add_annotation( text=f"Error creating time series: {str(e)}", x=0.5, y=0.5, xref="paper", yref="paper", showarrow=False, font=dict(size=16, color="red") ) return fig
def create_vertical_profile(file_path: str, variable: str, time_idx: int = 0) -> go.Figure: """Create vertical profile plot.""" try: ds = xr.open_dataset(file_path) if variable not in ds.data_vars: raise ValueError(f"Variable '{variable}' not found in dataset") data_var = ds[variable] # Find vertical dimension vertical_dim = None for dim in data_var.dims: if any(name in dim.lower() for name in ['level', 'depth', 'height', 'pressure']): vertical_dim = dim break if vertical_dim is None: raise ValueError("No vertical dimension found in the data") # Average over horizontal dimensions, select time dims_to_avg = [] for dim in data_var.dims: if dim != vertical_dim: if 'time' in dim.lower(): data_var = data_var.isel({dim: min(time_idx, data_var.sizes[dim]-1)}) else: dims_to_avg.append(dim) if dims_to_avg: profile = data_var.mean(dim=dims_to_avg) else: profile = data_var fig = go.Figure(data=go.Scatter( x=profile.values, y=profile.coords[vertical_dim].values, mode='lines+markers', name=variable )) fig.update_layout( title=f"Vertical Profile: {variable}", xaxis_title=f"{variable} ({data_var.attrs.get('units', 'Value')})", yaxis_title=vertical_dim, height=500 ) ds.close() return fig except Exception as e: fig = go.Figure() fig.add_annotation( text=f"Error creating profile: {str(e)}", x=0.5, y=0.5, xref="paper", yref="paper", showarrow=False, font=dict(size=16, color="red") ) return fig
def process_netcdf_file(file): """Process uploaded NetCDF file and return analysis.""" if file is None: return "Please upload a NetCDF file.", {}, [], [] try: # Save uploaded file temporarily with tempfile.NamedTemporaryFile(delete=False, suffix='.nc') as tmp_file: tmp_file.write(file.read()) tmp_path = tmp_file.name # Analyze the file summary, info = analyze_netcdf(tmp_path) # Get variable options variable_options = list(info.get('data_vars_info', {}).keys()) # Get dimension options for slicing dimensions = info.get('dimensions', {}) return summary, tmp_path, variable_options, list(dimensions.keys()) except Exception as e: return f"Error processing file: {str(e)}", "", [], []
def update_plot(file_path: str, variable: str, plot_type: str, time_idx: int, level_idx: int, colormap: str, aggregation_method: str): """Update plot based on user selections.""" if not file_path or not variable: return go.Figure() try: if plot_type == "2D Heatmap": return create_2d_plot(file_path, variable, time_idx, level_idx, colormap) elif plot_type == "Time Series": return create_time_series(file_path, variable, aggregation_method) elif plot_type == "Vertical Profile": return create_vertical_profile(file_path, variable, time_idx) else: return go.Figure() except Exception as e: fig = go.Figure() fig.add_annotation( text=f"Error: {str(e)}", x=0.5, y=0.5, xref="paper", yref="paper", showarrow=False ) return fig
# Create Gradio interfacewith gr.Blocks(title="NetCDF Explorer π", theme=gr.themes.Soft()) as app: gr.Markdown(""" # π NetCDF Explorer Upload and explore NetCDF (.nc) files with interactive visualizations! **Features:** - π Interactive 2D heatmaps - π Time series analysis - π Vertical profiles - π¨ Customizable colormaps - π Comprehensive metadata analysis """) # File upload section with gr.Row(): file_upload = gr.File( label="Upload NetCDF File (.nc)", file_types=[".nc", ".netcdf"], type="binary" ) # File analysis section with gr.Row(): file_info = gr.Markdown("Upload a file to see its structure and metadata.") # Control panel with gr.Row(): with gr.Column(scale=1): variable_dropdown = gr.Dropdown( label="Select Variable", choices=[], interactive=True ) plot_type = gr.Radio( label="Plot Type", choices=["2D Heatmap", "Time Series", "Vertical Profile"], value="2D Heatmap" ) colormap_dropdown = gr.Dropdown( label="Colormap", choices=["viridis", "plasma", "inferno", "magma", "cividis", "Blues", "Reds", "RdYlBu", "RdBu", "coolwarm"], value="viridis" ) aggregation_method = gr.Radio( label="Time Series Aggregation", choices=["mean", "max", "min"], value="mean", visible=False ) with gr.Column(scale=1): time_slider = gr.Slider( label="Time Index", minimum=0, maximum=100, value=0, step=1 ) level_slider = gr.Slider( label="Level Index", minimum=0, maximum=100, value=0, step=1 ) update_btn = gr.Button("Update Plot", variant="primary") # Plot display plot_display = gr.Plot(label="Visualization") # Hidden state to store file path file_path_state = gr.State("") # Event handlers def on_file_upload(file): summary, tmp_path, variables, dimensions = process_netcdf_file(file) # Update UI components updates = [ gr.update(value=summary), # file_info gr.update(choices=variables, value=variables[0] if variables else None), # variable_dropdown gr.update(value=tmp_path), # file_path_state ] return updates def on_plot_type_change(plot_type_val): if plot_type_val == "Time Series": return gr.update(visible=True) else: return gr.update(visible=False) def on_update_plot(file_path, variable, plot_type_val, time_idx, level_idx, colormap, agg_method): return update_plot(file_path, variable, plot_type_val, int(time_idx), int(level_idx), colormap, agg_method) # Connect event handlers file_upload.upload( fn=on_file_upload, inputs=[file_upload], outputs=[file_info, variable_dropdown, file_path_state] ) plot_type.change( fn=on_plot_type_change, inputs=[plot_type], outputs=[aggregation_method] ) update_btn.click( fn=on_update_plot, inputs=[file_path_state, variable_dropdown, plot_type, time_slider, level_slider, colormap_dropdown, aggregation_method], outputs=[plot_display] ) # Auto-update on variable change variable_dropdown.change( fn=on_update_plot, inputs=[file_path_state, variable_dropdown, plot_type, time_slider, level_slider, colormap_dropdown, aggregation_method], outputs=[plot_display] )
if __name__ == "__main__": app.launch()12345678910gradio==5.42.0xarray>=2023.1.0netcdf4>=1.6.0numpy>=1.21.0matplotlib>=3.5.0plotly>=5.10.0pandas>=1.5.0scipy>=1.9.0h5netcdf>=1.0.0dask>=2022.1.0app.pyAdded+445
requirements.txtAdded+10