1from __future__
import annotations
8import matplotlib.pyplot
as plt
9from statistics
import NormalDist
11from pyhyperiso.core.Math.RealMatrix
import Matrix
14from pyhyperiso.core.Statistic.Copula
import CopulaKind
16from pyhyperiso.core.Statistic.Copula
import CopulaFactoryWrapper
as CF
18from pyhyperiso.core.Statistic.CopulaConfig
import GaussianCopulaConfigPy
as GaussianCfg
20from pyhyperiso.core.Statistic.CopulaConfig
import StudentTCopulaConfigPy
as StudentTCfg
24 """R_ij = rho^{|i-j|}. SPD si |rho|<1."""
25 if not (-0.999 < rho < 0.999):
26 raise ValueError(
"rho doit être dans (-1,1) pour une corrélation AR(1) SPD.")
27 R = [[(rho ** abs(i - j))
for j
in range(d)]
for i
in range(d)]
32 """Ranks 1..n (mid-rank approx via argsort; suffisant pour tests visuels)."""
34 ranks = np.empty_like(order, dtype=float)
35 ranks[order] = np.arange(1, len(x) + 1, dtype=float)
40 """Corrélation de Spearman via corrcoef des rangs."""
41 R = np.vstack([
_rankdata(U[:, i])
for i
in range(U.shape[1])]).T
42 return np.corrcoef(R, rowvar=
False)
46 """Transforme U~(0,1) vers Z~N(0,1) via invCDF (sans scipy)."""
49 Uc = np.clip(U, eps, 1 - eps)
50 inv = np.vectorize(nd.inv_cdf, otypes=[float])
57 return np.corrcoef(Z, rowvar=
False)
61 os.makedirs(path, exist_ok=
True)
65 U: np.ndarray, title: str, outpath: str, use_hist2d: bool =
False
67 u1, u2 = U[:, 0], U[:, 1]
68 plt.figure(figsize=(6.8, 6.4))
70 plt.hist2d(u1, u2, bins=70, density=
True)
71 plt.colorbar(label=
"density")
73 plt.plot(u1, u2, linestyle=
"none", marker=
".", markersize=2, alpha=0.25)
75 plt.plot([0, 1], [0, 1], linestyle=
"--", linewidth=1.2)
81 plt.grid(
True, alpha=0.25)
83 plt.savefig(outpath, dpi=200)
90 plt.figure(figsize=(7.6, 4.6))
91 plt.hist(U[:, j], bins=50, density=
True, alpha=0.45, label=f
"u{j + 1}")
93 plt.plot([0, 1], [1, 1], linestyle=
"--", linewidth=1.6, label=
"Uniform(0,1) density")
94 plt.title(f
"{title_prefix} — Marginal uniformity (dim {j + 1})")
95 plt.xlabel(f
"u{j + 1}")
99 plt.grid(
True, alpha=0.25)
100 plt.legend(frameon=
True)
102 plt.savefig(os.path.join(outdir, f
"{title_prefix}_marginal_u{j + 1}.png"), dpi=200)
107 plt.figure(figsize=(6.8, 6.0))
108 im = plt.imshow(M, vmin=-1, vmax=1, interpolation=
"nearest")
109 plt.colorbar(im, label=
"correlation")
117 plt.text(j, i, f
"{M[i, j]:.2f}", ha=
"center", va=
"center", fontsize=8)
120 plt.savefig(outpath, dpi=200)
125 """Visualise exp(log_density(u)) sur [0,1]^2. (Seulement 2D)."""
127 xs = np.linspace(eps, 1 - eps, grid)
128 ys = np.linspace(eps, 1 - eps, grid)
129 D = np.empty((grid, grid), dtype=float)
131 for i, y
in enumerate(ys):
134 ld = float(copula.log_density([float(x), float(y)]))
135 row.append(math.exp(ld))
138 approx_integral = float(D.mean())
139 plt.figure(figsize=(7.0, 6.0))
140 im = plt.imshow(D, origin=
"lower", extent=[0, 1, 0, 1], interpolation=
"nearest")
141 plt.colorbar(im, label=
"density c(u)")
142 plt.title(f
"{title}\n(mean density ≈ {approx_integral:.3f} ; should be ~1 in 2D)")
147 plt.savefig(outpath, dpi=200)
152 cfg = GaussianCfg(R=R)
153 if hasattr(CF,
"gaussian"):
154 return CF.gaussian(R, seed=seed)
155 if hasattr(CF,
"create"):
156 return CF.create(CopulaKind.GAUSSIAN, cfg, seed=seed)
157 return CF.create_gaussian(cfg, seed)
161 cfg = StudentTCfg(R=R, nu=int(nu))
162 if hasattr(CF,
"student_t"):
163 return CF.student_t(R, nu=nu, seed=seed)
164 if hasattr(CF,
"create"):
165 return CF.create(CopulaKind.STUDENT_T, cfg, seed=seed)
166 return CF.create_student_t(cfg, seed)
170 outdir: str =
"copula_plots",
185 (
"GaussianCopula", cop_gauss),
186 (f
"StudentTCopula(nu={nu})", cop_t),
189 for name, cop
in specs:
190 U = np.array(cop.sample_u(int(n)), dtype=float)
195 title=f
"{name} — samples in (0,1)^2 (projection)",
196 outpath=os.path.join(outdir, f
"{name}_hist2d.png"),
203 title=f
"{name} — density surface in (0,1)^2",
204 outpath=os.path.join(outdir, f
"{name}_density_surface.png"),
215 title=f
"{name} — Spearman corr (ranks of U)",
216 outpath=os.path.join(outdir, f
"{name}_spearman.png"),
220 title=f
"{name} — Corr of Z = Phi^-1(U) (compare to target R)",
221 outpath=os.path.join(outdir, f
"{name}_corr_gaussianized.png"),
224 print(f
"[OK] Plots saved in: {outdir}/")
227if __name__ ==
"__main__":
229 outdir=
"copula_plots",
None plot_density_surface_2d(Any copula, str title, str outpath, int grid=90)
np.ndarray gaussianize(np.ndarray U)
np.ndarray corrcoef_Z(np.ndarray U)
None ensure_dir(str path)
make_gaussian_copula(Matrix R, int seed)
Matrix ar1_corr(int d, float rho)
np.ndarray spearman_corr(np.ndarray U)
None plot_scatter_or_hist2d(np.ndarray U, str title, str outpath, bool use_hist2d=False)
None plot_marginal_uniformity(np.ndarray U, str title_prefix, str outdir)
make_student_t_copula(Matrix R, int nu, int seed)
np.ndarray _rankdata(np.ndarray x)
None plot_corr_heatmap(np.ndarray M, str title, str outpath)