import pygrib
import eccodes
import numpy as np
def interpolate_values(values1, values2, factor):
return values1 + (values2 - values1) * factor
ds = pygrib.open(‘Tools/merged.grib’)
with open(‘Tools/merged_interpolated.grib’, ‘wb’) as out_grib:
with open(‘Tools/merged.grib’, ‘rb’) as in_grib:
while True:
gid = eccodes.codes_grib_new_from_file(in_grib)
if gid is None:
break
eccodes.codes_write(gid, out_grib)
eccodes.codes_release(gid)
steps = sorted(set([msg['step'] for msg in ds]))
expected_interval = 2
for i in range(1, len(steps)):
step_diff = steps[i] - steps[i - 1]
if step_diff > expected_interval:
missing_steps = list(range(steps[i - 1] + expected_interval, steps[i], expected_interval))
print(f"Interpolating between step {steps[i - 1]} and {steps[i]} for missing steps {missing_steps}")
msg_before = ds.select(step=steps[i - 1])[0]
msg_after = ds.select(step=steps[i])[0]
values_before = msg_before.values
values_after = msg_after.values
total_missing = len(missing_steps) + 1
for j, missing_step in enumerate(missing_steps, 1):
factor = j / total_missing
interpolated_values = interpolate_values(values_before, values_after, factor)
gid = eccodes.codes_new_from_message(msg_before.tostring())
eccodes.codes_set(gid, 'step', missing_step)
eccodes.codes_set(gid, 'dataDate', msg_before['dataDate'])
eccodes.codes_set(gid, 'dataTime', msg_before['dataTime'])
original_shape = msg_before.values.shape
interpolated_values = interpolated_values.reshape(original_shape)
eccodes.codes_set_values(gid, interpolated_values.flatten())
eccodes.codes_write(gid, out_grib)
eccodes.codes_release(gid)
ds.close()
i’m trying to close hour gaps in a grib file, however its creating a time1 dimensions and all the variables are not using the original time dimensions that has the new interpolated hours.