Sep-21-2024, 08:29 AM
(This post was last modified: Sep-21-2024, 09:38 AM by Gribouillis.)
Hi all,
I try to convert a netCDF to XML with the following lines of code, and I think the code handle the bounds issue. However, it still shows the error message: IndexError: index 31 is out of bounds for axis 0 with size 31
My code:
I try to convert a netCDF to XML with the following lines of code, and I think the code handle the bounds issue. However, it still shows the error message: IndexError: index 31 is out of bounds for axis 0 with size 31
My code:
import netCDF4 as nc from pykml.factory import KML_ElementMaker as KML from lxml import etree # Define input and output file paths input_file = 'C:/Users/asus/.spyder-py3/CarbonMonitor_0_Power_y2019_m01.nc' output_kml_file = 'carbon_monitor_emissions.kml' # Open the NetCDF file ds = nc.Dataset(input_file) # Extract latitude, longitude, and emission data latitudes = ds.variables['latitude'][:] longitudes = ds.variables['longitude'][:] emissions = ds.variables['emission'][:, :, :] # [lon, lat, day] # Ensure bounds don't exceed lat/lon limits lat_size = len(latitudes) lon_size = len(longitudes) num_days = emissions.shape[2] # Number of days in the data # Create KML structure kml_doc = KML.kml( KML.Document( KML.name("CO2 Emissions Data"), ) ) # Convert emissions to KML format for day in range(num_days): for lat_idx in range(lat_size): for lon_idx in range(lon_size): try: emission_value = emissions[lon_idx, lat_idx, day] if not emission_value is None and not isinstance(emission_value, float): # Skip if NaN lat = latitudes[lat_idx] lon = longitudes[lon_idx] # Create a Placemark for each emission data point placemark = KML.Placemark( KML.name(f"Emission Day {day+1}"), KML.Point( KML.coordinates(f"{lon},{lat}") ), KML.description(f"Emission: {emission_value} kgC/h"), ) kml_doc.Document.append(placemark) except IndexError: # Handle any potential indexing errors print(f"Index error at day {day}, lat {lat_idx}, lon {lon_idx}") continue # Save KML file with open(output_kml_file, 'w') as f: f.write(etree.tostring(kml_doc, pretty_print=True).decode('utf-8')) print(f"KML file saved to {output_kml_file}")
Gribouillis write Sep-21-2024, 09:38 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.