{
  "gates": {
    "geometry": "pass"
  },
  "summary": "The repaired scorer integrates disjoint slices of the true intersection. The near-coincident regression agrees with an independent Decimal Green integral. The compatible mode reproduces all six official versus analytic threshold disagreements on the supplied configuration, a published tie. The work is scoped to scoring and validation.",
  "official_setup": {
    "repo": "https://github.com/benedictbrady/shape-packing-challenge",
    "commit": "78a78626f098cd236f3a09bb2cb242f72951599d",
    "tracked_checkout_changes": [],
    "uv_install": "uv 0.13.10 standalone Linux x86_64 archive extracted in scratch because uv was absent",
    "uv_sync": "exit 0, 21 packages installed",
    "sample_cli": {
      "command": "uv run python run.py",
      "status": "VALID",
      "score": "3.500000"
    },
    "published_cli": {
      "command": "uv run --offline python run.py with the supplied BEST fixture",
      "status": "VALID",
      "score": "2.948527",
      "score_8dp": "2.94852695",
      "score_raw_from_library": 2.948526950912552,
      "record_result": "published tie"
    },
    "official_pytest": "31 passed"
  },
  "dependencies": {
    "analytic": "Python >=3.10 standard library only",
    "compatible": "NumPy and Shapely from the pinned official project's environment",
    "oracle": "Python Decimal standard library only",
    "full_test": "Pinned, synced official clone and Git, using its Python environment",
    "versions_tested": {
      "python": "3.10.12",
      "numpy": "2.2.6",
      "shapely": "2.1.2",
      "uv": "0.13.10"
    }
  },
  "replay_commands": "set -eu\nGEOMETRY_RESULT=\"$PWD/artifacts/goal/batches/geometry-fix-r3/items/geometry/result.json\"\nGEOMETRY_SCRATCH=\"$PWD/test/scratch/geometry-replay\"\nmkdir -p \"$GEOMETRY_SCRATCH\"\nexport UV_CACHE_DIR=\"$GEOMETRY_SCRATCH/uv-cache\"\nif ! command -v uv >/dev/null; then\n  curl -fLsS --max-time 90 https://github.com/astral-sh/uv/releases/download/0.13.10/uv-x86_64-unknown-linux-gnu.tar.gz -o \"$GEOMETRY_SCRATCH/uv.tgz\"\n  tar -xzf \"$GEOMETRY_SCRATCH/uv.tgz\" -C \"$GEOMETRY_SCRATCH\"\n  export PATH=\"$GEOMETRY_SCRATCH/uv-x86_64-unknown-linux-gnu:$PATH\"\nfi\npython3 - \"$GEOMETRY_RESULT\" \"$GEOMETRY_SCRATCH\" <<'EXTRACT'\nfrom hashlib import sha256\nimport json\nfrom pathlib import Path\nimport sys\nresult = json.loads(Path(sys.argv[1]).read_text())\nroot = Path(sys.argv[2])\nfor field, name in [('scorer_source', 'geometry_scorer.py'), ('test_source', 'geometry_test.py')]:\n    source = result[field].encode('utf-8')\n    assert sha256(source).hexdigest() == result['hashes'][field + '_sha256']\n    (root / name).write_bytes(source)\nEXTRACT\nif [ ! -d \"$GEOMETRY_SCRATCH/official/.git\" ]; then\n  timeout 120 git clone https://github.com/benedictbrady/shape-packing-challenge \"$GEOMETRY_SCRATCH/official\"\n  git -C \"$GEOMETRY_SCRATCH/official\" checkout --detach 78a78626f098cd236f3a09bb2cb242f72951599d\nfi\ncd \"$GEOMETRY_SCRATCH/official\"\ntest \"$(git rev-parse HEAD)\" = 78a78626f098cd236f3a09bb2cb242f72951599d\ntest -z \"$(git status --porcelain --untracked-files=no)\"\ntimeout 180 uv sync\ntimeout 60 uv run --offline python run.py\ntimeout 90 uv run --offline pytest\ntimeout 350 uv run --offline python ../geometry_test.py --write-best ../best.json > ../check.json\ntimeout 60 uv run --offline python run.py ../best.json\ntimeout 60 uv run --offline python ../geometry_scorer.py ../best.json --mode compatible\n",
  "replay_notes": [
    "The command block extracts both embedded sources into allowed scratch and checks their hashes.",
    "After cloning and syncing once, the verification commands using uv run --offline can be replayed without network.",
    "Run the extracted geometry_scorer.py with a 15-object solution JSON and --mode analytic or --mode compatible. Both round by default. --unrounded bypasses rounding.",
    "For a pair, import exact_overlap_area or polygon_overlap_area and pass triples. For a radius irrespective of overlap validity, call exact_mec on triples."
  ],
  "hashes": {
    "handed_audit_sha256": "293d0c088fc783bf85af2ac07a2d3eed4588d985dce5163448bb83416ee40fa2",
    "scorer_source_sha256": "c066a965ea2c847709dc9c509ab4ad9ab0dd95d1a131cfca16402f57af36fed9",
    "test_source_sha256": "34b92ada72d9699ac741f69dfc31f365b96e2a0ec85983364300072802671fba",
    "best_fixture_json_sha256": "cefac3368caae7f9dea0c4cdc0e87d869f3a9bd76ba75292b1cd4b7fff7c8fb9",
    "official_sample_json_sha256": "c7b7ceeb4b325baca26bddb4ef8284b95f1c0f0e9a2e066483090a16c43d6950",
    "official_run_py_sha256": "367d6eb1aab2c9afb89c3af88bf2e19ca3cb615adb369006869a07ffd5025b7b",
    "official_geometry_py_sha256": "e943a1a956815779b25533c436d6eba17b5345d9effd43fcf1d4958c656b2652",
    "official_config_py_sha256": "c694f258859152ddf3c7857a7b968c0d40d601e8e0fd6091fd58d351c433bfb8",
    "official_scoring_py_sha256": "4a822c1551cd15f70f040b0fac1a8253570a0474eb1592541ef0875513e58b3c"
  },
  "methods": {
    "analytic_overlap": "Translate to local coordinates and choose a sweep frame that keeps both diameter slopes bounded. Each vertical section is the interval bounded by the greatest lower and least upper of four circle branches and two half-planes. Split at both disk domains and all support intersections. The active envelopes cannot change within an open slice, so midpoint comparison selects the bounds and the area is an antiderivative difference. Use a factored chord height, a stable local angle difference, and a small-angle expansion for angle minus sine. Exactly equal centers use the exact sector formula. Every nonzero displacement takes the slice path regardless of size. Shared boundaries and near-duplicate cuts cannot contribute twice.",
    "reference_oracle": "Independent 70-digit Decimal Green integrals of retained directed arc and diameter intervals. The oracle computes the angular and line segment clipping events independently. Decimal(float) preserves the binary64 inputs. Oracle errors reported here compare the binary64 result with this integral in area units.",
    "compatible_overlap": "Same endpoints, NumPy linspace and trig, Shapely intersection, and distance shortcut as the pinned scorer. At the threshold it rejects area > 1e-6, matching the pinned source. Analytic mode rejects area >= 1e-6 to implement the brief's strict below-threshold rule. Polygon bias is oracle area minus polygon area.",
    "mec": "Seed the finite point MEC with each diameter's endpoints and each arc apex. Re-solve after adding analytic farthest witnesses from violating shapes. The farthest boundary point on an arc is the outward radial point when eligible, otherwise the farther diameter endpoint. An upper radius is the greatest analytic distance at the returned center plus the numerical allowance. A lower radius comes from the largest of 1 and the best support-distribution bound less the allowance. For weights on actual boundary points, the weighted variance is at most any enclosing radius squared, giving a lower bound even if a point MEC solve is inexact. The scorer tracks the best upper and lower estimates across iterations. The default convergence condition is a nonnegative gap at most 2e-12 with a maximum of 80 iterations."
  },
  "regression_witnesses": {
    "near_coincident": {
      "prior_reported_area_approx": 3e-06,
      "label": "defect",
      "a": [
        0.0,
        0.0,
        0.0
      ],
      "b": [
        1e-06,
        0.0,
        3.141593
      ],
      "analytic": 1.999999999999297e-06,
      "oracle": 1.9999999999992964e-06,
      "compatible": 1.9999999995548506e-06,
      "absolute_error": 4.235164736271502e-22,
      "polygon_bias": 4.444458107208567e-16,
      "source_prior": "Handed scorer-audit-r2 result with the recorded SHA-256"
    },
    "labelled_contacts": [
      {
        "label": "arc_arc",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          1.9999180027240073,
          0.0,
          3.141592653589793
        ],
        "analytic": 9.900000199486447e-07,
        "oracle": 9.900000199508902e-07,
        "compatible": 9.882368427695217e-07,
        "absolute_error": 2.2454843431711502e-18,
        "polygon_bias": 1.7631771813684623e-09
      },
      {
        "label": "arc_arc",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          1.9999174789976677,
          0.0,
          3.141592653589793
        ],
        "analytic": 9.994999814050276e-07,
        "oracle": 9.994999814041941e-07,
        "compatible": 9.977294961887973e-07,
        "absolute_error": 8.334804200982315e-19,
        "polygon_bias": 1.7704852153967804e-09
      },
      {
        "label": "arc_arc",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          1.9999174239652349,
          0.0,
          3.141592653589793
        ],
        "analytic": 1.0004999787954771e-06,
        "oracle": 1.00049997879383e-06,
        "compatible": 9.987287007654323e-07,
        "absolute_error": 1.647055565935987e-18,
        "polygon_bias": 1.771278028397758e-09
      },
      {
        "label": "arc_arc",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          1.9999169020666159,
          0.0,
          3.141592653589793
        ],
        "analytic": 1.0099999788112934e-06,
        "oracle": 1.0099999788117259e-06,
        "compatible": 1.0082209836414626e-06,
        "absolute_error": 4.324103195733203e-19,
        "polygon_bias": 1.7789951702632183e-09
      },
      {
        "label": "arc_flat",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          0.9999349185629399,
          0.0,
          0.0
        ],
        "analytic": 9.900000025771238e-07,
        "oracle": 9.90000002576844e-07,
        "compatible": 9.888857878473124e-07,
        "absolute_error": 2.7994438906754626e-19,
        "polygon_bias": 1.1142147295314528e-09
      },
      {
        "label": "arc_flat",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          0.9999345028787502,
          0.0,
          0.0
        ],
        "analytic": 9.994999710695451e-07,
        "oracle": 9.994999710681168e-07,
        "compatible": 9.983806792925675e-07,
        "absolute_error": 1.428309307307564e-18,
        "polygon_bias": 1.1192917755493703e-09
      },
      {
        "label": "arc_flat",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          0.999934459196811,
          0.0,
          0.0
        ],
        "analytic": 1.0005000247031992e-06,
        "oracle": 1.0005000247024394e-06,
        "compatible": 9.993801882480092e-07,
        "absolute_error": 7.597885536871074e-19,
        "polygon_bias": 1.1198364544302514e-09
      },
      {
        "label": "arc_flat",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          0.9999340449649025,
          0.0,
          0.0
        ],
        "analytic": 1.0099999946493188e-06,
        "oracle": 1.0099999946477604e-06,
        "compatible": 1.008874924379998e-06,
        "absolute_error": 1.558328864711099e-18,
        "polygon_bias": 1.1250702677625408e-09
      },
      {
        "label": "flat_flat",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          4.949999999953431e-07,
          0.0,
          3.141592653589793
        ],
        "analytic": 9.899999999906153e-07,
        "oracle": 9.899999999906156e-07,
        "compatible": 9.899999996047736e-07,
        "absolute_error": 2.117582368135751e-22,
        "polygon_bias": 3.858419304409366e-16
      },
      {
        "label": "flat_flat",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          4.99749999982305e-07,
          0.0,
          3.141592653589793
        ],
        "analytic": 9.994999999645372e-07,
        "oracle": 9.994999999645372e-07,
        "compatible": 9.994999995759788e-07,
        "absolute_error": 0.0,
        "polygon_bias": 3.8855836510278113e-16
      },
      {
        "label": "flat_flat",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          5.002500000176949e-07,
          0.0,
          3.141592653589793
        ],
        "analytic": 1.0005000000353168e-06,
        "oracle": 1.0005000000353168e-06,
        "compatible": 1.0004999996464709e-06,
        "absolute_error": 0.0,
        "polygon_bias": 3.8884593278837396e-16
      },
      {
        "label": "flat_flat",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          5.050000000046568e-07,
          0.0,
          3.141592653589793
        ],
        "analytic": 1.0100000000092387e-06,
        "oracle": 1.0100000000092384e-06,
        "compatible": 1.0099999996176473e-06,
        "absolute_error": 2.117582368135751e-22,
        "polygon_bias": 3.9159116657042515e-16
      }
    ],
    "published_pairs_zero_based": [
      {
        "label": "best:1,3",
        "a": [
          1.135484,
          -1.23874,
          2.227365
        ],
        "b": [
          1.843118,
          0.631801,
          -0.722762
        ],
        "analytic": 1.0013726918734964e-06,
        "oracle": 1.0013726918707471e-06,
        "compatible": 9.99594025502215e-07,
        "absolute_error": 2.7492571885506453e-18,
        "polygon_bias": 1.778666368532215e-09,
        "pair": [
          1,
          3
        ],
        "prior_audit_area": 1.0013726918648228e-06,
        "prior_audit_polygon_area": 9.995940255023496e-07,
        "prior_analytic_minus_oracle": -5.92436019133339e-18
      },
      {
        "label": "best:1,13",
        "a": [
          1.135484,
          -1.23874,
          2.227365
        ],
        "b": [
          -0.789401,
          -1.781407,
          -0.792106
        ],
        "analytic": 1.0003480671108567e-06,
        "oracle": 1.0003480671110788e-06,
        "compatible": 9.985677175080334e-07,
        "absolute_error": 2.2213439041744026e-19,
        "polygon_bias": 1.7803496030454266e-09,
        "pair": [
          1,
          13
        ],
        "prior_audit_area": 1.0003480671177956e-06,
        "prior_audit_polygon_area": 9.985677175080882e-07,
        "prior_analytic_minus_oracle": 6.716759513489788e-18
      },
      {
        "label": "best:2,11",
        "a": [
          -0.584124,
          -0.217653,
          -1.671787
        ],
        "b": [
          -1.573106,
          -1.149938,
          -1.641622
        ],
        "analytic": 1.0007704081410607e-06,
        "oracle": 1.0007704081408313e-06,
        "compatible": 9.996466942502033e-07,
        "absolute_error": 2.293341704691018e-19,
        "polygon_bias": 1.1237138906280607e-09,
        "pair": [
          2,
          11
        ],
        "prior_audit_area": 1.0007703869930468e-06,
        "prior_audit_polygon_area": 9.99646694252285e-07,
        "prior_analytic_minus_oracle": -2.1147784561462786e-14
      },
      {
        "label": "best:3,9",
        "a": [
          1.843118,
          0.631801,
          -0.722762
        ],
        "b": [
          1.261991,
          1.484613,
          0.453135
        ],
        "analytic": 1.0007205146315978e-06,
        "oracle": 1.0007205145887128e-06,
        "compatible": 9.995983747504195e-07,
        "absolute_error": 4.288506636124841e-17,
        "polygon_bias": 1.1221398382932908e-09,
        "pair": [
          3,
          9
        ],
        "prior_audit_area": 1.0007205352852155e-06,
        "prior_audit_polygon_area": 9.99598374751314e-07,
        "prior_analytic_minus_oracle": 2.0696502771341114e-14
      },
      {
        "label": "best:7,8",
        "a": [
          -0.56981,
          0.785952,
          -1.682231
        ],
        "b": [
          0.032918,
          1.724683,
          -0.877015
        ],
        "analytic": 1.0001613924004449e-06,
        "oracle": 1.0001613924002808e-06,
        "compatible": 9.990352164717355e-07,
        "absolute_error": 1.641126335305207e-19,
        "polygon_bias": 1.1261759285453158e-09,
        "pair": [
          7,
          8
        ],
        "prior_audit_area": 1.0001613859299263e-06,
        "prior_audit_polygon_area": 9.990352164742766e-07,
        "prior_analytic_minus_oracle": -6.47035445275996e-15
      },
      {
        "label": "best:8,9",
        "a": [
          0.032918,
          1.724683,
          -0.877015
        ],
        "b": [
          1.261991,
          1.484613,
          0.453135
        ],
        "analytic": 1.0008169502966069e-06,
        "oracle": 1.0008169502959498e-06,
        "compatible": 9.996957770875582e-07,
        "absolute_error": 6.570858088325235e-19,
        "polygon_bias": 1.1211732083916178e-09,
        "pair": [
          8,
          9
        ],
        "prior_audit_area": 1.0008169318183324e-06,
        "prior_audit_polygon_area": 9.996957770897247e-07,
        "prior_analytic_minus_oracle": -1.8477617380296117e-14
      }
    ],
    "rounding_decision_flips_unrounded_then_rounded": {
      "round_flip:0": [
        false,
        true
      ],
      "round_flip:1": [
        true,
        false
      ]
    }
  },
  "errors": {
    "worst_area_error_by_fixture": {
      "defect": {
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          1e-06,
          0.0,
          3.141593
        ],
        "analytic": 1.999999999999297e-06,
        "oracle": 1.9999999999992964e-06,
        "absolute_error": 4.235164736271502e-22
      },
      "near_centres": {
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          6.123233995736766e-21,
          0.0001,
          0.61
        ],
        "analytic": 1.265696326794938,
        "oracle": 1.2656963267949384,
        "absolute_error": 4.440892098500626e-16
      },
      "random": {
        "a": [
          -0.15689225531059048,
          -0.19890534926999548,
          0.5512581805046343
        ],
        "b": [
          0.8979413781438457,
          0.7593456932528032,
          -2.1819716399664784
        ],
        "analytic": 0.5554556891847817,
        "oracle": 0.555455689184782,
        "absolute_error": 3.3306690738754696e-16
      },
      "tangencies": {
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          1.0,
          0.0,
          1.5707963267948966
        ],
        "analytic": 0.6141848493043782,
        "oracle": 0.6141848493043784,
        "absolute_error": 2.220446049250313e-16
      },
      "arc_arc": {
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          1.9999180027240073,
          0.0,
          3.141592653589793
        ],
        "analytic": 9.900000199486447e-07,
        "oracle": 9.900000199508902e-07,
        "absolute_error": 2.2454843431711502e-18
      },
      "arc_flat": {
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          0.9999340449649025,
          0.0,
          0.0
        ],
        "analytic": 1.0099999946493188e-06,
        "oracle": 1.0099999946477604e-06,
        "absolute_error": 1.558328864711099e-18
      },
      "flat_flat": {
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          5.050000000046568e-07,
          0.0,
          3.141592653589793
        ],
        "analytic": 1.0100000000092387e-06,
        "oracle": 1.0100000000092384e-06,
        "absolute_error": 2.117582368135751e-22
      },
      "best": {
        "a": [
          -1.624637,
          1.076193,
          -2.992325
        ],
        "b": [
          -0.56981,
          0.785952,
          -1.682231
        ],
        "analytic": 9.949987524165288e-07,
        "oracle": 9.949987525031807e-07,
        "absolute_error": 8.665189402058855e-17
      }
    },
    "max_observed_abs_area_error": 4.440892098500626e-16,
    "max_abs_invariance_delta": {
      "swap": 4.440892098500626e-16,
      "translate": 8.881784197001252e-16,
      "rotate": 6.661338147750939e-16
    },
    "max_polygon_bias_separate_from_analytic_error": 2.0544674828038012e-07,
    "asserted_analytic_abs_error_ceiling": 3e-15,
    "asserted_invariance_abs_delta_ceiling": 7e-15
  },
  "test_counts": {
    "area_pairs_total": 570,
    "area_pair_groups": {
      "defect": 1,
      "near_centres": 280,
      "random": 160,
      "tangencies": 12,
      "arc_arc": 4,
      "arc_flat": 4,
      "flat_flat": 4,
      "best": 105
    },
    "area_invariance_checks": {
      "swap": 570,
      "translate": 570,
      "rotate": 570
    },
    "full_15packs": 40,
    "full_pack_groups": {
      "sample": 1,
      "published": 1,
      "sparse": 8,
      "random": 12,
      "half_grid": 16,
      "round_flip": 2
    },
    "compatible_valid_15packs": 27,
    "half_grid_placements": 240,
    "half_grid_seed_values_including_neighbors": 48,
    "dyadic_half_grid_seed_examples": [
      0.0078125,
      0.0234375,
      -0.0078125,
      -0.0234375
    ],
    "coordinate_rounding_hex_comparisons": 1800,
    "independent_known_mec_cases": 4,
    "official_repo_tests_passed": 31
  },
  "disagreements": {
    "compatible_vs_official_pair_decision": 0,
    "compatible_vs_official_pair_area": 0,
    "compatible_vs_official_pack_decision_or_overlap_list": 0,
    "analytic_vs_oracle_pair_decision": 0,
    "analytic_vs_compatible_pair_decision": 8,
    "analytic_vs_compatible_published_pair_decision": 6,
    "other_analytic_vs_compatible_pair_decisions": [
      {
        "label": "arc_arc",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          1.9999174239652349,
          0.0,
          3.141592653589793
        ],
        "analytic": 1.0004999787954771e-06,
        "oracle": 1.00049997879383e-06,
        "compatible": 9.987287007654323e-07,
        "absolute_error": 1.647055565935987e-18,
        "polygon_bias": 1.771278028397758e-09
      },
      {
        "label": "arc_flat",
        "a": [
          0.0,
          0.0,
          0.0
        ],
        "b": [
          0.999934459196811,
          0.0,
          0.0
        ],
        "analytic": 1.0005000247031992e-06,
        "oracle": 1.0005000247024394e-06,
        "compatible": 9.993801882480092e-07,
        "absolute_error": 7.597885536871074e-19,
        "polygon_bias": 1.1198364544302514e-09
      }
    ],
    "analytic_vs_compatible_pack_decisions": [
      "published"
    ]
  },
  "timings": {
    "scope": "One local audit run. Raw pair timings include both contacting and disjoint cases. Pack timings are end-to-end scorer calls, excluding JSON I/O and independent residual checks.",
    "pairs": {
      "analytic": {
        "pairs": 14250,
        "wall_seconds": 0.4821451101452112
      },
      "compatible": {
        "pairs": 570,
        "wall_seconds": 6.035270831082016
      }
    },
    "microseconds_per_pair": {
      "analytic": 33.83474457159377,
      "compatible": 10588.194440494764
    },
    "pack_count": 40,
    "pack_wall_seconds": {
      "official": 9.8502844478935,
      "compatible": 2.2390301879495382,
      "analytic": 0.058703035581856966
    },
    "milliseconds_per_pack": {
      "official": 246.2571111973375,
      "compatible": 55.975754698738456,
      "analytic": 1.4675758895464242
    },
    "whole_harness_wall_seconds": 36.0758554879576
  },
  "mec_residuals": {
    "definition": "Point residual is the positive difference between analytically required radius at the retained center and that iteration's finite point-circle radius. Decimal farthest uses independent high-precision normals and endpoint distance.",
    "max_gap": 1.6822099269120372e-12,
    "max_point_residual": 1.6542323066914832e-12,
    "max_radius_minus_decimal_farthest": 2.3092638912203256e-13,
    "max_abs_radius_delta_official": 1.1750600492632657e-12,
    "max_iterations": 17,
    "named_fixtures": {
      "sample": {
        "official_score": 3.5,
        "official_8dp": "3.50000000",
        "analytic_valid": true,
        "compatible_valid": true,
        "mec": {
          "x": -2.220446049250313e-16,
          "y": 1.5000000000000002,
          "radius": 3.5000000000000284,
          "lower_bound": 3.4999999999999716,
          "gap": 5.684341886080802e-14,
          "point_residual": 0.0,
          "iterations": 2,
          "converged": true,
          "numerical_padding": 2.842170943040401e-14
        },
        "decimal_farthest": 3.5000000000000004
      },
      "published": {
        "official_score": 2.948526950912552,
        "official_8dp": "2.94852695",
        "analytic_valid": false,
        "compatible_valid": true,
        "mec": {
          "x": -0.00018190806173068452,
          "y": 0.0001344899699196045,
          "radius": 2.948526950912714,
          "lower_bound": 2.9485269509126844,
          "gap": 2.9753977059954195e-14,
          "point_residual": 2.220446049250313e-15,
          "iterations": 4,
          "converged": true,
          "numerical_padding": 1.4210854715202004e-14
        },
        "decimal_farthest": 2.9485269509126995
      }
    },
    "forced_iteration_limit": {
      "x": 0.009928812335193271,
      "y": -0.024593551678441683,
      "radius": 2.975241384295754,
      "lower_bound": 2.923408902628052,
      "gap": 0.051832481667701824,
      "point_residual": 0.05183248166767296,
      "iterations": 1,
      "converged": false,
      "numerical_padding": 1.4210854715202004e-14
    }
  },
  "limitations": [
    "Analytic areas use binary64. Threshold decisions can be sensitive within floating-point error, especially for nearly tangent configurations. The measured worst-case errors apply to the reported fixtures.",
    "MEC bounds include a 32-ulp scale allowance on either side. They are floating-point estimates of mathematical bounds, without directed interval arithmetic. Large coordinate magnitudes can preclude the default absolute tolerance. Inspect converged and gap.",
    "Both modes use the same analytic MEC and return its padded enclosing radius. Polygon overlap compatibility is checked directly against the pinned source. The official radius can differ in its last digits because its sampled initialization and stopping rule differ.",
    "The pinned clone's local behavior is verified. Live scoring was outside the scope of this local task."
  ],
  "provenance": {
    "public_rules": "https://www.paradigm.xyz/puzzles/packing/about",
    "coordinates_and_rounding": [
      "https://raw.githubusercontent.com/benedictbrady/shape-packing-challenge/78a78626f098cd236f3a09bb2cb242f72951599d/README.md",
      "https://raw.githubusercontent.com/benedictbrady/shape-packing-challenge/78a78626f098cd236f3a09bb2cb242f72951599d/run.py"
    ],
    "local_polygon_and_threshold_behavior": [
      "https://raw.githubusercontent.com/benedictbrady/shape-packing-challenge/78a78626f098cd236f3a09bb2cb242f72951599d/src/semicircle_packing/geometry.py",
      "https://raw.githubusercontent.com/benedictbrady/shape-packing-challenge/78a78626f098cd236f3a09bb2cb242f72951599d/src/semicircle_packing/config.py"
    ],
    "local_mec_reference": "https://raw.githubusercontent.com/benedictbrady/shape-packing-challenge/78a78626f098cd236f3a09bb2cb242f72951599d/src/semicircle_packing/scoring.py",
    "prior_areas_and_regression": "Handed scorer-audit-r2 item, identified in hashes. Published BEST rows from the task are embedded in test_source.",
    "new_observations": "Assertions and deterministic fixtures in the embedded test_source, replayed against the pinned official checkout."
  },
  "source_characters_total": 29892,
  "scorer_source": "\"\"\"Unit-semicircle geometry. Triples are (disk-center x, y, curved-side radians).\"\"\"\nimport argparse\nfrom dataclasses import asdict, dataclass\nfrom itertools import combinations\nimport json\nimport math\nimport random\n\nOVERLAP_TOL = 1e-6\nARC_POINTS = 4096\n\n\ndef placement(row, round6=False):\n    \"\"\"Parse a triple or placement object and optionally round as in run.py.\"\"\"\n    if isinstance(row, dict):\n        row = (row[\"x\"], row[\"y\"], row[\"theta\"])\n    x, y, theta = map(float, row)\n    if not all(map(math.isfinite, (x, y, theta))):\n        raise ValueError(\"placements must be finite\")\n    if round6:\n        return round(x, 6), round(y, 6), round(theta, 6)\n    return x, y, theta\n\n\ndef _root(x):\n    \"\"\"Half-chord height, factored for stability at the rim.\"\"\"\n    x = min(abs(x), 1.0)\n    return math.sqrt((1.0 - x) * (1.0 + x))\n\n\ndef _root_integral(a, b):\n    \"\"\"Integral of sqrt(1-x*x) on [a,b], using a local angle difference.\"\"\"\n    a, b = max(-1.0, a), min(1.0, b)\n    if a >= b:\n        return 0.0\n    ca, cb = _root(a), _root(b)\n    width = b - a\n    dot = a*b + ca*cb\n    cross = width * (1.0 + dot) / (ca + cb) if a*b > 0 else b*ca - a*cb\n    angle = math.atan2(cross, dot)\n    # For tiny circular caps, avoid subtracting two nearly equal O(angle) terms.\n    if angle < 0.05:\n        s = angle*angle\n        angle_minus_sin = angle*s*(1/6 - s*(1/120 - s*(1/5040 - s/362880)))\n    else:\n        angle_minus_sin = angle - math.sin(angle)\n    one_plus_cos_sum = ((ca + cb)**2 + width**2) / 2.0\n    return (angle_minus_sin + one_plus_cos_sum*math.sin(angle)) / 2.0\n\n\ndef _sweep_frame(delta, unit, na, nb):\n    # The normals' y components must stay away from zero to bound both slopes.\n    h = math.sqrt(0.5)\n    candidates = [(1., 0.), (0., 1.), (h, h), (-h, h)]\n\n    def to_frame(p, basis):\n        x, y = p\n        c, s = basis\n        return c*x + s*y, c*y - s*x\n\n    basis = max(candidates, key=lambda v: min(abs(to_frame(n, v)[1])\n                                              for n in (na, nb)))\n    return [to_frame(v, basis) for v in (delta, unit, na, nb)]\n\n\ndef exact_overlap_area(a, b):\n    \"\"\"True intersection area for unrounded triples, computed in binary64.\"\"\"\n    ax, ay, at = a\n    bx, by, bt = b\n    dx, dy = bx-ax, by-ay\n    distance = math.hypot(dx, dy)\n    if distance >= 2.0:\n        return 0.0\n    na = math.cos(at), math.sin(at)\n    nb = math.cos(bt), math.sin(bt)\n    if distance == 0:\n        # Shared disk: half of the angular width of the intersecting sectors.\n        cross = na[0]*nb[1] - na[1]*nb[0]\n        dot = na[0]*nb[0] + na[1]*nb[1]\n        return 0.5*math.atan2(abs(cross), -dot)\n\n    # Divide by the largest component before normalizing even subnormal offsets.\n    scale = max(abs(dx), abs(dy))\n    ux, uy = dx/scale, dy/scale\n    norm = math.hypot(ux, uy)\n    (dx, dy), (_, uy), na, nb = _sweep_frame((dx, dy), (ux/norm, uy/norm), na, nb)\n    centres = ((0.0, 0.0), (dx, dy))\n    lo, hi = max(-1.0, dx-1.0), min(1.0, dx+1.0)\n    if lo >= hi:\n        return 0.0\n    cuts = [lo, hi]\n\n    def split(x):\n        if lo < x < hi:\n            cuts.append(x)\n\n    # Split at every support crossing to keep the envelope fixed per slice.\n    height = math.sqrt(max(0.0, (1.0-distance/2)*(1.0+distance/2)))\n    split(dx/2 - height*uy)\n    split(dx/2 + height*uy)\n\n    lines = []\n    for (lx, ly), (nx, ny) in zip(centres, (na, nb)):\n        slope = -nx/ny\n        intercept = ly - slope*lx\n        lines.append((slope, intercept, ny > 0.0))\n        norm = math.hypot(nx, ny)\n        for cx, cy in centres:\n            signed = (cx-lx)*nx + (cy-ly)*ny\n            offset = signed/norm\n            if abs(offset) <= 1.0:\n                foot_x = cx - offset*(nx/norm)\n                extent = _root(offset)*(ny/norm)\n                split(foot_x - extent)\n                split(foot_x + extent)\n    ma, qa, _ = lines[0]\n    mb, qb, _ = lines[1]\n    if ma != mb:\n        split((qb-qa)/(ma-mb))\n\n    cuts = sorted(set(cuts))\n    pieces = []\n    for left, right in zip(cuts, cuts[1:]):\n        mid = left + (right-left)/2\n        upper, lower = [], []\n        for cx, cy in centres:\n            height = _root(mid-cx)\n            upper.append((cy+height, cy, cx, 1))\n            lower.append((cy-height, cy, cx, -1))\n        for slope, intercept, is_lower in lines:\n            y = slope*mid + intercept\n            (lower if is_lower else upper).append((y, y, 0., 0))\n        up, up_base, up_x, up_sign = min(upper)\n        down, down_base, down_x, down_sign = max(lower)\n        if up > down:\n            chord = (up_sign*_root_integral(left-up_x, right-up_x)\n                     if up_sign else 0.0)\n            bottom = (down_sign*_root_integral(left-down_x, right-down_x)\n                      if down_sign else 0.0)\n            area = math.fsum(((up_base-down_base)*(right-left), chord, -bottom))\n            pieces.append(max(0.0, area))\n    return min(math.pi/2, math.fsum(pieces))\n\n\ndef polygon(sc):\n    \"\"\"Construct exactly the pinned scorer's 4096-point polygon.\"\"\"\n    import numpy as np\n    from shapely.geometry import Polygon\n    x, y, theta = sc\n    angles = np.linspace(theta-math.pi/2, theta+math.pi/2, ARC_POINTS)\n    return Polygon(list(zip(x + np.cos(angles), y + np.sin(angles))))\n\n\ndef polygon_overlap_area(a, b):\n    if math.hypot(a[0]-b[0], a[1]-b[1]) > 2.0:\n        return 0.0\n    return polygon(a).intersection(polygon(b)).area\n\n\ndef _farthest(sc, q):\n    x, y, nx, ny = sc\n    dx, dy = x-q[0], y-q[1]\n    length = math.hypot(dx, dy)\n    if length == 0.0:\n        return (x+nx, y+ny), 1.0\n    if dx*nx + dy*ny >= 0.0:\n        return (x+dx/length, y+dy/length), length+1.0\n    tx, ty = -ny, nx\n    if dx*tx + dy*ty < 0.0:\n        tx, ty = -tx, -ty\n    return (x+tx, y+ty), math.hypot(dx+tx, dy+ty)\n\n\ndef farthest_point(sc, q):\n    x, y, theta = sc\n    return _farthest((x, y, math.cos(theta), math.sin(theta)), q)[0]\n\n\ndef _dist(a, b):\n    return math.hypot(a[0]-b[0], a[1]-b[1])\n\n\ndef _pair(a, b):\n    return ((a[0]+b[0])/2, (a[1]+b[1])/2), _dist(a, b)/2, (a, b)\n\n\ndef _triple(a, b, c):\n    ux, uy = b[0]-a[0], b[1]-a[1]\n    vx, vy = c[0]-a[0], c[1]-a[1]\n    det = 2*(ux*vy - uy*vx)\n    if abs(det) <= 8*math.ulp(1.0)*math.hypot(ux, uy)*math.hypot(vx, vy):\n        return max((_pair(p, q) for p, q in combinations((a, b, c), 2)),\n                   key=lambda circle: circle[1])\n    uu, vv = ux*ux + uy*uy, vx*vx + vy*vy\n    x, y = (vy*uu-uy*vv)/det, (ux*vv-vx*uu)/det\n    return (a[0]+x, a[1]+y), math.hypot(x, y), (a, b, c)\n\n\ndef _point_circle(points, eps):\n    points = list(points)\n    random.Random(42).shuffle(points)\n    centre, radius, support = points[0], 0.0, (points[0],)\n    for i, a in enumerate(points):\n        if _dist(a, centre) <= radius+eps:\n            continue\n        centre, radius, support = a, 0.0, (a,)\n        for j in range(i):\n            b = points[j]\n            if _dist(b, centre) <= radius+eps:\n                continue\n            centre, radius, support = _pair(a, b)\n            for k in range(j):\n                c = points[k]\n                if _dist(c, centre) > radius+eps:\n                    centre, radius, support = _triple(a, b, c)\n    return centre, radius, support\n\n\ndef _support_bound(q, points):\n    \"\"\"Lower bound from the variance of a boundary-point distribution.\"\"\"\n    if len(points) < 2:\n        return 0.0\n    if len(points) == 2:\n        return _dist(*points)/2\n    a, b, c = points\n    ux, uy = b[0]-a[0], b[1]-a[1]\n    vx, vy = c[0]-a[0], c[1]-a[1]\n    det = ux*vy - uy*vx\n    if det == 0.0:\n        return max(_dist(p, r)/2 for p, r in combinations(points, 2))\n    x, y = q[0]-a[0], q[1]-a[1]\n    wb, wc = (x*vy-y*vx)/det, (ux*y-uy*x)/det\n    weights = [max(0., w) for w in (1.-wb-wc, wb, wc)]\n    total = math.fsum(weights)\n    weights = [w/total for w in weights]\n    return math.sqrt(math.fsum(weights[i]*weights[j]*_dist(points[i], points[j])**2\n                               for i, j in combinations(range(3), 2)))\n\n\n@dataclass(frozen=True)\nclass MEC:\n    x: float\n    y: float\n    radius: float\n    lower_bound: float\n    gap: float\n    point_residual: float\n    iterations: int\n    converged: bool\n    numerical_padding: float\n\n\ndef exact_mec(shapes, atol=2e-12, max_iterations=80):\n    \"\"\"MEC via finite point exchange and an analytic farthest-point oracle.\n\n    Radius is an upper estimate at the reported centre. A witness distribution\n    gives a lower estimate. The bracket has a floating-point safety allowance,\n    not directed-rounding certification. Inspect converged/gap before claiming\n    the requested accuracy.\n    \"\"\"\n    shapes = list(shapes)\n    if not shapes or not math.isfinite(atol) or atol <= 0 or max_iterations < 1:\n        raise ValueError(\"expected nonempty shapes, positive atol and iterations\")\n    ox, oy, _ = shapes[0]\n    local = [(x-ox, y-oy, math.cos(t), math.sin(t)) for x, y, t in shapes]\n    scale = max(1., *(abs(v) for p in local for v in p[:2]), abs(ox), abs(oy))\n    if not scale < 1e90:\n        raise ValueError(\"coordinates outside the MEC numerical range\")\n    # Account for rounding of the world-coordinate centre.\n    padding = 32*math.ulp(scale)\n    points = []\n    for x, y, nx, ny in local:\n        points.extend(((x-ny, y+nx), (x+ny, y-nx), (x+nx, y+ny)))\n    lower = 1.0\n    upper = math.inf\n    for iteration in range(1, max_iterations+1):\n        q, sample_radius, support = _point_circle(points, 4*math.ulp(scale))\n        lower = max(lower, _support_bound(q, support)-padding)\n        world = ox+q[0], oy+q[1]\n        relative_q = world[0]-ox, world[1]-oy\n        far = [_farthest(sc, relative_q) for sc in local]\n        current = max(distance for _, distance in far)\n        if current+padding < upper:\n            upper, best = current+padding, world\n            residual = max(0., current-sample_radius)\n        gap = upper-lower\n        if 0 <= gap <= atol:\n            break\n        additions = [p for p, d in far if d > sample_radius and p not in points]\n        if not additions:\n            break\n        points.extend(additions)\n    return MEC(*best, upper, lower, gap, residual, iteration, 0 <= gap <= atol,\n               padding)\n\n\ndef score(rows, mode=\"analytic\", round6=True):\n    \"\"\"Validate a 15-pack. Mode selects overlap only; both modes use analytic MEC.\"\"\"\n    if mode not in (\"analytic\", \"compatible\"):\n        raise ValueError(\"mode must be analytic or compatible\")\n    shapes = [placement(row, round6) for row in rows]\n    if len(shapes) != 15:\n        return {\"valid\": False, \"score\": None, \"mec\": None, \"overlaps\": [],\n                \"error\": f\"expected 15 semicircles, got {len(shapes)}\"}\n    cache = {}\n    overlaps = []\n    for i, j in combinations(range(15), 2):\n        a, b = shapes[i], shapes[j]\n        if _dist(a, b) > 2.0:\n            continue\n        if mode == \"analytic\":\n            area = exact_overlap_area(a, b)\n        else:\n            for k in (i, j):\n                if k not in cache:\n                    cache[k] = polygon(shapes[k])\n            area = cache[i].intersection(cache[j]).area\n        exceeds = area >= OVERLAP_TOL if mode == \"analytic\" else area > OVERLAP_TOL\n        if exceeds:\n            overlaps.append((i, j, area))\n    if overlaps:\n        return {\"valid\": False, \"score\": None, \"mec\": None, \"overlaps\": overlaps}\n    mec = exact_mec(shapes)\n    return {\"valid\": True, \"score\": mec.radius, \"mec\": asdict(mec), \"overlaps\": []}\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument(\"solution\")\n    parser.add_argument(\"--mode\", choices=(\"analytic\", \"compatible\"), default=\"analytic\")\n    parser.add_argument(\"--unrounded\", action=\"store_true\")\n    args = parser.parse_args()\n    with open(args.solution) as source:\n        print(json.dumps(score(json.load(source), args.mode, not args.unrounded), indent=2))\n",
  "test_source": "\"\"\"Executable audit against the pinned local project and a Decimal Green oracle.\"\"\"\nimport argparse\nfrom collections import Counter\nfrom dataclasses import asdict\nfrom decimal import Decimal as D, localcontext\nfrom functools import lru_cache\nfrom itertools import combinations, product\nfrom pathlib import Path\nimport json\nimport math\nimport random\nfrom tempfile import TemporaryDirectory\nfrom time import perf_counter\n\nfrom geometry_scorer import (OVERLAP_TOL, exact_mec, exact_overlap_area, placement,\n                             polygon_overlap_area, score)\n\nPIN = \"78a78626f098cd236f3a09bb2cb242f72951599d\"\nBEST = [\n    (0.545425, 0.67215, -0.570778), (1.135484, -1.23874, 2.227365),\n    (-0.584124, -0.217653, -1.671787), (1.843118, 0.631801, -0.722762),\n    (0.278186, 1.928675, 2.264578), (-0.723715, 1.809349, 3.126118),\n    (-1.624637, 1.076193, -2.992325), (-0.56981, 0.785952, -1.682231),\n    (0.032918, 1.724683, -0.877015), (1.261991, 1.484613, 0.453135),\n    (-1.944933, -0.121111, -2.464295), (-1.573106, -1.149938, -1.641622),\n    (1.049635, -2.567295, 1.95895), (-0.789401, -1.781407, -0.792106),\n    (1.811166, -0.718041, -0.914204),\n]\nAUDIT_PAIRS = {\n    (1, 3): 1.0013726918648228e-6, (1, 13): 1.0003480671177956e-6,\n    (2, 11): 1.0007703869930468e-6, (3, 9): 1.0007205352852155e-6,\n    (7, 8): 1.0001613859299263e-6, (8, 9): 1.0008169318183324e-6,\n}\nPI = D(\"3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628\")\nEPS = D(\"1e-62\")\n\n\n@lru_cache(maxsize=4096)\ndef sincos(t):\n    t = (t+PI) % (2*PI)\n    if t < 0:\n        t += 2*PI\n    t -= PI\n    s, c, ds, dc, neg_square = t, D(1), t, D(1), -t*t\n    k = 1\n    while max(abs(ds), abs(dc)) > EPS:\n        ds *= neg_square / ((2*k)*(2*k+1))\n        dc *= neg_square / ((2*k-1)*(2*k))\n        s, c = s+ds, c+dc\n        k += 1\n    return s, c\n\n\ndef atan2(y, x):\n    if y < 0:\n        return -atan2(-y, x)\n    if x < 0:\n        return PI-atan2(y, -x)\n    if x == 0:\n        return PI/2 if y else D(0)\n    if y > x:\n        return PI/2-atan2(x, y)\n    z = y/x\n    for _ in range(4):\n        z /= 1+(1+z*z).sqrt()\n    term, value, k = z, z, 3\n    while abs(term) > EPS:\n        term *= -z*z\n        value += term/k\n        k += 2\n    return 16*value\n\n\ndef dot(a, b):\n    return a[0]*b[0]+a[1]*b[1]\n\n\ndef cross(a, b):\n    return a[0]*b[1]-a[1]*b[0]\n\n\ndef subtract(a, b):\n    return a[0]-b[0], a[1]-b[1]\n\n\ndef normal(t):\n    s, c = sincos(t)\n    return c, s\n\n\ndef intervals(lo, hi, events):\n    cuts = [lo, *sorted({v for v in events if lo < v < hi}), hi]\n    return zip(cuts, cuts[1:])\n\n\ndef arc_roots(v, target):\n    mag = dot(v, v).sqrt()\n    if not mag or abs(target) > mag:\n        return []\n    phi = atan2(v[1], v[0])\n    offset = atan2(max(D(0), (mag-target)*(mag+target)).sqrt(), target)\n    return [phi+sign*offset+turn*2*PI for sign in (-1, 1) for turn in range(-2, 3)]\n\n\ndef oracle(a, b):\n    \"\"\"Integrate clipped, oriented arcs and diameters at 70 Decimal digits.\"\"\"\n    with localcontext() as ctx:\n        ctx.prec = 70\n        a, b = tuple(map(D, a)), tuple(map(D, b))\n        shift = subtract(b, a)\n        centres = ((D(0), D(0)), shift)\n        angles = tuple(t % (2*PI) for t in (a[2], b[2]))\n        normals = tuple(map(normal, angles))\n        if not any(shift):\n            n, m = normals\n            return atan2(abs(cross(n, m)), -dot(n, m))/2\n        if dot(shift, shift) >= 4:\n            return D(0)\n        twice_area = D(0)\n        for i in range(2):\n            j = 1-i\n            centre, angle, n = centres[i], angles[i], normals[i]\n            other = normals[j]\n            d = subtract(centre, centres[j])\n            plane = dot(d, other)\n            disk = dot(d, d)/2\n            events = arc_roots(d, -disk) + arc_roots(other, -plane)\n            for l, r in intervals(angle-PI/2, angle+PI/2, events):\n                u = normal((l+r)/2)\n                if dot(u, d) <= -disk and dot(u, other) >= -plane-EPS:\n                    sl, cl = sincos(l)\n                    sr, cr = sincos(r)\n                    twice_area += r-l + centre[0]*(sr-sl) - centre[1]*(cr-cl)\n\n            e = n[1], -n[0]\n            rate = dot(e, other)\n            if abs(rate) <= EPS and abs(plane) <= EPS:\n                if i == 1 or dot(n, other) < 0:\n                    continue\n            along, side = dot(d, e), cross(d, e)\n            events = []\n            if abs(side) <= 1:\n                root = (1-side*side).sqrt()\n                events.extend((-along-root, -along+root))\n            if rate:\n                events.append(-plane/rate)\n            for l, r in intervals(D(-1), D(1), events):\n                mid = (l+r)/2\n                if (mid+along)**2+side**2 <= 1 and plane+rate*mid >= -EPS:\n                    twice_area += cross(centre, e)*(r-l)\n        return max(D(0), twice_area/2)\n\n\ndef oracle_farthest(shapes, x, y):\n    with localcontext() as ctx:\n        ctx.prec = 70\n        distances = []\n        for sx, sy, theta in shapes:\n            offset = D(sx)-D(x), D(sy)-D(y)\n            n = normal(D(theta))\n            if dot(offset, n) >= 0:\n                distances.append(dot(offset, offset).sqrt()+1)\n            else:\n                distances.append((dot(offset, offset)+1+2*abs(cross(offset, n))).sqrt())\n        return float(max(distances))\n\n\ndef objects(rows):\n    return [dict(zip((\"x\", \"y\", \"theta\"), row)) for row in rows]\n\n\ndef fixtures():\n    rng = random.Random(3762017)\n    yield \"defect\", (0., 0., 0.), (1e-6, 0., 3.141593)\n    separations = [0., *(10.**e for e in range(-12, -3))]\n    directions = [0., math.pi/2, 0.64, math.pi]\n    angles = [0., 1e-12, math.pi, 3.141593, math.pi-1e-10, math.pi+1e-10, 0.61]\n    for d, u, t in product(separations, directions, angles):\n        yield \"near_centres\", (0., 0., 0.), (d*math.cos(u), d*math.sin(u), t)\n    for i in range(160):\n        ax, ay, at, dx, dy, bt = [rng.uniform(-1, 1) for _ in range(6)]\n        scale = (0.45, 1., 2.2, 1.75)[i % 4]\n        yield \"random\", (ax, ay, at*math.pi), (ax+scale*dx, ay+scale*dy, bt*math.pi)\n    for d in (1., 2-1e-12, 2., 2+1e-12):\n        for t in (0., math.pi/2, math.pi):\n            yield \"tangencies\", (0., 0., 0.), (d, 0., t)\n    for label, ends, theta in (\n        (\"arc_arc\", (1.95, 2.), math.pi),\n        (\"arc_flat\", (.95, 1.), 0.),\n        (\"flat_flat\", (2e-7, 1e-6), math.pi),\n    ):\n        for factor in (.99, .9995, 1.0005, 1.01):\n            a = 0., 0., 0.\n            lo, hi = ends\n            for _ in range(34):\n                d = (lo+hi)/2\n                above = float(oracle(a, (d, 0., theta))) > factor*OVERLAP_TOL\n                if above == (label != \"flat_flat\"):\n                    lo = d\n                else:\n                    hi = d\n            b = (lo+hi)/2, 0., theta\n            area = float(oracle(a, b))\n            assert abs(area-factor*OVERLAP_TOL) < 2e-13, (label, factor, area)\n            yield label, a, b\n    for i, j in combinations(range(15), 2):\n        yield f\"best:{i},{j}\", BEST[i], BEST[j]\n\n\ndef transformed(row, angle=0., tx=0., ty=0.):\n    x, y, theta = row\n    c, s = math.cos(angle), math.sin(angle)\n    return c*x-s*y+tx, s*x+c*y+ty, theta+angle\n\n\ndef pair_checks(official_poly, official_overlap, Semicircle):\n    counts, worst, invariance = Counter(), {}, Counter()\n    invariance_counts = Counter()\n    threshold, contacts, baseline = [], [], []\n    max_polygon_bias = 0.\n    fixture_pairs = []\n    for label, a, b in fixtures():\n        counts[label.split(\":\")[0]] += 1\n        area = exact_overlap_area(a, b)\n        reference = float(oracle(a, b))\n        error = abs(area-reference)\n        group = label.split(\":\")[0]\n        if error >= worst.get(group, {}).get(\"absolute_error\", -1):\n            worst[group] = dict(a=a, b=b, analytic=area, oracle=reference,\n                                absolute_error=error)\n        assert error < 3e-15, (label, a, b, area, reference)\n        assert (area >= OVERLAP_TOL) == (reference >= OVERLAP_TOL), (label, area, reference)\n        for name, aa, bb in [\n            (\"swap\", b, a),\n            (\"translate\", transformed(a, tx=3.25, ty=-2.75),\n                          transformed(b, tx=3.25, ty=-2.75)),\n            (\"rotate\", transformed(a, angle=.917), transformed(b, angle=.917)),\n        ]:\n            delta = abs(exact_overlap_area(aa, bb)-area)\n            invariance_counts[name] += 1\n            invariance[name] = max(invariance[name], delta)\n            assert delta < 7e-15, (label, name, delta)\n        poly = polygon_overlap_area(a, b)\n        oa, ob = Semicircle(*a), Semicircle(*b)\n        if math.hypot(a[0]-b[0], a[1]-b[1]) > 2.:\n            direct = 0.\n        else:\n            direct = official_poly(oa).intersection(official_poly(ob)).area\n        assert poly == direct, (label, poly, direct)\n        assert (poly > OVERLAP_TOL) == official_overlap(oa, ob)\n        assert poly <= reference+3e-15, (label, reference, poly)\n        max_polygon_bias = max(max_polygon_bias, reference-poly)\n        entry = dict(label=label, a=a, b=b, analytic=area, oracle=reference,\n                     compatible=poly, absolute_error=error, polygon_bias=reference-poly)\n        if group in (\"arc_arc\", \"arc_flat\", \"flat_flat\"):\n            contacts.append(entry)\n        if (poly > OVERLAP_TOL) != (area >= OVERLAP_TOL):\n            threshold.append(entry)\n            if group == \"best\":\n                i, j = map(int, label.split(\":\")[1].split(\",\"))\n                entry.update(pair=(i, j), prior_audit_area=AUDIT_PAIRS.get((i, j)))\n                baseline.append((i, j))\n        if label == \"defect\":\n            defect = entry\n            assert 1.999999e-6 < area < 2.000001e-6\n        fixture_pairs.append((a, b))\n\n    assert set(baseline) == set(AUDIT_PAIRS)\n    for label in (\"arc_arc\", \"arc_flat\", \"flat_flat\"):\n        assert [e[\"oracle\"] > OVERLAP_TOL for e in contacts if e[\"label\"] == label] == [\n            False, False, True, True]\n    return dict(counts=dict(counts), worst_area_errors=worst, invariance_max_delta=invariance,\n                invariance_counts=invariance_counts, threshold_disagreements=threshold,\n                compatible_vs_official_decision_mismatches=0,\n                max_polygon_bias=max_polygon_bias, defect=defect, labelled_contacts=contacts), fixture_pairs\n\n\ndef pack_checks(official_dir, load, validate, official_mec, Semicircle):\n    rng = random.Random(283071)\n    sample = json.loads((official_dir/\"solution.json\").read_text())\n    rounded_sample = [placement(r, True) for r in sample]\n    packs = [(\"sample\", sample), (\"published\", objects(BEST))]\n    for i in range(8):\n        angle = rng.uniform(-3., 3.)\n        ax, ay = rng.uniform(-4., 4.), rng.uniform(-4., 4.)\n        scaled = [(1.18*x, 1.18*y, t) for x, y, t in rounded_sample]\n        packs.append((f\"sparse:{i}\", objects(transformed(p, angle, ax, ay) for p in scaled)))\n    for i in range(12):\n        spread = (0.8, 2.3, 4.)[i % 3]\n        rows = [(rng.uniform(-spread, spread), rng.uniform(-spread, spread),\n                 rng.uniform(-math.pi, math.pi)) for _ in range(15)]\n        packs.append((f\"random:{i}\", objects(rows)))\n    halfgrid = []\n    for sign, k, nudge in product((-1, 1), (0, 1, 2, 5, 14, 7812, 23437, 123456), (-1, 0, 1)):\n        t = sign*(k + .5)/1_000_000\n        if nudge:\n            t = math.nextafter(t, math.copysign(math.inf, nudge))\n        halfgrid.append(t)\n    for i in range(0, len(halfgrid), 3):\n        vals = halfgrid[i:i+3]\n        rows = [(3*j + vals[j % 3], (vals[j % 3]), -vals[j % 3]) for j in range(15)]\n        packs.append((f\"half_grid:{i//3}\", objects(rows)))\n\n    rounding_flips = {}\n    for i, (a, b) in enumerate(((-.49e-6, .49e-6), (.49e-6, .51e-6))):\n        name = f\"round_flip:{i}\"\n        raw = objects([(a, 0., 0.), (b, 0., math.pi)] +\n                      [(3.*j, 0., 0.) for j in range(1, 14)])\n        before, after = score(raw, round6=False)[\"valid\"], score(raw)[\"valid\"]\n        assert (before, after) == (bool(i), not bool(i))\n        rounding_flips[name] = [before, after]\n        packs.append((name, raw))\n\n    counts = Counter()\n    times = Counter()\n    records = []\n    gold = {}\n    with TemporaryDirectory(dir=official_dir.parent) as temp:\n        path = Path(temp)/\"fixture.json\"\n        for name, raw in packs:\n            counts[name.split(\":\")[0]] += 1\n            path.write_text(json.dumps(raw))\n            library_rows = load(path)\n            rounded = [placement(r, True) for r in raw]\n            official_rows = [(s.x, s.y, s.theta) for s in library_rows]\n            assert [tuple(x.hex() for x in p) for p in rounded] == [\n                tuple(x.hex() for x in p) for p in official_rows]\n            start = perf_counter()\n            official = validate(library_rows)\n            times[\"official\"] += perf_counter()-start\n            start = perf_counter()\n            compatible = score(raw, \"compatible\")\n            times[\"compatible\"] += perf_counter()-start\n            start = perf_counter()\n            analytic = score(raw)\n            times[\"analytic\"] += perf_counter()-start\n            assert compatible[\"valid\"] == official.valid, name\n            actual_pairs = [f\"Semicircles {i} and {j} overlap\" for i, j, _ in compatible[\"overlaps\"]]\n            assert actual_pairs == official.errors, (name, actual_pairs, official.errors)\n            mec = exact_mec(rounded)\n            reference = official.mec or official_mec(library_rows)\n            far = oracle_farthest(rounded, mec.x, mec.y)\n            assert mec.converged and mec.gap <= 2e-12, (name, mec)\n            assert far <= mec.radius and far >= mec.lower_bound, (name, far, mec)\n            assert abs(mec.radius-reference[2]) < 3e-9, (name, mec, reference)\n            if official.valid:\n                assert compatible[\"score\"] == mec.radius\n            if name in (\"sample\", \"published\"):\n                target = 3.5 if name == \"sample\" else 2.948526950912552\n                assert official.valid and abs(official.score-target) < 2e-12\n                assert analytic[\"valid\"] == (name == \"sample\")\n                assert mec.lower_bound-3e-12 <= target <= mec.radius+3e-12\n                gold[name] = dict(official_score=official.score, official_8dp=f\"{official.score:.8f}\",\n                                  analytic_valid=analytic[\"valid\"], compatible_valid=compatible[\"valid\"],\n                                  mec=asdict(mec), decimal_farthest=far)\n            else:\n                assert analytic[\"valid\"] == official.valid, name\n            records.append((name, mec, far, reference[2], official.valid))\n\n    known = [\n        ([(0., 0., .261)], 1.),\n        ([(0., 0., 0.), (0., 0., math.pi)], 1.),\n        ([(0., 0., math.pi), (2., 0., 0.)], 2.),\n        ([(0., 0., 0.), (2., 0., math.pi)], math.sqrt(2.)),\n    ]\n    for rows, target in known:\n        mec = exact_mec(rows)\n        assert mec.converged and mec.lower_bound <= target <= mec.radius, (rows, mec)\n    capped = exact_mec(BEST, atol=1e-16, max_iterations=1)\n    assert not capped.converged and capped.iterations == 1 and capped.gap > 0\n    assert not score([])[\"valid\"] and not score([BEST[0]]*16)[\"valid\"]\n    return dict(counts=counts,\n                coordinate_rounding_comparisons=len(packs)*45,\n                half_grid_placements=counts[\"half_grid\"]*15, rounding_flips=rounding_flips,\n                compatible_valid_packs=sum(r[4] for r in records),\n                compatible_vs_official_pack_mismatches=0, analytic_vs_official_pack_mismatches=[\"published\"],\n                known_mec_cases=len(known), forced_iteration_limit=asdict(capped),\n                mec=dict(max_gap=max(m.gap for _, m, *_ in records),\n                         max_point_residual=max(m.point_residual for _, m, *_ in records),\n                         max_radius_minus_decimal_farthest=max(m.radius-f for _, m, f, *_ in records),\n                         max_abs_radius_delta_official=max(abs(m.radius-o) for _, m, _, o, _ in records),\n                         max_iterations=max(m.iterations for _, m, *_ in records)),\n                timed_pack_count=len(packs), pack_wall_seconds=times, gold=gold)\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument(\"--official-dir\", type=Path, default=Path.cwd())\n    parser.add_argument(\"--write-best\", type=Path)\n    args = parser.parse_args()\n    if args.write_best:\n        args.write_best.write_text(json.dumps(objects(BEST), indent=2)+\"\\n\")\n    import subprocess\n    import sys\n    from importlib.metadata import version\n\n    root = args.official_dir.resolve()\n    found = subprocess.check_output([\"git\", \"-C\", str(root), \"rev-parse\", \"HEAD\"], text=True).strip()\n    assert found == PIN\n    assert not subprocess.check_output([\"git\", \"-C\", str(root), \"status\", \"--porcelain\",\n                                        \"--untracked-files=no\"], text=True)\n    sys.path.insert(0, str(root))\n    from run import _load_solution\n    from semicircle_packing.geometry import Semicircle, semicircle_polygon, semicircles_overlap\n    from semicircle_packing.scoring import validate_and_score, compute_mec\n\n    started = perf_counter()\n    pairs, fixtures_tested = pair_checks(semicircle_polygon, semicircles_overlap, Semicircle)\n    packs = pack_checks(root, _load_solution, validate_and_score, compute_mec, Semicircle)\n    times = {}\n    for name, fn, repeats in [(\"analytic\", exact_overlap_area, 25),\n                               (\"compatible\", polygon_overlap_area, 1)]:\n        start = perf_counter()\n        for _ in range(repeats):\n            for a, b in fixtures_tested:\n                fn(a, b)\n        times[name] = {\"pairs\": len(fixtures_tested)*repeats,\n                       \"wall_seconds\": perf_counter()-start}\n    print(json.dumps(dict(\n        status=\"passed\", dependencies=dict(python=sys.version.split()[0],\n                                           numpy=version(\"numpy\"), shapely=version(\"shapely\")),\n        pairs=pairs, packs=packs, pair_timings=times, total_wall_seconds=perf_counter()-started),\n        indent=2, allow_nan=False))\n\n\nif __name__ == \"__main__\":\n    main()\n"
}
