import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor

# INPUT DATA
data = pd.read_csv(
    r"H:\wetland_warmer_response\dregree_0.05\delta_temperature\data_2020\forest_minus_wetland_class_all_delta_variables_data_for_ml_95%_et.csv")


x = data.iloc[:, [7,9,10,11,12,13,14,15,16,17]].values###Selecting feature variables
y = data.iloc[:,6].values#response variable

# =========【Phase 1: Model training (with OOB error evaluation)】=========
rfc = RandomForestRegressor(n_estimators=200, max_features="sqrt", oob_score=True, random_state=1)
rfc.fit(x, y)

# =========【Phase 2: Model application - for full data prediction】=========

additional_cols = data.iloc[:, 2:6]
additional_col_names = data.columns[2:6].tolist()


# 定义特征索引
feature_names = ['delta_G', 'delta_ra', 'delta_W','delta_ET', 'delta_alpha', 'delta_epsilon',
                 'delta_dsr', 'delta_lin', 'delta_Ta','delta_qa']
atmospheric_indices = [0,3,9,1,4,5]
biophysical_indices = [6,7,8,2]

# Function: Prediction after zeroing
def predict_with_zero_features(model, original_x, zero_indices):
    modified_x = original_x.copy()
    modified_x[:, zero_indices] = 0.000001
    return model.predict(modified_x)

# Predicting raw data
original_predictions = rfc.predict(x)

# Zero prediction for each factor
single_zero_predictions = {}
for i, name in enumerate(feature_names):
    single_zero_predictions[f"predicted_y_{name}_zeroed"] = predict_with_zero_features(rfc, x, [i])

# Zero prediction of atmospheric factors and biophysical factors
atmospheric_zero_predictions = predict_with_zero_features(rfc, x, atmospheric_indices)
biophysical_zero_predictions = predict_with_zero_features(rfc, x, biophysical_indices)

# Build output
result_df = pd.DataFrame({
    "original_y": y,
    "original_predicted_y": original_predictions,
    "predicted_y_all_atmospheric_zeroed": atmospheric_zero_predictions,
    "predicted_y_all_biophysical_zeroed": biophysical_zero_predictions
})

# Add zero prediction columns for each single factor
for name, pred in single_zero_predictions.items():
    result_df[name] = pred

# Adding extra information to the original (such as row and column numbers)
# Add columns 2 to 6 to the result
for col_name in additional_col_names:
    result_df[col_name] = additional_cols[col_name].values

# save to CSV
output_path = r"H:\wetland_warmer_response\dregree_0.05\delta_temperature\data_2020\predictions_all_samples_direct_delta_variables_95%_et.csv"
result_df.to_csv(output_path, index=False)
