File size: 15,695 Bytes
613ee99 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | import os
import argparse
import xarray as xr
import numpy as np
import pandas as pd
# --- Utility Functions (unchanged logic) ---
def generate_empty_dataframe(start_year, end_year, latitude_len, longitude_len):
"""Generates an empty DataFrame with a MultiIndex for time and grid coordinates."""
df = pd.MultiIndex.from_product([[year for year in range(start_year, end_year + 1)],
[month + 1 for month in range(12)],
[latitude for latitude in range(latitude_len)],
[longitude for longitude in range(longitude_len)]],
names=['year', 'month', 'latitude', 'longitude']).to_frame(index=False)
return df
def count_month(start_year, start_month, end_year, end_month, start, end):
"""Calculates the number of months before and after the data range, relative to the target range."""
s_year, s_month = start
e_year, e_month = end
pre_mon = (start_year - s_year) * 12 + (start_month - s_month)
tail_mon = (e_year - end_year) * 12 + (e_month - end_month)
return pre_mon, tail_mon
def concat_pre_end(pre_month, tail_month, data):
"""Pads or trims the data array to fit the target time range with NaNs."""
# Assuming a fixed spatial resolution for padding/trimming based on the original script's logic: 180*360
spatial_size = 180 * 360
new_data = data.copy()
if pre_month > 0:
prefix_len = spatial_size * pre_month
prefix = np.full(prefix_len, np.nan)
new_data = np.concatenate((prefix, new_data))
elif pre_month < 0:
del_length = abs(spatial_size * pre_month)
new_data = new_data[del_length:]
if tail_month > 0:
tail_len = spatial_size * tail_month
tail = np.full(tail_len, np.nan)
new_data = np.concatenate((new_data, tail))
elif tail_month < 0:
del_length = abs(spatial_size * tail_month)
new_data = new_data[:-del_length]
return new_data
def get_time(pro_data):
"""Extracts the start and end year/month from the xarray Dataset time coordinate."""
time_var = 'time'
for var in list(pro_data.coords):
if 'time' in var:
time_var = var
break
start_time = pd.to_datetime(pro_data[time_var].values[0])
end_time = pd.to_datetime(pro_data[time_var].values[-1])
return start_time.year, start_time.month, end_time.year, end_time.month
def get_nc_data(key, dic, env_path, target_start, target_end):
"""Loads, processes, and time-aligns a single NetCDF variable."""
pro_dir = os.path.join(env_path, f'{key}.nc')
variable = dic[key.lower()]
with xr.open_dataset(pro_dir) as pro_data:
data = pro_data[variable].values.flatten()
start_year, start_month, end_year, end_month = get_time(pro_data)
pre_mon, tail_mon = count_month(start_year, start_month, end_year, end_month,
start=target_start, end=target_end)
new_data = concat_pre_end(pre_mon, tail_mon, data)
return new_data
# --- Main Processing Function ---
def main(env_path, gobm_dir, dgvm_dir, co2_path, output_dir,
env_start_year, env_start_month, env_end_year, env_end_month, nrt_dir=None):
# Configuration based on original script
LAT_LEN, LON_LEN = 180, 360
DIC = {
'sst':'sst', 'ice':'ice', 'chl':'CHL1_mean', 'mld':'somxl030',
'sss':'salinity', 'ssh':'sossheig', 'slp':'msl', 'wind':'wind',
}
TARGET_START = (env_start_year, env_start_month)
TARGET_END = (env_end_year, env_end_month)
print(f"🌊 **Starting Data Processing**")
print(f"Target Time Range: {env_start_year}/{env_start_month} to {env_end_year}/{env_end_month}")
print(f"Environmental Data Path: {env_path}")
# 1. Initialize DataFrame for Environmental Data
print("\n## 1. Processing Environmental Variables")
add_data = generate_empty_dataframe(start_year=env_start_year, end_year=env_end_year,
latitude_len=LAT_LEN, longitude_len=LON_LEN)
print(f"Initialized DataFrame with shape: {add_data.shape}")
# Process each environmental variable file
for key_file in os.listdir(env_path):
key = key_file.split('.')[0]
if key.lower() not in DIC:
print(f"Skipping unknown file: {key_file}")
continue
print(f"Processing environmental variable: **{key}**")
new_data = get_nc_data(key, DIC, env_path=env_path,
target_start=TARGET_START, target_end=TARGET_END)
add_data[key.lower()] = new_data
# Handle fill values/outliers
for i in ['sst', 'ice', 'chl']:
err_idx = add_data[add_data[i] == -999].index
if err_idx.shape[0] > 0:
print(f"Found and replaced {err_idx.shape[0]} fill values (-999) in {i}")
add_data.loc[err_idx, i] = np.nan
for i in ['mld', 'ssh']:
if add_data[i].max() > 1e36:
err_idx = add_data[add_data[i] == add_data[i].max()].index
if err_idx.shape[0] > 0:
print(f"Found and replaced {err_idx.shape[0]} max-value outliers in {i}")
add_data.loc[err_idx, i] = np.nan
# 2. Add Coast and Region Mask Data
print("\n## 2. Adding Region and Coast Mask Data")
region_mask_path = os.path.join(env_path, 'Ocean_RECCAP2_mask.nc')
if not os.path.exists(region_mask_path):
print(f"❌ Error: Mask file not found at {region_mask_path}")
return
with xr.open_dataset(region_mask_path) as region_mask:
df_spatial = pd.MultiIndex.from_product([[lat for lat in range(LAT_LEN)],
[lon for lon in range(LON_LEN)]],
names=['latitude', 'longitude']).to_frame(index=False)
map_arr = ['land', 'Atlantic', 'Pacific', 'Indian', 'Arctic', 'Southern']
df_spatial['type'] = region_mask.variables['open_ocean'].values.flatten()
df_spatial['type'] = df_spatial['type'].apply(lambda x: map_arr[x] if x < len(map_arr) else 'Unknown')
df_encoded = pd.get_dummies(df_spatial, columns=['type'])
df_encoded['type_ocean'] = ~df_encoded.get('type_land', False) # True if 'type_land' column doesn't exist or is False
df_encoded['type_coast'] = region_mask.variables['coast'].values.flatten()
cols = [c for c in df_encoded.columns if c.startswith('type_')]
for col in cols:
df_encoded[col] = df_encoded[col].astype(int)
# Repeat spatial data for all months/years in the target range
num_repetitions = add_data.shape[0] // df_encoded.shape[0]
df_repeated = pd.concat([df_encoded] * num_repetitions, ignore_index=True)
add_data[cols] = df_repeated[cols].values
print(f"Added {len(cols)} spatial mask columns.")
# 3. Process GOBM and Data Product (GCB)
print("\n## 3. Processing GCB Model/Product Data")
# Determine the actual model end year by scanning directories
model_start_year = 2000
model_end_year = 2020
for dir_path in [gobm_dir, dgvm_dir]:
if not os.path.isdir(dir_path):
print(f"⚠️ Warning: Model directory not found: {dir_path}. Skipping.")
continue
for i in os.listdir(dir_path):
if i.endswith('.nc'):
try:
with xr.open_dataset(os.path.join(dir_path, i)) as model:
year = pd.to_datetime(model.time.values[-1]).year
if year > model_end_year:
model_end_year = year
except Exception as e:
print(f"Error reading time from {i}: {e}")
print(f"Model/Product Time Range: {model_start_year} to {model_end_year}")
# Prepare DataFrame for GCB data
df_gcb = generate_empty_dataframe(start_year=model_start_year, end_year=model_end_year,
latitude_len=LAT_LEN, longitude_len=LON_LEN)
# var_name = 'fgco2' # Assuming 'fgco2' is the variable of interest in GCB files
# var_name = 'sfco2'
# Load and flatten GCB data
for dir_path in [gobm_dir, dgvm_dir]:
if not os.path.isdir(dir_path): continue
for i in os.listdir(dir_path):
if i.endswith('.nc'):
name = i.split('.')[0]
print(f"Loading GCB data: **{name}**")
try:
with xr.open_dataset(os.path.join(dir_path, i)) as model:
# Select relevant time slice
value_var = 'fgco2'
for var in list(model.variables):
if 'co2' in var:
value_var = var
break
print(f"Identified variable for GCB data: {value_var}")
model_sel = model.sel(time=slice(str(model_start_year), str(model_end_year)))
df_gcb[name] = model_sel[value_var].values.flatten()
except Exception as e:
print(f"Error processing GCB file {i}: {e}")
# Merge GCB data into the main DataFrame (add_data)
# Get index range in add_data that matches GCB time range
target_idx = add_data[(add_data['year'] >= model_start_year) &
(add_data['year'] <= model_end_year)].index
target_cols = df_gcb.columns[4:]
if len(target_idx) == df_gcb.shape[0]:
add_data.loc[target_idx, target_cols] = df_gcb[target_cols].values
print("Merged GCB data successfully.")
else:
print("❌ GCB data size mismatch. Not merged.")
# 4. Add CO2 data
print("\n## 4. Adding CO2 Data")
try:
co2 = pd.read_csv(co2_path)
except Exception as e:
print(f"❌ Error reading CO2 file: {e}. Skipping CO2 data.")
co2 = None
if co2 is not None and 'co2' in co2.columns:
co2_start_year = max(int(co2.head(1)['year'].values[0]), env_start_year)
co2_end_year = min(int(co2.tail(1)['year'].values[0]), env_end_year)
target_idx = co2[(co2['year'] >= co2_start_year) &
(co2['year'] <= co2_end_year)].index
src_idx = add_data[(add_data['year'] >= co2_start_year) &
(add_data['year'] <= co2_end_year)].index
target_col = 'co2'
if len(src_idx) == len(target_idx):
add_data.loc[src_idx, target_col] = co2.loc[target_idx, target_col].values
print(f"Merged CO2 data for years {co2_start_year} to {co2_end_year}.")
else:
print("❌ CO2 data size mismatch for the overlapping period. Not merged.")
# 5. Final Save
print("\n## 5. Saving Final Data")
os.makedirs(output_dir, exist_ok=True)
output_filename = f'new_{env_end_year}{env_end_month:02d}.feather'
# output_filename = f'new_{env_end_year}{env_end_month:02d}_64.feather'
output_filepath = os.path.join(output_dir, output_filename)
# Convert float64 to float32 to save space (as per original file's logic)
float64_cols = add_data.select_dtypes(include=['float64']).columns
add_data[float64_cols] = add_data[float64_cols].astype('float32')
add_data.to_feather(output_filepath)
print(f"✅ Successfully saved final DataFrame to: **{output_filepath}**")
print(f"Final DataFrame shape: {add_data.shape}")
# process nrt data
if nrt_dir:
nrt_start_year = 2000
add_data = add_data[add_data.year >= nrt_start_year]
nrt_filepath = os.path.join(nrt_dir, f'new_{env_end_year}{env_end_month:02d}.feather')
add_data.to_feather(nrt_filepath)
print(f"✅ Successfully saved NRT DataFrame to: **{nrt_filepath}**")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Process and merge environmental and model data into a single feather file.")
# Directory/File Paths
parser.add_argument('--env_path', type=str,
default='/data/angcb/home/kpiyu/data/Environmental_variables/2025/Environmental_variables',
help='Path to the directory containing environmental variable NetCDF files and the mask file.')
parser.add_argument('--gobm_dir', type=str,
default='/data/angcb/home/kpiyu/data/Model/GCB2025/GCB2025/',
help='Path to the directory containing GOBM model NetCDF files.')
parser.add_argument('--dgvm_dir', type=str,
default='/data/angcb/home/kpiyu/data/Data_product/GCB2025/GCB2025',
help='Path to the directory containing DGVM data product NetCDF files.')
parser.add_argument('--co2_path', type=str,
default='/data/angcb/home/kpiyu/ANGCB/dataset/co2_output/co2_full_grid_2025_8.csv',
help='Path to the CO2 CSV file.')
parser.add_argument('--output_dir', type=str,
default='/data/angcb/home/kpiyu/ANGCB/dataset/preprocessed_data',
help='Directory where the final feather file will be saved.')
parser.add_argument('--nrt_dir', type=str,
default=None,
help='Directory where the final NRT feather file will be saved.')
# Time Parameters
parser.add_argument('--env_start_year', type=int, default=1959,
help='Start year for the main environmental data processing range.')
parser.add_argument('--env_start_month', type=int, default=1, choices=range(1, 13),
help='Start month for the main environmental data processing range.')
parser.add_argument('--env_end_year', type=int, default=2025,
help='End year for the main environmental data processing range.')
parser.add_argument('--env_end_month', type=int, default=12, choices=range(1, 13),
help='End month for the main environmental data processing range.')
args = parser.parse_args()
main(env_path=args.env_path, gobm_dir=args.gobm_dir, dgvm_dir=args.dgvm_dir,
co2_path=args.co2_path, output_dir=args.output_dir,
env_start_year=args.env_start_year, env_start_month=args.env_start_month,
env_end_year=args.env_end_year, env_end_month=args.env_end_month,
nrt_dir=args.nrt_dir)
# python data_preprocess.py \
# --env_path /data/angcb/home/kpiyu/data/Environmental_variables/2025/Environmental_variables \
# --gobm_dir /data/angcb/home/kpiyu/data/Model/GCB2025/GCB2025/ \
# --dgvm_dir /data/angcb/home/kpiyu/data/Data_product/GCB2025/GCB2025 \
# --co2_path /data/angcb/home/kpiyu/ANGCB/dataset/co2_output/co2_full_grid_2025_8.csv \
# --output_dir /data/angcb/home/kpiyu/ANGCB/dataset/preprocessed_data \
# --env_start_year 1959 \
# --env_start_month 1 \
# --env_end_year 2025 \
# --env_end_month 12
# python data_preprocess.py \
# --env_path /data/angcb/home/kpiyu/data/Environmental_variables/2025/Environmental_variables \
# --gobm_dir /data/angcb/home/kpiyu/data/Model/GCB2025/fCO2/ \
# --dgvm_dir /data/angcb/home/kpiyu/data/Data_product/GCB2025/fCO2/ \
# --co2_path /data/angcb/home/kpiyu/ANGCB/dataset/co2_output/co2_full_grid_2025_8.csv \
# --output_dir /data/angcb/home/kpiyu/ANGCB/dataset/flux/ \
# --env_start_year 1959 \
# --env_start_month 1 \
# --env_end_year 2025 \
# --env_end_month 12 |