source: trunk/LMDZ.MARS/util/display_netcdf.py @ 3681

Last change on this file since 3681 was 3681, checked in by jbclement, 3 months ago

PEM:
Small improvements for the python script to display variables in a NetCDF file.
JBC

  • Property svn:executable set to *
File size: 4.2 KB
Line 
1##############################################################
2### Python script to visualize a variable in a NetCDF file ###
3##############################################################
4
5### This script can display any variable of a NetCDF file.
6### The file name, the variable to display and eventually the
7### dimension are asked to the user in the terminal.
8
9import os
10import readline
11import glob
12from netCDF4 import Dataset
13import matplotlib.pyplot as plt
14import numpy as np
15
16##############################################################
17### Setup readline for file name autocompletion
18def complete(text,state):
19    line = readline.get_line_buffer().split()
20    # Use glob to find all matching files/directories for the current text
21    if '*' not in text:
22        text += '*'
23    matches = glob.glob(os.path.expanduser(text))
24    # Add '/' if the match is a directory
25    matches = [match + '/' if os.path.isdir(match) else match for match in matches]
26    try:
27        return matches[state]
28    except IndexError:
29        return None
30
31### Function to handle autocomplete for variable names
32def complete_variable_names(variable_names):
33    def completer(text, state):
34        options = [name for name in variable_names if name.startswith(text)]
35        if state < len(options):
36            return options[state]
37        else:
38            return None
39    return completer
40
41### Function to visualize a variable from a NetCDF file
42def visualize_variable():
43    # Ask for the NetCDF file name
44    readline.set_completer(complete)
45    readline.parse_and_bind('tab: complete')
46    file = input("Enter the name of the NetCDF file: ")
47   
48    # Open the NetCDF file
49    try:
50        dataset = Dataset(file,mode='r')
51    except FileNotFoundError:
52        print(f"File '{file}' not found.")
53        return
54
55    # Display available variables
56    variable_names = list(dataset.variables.keys())
57    print("Available variables:\n",variable_names)
58   
59    # Ask for the variable to display
60    readline.set_completer(complete_variable_names(variable_names))
61    variable_name = input("\nEnter the name of the variable you want to visualize: ")
62   
63    # Check if the variable exists
64    if variable_name not in dataset.variables:
65        print(f"Variable '{variable_name}' not found in the dataset.")
66        dataset.close()
67        return
68   
69    # Extract the selected variable
70    variable = dataset.variables[variable_name][:]
71   
72    # Extract latitude, longitude and altitude
73    latitude = dataset.variables['latitude'][:]
74    longitude = dataset.variables['longitude'][:]
75   
76    # Check if the variable has altitude and time dimensions
77    dimensions = dataset.variables[variable_name].dimensions
78    print(f"\nDimensions of '{variable_name}': {dimensions}")
79   
80    # If the variable has a time dimension, ask for the time index
81    if 'Time' in dimensions:
82        if variable.shape[0] == 1:
83            time_index = 0
84        else:
85            time_index = int(input(f"Enter the time index (0 to {variable.shape[0] - 1}): "))
86    else:
87        time_index = None
88   
89    # If the variable has an altitude dimension, ask for the altitude index
90    if 'altitude' in dimensions:
91        altitude = dataset.variables['altitude'][:]
92        altitude_index = int(input(f"Enter the altitude index (0 to {altitude.shape[0] - 1}): "))
93    else:
94        altitude_index = None
95   
96    # Prepare the 2D slice for plotting
97    if time_index is not None and altitude_index is not None:
98        data_slice = variable[time_index,altitude_index,:,:]
99    elif time_index is not None:
100        data_slice = variable[time_index,:,:]
101    elif altitude_index is not None:
102        data_slice = variable[altitude_index,:,:]
103    else:
104        data_slice = variable[:,:]
105   
106    # Plot the selected variable
107    plt.figure(figsize = (10,6))
108    plt.contourf(longitude,latitude,data_slice,cmap = 'jet')
109    plt.colorbar(label=f"{variable_name.capitalize()} (units)") # Adjust units based on your data
110    plt.xlabel('Longitude (degrees)')
111    plt.ylabel('Latitude (degrees)')
112    plt.title(f"{variable_name.capitalize()} visualization")
113   
114    # Show the plot
115    plt.show()
116   
117    # Close the NetCDF file
118    dataset.close()
119
120### Call the main function
121visualize_variable()
Note: See TracBrowser for help on using the repository browser.