Вычисление среднего значения движущейся площади с отсутствующим значением над моремPython

Программы на Python
Ответить
Anonymous
 Вычисление среднего значения движущейся площади с отсутствующим значением над морем

Сообщение Anonymous »

Я хотел бы попросить помощи в настройке этого кода Python для расчета среднего значения движущейся площади в окне 5 градусов с площадью моря, которая представляет собой недостающее значение 1e + 20 и не должна включаться в расчет среднего скользящего значения. Это данные о температуре с именем «tas».
На самом деле этот код очень хорошо работает в области, где нет моря или отсутствует значение, но когда я использовал его в какой-то части Европы, где есть море, выходные данные пропадают. .
Спасибо за помощь.
###FOR EUROPE with missing value
#Moving area for one time step
import xarray as xr
import numpy as np
from scipy.ndimage import uniform_filter

# Load the NetCDF file
file_path = 'C:/Users/Hundi/Documents/PhDwork/Research/data/hybrid/EU_anal/subENSMEAN_cmip6_ssp245hist_timmean_EU_seamasked.nc'

ds = xr.open_dataset(file_path)

# Specify the exact names of the longitude, latitude, and time variables
lon_name = 'lon'
lat_name = 'lat'
time_name = 'time'

# Define the initial and final boundaries of the area of interest
lon_start, lon_end = 3.375, 25.875
lat_start, lat_end = 42.05, 55.55 #for lat_end add 0.125 cause at the result will be missing 0.125
lon_extend_start, lon_extend_end = 0.875, 28.375
lat_extend_start, lat_extend_end = 39.55, 58.05

# Define the degree resolution and calculate the window width in grid points (0.125° grid, 5° window)
resolution = 0.125
window_size = int(5 / resolution) # This should be 40 for a 5° window with a 0.125° grid

#*******FOR ALL 3Dimension DATA*******************************************************************************
data_subset = ds.sel(
**{lon_name: slice(lon_extend_start, lon_extend_end),
lat_name: slice(lat_extend_start, lat_extend_end)}
).isel({time_name: 0}) # Selecting only the first time step

var_data = data_subset['tas'] #change the var name
#*************************************************************************************************************

# Apply moving average with a square width of 5° (40x40 grid points)
#The uniform_filter from scipy.ndimage is used to calculate a mean over each 5° x 5° square,
# with the specified grid resolution.
smoothed_array = uniform_filter(var_data.values, size=(window_size, window_size), mode='constant')

#************FOR ALL 3D data******************************************************************************
# Convert smoothed_array back to an xarray.DataArray and add the time dimension
smoothed_data = xr.DataArray(
smoothed_array,
dims=(lat_name, lon_name),
coords={lat_name: var_data[lat_name], lon_name: var_data[lon_name]}
).expand_dims(time_name)

# Assign the single time value from the original dataset
smoothed_data = smoothed_data.assign_coords({time_name: [ds[time_name].isel({time_name: 0}).values]})
#***********************************************************************************************************

# Subset the smoothed data back to the area of interest (original boundaries)
smoothed_data_subset = smoothed_data.sel(
**{lat_name: slice(lat_start, lat_end),
lon_name: slice(lon_start, lon_end)}
)

# Save the output as a new xarray Dataset
output_ds = xr.Dataset(
{'moving_mean': smoothed_data_subset}, # 'moving_mean' became the name of the new variable
coords={time_name: smoothed_data_subset[time_name],
lat_name: smoothed_data_subset[lat_name],
lon_name: smoothed_data_subset[lon_name]}
)

# Save to a new NetCDF file
output_ds.to_netcdf('C:/Users/Hundi/Documents/PhDwork/Research/data/hybrid/EU_anal/movingMean_datamask.nc')



Подробнее здесь: https://stackoverflow.com/questions/792 ... e-over-sea
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»