Simplify lattice inference and hosted landing

This commit is contained in:
Meta Vens 2026-04-28 14:55:35 +01:00
commit 16c86d54aa
46 changed files with 1844 additions and 1492 deletions

View file

@ -3,8 +3,6 @@
"input": "tests/fixtures/real/ai-badge-cleaned.png",
"target_width": 126,
"target_height": 126,
"phase_x": 0.0,
"phase_y": -0.2,
"steps": 48,
"cell_bbox": [67, 90, 97, 122]
}

BIN
tests/fixtures/real/character.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

View file

@ -10,8 +10,6 @@
"date": "2026-04-26",
"target_width": 418,
"target_height": 418,
"phase_x": 0.2,
"phase_y": -0.2
},
"preview_focus_cell_bbox": [44, 396, 124, 476],
"notes": [

View file

@ -9,7 +9,7 @@ from repixelizer.synthetic import fake_pixelize, make_emblem
def test_default_command_runs_without_explicit_run_subcommand(tmp_path: Path) -> None:
source = make_emblem(16, 16)
fake = fake_pixelize(source, upscale=8, phase_x=0.2, phase_y=0.25, blur_radius=0.4)
fake = fake_pixelize(source, upscale=8, blur_radius=0.4)
input_path = tmp_path / "input.png"
output_path = tmp_path / "output.png"
save_rgba(input_path, fake)
@ -20,7 +20,7 @@ def test_default_command_runs_without_explicit_run_subcommand(tmp_path: Path) ->
def test_default_command_accepts_strip_background_flag(tmp_path: Path) -> None:
source = make_emblem(16, 16)
fake = fake_pixelize(source, upscale=8, phase_x=0.2, phase_y=0.25, blur_radius=0.4)
fake = fake_pixelize(source, upscale=8, blur_radius=0.4)
input_path = tmp_path / "input.png"
output_path = tmp_path / "output.png"
save_rgba(input_path, fake)
@ -31,7 +31,7 @@ def test_default_command_accepts_strip_background_flag(tmp_path: Path) -> None:
def test_default_command_accepts_fixed_lattice_flags(tmp_path: Path) -> None:
source = make_emblem(16, 16)
fake = fake_pixelize(source, upscale=8, phase_x=0.2, phase_y=0.25, blur_radius=0.4)
fake = fake_pixelize(source, upscale=8, blur_radius=0.4)
input_path = tmp_path / "input.png"
output_path = tmp_path / "output.png"
save_rgba(input_path, fake)
@ -46,11 +46,7 @@ def test_default_command_accepts_fixed_lattice_flags(tmp_path: Path) -> None:
"16",
"--target-height",
"16",
"--phase-x",
"0.2",
"--phase-y",
"0.25",
"--skip-phase-rerank",
"--skip-candidate-rerank",
]
)
assert exit_code == 0

View file

@ -9,7 +9,7 @@ from repixelizer.synthetic import fake_pixelize, make_emblem
def test_compare_writes_comparison_artifacts(tmp_path: Path) -> None:
source = make_emblem(32, 32)
fake = fake_pixelize(source, upscale=10, phase_x=0.2, phase_y=0.3, blur_radius=0.5)
fake = fake_pixelize(source, upscale=10, blur_radius=0.5)
input_path = tmp_path / "input.png"
output_path = tmp_path / "output.png"
diagnostics_dir = tmp_path / "diagnostics"

View file

@ -174,7 +174,7 @@ def _response_json(response) -> dict[str, object]:
def test_run_pipeline_rgba_emits_observer_events_for_gui() -> None:
source = make_emblem(20, 20)
fake = fake_pixelize(source, upscale=8, phase_x=0.15, phase_y=0.2, blur_radius=0.45, seed=3)
fake = fake_pixelize(source, upscale=8, blur_radius=0.45, seed=3)
events: list[str] = []
def observer(event: str, payload) -> None:
@ -185,19 +185,17 @@ def test_run_pipeline_rgba_emits_observer_events_for_gui() -> None:
fake,
target_width=20,
target_height=20,
phase_x=0.0,
phase_y=0.0,
steps=2,
device="cpu",
enable_phase_rerank=False,
enable_candidate_rerank=False,
observer=observer,
)
assert events[0] == "source_loaded"
assert events.count("stage_started") == 6
assert events.index("inference_candidates_ready") < events.index("analysis_completed")
assert events.index("analysis_completed") < events.index("phase_selection_completed")
assert events.index("phase_selection_completed") < events.index("phase_field_prepared")
assert events.index("analysis_completed") < events.index("candidate_selection_completed")
assert events.index("candidate_selection_completed") < events.index("phase_field_prepared")
assert "phase_field_prepared" in events
assert "phase_field_initial" in events
assert events.count("phase_field_step") == 2
@ -206,7 +204,7 @@ def test_run_pipeline_rgba_emits_observer_events_for_gui() -> None:
def test_run_pipeline_rgba_respects_phase_field_preview_stride() -> None:
source = make_emblem(12, 12)
fake = fake_pixelize(source, upscale=6, phase_x=0.12, phase_y=-0.08, blur_radius=0.35, seed=5)
fake = fake_pixelize(source, upscale=6, blur_radius=0.35, seed=5)
class PreviewObserver:
phase_field_preview_stride = 2
@ -223,11 +221,9 @@ def test_run_pipeline_rgba_respects_phase_field_preview_stride() -> None:
fake,
target_width=12,
target_height=12,
phase_x=0.0,
phase_y=0.0,
steps=5,
device="cpu",
enable_phase_rerank=False,
enable_candidate_rerank=False,
observer=observer,
)
@ -416,7 +412,7 @@ def test_gui_hosted_root_serves_landing_page(monkeypatch, tmp_path: Path) -> Non
assert status == 200
assert headers["cache-control"] == "no-store, no-cache, must-revalidate, max-age=0"
assert "Repixelizer hosted demo" in html
assert "Force fake pixel art back onto a real grid." in html
assert "Force fake pixel art back onto a real grid, then inspect each step with a full solver view." in html
assert 'href="/app/"' in html
@ -532,7 +528,7 @@ def test_infer_lattice_emits_search_progress_events(monkeypatch) -> None:
lambda width, height, target_size, *, hinted_sizes=None: [(10, 8), (12, 10)],
)
def fake_score_phase_group(
def fake_score_size_candidate(
rgba,
*,
target_width,
@ -540,23 +536,19 @@ def test_infer_lattice_emits_search_progress_events(monkeypatch) -> None:
prior_cell_x,
prior_cell_y,
prior_reliability,
phase_x_values,
phase_y_values,
device,
):
del rgba, prior_cell_x, prior_cell_y, prior_reliability, phase_x_values, phase_y_values, device
del rgba, prior_cell_x, prior_cell_y, prior_reliability, device
return [
InferenceCandidate(
target_width=target_width,
target_height=target_height,
phase_x=0.0,
phase_y=0.0,
score=0.9 if target_width == 12 else 0.6,
breakdown={},
)
]
monkeypatch.setattr(inference_module, "_score_phase_group", fake_score_phase_group)
monkeypatch.setattr(inference_module, "_score_size_candidate", fake_score_size_candidate)
monkeypatch.setattr(inference_module, "_top_candidates_by_size", lambda candidates, limit: candidates[:limit])
monkeypatch.setattr(
inference_module,
@ -583,16 +575,14 @@ def test_infer_lattice_emits_search_progress_events(monkeypatch) -> None:
assert events[2][1]["target_width"] == 12
def test_phase_rerank_emits_candidate_progress_events(monkeypatch) -> None:
def test_candidate_rerank_emits_candidate_progress_events(monkeypatch) -> None:
inference = InferenceResult(
target_width=16,
target_height=16,
phase_x=0.0,
phase_y=0.0,
confidence=0.0,
top_candidates=[
InferenceCandidate(target_width=16, target_height=16, phase_x=0.0, phase_y=0.0, score=0.75, breakdown={}),
InferenceCandidate(target_width=18, target_height=18, phase_x=0.1, phase_y=-0.1, score=0.73, breakdown={}),
InferenceCandidate(target_width=16, target_height=16, score=0.75, breakdown={}),
InferenceCandidate(target_width=18, target_height=18, score=0.73, breakdown={}),
],
)
analysis = PhaseFieldSourceAnalysis(edge_map=np.zeros((4, 4), dtype=np.float32))
@ -629,23 +619,23 @@ def test_phase_rerank_emits_candidate_progress_events(monkeypatch) -> None:
def observer(event: str, payload: dict[str, object]) -> None:
events.append((event, payload))
pipeline_module._select_phase_candidate_with_reconstruction(
pipeline_module._select_candidate_with_reconstruction(
np.zeros((16, 16, 4), dtype=np.uint8),
inference,
analysis=analysis,
steps=2,
seed=1,
device="cpu",
solver_params=SolverHyperParams(phase_rerank_preview_steps=2, phase_rerank_confidence_threshold=1.0),
solver_params=SolverHyperParams(candidate_rerank_preview_steps=2, candidate_rerank_confidence_threshold=1.0),
observer=observer,
)
event_names = [event for event, _payload in events]
assert event_names[0] == "phase_rerank_started"
assert event_names.count("phase_rerank_candidate_started") == 2
assert event_names.count("phase_rerank_candidate_step") == 6
assert event_names.count("phase_rerank_candidate_completed") == 2
first_step_payload = next(payload for event, payload in events if event == "phase_rerank_candidate_step")
assert event_names[0] == "candidate_rerank_started"
assert event_names.count("candidate_rerank_candidate_started") == 2
assert event_names.count("candidate_rerank_candidate_step") == 6
assert event_names.count("candidate_rerank_candidate_completed") == 2
first_step_payload = next(payload for event, payload in events if event == "candidate_rerank_candidate_step")
assert first_step_payload["candidate_index"] == 1
assert first_step_payload["total_steps"] == 2
@ -866,19 +856,17 @@ def test_hosted_job_options_use_direct_autocorr_and_skip_rerank() -> None:
target_size=None,
target_width=None,
target_height=None,
phase_x=None,
phase_y=None,
steps=None,
seed=7,
device="auto",
strip_background=False,
skip_phase_rerank=False,
skip_candidate_rerank=False,
)
assert options["target_size"] is None
assert options["lattice_inference_mode"] == "autocorr"
assert options["max_inferred_target_size"] == 256
assert options["skip_phase_rerank"] is True
assert options["skip_candidate_rerank"] is True
def test_gui_job_routes_enforce_bound_subject_ownership(monkeypatch, tmp_path: Path) -> None:
@ -907,13 +895,11 @@ def test_gui_job_routes_enforce_bound_subject_ownership(monkeypatch, tmp_path: P
target_size=None,
target_width=None,
target_height=None,
phase_x=None,
phase_y=None,
steps=None,
seed=7,
device="auto",
strip_background=False,
skip_phase_rerank=False,
skip_candidate_rerank=False,
)
)
assert created.status_code == 200
@ -985,13 +971,11 @@ def test_gui_queue_rejects_eleventh_waiting_job(monkeypatch, tmp_path: Path) ->
target_size=None,
target_width=None,
target_height=None,
phase_x=None,
phase_y=None,
steps=None,
seed=7,
device="auto",
strip_background=False,
skip_phase_rerank=False,
skip_candidate_rerank=False,
)
)
)
@ -1003,13 +987,11 @@ def test_gui_queue_rejects_eleventh_waiting_job(monkeypatch, tmp_path: Path) ->
target_size=None,
target_width=None,
target_height=None,
phase_x=None,
phase_y=None,
steps=None,
seed=7,
device="auto",
strip_background=False,
skip_phase_rerank=False,
skip_candidate_rerank=False,
)
)
except Exception as exc:
@ -1044,13 +1026,11 @@ def test_gui_hosted_jobs_dispatch_direct_autocorr_pipeline(monkeypatch, tmp_path
target_size=None,
target_width=None,
target_height=None,
phase_x=None,
phase_y=None,
steps=None,
seed=7,
device="auto",
strip_background=False,
skip_phase_rerank=False,
skip_candidate_rerank=False,
)
)
deadline = time.time() + 2.0
@ -1062,7 +1042,7 @@ def test_gui_hosted_jobs_dispatch_direct_autocorr_pipeline(monkeypatch, tmp_path
assert calls
assert calls[0]["lattice_inference_mode"] == "autocorr"
assert calls[0]["max_inferred_target_size"] == 256
assert calls[0]["enable_phase_rerank"] is False
assert calls[0]["enable_candidate_rerank"] is False
assert calls[0]["target_size"] is None
@ -1090,13 +1070,11 @@ def test_gui_canceling_queued_job_cleans_spool_file(monkeypatch, tmp_path: Path)
target_size=None,
target_width=None,
target_height=None,
phase_x=None,
phase_y=None,
steps=None,
seed=7,
device="auto",
strip_background=False,
skip_phase_rerank=False,
skip_candidate_rerank=False,
)
)
second = asyncio.run(
@ -1105,13 +1083,11 @@ def test_gui_canceling_queued_job_cleans_spool_file(monkeypatch, tmp_path: Path)
target_size=None,
target_width=None,
target_height=None,
phase_x=None,
phase_y=None,
steps=None,
seed=7,
device="auto",
strip_background=False,
skip_phase_rerank=False,
skip_candidate_rerank=False,
)
)
assert first.status_code == 200
@ -1158,13 +1134,11 @@ def test_gui_running_job_is_canceled_after_stale_heartbeat(monkeypatch, tmp_path
target_size=None,
target_width=None,
target_height=None,
phase_x=None,
phase_y=None,
steps=None,
seed=7,
device="auto",
strip_background=False,
skip_phase_rerank=False,
skip_candidate_rerank=False,
)
)
assert created.status_code == 200
@ -1199,13 +1173,11 @@ def test_gui_rejects_oversized_upload_and_output(monkeypatch, tmp_path: Path) ->
target_size=None,
target_width=None,
target_height=None,
phase_x=None,
phase_y=None,
steps=None,
seed=7,
device="auto",
strip_background=False,
skip_phase_rerank=False,
skip_candidate_rerank=False,
)
)
except Exception as exc:
@ -1223,13 +1195,11 @@ def test_gui_rejects_oversized_upload_and_output(monkeypatch, tmp_path: Path) ->
target_size=None,
target_width=16,
target_height=None,
phase_x=None,
phase_y=None,
steps=None,
seed=7,
device="auto",
strip_background=False,
skip_phase_rerank=False,
skip_candidate_rerank=False,
)
)
except Exception as exc:

View file

@ -141,21 +141,21 @@ def test_direct_badge_autocorr_consensus_stays_in_canonical_family() -> None:
result = infer_autocorr_lattice(rgba, device="cpu")
assert result.target_width in {125, 126}
assert result.top_candidates
assert all(candidate.target_width == result.target_width for candidate in result.top_candidates)
assert result.top_candidates[0].target_width == result.target_width
def test_top_candidates_are_diversified_by_size() -> None:
candidates = [
InferenceCandidate(target_width=113, target_height=113, phase_x=0.0, phase_y=0.0, score=0.90, breakdown={}),
InferenceCandidate(target_width=113, target_height=113, phase_x=0.2, phase_y=0.0, score=0.89, breakdown={}),
InferenceCandidate(target_width=117, target_height=117, phase_x=0.0, phase_y=0.0, score=0.88, breakdown={}),
InferenceCandidate(target_width=128, target_height=128, phase_x=0.0, phase_y=0.0, score=0.87, breakdown={}),
InferenceCandidate(target_width=113, target_height=113, score=0.90, breakdown={}),
InferenceCandidate(target_width=113, target_height=113, score=0.89, breakdown={}),
InferenceCandidate(target_width=117, target_height=117, score=0.88, breakdown={}),
InferenceCandidate(target_width=128, target_height=128, score=0.87, breakdown={}),
]
selected = _top_candidates_by_size(candidates, limit=8)
assert [(candidate.target_width, candidate.phase_x) for candidate in selected] == [
(113, 0.0),
(117, 0.0),
(128, 0.0),
assert [(candidate.target_width, candidate.target_height) for candidate in selected] == [
(113, 113),
(117, 117),
(128, 128),
]
@ -164,8 +164,6 @@ def test_infer_lattice_recovers_emblem_scale() -> None:
fake = fake_pixelize(
source,
upscale=12,
phase_x=0.2,
phase_y=0.35,
blur_radius=0.75,
warp_strength=0.28,
warp_detail=6,
@ -177,27 +175,23 @@ def test_infer_lattice_recovers_emblem_scale() -> None:
assert result.confidence >= 0.0
def test_infer_fixed_lattice_honors_exact_size_and_phase() -> None:
def test_infer_fixed_lattice_uses_canonical_cell_centers_for_pinned_size() -> None:
source = make_emblem(16, 16)
fake = fake_pixelize(source, upscale=10, phase_x=0.2, phase_y=-0.2, blur_radius=0.4, seed=9)
fake = fake_pixelize(source, upscale=10, blur_radius=0.4, seed=9)
result = infer_fixed_lattice(
fake,
target_width=16,
target_height=16,
phase_x=0.2,
phase_y=-0.2,
device="cpu",
)
assert result.target_width == 16
assert result.target_height == 16
assert abs(result.phase_x - 0.2) <= 1e-6
assert abs(result.phase_y + 0.2) <= 1e-6
assert len(result.top_candidates) == 1
def test_infer_fixed_lattice_searches_phase_within_pinned_size() -> None:
def test_infer_fixed_lattice_uses_canonical_cell_centers_within_pinned_size() -> None:
source = make_emblem(16, 16)
fake = fake_pixelize(source, upscale=8, phase_x=0.2, phase_y=0.25, blur_radius=0.45, seed=3)
fake = fake_pixelize(source, upscale=8, blur_radius=0.45, seed=3)
result = infer_fixed_lattice(
fake,
target_width=16,
@ -206,7 +200,7 @@ def test_infer_fixed_lattice_searches_phase_within_pinned_size() -> None:
)
assert result.target_width == 16
assert result.target_height == 16
assert len(result.top_candidates) > 1
assert len(result.top_candidates) == 1
assert all(candidate.target_width == 16 for candidate in result.top_candidates)
assert all(candidate.target_height == 16 for candidate in result.top_candidates)
@ -245,13 +239,11 @@ def test_infer_lattice_honors_cooperative_cancellation(monkeypatch) -> None:
)
monkeypatch.setattr(
inference_module,
"_score_phase_group",
"_score_size_candidate",
lambda *args, **kwargs: [
inference_module.InferenceCandidate(
target_width=10,
target_height=8,
phase_x=0.0,
phase_y=0.0,
score=0.5,
breakdown={},
)

View file

@ -171,16 +171,12 @@ def test_source_lattice_consistency_prefers_matching_cell_structure() -> None:
good,
target_width=2,
target_height=2,
phase_x=0.0,
phase_y=0.0,
)["score"]
bad_score = source_lattice_consistency_breakdown(
source,
bad,
target_width=2,
target_height=2,
phase_x=0.0,
phase_y=0.0,
)["score"]
assert good_score < bad_score

View file

@ -19,8 +19,6 @@ def test_optimize_phase_field_emits_displacement_diagnostics_and_source_colors()
inference = InferenceResult(
target_width=6,
target_height=6,
phase_x=0.0,
phase_y=0.0,
confidence=1.0,
top_candidates=[],
)
@ -49,8 +47,6 @@ def test_optimize_phase_field_moves_off_zero_when_phase_is_wrong() -> None:
fake = fake_pixelize(
source,
upscale=8,
phase_x=0.18,
phase_y=-0.14,
blur_radius=0.35,
warp_strength=0.12,
warp_detail=4,
@ -59,8 +55,6 @@ def test_optimize_phase_field_moves_off_zero_when_phase_is_wrong() -> None:
inference = InferenceResult(
target_width=18,
target_height=18,
phase_x=0.0,
phase_y=0.0,
confidence=1.0,
top_candidates=[],
)
@ -81,8 +75,6 @@ def test_optimize_phase_field_honors_cooperative_cancellation() -> None:
inference = InferenceResult(
target_width=12,
target_height=12,
phase_x=0.0,
phase_y=0.0,
confidence=1.0,
top_candidates=[],
)

View file

@ -10,7 +10,7 @@ from repixelizer.analysis import analyze_phase_field_source
from repixelizer.baselines import naive_resize_baseline
from repixelizer.metrics import coherence_breakdown, foreground_reconstruction_error, source_lattice_consistency_breakdown
from repixelizer.params import SolverHyperParams
from repixelizer.pipeline import _run_reconstruction, _select_phase_candidate, run_pipeline
from repixelizer.pipeline import _run_reconstruction, _select_candidate, run_pipeline
from repixelizer.observe import PipelineCancelled
from repixelizer.phase_field import optimize_phase_field
from repixelizer.io import nearest_resize
@ -20,7 +20,7 @@ from repixelizer.types import InferenceCandidate, InferenceResult, SolverArtifac
def test_pipeline_writes_output_and_diagnostics(tmp_path: Path) -> None:
source = make_emblem(32, 32)
fake = fake_pixelize(source, upscale=10, phase_x=0.15, phase_y=0.25, blur_radius=0.5)
fake = fake_pixelize(source, upscale=10, blur_radius=0.5)
input_path = tmp_path / "input.png"
output_path = tmp_path / "output.png"
diagnostics_dir = tmp_path / "diagnostics"
@ -40,7 +40,7 @@ def test_pipeline_writes_output_and_diagnostics(tmp_path: Path) -> None:
assert set(run_json["source_fidelity"].keys()) == {"initial_output", "solver_target", "final_output"}
assert "source_structure" in run_json
assert {"edge_f1", "exact_match_ratio", "score"} <= set(run_json["source_structure"].keys())
assert "phase_rerank_candidates" in run_json
assert "candidate_rerank_candidates" in run_json
assert {"initial_output", "final_output"} <= set(run_json["optimizer_displacement"].keys())
assert result.output_rgba.shape[0] == result.inference.target_height
assert result.output_rgba.shape[1] == result.inference.target_width
@ -51,8 +51,6 @@ def test_pipeline_beats_naive_on_roundtrip_fidelity_for_synthetic_emblem(tmp_pat
fake = fake_pixelize(
source,
upscale=12,
phase_x=0.2,
phase_y=0.35,
blur_radius=0.65,
warp_strength=0.28,
warp_detail=6,
@ -75,7 +73,7 @@ def test_pipeline_beats_naive_on_roundtrip_fidelity_for_synthetic_emblem(tmp_pat
def test_pipeline_preserves_transparency_for_sprite(tmp_path: Path) -> None:
source = make_sprite(24, 24)
fake = fake_pixelize(source, upscale=9, phase_x=0.1, phase_y=0.22, blur_radius=0.45)
fake = fake_pixelize(source, upscale=9, blur_radius=0.45)
input_path = tmp_path / "input.png"
output_path = tmp_path / "output.png"
@ -116,7 +114,7 @@ def test_pipeline_can_strip_checkerboard_background(tmp_path: Path) -> None:
def test_pipeline_can_emit_initialized_output_without_optimizer_steps(tmp_path: Path) -> None:
source = make_emblem(24, 24)
fake = fake_pixelize(source, upscale=10, phase_x=0.15, phase_y=0.2, blur_radius=0.6, warp_strength=0.2, warp_detail=5)
fake = fake_pixelize(source, upscale=10, blur_radius=0.6, warp_strength=0.2, warp_detail=5)
input_path = tmp_path / "input.png"
output_path = tmp_path / "output.png"
@ -134,8 +132,6 @@ def test_fixed_phase_field_pipeline_output_matches_refactor_baseline(tmp_path: P
fake = fake_pixelize(
source,
upscale=8,
phase_x=0.1,
phase_y=-0.05,
blur_radius=0.4,
warp_strength=0.15,
warp_detail=4,
@ -152,33 +148,29 @@ def test_fixed_phase_field_pipeline_output_matches_refactor_baseline(tmp_path: P
output_path,
target_width=24,
target_height=24,
phase_x=0.1,
phase_y=-0.05,
enable_phase_rerank=False,
enable_candidate_rerank=False,
steps=0,
device="cpu",
)
output_hash = hashlib.sha256(np.ascontiguousarray(result.output_rgba).view(np.uint8)).hexdigest()
assert output_hash == "9e01caa4ee4b508876d9a8360e5c8471f5ab07baf8ed1e5a08e76b9d3533c58e"
assert output_hash == "6ff8f628e1d926e7a5f00d9dceea7decf079d2b070824e18ebe53676311631a0"
def test_phase_rerank_can_override_low_confidence_inference_pick(monkeypatch) -> None:
source = np.zeros((2, 2, 4), dtype=np.float32)
def test_candidate_rerank_can_override_low_confidence_inference_pick(monkeypatch) -> None:
source = np.zeros((3, 3, 4), dtype=np.float32)
source[0, 0] = np.asarray([1.0, 0.0, 0.0, 1.0], dtype=np.float32)
candidate_a = InferenceCandidate(target_width=2, target_height=2, phase_x=-0.4, phase_y=0.2, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=2, target_height=2, phase_x=0.4, phase_y=0.2, score=0.909, breakdown={})
candidate_a = InferenceCandidate(target_width=2, target_height=2, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=3, target_height=3, score=0.909, breakdown={})
inference = InferenceResult(
target_width=2,
target_height=2,
phase_x=candidate_a.phase_x,
phase_y=candidate_a.phase_y,
confidence=0.1,
top_candidates=[candidate_a, candidate_b],
)
outputs = {
(candidate_a.phase_x, candidate_a.phase_y): np.ones_like(source),
(candidate_b.phase_x, candidate_b.phase_y): source.copy(),
(candidate_a.target_width, candidate_a.target_height): np.ones((2, 2, 4), dtype=np.float32),
(candidate_b.target_width, candidate_b.target_height): source.copy(),
}
class DummyArtifacts:
@ -187,24 +179,37 @@ def test_phase_rerank_can_override_low_confidence_inference_pick(monkeypatch) ->
def fake_optimize_phase_field(source_rgba, inference, analysis, steps, seed, device, solver_params=None):
assert steps == 8
return DummyArtifacts(outputs[(inference.phase_x, inference.phase_y)])
return DummyArtifacts(outputs[(inference.target_width, inference.target_height)])
monkeypatch.setattr("repixelizer.pipeline.optimize_phase_field", fake_optimize_phase_field)
monkeypatch.setattr(
"repixelizer.pipeline.source_lattice_consistency_breakdown",
lambda source_rgba, output_rgba, *, target_width, target_height: {"score": 0.10 if target_width == 2 else 0.01},
)
monkeypatch.setattr("repixelizer.pipeline.foreground_edge_position_error", lambda preview, source_rgba: 0.0)
monkeypatch.setattr("repixelizer.pipeline.foreground_stroke_wobble_error", lambda preview, source_rgba: 0.0)
monkeypatch.setattr("repixelizer.pipeline.foreground_edge_concentration", lambda rgba: 0.0)
selected = _select_phase_candidate(source, inference, analysis=object(), steps=32, seed=7, device="cpu")
assert selected.phase_x == candidate_b.phase_x
assert selected.phase_y == candidate_b.phase_y
selected = _select_candidate(
source,
inference,
analysis=object(),
steps=32,
seed=7,
device="cpu",
solver_params=SolverHyperParams(candidate_rerank_max_size_delta_ratio=1.0, candidate_rerank_margin=0.0),
)
assert selected.target_width == candidate_b.target_width
assert selected.target_height == candidate_b.target_height
def test_phase_rerank_preview_respects_requested_zero_steps(monkeypatch) -> None:
def test_candidate_rerank_preview_respects_requested_zero_steps(monkeypatch) -> None:
source = np.zeros((2, 2, 4), dtype=np.float32)
candidate_a = InferenceCandidate(target_width=2, target_height=2, phase_x=-0.4, phase_y=0.2, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=2, target_height=2, phase_x=0.4, phase_y=0.2, score=0.909, breakdown={})
candidate_a = InferenceCandidate(target_width=2, target_height=2, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=3, target_height=3, score=0.909, breakdown={})
inference = InferenceResult(
target_width=2,
target_height=2,
phase_x=candidate_a.phase_x,
phase_y=candidate_a.phase_y,
confidence=0.1,
top_candidates=[candidate_a, candidate_b],
)
@ -215,22 +220,28 @@ def test_phase_rerank_preview_respects_requested_zero_steps(monkeypatch) -> None
def fake_optimize_phase_field(source_rgba, inference, analysis, steps, seed, device, solver_params=None):
assert steps == 0
return DummyArtifacts(np.zeros_like(source_rgba))
return DummyArtifacts(np.zeros((inference.target_height, inference.target_width, 4), dtype=np.float32))
monkeypatch.setattr("repixelizer.pipeline.optimize_phase_field", fake_optimize_phase_field)
_select_phase_candidate(source, inference, analysis=object(), steps=0, seed=7, device="cpu")
_select_candidate(
source,
inference,
analysis=object(),
steps=0,
seed=7,
device="cpu",
solver_params=SolverHyperParams(candidate_rerank_max_size_delta_ratio=1.0),
)
def test_phase_rerank_honors_cooperative_cancellation(monkeypatch) -> None:
def test_candidate_rerank_honors_cooperative_cancellation(monkeypatch) -> None:
source = np.zeros((2, 2, 4), dtype=np.float32)
candidate_a = InferenceCandidate(target_width=2, target_height=2, phase_x=-0.4, phase_y=0.2, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=2, target_height=2, phase_x=0.4, phase_y=0.2, score=0.909, breakdown={})
candidate_a = InferenceCandidate(target_width=2, target_height=2, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=3, target_height=3, score=0.909, breakdown={})
inference = InferenceResult(
target_width=2,
target_height=2,
phase_x=candidate_a.phase_x,
phase_y=candidate_a.phase_y,
confidence=0.1,
top_candidates=[candidate_a, candidate_b],
)
@ -243,7 +254,7 @@ def test_phase_rerank_honors_cooperative_cancellation(monkeypatch) -> None:
return True
with pytest.raises(PipelineCancelled):
_select_phase_candidate(
_select_candidate(
source,
inference,
analysis=object(),
@ -254,15 +265,13 @@ def test_phase_rerank_honors_cooperative_cancellation(monkeypatch) -> None:
)
def test_phase_rerank_can_override_to_better_size_candidate(monkeypatch) -> None:
def test_candidate_rerank_can_override_to_better_size_candidate(monkeypatch) -> None:
source = np.zeros((16, 16, 4), dtype=np.float32)
candidate_a = InferenceCandidate(target_width=16, target_height=16, phase_x=0.0, phase_y=0.0, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=18, target_height=18, phase_x=0.0, phase_y=0.0, score=0.88, breakdown={})
candidate_a = InferenceCandidate(target_width=16, target_height=16, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=18, target_height=18, score=0.88, breakdown={})
inference = InferenceResult(
target_width=16,
target_height=16,
phase_x=0.0,
phase_y=0.0,
confidence=0.0,
top_candidates=[candidate_a, candidate_b],
)
@ -275,7 +284,7 @@ def test_phase_rerank_can_override_to_better_size_candidate(monkeypatch) -> None
rgba = np.zeros((inference.target_height, inference.target_width, 4), dtype=np.float32)
return DummyArtifacts(rgba)
def fake_support(source_rgba, output_rgba, *, target_width, target_height, phase_x, phase_y):
def fake_support(source_rgba, output_rgba, *, target_width, target_height):
if target_width == 16:
return {"score": 0.10}
return {"score": 0.01}
@ -283,20 +292,18 @@ def test_phase_rerank_can_override_to_better_size_candidate(monkeypatch) -> None
monkeypatch.setattr("repixelizer.pipeline.optimize_phase_field", fake_optimize_phase_field)
monkeypatch.setattr("repixelizer.pipeline.source_lattice_consistency_breakdown", fake_support)
selected = _select_phase_candidate(source, inference, analysis=object(), steps=32, seed=7, device="cpu")
selected = _select_candidate(source, inference, analysis=object(), steps=32, seed=7, device="cpu")
assert selected.target_width == candidate_b.target_width
assert selected.target_height == candidate_b.target_height
def test_phase_rerank_rejects_large_size_jump(monkeypatch) -> None:
def test_candidate_rerank_rejects_large_size_jump(monkeypatch) -> None:
source = np.zeros((16, 16, 4), dtype=np.float32)
candidate_a = InferenceCandidate(target_width=16, target_height=16, phase_x=0.0, phase_y=0.0, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=24, target_height=24, phase_x=0.0, phase_y=0.0, score=0.88, breakdown={})
candidate_a = InferenceCandidate(target_width=16, target_height=16, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=24, target_height=24, score=0.88, breakdown={})
inference = InferenceResult(
target_width=16,
target_height=16,
phase_x=0.0,
phase_y=0.0,
confidence=0.0,
top_candidates=[candidate_a, candidate_b],
)
@ -309,7 +316,7 @@ def test_phase_rerank_rejects_large_size_jump(monkeypatch) -> None:
rgba = np.zeros((inference.target_height, inference.target_width, 4), dtype=np.float32)
return DummyArtifacts(rgba)
def fake_support(source_rgba, output_rgba, *, target_width, target_height, phase_x, phase_y):
def fake_support(source_rgba, output_rgba, *, target_width, target_height):
if target_width == 16:
return {"score": 0.10}
return {"score": 0.01}
@ -317,36 +324,34 @@ def test_phase_rerank_rejects_large_size_jump(monkeypatch) -> None:
monkeypatch.setattr("repixelizer.pipeline.optimize_phase_field", fake_optimize_phase_field)
monkeypatch.setattr("repixelizer.pipeline.source_lattice_consistency_breakdown", fake_support)
selected = _select_phase_candidate(source, inference, analysis=object(), steps=32, seed=7, device="cpu")
selected = _select_candidate(source, inference, analysis=object(), steps=32, seed=7, device="cpu")
assert selected.target_width == candidate_a.target_width
assert selected.target_height == candidate_a.target_height
def test_select_phase_candidate_can_skip_phase_rerank(monkeypatch) -> None:
def test_select_candidate_can_skip_candidate_rerank(monkeypatch) -> None:
source = np.zeros((8, 8, 4), dtype=np.float32)
candidate_a = InferenceCandidate(target_width=8, target_height=8, phase_x=0.0, phase_y=0.0, score=0.9, breakdown={})
candidate_b = InferenceCandidate(target_width=10, target_height=10, phase_x=0.2, phase_y=0.2, score=0.89, breakdown={})
candidate_a = InferenceCandidate(target_width=8, target_height=8, score=0.9, breakdown={})
candidate_b = InferenceCandidate(target_width=10, target_height=10, score=0.89, breakdown={})
inference = InferenceResult(
target_width=8,
target_height=8,
phase_x=0.0,
phase_y=0.0,
confidence=0.0,
top_candidates=[candidate_a, candidate_b],
)
def fail(*args, **kwargs):
raise AssertionError("phase rerank probe should not run when disabled")
raise AssertionError("candidate rerank probe should not run when disabled")
monkeypatch.setattr("repixelizer.pipeline.optimize_phase_field", fail)
selected = _select_phase_candidate(
selected = _select_candidate(
source,
inference,
analysis=object(),
steps=32,
seed=7,
device="cpu",
enable_phase_rerank=False,
enable_candidate_rerank=False,
)
assert selected.target_width == candidate_a.target_width
assert selected.target_height == candidate_a.target_height
@ -365,8 +370,6 @@ def test_pipeline_runs_phase_field_mode(tmp_path: Path, monkeypatch) -> None:
inference = InferenceResult(
target_width=3,
target_height=3,
phase_x=0.0,
phase_y=0.0,
confidence=1.0,
top_candidates=[],
)
@ -407,7 +410,7 @@ def test_pipeline_runs_phase_field_mode(tmp_path: Path, monkeypatch) -> None:
assert result.diagnostics["reconstruction"]["mode"] == "phase-field"
def test_pipeline_fixed_target_and_phase_skip_search_inference(tmp_path: Path, monkeypatch) -> None:
def test_pipeline_fixed_target_skips_search_inference(tmp_path: Path, monkeypatch) -> None:
source = np.zeros((6, 6, 4), dtype=np.float32)
source[..., 3] = 1.0
input_path = tmp_path / "input.png"
@ -420,8 +423,6 @@ def test_pipeline_fixed_target_and_phase_skip_search_inference(tmp_path: Path, m
inference = InferenceResult(
target_width=3,
target_height=3,
phase_x=0.2,
phase_y=-0.2,
confidence=1.0,
top_candidates=[],
)
@ -430,7 +431,7 @@ def test_pipeline_fixed_target_and_phase_skip_search_inference(tmp_path: Path, m
edge_map = np.zeros((6, 6), dtype=np.float32)
def fail_infer(*args, **kwargs):
raise AssertionError("full lattice search should not run for fixed target/phase")
raise AssertionError("full lattice search should not run for fixed target")
def fake_infer_fixed(*args, **kwargs):
return inference
@ -456,9 +457,7 @@ def test_pipeline_fixed_target_and_phase_skip_search_inference(tmp_path: Path, m
output_path,
target_width=3,
target_height=3,
phase_x=0.2,
phase_y=-0.2,
enable_phase_rerank=False,
enable_candidate_rerank=False,
steps=0,
device="cpu",
)
@ -466,8 +465,6 @@ def test_pipeline_fixed_target_and_phase_skip_search_inference(tmp_path: Path, m
assert output_path.exists()
assert result.inference.target_width == 3
assert result.inference.target_height == 3
assert result.inference.phase_x == 0.2
assert result.inference.phase_y == -0.2
def test_pipeline_autocorr_mode_skips_size_search(tmp_path: Path, monkeypatch) -> None:
@ -483,11 +480,9 @@ def test_pipeline_autocorr_mode_skips_size_search(tmp_path: Path, monkeypatch) -
inference = InferenceResult(
target_width=3,
target_height=3,
phase_x=0.2,
phase_y=-0.2,
confidence=1.0,
top_candidates=[
InferenceCandidate(target_width=3, target_height=3, phase_x=0.2, phase_y=-0.2, score=0.9, breakdown={})
InferenceCandidate(target_width=3, target_height=3, score=0.9, breakdown={})
],
)
@ -520,7 +515,7 @@ def test_pipeline_autocorr_mode_skips_size_search(tmp_path: Path, monkeypatch) -
result = run_pipeline(
input_path,
output_path,
enable_phase_rerank=False,
enable_candidate_rerank=False,
lattice_inference_mode="autocorr",
max_inferred_target_size=5,
steps=0,
@ -530,19 +525,15 @@ def test_pipeline_autocorr_mode_skips_size_search(tmp_path: Path, monkeypatch) -
assert output_path.exists()
assert result.inference.target_width == 3
assert result.inference.target_height == 3
assert result.inference.phase_x == 0.2
assert result.inference.phase_y == -0.2
def test_phase_rerank_can_accept_low_confidence_size_jump_with_strong_support(monkeypatch) -> None:
def test_candidate_rerank_can_accept_low_confidence_size_jump_with_strong_support(monkeypatch) -> None:
source = np.zeros((16, 16, 4), dtype=np.float32)
candidate_a = InferenceCandidate(target_width=16, target_height=16, phase_x=0.0, phase_y=0.0, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=21, target_height=21, phase_x=0.2, phase_y=-0.2, score=0.89, breakdown={})
candidate_a = InferenceCandidate(target_width=16, target_height=16, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=21, target_height=21, score=0.89, breakdown={})
inference = InferenceResult(
target_width=16,
target_height=16,
phase_x=0.0,
phase_y=0.0,
confidence=0.0,
top_candidates=[candidate_a, candidate_b],
)
@ -559,7 +550,7 @@ def test_phase_rerank_can_accept_low_confidence_size_jump_with_strong_support(mo
def fake_optimize_phase_field(source_rgba, inference, analysis, steps, seed, device, solver_params=None):
return DummyArtifacts(outputs[inference.target_width])
def fake_support(source_rgba, output_rgba, *, target_width, target_height, phase_x, phase_y):
def fake_support(source_rgba, output_rgba, *, target_width, target_height):
return {"score": 0.22 if target_width == 16 else 0.03}
def fake_edge_position(preview, source_rgba):
@ -577,20 +568,18 @@ def test_phase_rerank_can_accept_low_confidence_size_jump_with_strong_support(mo
monkeypatch.setattr("repixelizer.pipeline.foreground_stroke_wobble_error", fake_wobble)
monkeypatch.setattr("repixelizer.pipeline.foreground_edge_concentration", fake_concentration)
selected = _select_phase_candidate(source, inference, analysis=object(), steps=32, seed=7, device="cpu")
selected = _select_candidate(source, inference, analysis=object(), steps=32, seed=7, device="cpu")
assert selected.target_width == candidate_b.target_width
assert selected.target_height == candidate_b.target_height
def test_phase_rerank_keeps_high_confidence_candidate_without_probe(monkeypatch) -> None:
def test_candidate_rerank_keeps_high_confidence_candidate_without_probe(monkeypatch) -> None:
source = np.zeros((8, 8, 4), dtype=np.float32)
candidate_a = InferenceCandidate(target_width=8, target_height=8, phase_x=0.0, phase_y=0.0, score=0.9, breakdown={})
candidate_b = InferenceCandidate(target_width=10, target_height=10, phase_x=0.2, phase_y=0.2, score=0.89, breakdown={})
candidate_a = InferenceCandidate(target_width=8, target_height=8, score=0.9, breakdown={})
candidate_b = InferenceCandidate(target_width=10, target_height=10, score=0.89, breakdown={})
inference = InferenceResult(
target_width=8,
target_height=8,
phase_x=0.0,
phase_y=0.0,
confidence=0.5,
top_candidates=[candidate_a, candidate_b],
)
@ -599,20 +588,18 @@ def test_phase_rerank_keeps_high_confidence_candidate_without_probe(monkeypatch)
raise AssertionError("rerank probe should not run for high-confidence inference")
monkeypatch.setattr("repixelizer.pipeline.optimize_phase_field", fail)
selected = _select_phase_candidate(source, inference, analysis=object(), steps=32, seed=7, device="cpu")
selected = _select_candidate(source, inference, analysis=object(), steps=32, seed=7, device="cpu")
assert selected.target_width == candidate_a.target_width
assert selected.target_height == candidate_a.target_height
def test_phase_rerank_can_prefer_better_line_metrics(monkeypatch) -> None:
def test_candidate_rerank_can_prefer_better_line_metrics(monkeypatch) -> None:
source = np.zeros((4, 4, 4), dtype=np.float32)
candidate_a = InferenceCandidate(target_width=2, target_height=2, phase_x=-0.2, phase_y=0.0, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=2, target_height=2, phase_x=0.2, phase_y=0.0, score=0.909, breakdown={})
candidate_a = InferenceCandidate(target_width=2, target_height=2, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=3, target_height=3, score=0.909, breakdown={})
inference = InferenceResult(
target_width=2,
target_height=2,
phase_x=candidate_a.phase_x,
phase_y=candidate_a.phase_y,
confidence=0.0,
top_candidates=[candidate_a, candidate_b],
)
@ -621,7 +608,7 @@ def test_phase_rerank_can_prefer_better_line_metrics(monkeypatch) -> None:
def __init__(self, rgba: np.ndarray) -> None:
self.target_rgba = rgba
def fake_support(source_rgba, output_rgba, *, target_width, target_height, phase_x, phase_y):
def fake_support(source_rgba, output_rgba, *, target_width, target_height):
return {"score": 0.02}
def fake_edge_position(preview, source_rgba):
@ -634,12 +621,12 @@ def test_phase_rerank_can_prefer_better_line_metrics(monkeypatch) -> None:
return 0.15 if np.mean(rgba) < 0.01 else 0.28
outputs = {
candidate_a.phase_x: np.zeros((2, 2, 4), dtype=np.float32),
candidate_b.phase_x: np.ones((2, 2, 4), dtype=np.float32),
candidate_a.target_width: np.zeros((2, 2, 4), dtype=np.float32),
candidate_b.target_width: np.ones((3, 3, 4), dtype=np.float32),
}
def fake_optimize_phase_field(source_rgba, inference, analysis, steps, seed, device, solver_params=None):
return DummyArtifacts(outputs[inference.phase_x])
return DummyArtifacts(outputs[inference.target_width])
monkeypatch.setattr("repixelizer.pipeline.optimize_phase_field", fake_optimize_phase_field)
monkeypatch.setattr("repixelizer.pipeline.source_lattice_consistency_breakdown", fake_support)
@ -647,6 +634,19 @@ def test_phase_rerank_can_prefer_better_line_metrics(monkeypatch) -> None:
monkeypatch.setattr("repixelizer.pipeline.foreground_stroke_wobble_error", fake_wobble)
monkeypatch.setattr("repixelizer.pipeline.foreground_edge_concentration", fake_concentration)
selected = _select_phase_candidate(source, inference, analysis=object(), steps=32, seed=7, device="cpu")
assert selected.phase_x == candidate_b.phase_x
assert selected.phase_y == candidate_b.phase_y
selected = _select_candidate(
source,
inference,
analysis=object(),
steps=32,
seed=7,
device="cpu",
solver_params=SolverHyperParams(
candidate_rerank_size_penalty_weight=0.0,
candidate_rerank_inference_penalty_weight=0.0,
candidate_rerank_max_size_delta_ratio=1.0,
candidate_rerank_margin=0.0,
),
)
assert selected.target_width == candidate_b.target_width
assert selected.target_height == candidate_b.target_height

View file

@ -20,8 +20,6 @@ def test_source_lattice_reference_recovers_stable_cell_colors() -> None:
source,
target_width=2,
target_height=2,
phase_x=0.0,
phase_y=0.0,
)
assert np.allclose(reference.sharp_rgba, lowres, atol=1e-5)
@ -44,8 +42,6 @@ def test_source_lattice_reference_tracks_edge_peaks_and_gradients() -> None:
source,
target_width=2,
target_height=2,
phase_x=0.0,
phase_y=0.0,
edge_hint=edge_hint,
edge_grad_x_hint=edge_grad_x,
edge_grad_y_hint=edge_grad_y,
@ -65,15 +61,11 @@ def test_source_lattice_reference_cpu_device_matches_default_path() -> None:
source,
target_width=4,
target_height=4,
phase_x=0.0,
phase_y=0.0,
)
accelerated = build_source_lattice_reference(
source,
target_width=4,
target_height=4,
phase_x=0.0,
phase_y=0.0,
device="cpu",
)