from future import annotations
import csv
import heapq
import itertools
import json
import re
import time
import unicodedata
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
import numpy as np
CHRON_FILE = Path("quran-chronological.txt")
OUT_DIR = Path("chron_surah_swaps_out")
STRIP_BASMALA = True
MAX_BRUTE_SWAPS = 2 # 1 = all C(N, 2) single swaps; 2 = single + double swaps
TOP_K_SAVE = 25 # Top candidate orderings to export
BATCH_SIZE = 16_384 # Candidate orders scored per vectorized NumPy batch
PROGRESS_EVERY = 2_000_000 # Progress print interval during large searches
RANDOM_NULL_SAMPLES = 2_000 # Random single-swap draws for baseline comparison
RNG_SEED = 42
MIN_TRANSITION_SCORE = 0.0 # Minimum allowed edge score across all adjacent pairs
CONTINUITY_SMOOTH_W = 0.05 # Penalty weight on edge score standard deviation
DISPLACEMENT_PENALTY = 0.001 # Penalty per chapter moved from base_order
MAX_SLOT_JUMP: int | None = None # Max allowed index shift from base position (None = off)
LOCKED_0BASED_SLOTS: set[int] = set() # Positions held fixed (e.g. {0, 113})
METRIC_NAMES = [
"echo_1letter",
"echo_2letter",
"echo_3letter",
"echo_word",
"profile_sim_1",
"profile_sim_2",
"modal_match_1",
"modal_match_2",
"close_to_next_modal",
"open_after_prev_modal",
]
FORMULA_CANDIDATES: dict[str, np.ndarray] = {
"uniform": np.ones(len(METRIC_NAMES)),
"echo_heavy": np.array([2.0, 4.0, 5.0, 4.0, 0.25, 0.25, 1.0, 1.5, 1.5, 1.0]),
"exact_rhyme_only": np.array([1.0, 3.0, 5.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
"modal_and_echo": np.array([1.5, 3.0, 3.5, 2.5, 0.5, 0.5, 1.5, 2.5, 2.5, 1.5]),
"profile_and_flow": np.array([1.0, 1.5, 2.0, 1.5, 1.5, 2.0, 1.0, 1.5, 1.5, 1.5]),
}
PENALTY_CANDIDATES = [0.0, 0.0005, 0.001, 0.002, 0.005, 0.01]
LETTER_MAP = str.maketrans({
"ٱ": "ا", "أ": "ا", "إ": "ا", "آ": "ا",
"ى": "ي", "ی": "ي", "ة": "ه", "ؤ": "و",
"ئ": "ي", "ک": "ك",
})
BASMALA_WORDS = "بسم الله الرحمن الرحيم".split()
PIPE_RE = re.compile(r"^\s(\d+)\s|\s(\d+)\s|\s(.+?)\s$")
@dataclass
class SwapCandidate:
objective: float
mean_score: float
min_edge_score: float
edge_std: float
gain_vs_base: float
displaced: int
swaps: str
order: np.ndarray
metrics: np.ndarray
def normalize_arabic(text: str) -> str:
chars = []
for ch in text:
if ch.isspace():
chars.append(" ")
elif unicodedata.category(ch) in ("Lo", "Ll", "Lu", "Lt"):
chars.append(ch)
return re.sub(r"\s+", " ", "".join(chars)).translate(LETTER_MAP).strip()
def load_chronological(path: Path) -> list[dict]:
if not path.exists():
raise FileNotFoundError(f"Chronological input file not found: {path}")
chapters: list[dict] = []
current: dict | None = None
for line in path.read_text(encoding="utf-8-sig").splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
match = PIPE_RE.match(stripped)
if not match:
continue
surah = int(match.group(1))
if current is None or current["surah"] != surah:
current = {"surah": surah, "raw": []}
chapters.append(current)
current["raw"].append(match.group(3))
if not chapters:
raise ValueError(f"{path}: no 'surah|ayah|text' lines found")
for chapter in chapters:
verses: list[list[str]] = []
for idx, raw_line in enumerate(chapter["raw"]):
words = normalize_arabic(raw_line).split()
if STRIP_BASMALA and chapter["surah"] not in (1, 9):
if words == BASMALA_WORDS:
continue
if idx == 0 and words[:4] == BASMALA_WORDS:
words = words[4:]
if words:
verses.append(words)
chapter["verses"] = verses
return [ch for ch in chapters if ch["verses"]]
def verse_ending(words: list[str], k: int) -> str:
last_word = words[-1]
return last_word[-k:] if len(last_word) >= k else ""
def describe_chapter(chapter: dict) -> dict:
verses = chapter["verses"]
info: dict = {
"surah": chapter["surah"],
"n_verses": len(verses),
"end_word": [v[-1] for v in verses],
}
for k in (1, 2, 3):
endings = [verse_ending(v, k) for v in verses]
hist = Counter(e for e in endings if e)
info[f"e{k}"] = endings
info[f"hist{k}"] = hist
info[f"modal{k}"] = hist.most_common(1)[0][0] if hist else ""
return info
def cosine_similarity_matrix(counters: list[Counter]) -> np.ndarray:
keys = sorted(set().union(*counters))
n = len(counters)
if not keys or n == 0:
return np.zeros((n, n), dtype=float)
pos = {k: i for i, k in enumerate(keys)}
mat = np.zeros((n, len(keys)), dtype=float)
for row_idx, cnt in enumerate(counters):
for key, val in cnt.items():
mat[row_idx, pos[key]] = val
norms = np.maximum(np.linalg.norm(mat, axis=1, keepdims=True), 1e-12)
normed = mat / norms
return normed @ normed.T
def equal_nonempty_matrix(left: np.ndarray, right: np.ndarray) -> np.ndarray:
return ((left[:, None] == right[None, :]) & (left[:, None] != "")).astype(float)
def build_boundary_stack(sorted_chapters: list[dict]) -> np.ndarray:
"""Return 3D array of shape (num_metrics, N, N) for fast transition lookups."""
last_e1 = np.array([c["e1"][-1] for c in sorted_chapters])
first_e1 = np.array([c["e1"][0] for c in sorted_chapters])
last_e2 = np.array([c["e2"][-1] for c in sorted_chapters])
first_e2 = np.array([c["e2"][0] for c in sorted_chapters])
last_e3 = np.array([c["e3"][-1] for c in sorted_chapters])
first_e3 = np.array([c["e3"][0] for c in sorted_chapters])
last_word = np.array([c["end_word"][-1] for c in sorted_chapters])
first_word = np.array([c["end_word"][0] for c in sorted_chapters])
modal1 = np.array([c["modal1"] for c in sorted_chapters])
modal2 = np.array([c["modal2"] for c in sorted_chapters])
mats = [
equal_nonempty_matrix(last_e1, first_e1),
equal_nonempty_matrix(last_e2, first_e2),
equal_nonempty_matrix(last_e3, first_e3),
equal_nonempty_matrix(last_word, first_word),
cosine_similarity_matrix([c["hist1"] for c in sorted_chapters]),
cosine_similarity_matrix([c["hist2"] for c in sorted_chapters]),
equal_nonempty_matrix(modal1, modal1),
equal_nonempty_matrix(modal2, modal2),
equal_nonempty_matrix(last_e2, modal2),
equal_nonempty_matrix(modal2, first_e2),
]
return np.stack(mats, axis=0)
def normalize_weights(weights: np.ndarray) -> np.ndarray:
arr = np.asarray(weights, dtype=float)
total = float(np.sum(arr))
if total <= 1e-12 or np.any(arr < 0):
raise ValueError("Formula weights must be non-negative with positive sum.")
return arr / total
def edge_scores_for_batch(
stack: np.ndarray,
orders_batch: np.ndarray,
norm_w: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
"""
orders_batch shape: (B, N)
returns:
edge_weighted: (B, N - 1) weighted boundary score per adjacent surah pair
mean_metrics: (B, M) mean of each metric across all N - 1 transitions
"""
if orders_batch.shape[1] < 2:
b = orders_batch.shape[0]
return np.zeros((b, 0), dtype=float), np.zeros((b, stack.shape[0]), dtype=float)
src = orders_batch[:, :-1]
dst = orders_batch[:, 1:]
# stack[:, src, dst] has shape (M, B, N - 1)
per_edge_metrics = np.moveaxis(stack[:, src, dst], 0, -1) # (B, N - 1, M)
edge_weighted = per_edge_metrics @ norm_w # (B, N - 1)
mean_metrics = per_edge_metrics.mean(axis=1) # (B, M)
return edge_weighted, mean_metrics
def satisfies_structural_rules(
order: np.ndarray,
base_order: np.ndarray,
edge_weighted_row: np.ndarray,
) -> bool:
for slot in LOCKED_0BASED_SLOTS:
if order[slot] != base_order[slot]:
return False
if MAX_SLOT_JUMP is not None:
positions = np.arange(len(order))
if np.any(np.abs(positions - order) > MAX_SLOT_JUMP):
return False
if MIN_TRANSITION_SCORE > 0.0 and len(edge_weighted_row) > 0:
if float(np.min(edge_weighted_row)) < MIN_TRANSITION_SCORE:
return False
return True
def allowed_swap_pairs(n: int) -> list[tuple[int, int]]:
return [
(i, j)
for i, j in itertools.combinations(range(n), 2)
if i not in LOCKED_0BASED_SLOTS and j not in LOCKED_0BASED_SLOTS
]
def iter_swap_orders(base_order: np.ndarray, max_swaps: int):
"""Yield (swap_description, candidate_order) for single and optional double swaps."""
n = len(base_order)
pairs = allowed_swap_pairs(n)
for i, j in pairs:
cand = base_order.copy()
cand[i], cand[j] = cand[j], cand[i]
yield f"swap({i + 1},{j + 1})", cand
if max_swaps >= 2:
for (a, b), (c, d) in itertools.combinations(pairs, 2):
cand = base_order.copy()
cand[a], cand[b] = cand[b], cand[a]
cand[c], cand[d] = cand[d], cand[c]
yield f"swap({a + 1},{b + 1})+swap({c + 1},{d + 1})", cand
def evaluate_swap_variations_batched(
stack: np.ndarray,
base_order: np.ndarray,
weights: np.ndarray,
disp_penalty: float,
smooth_w: float = CONTINUITY_SMOOTH_W,
max_swaps: int = MAX_BRUTE_SWAPS,
keep_top_k: int | None = TOP_K_SAVE,
log_progress: bool = False,
) -> tuple[float, float, list[SwapCandidate], int]:
norm_w = normalize_weights(weights)
base_edges, base_metrics = edge_scores_for_batch(stack, base_order[None, :], norm_w)
base_mean = float((base_metrics @ norm_w)[0])
base_min_edge = float(base_edges.min()) if base_edges.size else 0.0
heap: list[tuple[float, int, SwapCandidate]] = []
accepted: list[SwapCandidate] = []
seen = 0
next_log = PROGRESS_EVERY
t0 = time.perf_counter()
batch_descs: list[str] = []
batch_orders: list[np.ndarray] = []
def flush() -> None:
nonlocal seen
if not batch_orders:
return
orders_arr = np.vstack(batch_orders)
edge_w, mean_m = edge_scores_for_batch(stack, orders_arr, norm_w)
mean_scores = mean_m @ norm_w
min_edges = edge_w.min(axis=1) if edge_w.shape[1] > 0 else np.zeros(len(batch_descs))
edge_stds = edge_w.std(axis=1) if edge_w.shape[1] > 0 else np.zeros(len(batch_descs))
displaced_arr = np.sum(orders_arr != base_order[None, :], axis=1)
for idx in range(len(batch_descs)):
if not satisfies_structural_rules(orders_arr[idx], base_order, edge_w[idx]):
continue
m_score = float(mean_scores[idx])
min_e = float(min_edges[idx])
e_std = float(edge_stds[idx])
disp = int(displaced_arr[idx])
obj = m_score - smooth_w * e_std - disp_penalty * disp
item = SwapCandidate(
objective=obj,
mean_score=m_score,
min_edge_score=min_e,
edge_std=e_std,
gain_vs_base=m_score - base_mean,
displaced=disp,
swaps=batch_descs[idx],
order=orders_arr[idx],
metrics=mean_m[idx],
)
if keep_top_k is not None:
entry = (obj, seen + idx, item)
if len(heap) < keep_top_k:
heapq.heappush(heap, entry)
elif entry[0] > heap[0][0]:
heapq.heapreplace(heap, entry)
else:
accepted.append(item)
seen += len(batch_descs)
batch_descs.clear()
batch_orders.clear()
for desc, cand in iter_swap_orders(base_order, max_swaps=max_swaps):
batch_descs.append(desc)
batch_orders.append(cand)
if len(batch_orders) >= BATCH_SIZE:
flush()
if log_progress and seen >= next_log:
elapsed = time.perf_counter() - t0
rate = seen / max(elapsed, 1e-6)
print(f" ... scanned {seen:,} swap candidates ({rate:,.0f}/s, {elapsed:.1f}s)")
next_log += PROGRESS_EVERY
flush()
ranked = (
[entry[2] for entry in sorted(heap, key=lambda x: x[0], reverse=True)]
if keep_top_k is not None
else sorted(accepted, key=lambda r: r.objective, reverse=True)
)
return base_mean, base_min_edge, ranked, seen
def random_swap_null_stats(
stack: np.ndarray,
base_order: np.ndarray,
norm_w: np.ndarray,
n_samples: int = RANDOM_NULL_SAMPLES,
seed: int = RNG_SEED,
) -> dict[str, float]:
rng = np.random.default_rng(seed)
n = len(base_order)
_, base_metrics = edge_scores_for_batch(stack, base_order[None, :], norm_w)
base_score = float((base_metrics @ norm_w)[0])
orders = np.broadcast_to(base_order, (n_samples, n)).copy()
idx_i = rng.integers(0, n, size=n_samples)
idx_j = rng.integers(0, n - 1, size=n_samples)
idx_j = np.where(idx_j >= idx_i, idx_j + 1, idx_j)
rows = np.arange(n_samples)
left_vals = orders[rows, idx_i].copy()
orders[rows, idx_i] = orders[rows, idx_j]
orders[rows, idx_j] = left_vals
_, mean_m = edge_scores_for_batch(stack, orders, norm_w)
gains = (mean_m @ norm_w) - base_score
return {
"n_samples": float(n_samples),
"mean_gain": float(np.mean(gains)),
"std_gain": float(np.std(gains)),
"p95_gain": float(np.percentile(gains, 95)),
"max_gain": float(np.max(gains)),
}
def fit_ridge_weights(
X_samples: np.ndarray,
y_scores: np.ndarray,
l2_reg: float = 1e-3,
train_frac: float = 0.8,
) -> tuple[np.ndarray, float, float]:
"""Fit centered non-negative normalized weights and compute R^2 with intercept."""
n_samples = len(y_scores)
if n_samples < 2:
d = X_samples.shape[1]
return normalize_weights(np.ones(d)), 0.0, 0.0
split = max(1, min(n_samples - 1, int(n_samples * train_frac)))
X_train, y_train = X_samples[:split], y_scores[:split]
x_mean = X_train.mean(axis=0, keepdims=True)
y_mean = float(y_train.mean())
Xc = X_train - x_mean
yc = y_train - y_mean
d = Xc.shape[1]
A = Xc.T @ Xc + l2_reg * np.eye(d)
w_raw = np.linalg.solve(A, Xc.T @ yc)
w_pos = np.clip(w_raw, 0.0, None)
w_norm = normalize_weights(w_pos if np.sum(w_pos) > 1e-12 else np.ones(d))
def r2_on(x_mat: np.ndarray, y_arr: np.ndarray) -> float:
pred = (x_mat - x_mean) @ w_norm + y_mean
ss_res = float(np.sum((y_arr - pred) ** 2))
ss_tot = float(np.sum((y_arr - y_arr.mean()) ** 2))
return 1.0 - (ss_res / max(ss_tot, 1e-12))
train_r2 = r2_on(X_train, y_train)
val_r2 = r2_on(X_samples[split:], y_scores[split:]) if split < n_samples else train_r2
return w_norm, train_r2, val_r2
def format_swaps_with_surahs(
swap_desc: str,
base_order: np.ndarray,
idx_to_s: dict[int, int],
) -> str:
parts = []
for token in swap_desc.split("+"):
m = re.fullmatch(r"swap((\d+),(\d+))", token.strip())
if not m:
parts.append(token)
continue
p1, p2 = int(m.group(1)), int(m.group(2))
s1 = idx_to_s[int(base_order[p1 - 1])]
s2 = idx_to_s[int(base_order[p2 - 1])]
parts.append(f"swap(slot {p1}->S{s1}, slot {p2}->S{s2})")
return " + ".join(parts)
def main() -> None:
OUT_DIR.mkdir(parents=True, exist_ok=True)
raw_chapters = load_chronological(CHRON_FILE)
chron_desc = [describe_chapter(ch) for ch in raw_chapters]
chapters_by_surah = sorted(chron_desc, key=lambda c: c["surah"])
s_to_idx = {c["surah"]: i for i, c in enumerate(chapters_by_surah)}
idx_to_s = {i: c["surah"] for i, c in enumerate(chapters_by_surah)}
base_order = np.array([s_to_idx[c["surah"]] for c in chron_desc], dtype=int)
stack = build_boundary_stack(chapters_by_surah)
base_edges, base_metrics = edge_scores_for_batch(
stack, base_order[None, :], normalize_weights(FORMULA_CANDIDATES["uniform"])
)
base_min_edge = float(base_edges.min()) if base_edges.size else 0.0
# Precompute single swaps once for fast grid search across formulas and penalties
single_swaps: list[tuple[str, int, np.ndarray, np.ndarray]] = []
for desc, cand_order in iter_swap_orders(base_order, max_swaps=1):
displaced = int(np.sum(cand_order != base_order))
_, m_vec = edge_scores_for_batch(
stack, cand_order[None, :], normalize_weights(FORMULA_CANDIDATES["uniform"])
)
single_swaps.append((desc, displaced, m_vec[0], cand_order))
print("=== 1. FORMULA & PENALTY GRID SEARCH (SINGLE SWAPS) ===")
best_overall: dict | None = None
grid_rows: list[dict] = []
for fname, raw_w in FORMULA_CANDIDATES.items():
norm_w = normalize_weights(raw_w)
f_edges, f_base_m = edge_scores_for_batch(stack, base_order[None, :], norm_w)
base_s = float((f_base_m @ norm_w)[0])
scored_singles = []
for desc, displaced, _, cand_order in single_swaps:
e_w, m_vec = edge_scores_for_batch(stack, cand_order[None, :], norm_w)
if not satisfies_structural_rules(cand_order, base_order, e_w[0]):
continue
f_s = float((m_vec @ norm_w)[0])
e_std = float(e_w[0].std()) if e_w.shape[1] > 0 else 0.0
min_e = float(e_w[0].min()) if e_w.shape[1] > 0 else 0.0
scored_singles.append((f_s, e_std, min_e, displaced, desc, cand_order, m_vec[0]))
for pen in PENALTY_CANDIDATES:
if not scored_singles:
continue
best_row = max(
scored_singles,
key=lambda item: item[0] - CONTINUITY_SMOOTH_W * item[1] - pen * item[3],
)
best_f_s, best_std, best_min_e, best_disp, best_desc, best_order, best_m = best_row
best_obj = best_f_s - CONTINUITY_SMOOTH_W * best_std - pen * best_disp
best_gain = best_f_s - base_s
surah_desc = format_swaps_with_surahs(best_desc, base_order, idx_to_s)
grid_rows.append({
"formula": fname,
"penalty": pen,
"base_score": round(base_s, 6),
"best_score": round(best_f_s, 6),
"best_obj": round(best_obj, 6),
"best_gain": round(best_gain, 6),
"min_edge": round(best_min_e, 6),
"edge_std": round(best_std, 6),
"best_swaps": best_desc,
"surah_swaps": surah_desc,
"displaced": best_disp,
})
if best_overall is None or best_obj > best_overall["objective"]:
best_overall = {
"formula": fname,
"weights": norm_w,
"penalty": pen,
"base_score": base_s,
"objective": best_obj,
}
grid_rows.sort(key=lambda r: r["best_obj"], reverse=True)
for row in grid_rows[:10]:
print(
f" formula={row['formula']:<16} pen={row['penalty']:<6} "
f"base={row['base_score']:.4f} -> best={row['best_score']:.4f} "
f"(gain={row['best_gain']:+.4f}, obj={row['best_obj']:+.4f}, std={row['edge_std']:.4f}) "
f"| {row['surah_swaps']}"
)
assert best_overall is not None
win_weights = best_overall["weights"]
win_pen = best_overall["penalty"]
null_stats = random_swap_null_stats(stack, base_order, win_weights)
print(
f"\nRandom single-swap null ({int(null_stats['n_samples'])} draws): "
f"mean gain={null_stats['mean_gain']:+.5f}, "
f"95th pct={null_stats['p95_gain']:+.5f}, "
f"max={null_stats['max_gain']:+.5f}"
)
print(
f"\n=== 2. SWAP VARIATION SEARCH "
f"(max_swaps={MAX_BRUTE_SWAPS}, formula={best_overall['formula']}, pen={win_pen}) ==="
)
t0 = time.perf_counter()
base_m, _, top_vars, total_scanned = evaluate_swap_variations_batched(
stack,
base_order,
win_weights,
disp_penalty=win_pen,
smooth_w=CONTINUITY_SMOOTH_W,
max_swaps=MAX_BRUTE_SWAPS,
keep_top_k=TOP_K_SAVE,
log_progress=MAX_BRUTE_SWAPS >= 2,
)
elapsed = time.perf_counter() - t0
print(f"Scanned {total_scanned:,} swap combinations in {elapsed:.2f}s; kept {len(top_vars)} valid.")
if not top_vars:
print("No candidate satisfied continuity rules. Relax MIN_TRANSITION_SCORE or MAX_SLOT_JUMP.")
return
best_top = top_vars[0]
print(
f"Baseline mean={base_m:.6f} (min_edge={base_min_edge:.6f}) -> "
f"Best mean={best_top.mean_score:.6f} (min_edge={best_top.min_edge_score:.6f}, "
f"std={best_top.edge_std:.6f}) | {format_swaps_with_surahs(best_top.swaps, base_order, idx_to_s)}"
)
X_mat = np.vstack([v.metrics for v in top_vars])
y_vec = np.array([v.mean_score for v in top_vars])
learned_w, train_r2, val_r2 = fit_ridge_weights(X_mat, y_vec)
print("\n=== 3. RIDGE WEIGHT FIT ON EVALUATED CANDIDATES ===")
print(f"Train R^2: {train_r2:.6f} | Hold-out R^2: {val_r2:.6f}")
formula_terms = [
f"{learned_w[i]:.4f} * {METRIC_NAMES[i]}" for i in range(len(METRIC_NAMES))
]
print("Fitted non-negative weights: " + " + ".join(formula_terms))
top_csv = OUT_DIR / "top_variations.csv"
with top_csv.open("w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(
f,
fieldnames=[
"rank", "swaps", "surah_swaps", "displaced", "mean_score",
"min_edge_score", "edge_std", "gain_vs_base", "objective", "surah_order",
],
)
writer.writeheader()
for rank, item in enumerate(top_vars, start=1):
writer.writerow({
"rank": rank,
"swaps": item.swaps,
"surah_swaps": format_swaps_with_surahs(item.swaps, base_order, idx_to_s),
"displaced": item.displaced,
"mean_score": round(item.mean_score, 6),
"min_edge_score": round(item.min_edge_score, 6),
"edge_std": round(item.edge_std, 6),
"gain_vs_base": round(item.gain_vs_base, 6),
"objective": round(item.objective, 6),
"surah_order": " ".join(str(idx_to_s[int(i)]) for i in item.order),
})
(OUT_DIR / "summary.json").write_text(
json.dumps(
{
"winning_grid": {
"formula": best_overall["formula"],
"weights": dict(zip(METRIC_NAMES, win_weights.tolist())),
"penalty": win_pen,
"continuity_smooth_w": CONTINUITY_SMOOTH_W,
"min_transition_score": MIN_TRANSITION_SCORE,
"base_mean_score": base_m,
"base_min_edge_score": base_min_edge,
"best_mean_score": best_top.mean_score,
"best_min_edge_score": best_top.min_edge_score,
"best_edge_std": best_top.edge_std,
"best_swaps": best_top.swaps,
"best_surah_swaps": format_swaps_with_surahs(
best_top.swaps, base_order, idx_to_s
),
},
"random_swap_null": null_stats,
"ridge_weight_fit": {
"train_r2": train_r2,
"val_r2": val_r2,
"weights": dict(zip(METRIC_NAMES, learned_w.tolist())),
"expression": " + ".join(formula_terms),
},
},
indent=2,
ensure_ascii=False,
),
encoding="utf-8",
)
print(f"\nSaved results to {OUT_DIR.resolve()}")
if name == "main":
main()
output:
=== 1. FORMULA & PENALTY GRID SEARCH (SINGLE SWAPS) ===
formula=uniform pen=0.0 base=0.1798 -> best=0.1978 (gain=+0.0180, obj=+0.1868, std=0.2194) | swap(slot 40->S72, slot 70->S16)
formula=uniform pen=0.0005 base=0.1798 -> best=0.1978 (gain=+0.0180, obj=+0.1858, std=0.2194) | swap(slot 40->S72, slot 70->S16)
formula=uniform pen=0.001 base=0.1798 -> best=0.1978 (gain=+0.0180, obj=+0.1848, std=0.2194) | swap(slot 40->S72, slot 70->S16)
formula=uniform pen=0.002 base=0.1798 -> best=0.1978 (gain=+0.0180, obj=+0.1828, std=0.2194) | swap(slot 40->S72, slot 70->S16)
formula=profile_and_flow pen=0.0 base=0.1735 -> best=0.1907 (gain=+0.0172, obj=+0.1800, std=0.2127) | swap(slot 41->S36, slot 50->S17)
formula=profile_and_flow pen=0.0005 base=0.1735 -> best=0.1907 (gain=+0.0172, obj=+0.1790, std=0.2127) | swap(slot 41->S36, slot 50->S17)
formula=profile_and_flow pen=0.001 base=0.1735 -> best=0.1907 (gain=+0.0172, obj=+0.1780, std=0.2127) | swap(slot 41->S36, slot 50->S17)
formula=uniform pen=0.005 base=0.1798 -> best=0.1978 (gain=+0.0180, obj=+0.1768, std=0.2194) | swap(slot 40->S72, slot 70->S16)
formula=profile_and_flow pen=0.002 base=0.1735 -> best=0.1907 (gain=+0.0172, obj=+0.1760, std=0.2127) | swap(slot 41->S36, slot 50->S17)
formula=profile_and_flow pen=0.005 base=0.1735 -> best=0.1907 (gain=+0.0172, obj=+0.1700, std=0.2127) | swap(slot 41->S36, slot 50->S17)
=== 2. COMPARISON OF ALL 6 PERMUTATIONS OF SURAHS 61, 62, 64 ===
#1 S64 -> S61 -> S62 [base_chron,example_64_61_62] mean=0.179774 (gain=+0.000000) min_e=0.0000 std=0.209680 obj=+0.169290 disp=0
#2 S64 -> S62 -> S61 [other_perm ] mean=0.178945 (gain=-0.000829) min_e=0.0000 std=0.209089 obj=+0.168490 disp=2
#3 S62 -> S64 -> S61 [noldeke_62_64_61 ] mean=0.177955 (gain=-0.001819) min_e=0.0000 std=0.209287 obj=+0.167490 disp=3
#4 S61 -> S64 -> S62 [other_perm ] mean=0.177047 (gain=-0.002727) min_e=0.0000 std=0.208895 obj=+0.166602 disp=2
#5 S61 -> S62 -> S64 [other_perm ] mean=0.175281 (gain=-0.004493) min_e=0.0000 std=0.206043 obj=+0.164979 disp=3
#6 S62 -> S61 -> S64 [other_perm ] mean=0.175249 (gain=-0.004525) min_e=0.0000 std=0.205875 obj=+0.164955 disp=2
Random swap null (2000 draws): mean gain=-0.00173, p95=+0.00374, max=+0.01329
Full shuffle null (500 shuffles): mean=0.12799, p95=0.14843, max=0.16621
=== 3. SWAP VARIATION SEARCH (max_swaps=2, formula=uniform, pen=0.0) ===
... scanned 2,015,232 swap candidates (53,491/s, 37.7s)
... scanned 4,014,080 swap candidates (53,676/s, 74.8s)
Burada yeni gibi görünüyorsunuz. Eğer katılmak istiyorsanız düğmelerden birine tıklayınız.