source: trunk/LMDZ.MARS/util/analyse_netcdf.py @ 3459

Last change on this file since 3459 was 3459, checked in by jbclement, 9 months ago

Mars PCM:

  • Addition in the "util" folder of two python scripts: one is to visualize easily any variable of a NetCDF file; the other is to display useful information about the variables of a NetCDF file to help for debugging.
  • Move of the launching scripts for the 1D model from the "deftank" to the "util" folder.

JBC

  • Property svn:executable set to *
File size: 2.7 KB
Line 
1############################################################
2### Python script to analyse a NetCDF file for debugging ###
3############################################################
4
5### This script gives useful information about a NetCDF file
6### to help for debugging. For each variable, it outputs the
7### dimensions, the min & max values, the average value and
8### warns the user in case of NaN or negative values.
9### The file name is asked to the user in the terminal.
10
11import os
12import readline
13import glob
14from netCDF4 import Dataset
15import numpy as np
16
17############################################################
18### Setup readline for file name autocompletion
19def complete(text,state):
20    line = readline.get_line_buffer().split()
21    # Use glob to find all matching files/directories for the current text
22    if '*' not in text:
23        text += '*'
24    matches = glob.glob(os.path.expanduser(text))
25    # Add '/' if the match is a directory
26    matches = [match + '/' if os.path.isdir(match) else match for match in matches]
27   
28    try:
29        return matches[state]
30    except IndexError:
31        return None
32
33### Function to analyze a variable in a NetCDF file
34def analyze_variable(variable):
35    # Get the data for the variable
36    data = variable[:]
37   
38    # Calculate min, max and mean
39    data_min = np.nanmin(data) # Min value ignoring NaN
40    data_max = np.nanmax(data) # Max value ignoring NaN
41    data_mean = np.nanmean(data) # Mean value ignoring NaN
42   
43    # Check if there are any NaN values
44    has_nan = np.isnan(data).any()
45
46    # Check for negative values
47    has_negative = (data < 0).any()
48   
49    # Print the results
50    print(f"\nAnalysis of variable: {variable.name}")
51    print(f"  Dimensions: {variable.dimensions}")
52    print(f"  Min value : {data_min:>12.6e}")
53    print(f"  Max value : {data_max:>12.6e}")
54    print(f"  Mean value: {data_mean:>12.6e}")
55    if has_nan:
56        print(f\033[91mContains NaN values!\033[0m")
57    if has_negative:
58        print(f\033[93mWarning: contains negative values!\033[0m")
59
60### Main function
61def analyze_netcdf():
62    # Ask for the file name
63    readline.set_completer(complete)
64    readline.parse_and_bind('tab: complete')
65    file = input("Enter the name of the NetCDF file: ")
66   
67    # Open the NetCDF file
68    try:
69        dataset = Dataset(file,mode='r')
70    except FileNotFoundError:
71        print(f"File '{file}' not found.")
72        return
73   
74    # Iterate through all variables in the dataset to analyze them
75    for variable_name in dataset.variables:
76        variable = dataset.variables[variable_name]
77        analyze_variable(variable)
78   
79    # Close the NetCDF file
80    dataset.close()
81
82### Call the main function
83analyze_netcdf()
84
Note: See TracBrowser for help on using the repository browser.