def p_deficient_ik(xy_tr, z_tr, xy_te, params, k=K):
# P(Z < c) from IndicatorKriging, which returns P(I >= t). The deficiency indicator is kriged directly:
# threshold 0.5 on the 0/1 indicator, so P(indicator >= 0.5) = P(deficient).
ik = IndicatorKriging(cov_model="exponential", max_neighbors=min(k, len(z_tr)), use_gpu=USE_GPU).fit(xy_tr, z_tr)
return np.clip(ik.predict(xy_te, [0.5], {0.5: params})[0.5], 0, 1)
# Krige inside the upazila, and fall back to the national model where the upazila is too small
def p_deficient_ik_upazila(xy_tr, z_tr, g_tr, xy_te, g_te, params_in, params_all, k=K):
out = np.full(len(xy_te), np.nan)
for g in np.unique(g_te):
it, ip = np.flatnonzero(g_tr == g), np.flatnonzero(g_te == g)
# Local kriging needs at least five samples and both classes
if len(it) >= 5 and z_tr[it].min() != z_tr[it].max():
out[ip] = p_deficient_ik(xy_tr[it], z_tr[it], xy_te[ip], params_in, k)
# Every training sample in the upazila carries the same label, so the probability is that label
elif len(it) >= 5:
out[ip] = z_tr[it][0]
# Nodes still empty take indicator kriging on all training samples
miss = np.isnan(out)
if miss.any():
out[miss] = p_deficient_ik(xy_tr, z_tr, xy_te[miss], params_all, k)
return out
def simple_krige_local(xy, r, xp, params, k=K, chunk=4000):
# Local simple kriging (mean 0) of residuals with an exponential covariance.
nug, ps, a = params
tree = cKDTree(xy); out = np.empty(len(xp))
cov = lambda d: ps * np.exp(-d / a) + nug * (d < 1e-9)
# Predict in chunks so the neighbour-distance matrices stay small
for c0 in range(0, len(xp), chunk):
p = xp[c0:c0 + chunk]
dd, ii = tree.query(p, k=k)
nb = xy[ii]
D = np.sqrt(((nb[:, :, None, :] - nb[:, None, :, :]) ** 2).sum(-1))
w = np.linalg.solve(cov(D), cov(dd)[:, :, None])[:, :, 0]
out[c0:c0 + len(p)] = (w * r[ii]).sum(1)
return out
# Dummies for zone, cropping pattern, and geology, plus land type, drainage, and elevation
def landscape_features(df, coords):
F = pd.get_dummies(df[["AEZ_ID", "CP_ID", "SGEO_ID"]].astype("category"), dtype=float)
cols = ["LT_ID", "DC_ID", "ELEV"] + (["X", "Y"] if coords else [])
F[cols] = df[cols].to_numpy(float)
return F
# Shared dummy columns for samples and grid
_all = pd.concat([soil[["AEZ_ID", "CP_ID", "SGEO_ID", "LT_ID", "DC_ID", "ELEV", "X", "Y"]],
GM[["AEZ_ID", "CP_ID", "SGEO_ID", "LT_ID", "DC_ID", "ELEV", "X", "Y"]]], ignore_index=True)
F_XY_ALL, F_NO_ALL = landscape_features(_all, True).to_numpy(), landscape_features(_all, False).to_numpy()
F_XY, F_NO = F_XY_ALL[:len(soil)], F_NO_ALL[:len(soil)]
G_XY, G_NO = F_XY_ALL[len(soil):], F_NO_ALL[len(soil):]
# Each tree sees 30% of the features and half the rows, and each leaf holds at least five samples
RF_KW = dict(n_estimators=N_TREES, min_samples_leaf=5, max_features=0.3, max_samples=0.5, n_jobs=-1, random_state=SEED)
print("Landscape features:", F_NO.shape[1], "(plus X, Y for RF)")