EDGES = np.linspace(0, 2.0, 17)
d_pairs = pdist(xy)
h_lags = np.array([d_pairs[(d_pairs > lo) & (d_pairs <= hi)].mean() for lo, hi in zip(EDGES[:-1], EDGES[1:])])
exp_ind = {}
for c in NAMES:
i_c = (df["rock"] == c).to_numpy(float)
g = 0.5 * pdist(i_c[:, None], "sqeuclidean")
exp_ind[c] = np.array([g[(d_pairs > lo) & (d_pairs <= hi)].mean() for lo, hi in zip(EDGES[:-1], EDGES[1:])])
CORRELOGRAMS = {
"spherical": lambda h, a: 1 - (1.5 * np.minimum(h / a, 1) - 0.5 * np.minimum(h / a, 1) ** 3),
"exponential": lambda h, a: np.exp(-3 * h / a),
"gaussian": lambda h, a: np.exp(-3 * (h / a) ** 2),
}
def both_in(lo, hi, r):
# P(lo <= X < hi, lo <= X' < hi) for standard normals with correlation r
lo, hi = max(lo, -8.0), min(hi, 8.0)
r = min(r, 0.9999)
mv = multivariate_normal(mean=[0, 0], cov=[[1, r], [r, 1]])
return mv.cdf([hi, hi]) - mv.cdf([lo, hi]) - mv.cdf([hi, lo]) + mv.cdf([lo, lo])
BOXES = {cat: (a, b, c, d) for cat, a, b, c, d in rule.rectangles}
def model_indicator(cat, a1, a2, h, vtype):
rho_f = CORRELOGRAMS[vtype]
u1a, u1b, u2a, u2b = BOXES[cat]
p_k = (u1b - u1a) * (u2b - u2a)
out = []
for hh in h:
p1 = both_in(ndtri(u1a), ndtri(u1b), rho_f(hh, a1))
p2 = both_in(ndtri(u2a), ndtri(u2b), rho_f(hh, a2)) if (u2a > 0 or u2b < 1) else 1.0
out.append(p_k - p1 * p2)
return np.array(out)
def fit_latent(vtype, cands=np.arange(0.2, 3.01, 0.1)):
e1 = [np.sum((model_indicator("Quaternary", a, 1.0, h_lags, vtype) - exp_ind["Quaternary"]) ** 2) for a in cands]
a1 = float(cands[int(np.argmin(e1))])
e2 = [sum(np.sum((model_indicator(c, a1, a, h_lags, vtype) - exp_ind[c]) ** 2) for c in STRAT) for a in cands]
a2 = float(cands[int(np.argmin(e2))])
return round(a1, 2), round(a2, 2), float(min(e1) + min(e2))
t0 = time.perf_counter()
A1, A2, SSE = fit_latent("spherical")
VARIO1 = [0.0, 0.0, A1, A1, 1.0, "spherical"]
VARIO2 = [0.0, 0.0, A2, A2, 1.0, "spherical"]
print(f"fitted in {time.perf_counter() - t0:.1f} s: Y1 range {A1} km, Y2 range {A2} km (SSE {SSE:.4f})")
print("vario1 =", VARIO1, " vario2 =", VARIO2)
hh = np.linspace(0.02, 2.0, 40)
fig, axes = plt.subplots(1, 5, figsize=(24, 3.9))
for ax, c in zip(axes, NAMES):
ax.plot(h_lags, exp_ind[c], "o", color=COLORS[c], mec="k", label="samples")
ax.plot(hh, model_indicator(c, A1, A2, hh, "spherical"), "k-", label="PGS model")
ax.set_title(c)
ax.set_xlabel("h (km)")
axes[0].set_ylabel("indicator semivariance")
axes[0].legend()
plt.tight_layout()
plt.show()