diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..456ee2faedb2514e72a6d3c735adb745dc943146 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,9 @@ +# Licenses + +This collection repackages tasks from several sources. Each row's `license` column gives the license of its source: + +- MIT: RLVE-Gym, NPPC, EinsteinArena (platform and baselines) +- CC-BY-4.0: MathConstraint; AlphaEvolve repository of problems (materials) +- Apache-2.0: Reasoning Gym, FunSearch, AlphaEvolve repository of problems (code), Finch / Evolution Fine-Tuning (code) + +Please attribute the original authors when using the corresponding tasks. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..44db126ecd89e85e34fb3d5a0d129672fc8feae4 --- /dev/null +++ b/README.md @@ -0,0 +1,143 @@ +--- +license: other +license_name: mixed-permissive +license_link: LICENSE.md +configs: +- config_name: construct + data_files: data/construct.parquet +- config_name: optimize + data_files: data/optimize.parquet +tags: +- math +- reinforcement-learning +- rl-environment +- verifiable-rewards +- harbor +size_categories: +- 1K 1.0, {"valid": True} +``` + +Graders need Python ≥ 3.10 with numpy, scipy, sympy and networkx. Every check runs in under 60 s. Feasibility checks use exact integer or rational arithmetic wherever the problem allows. + +The **optimize reward** is `0` for an invalid answer, else `0.1 + 0.9 · clip(progress, 0, 1)`. Progress is linear between `baseline` (a deliberately weak valid construction) and `best_known`. The kissing-number tasks use a log scale of the overlap loss instead. The 0.1 floor for validity keeps GRPO groups from being all-zero, because without it research-level tasks gave no signal in our pilot. + +## Tags + +| tag | meaning | +|---|---| +| `agentic_trivial` | a solver (CP-SAT, z3, brute force) cracks the top level within seconds, so the task is useful single-turn but weak for sandboxed agents (2,368 tasks) | +| `np_search` | the task is essentially combinatorial search | +| `best_known_uncertain` | `best_known` comes from our own search or an uncited value | +| `ea_under_review` | EinsteinArena marks the problem as under review. We audited each one and included it only when we could make the check sound | +| `unique_answer` | the answer is unique, but it is still verified as a witness (e.g. by expanding a factorization) | +| `float_objective`, `exact_integer`, `exact_rational`, ... | how the objective is computed | + +## Reference pass rates (pilot, 66 tasks) + +Pilot with 8 single-turn samples and 4 agentic attempts per task (Harbor `terminus-2`, no network): + +| model / mode | trivial (≥0.9) | trainable | too hard (≤0.1) | +|---|---|---|---| +| gpt-oss-120b, single-turn | 23 | 23 | 20 | +| gpt-oss-120b, agentic | 33 | 19 | 13 | +| Qwen3-8B, single-turn | 13 | 15 | 38 | +| Qwen3-8B, agentic | 8 | 10 | 47 | + +Pass rates vary a lot by model and mode, so filter for your policy. Difficulty levels are monotone within every generator family. + +## Upstream verifier bugs found and fixed + +Re-implementing the checkers surfaced problems in the source verifiers that an RL policy could exploit: + +- **Model output executed as code.** RLVE `integral` (`sympify`) and Reasoning Gym integration (`parse_expr`) evaluate the model's answer as Python, and they also accept an unevaluated `Integral(f, x)`. Our checkers parse through a whitelist syntax tree. +- **Empty answers accepted.** MathConstraint `verify()` lets the solver fill in any variable the answer omits, so `{}` passes. +- **Missing range, length or type checks.** + - NPPC 3-colouring accepts an all-distinct colouring. + - Clique and independent set accept a vertex repeated k times. + - Quadratic congruence accepts x = 0. + - Several verifiers accept floats or bools. +- **Floating-point feasibility checks.** + - EinsteinArena circle packing and circles-in-rectangle (the AlphaEvolve seed overlaps by about 1e-16). + - Heilbronn triangle containment (uses a rounded √3). + - Finch tolerances that allowed beating the proven 10/3 bound. + - AlphaEvolve p58 (Erdős–Szekeres): the published 33- and 65-point sets reported as having no convex 7- or 8-gon **do contain one** under exact arithmetic. +- **Checks that are wrong or too weak.** + - AlphaEvolve spherical designs: the pass test compares a negated error, so it always passes. + - AlphaEvolve 3D Kakeya ignores tubes that leave its Monte Carlo box. + - Arithmetic Kakeya "repairs" the submitted distribution before scoring it. + - The prime-number-theorem constraint was checked on random samples. + - The uncertainty-principle root scan could miss roots. +- **Wrong or unreachable targets.** Several Finch targets are above a provable maximum, below a known optimum, or infeasible. + +## Excluded + +- AlphaEvolve problem 6: the notebook's functional differs from the one a construction-checker can certify. +- Problems with no checkable objective (proof-only or meta problems), or no recoverable construction or verifier. +- FunSearch corner-free sets (checker not released). +- Sources without a license. +- Duplicate problem and size pairs across sources (deduplicated by `problem_key`). + +## License + +Each row carries the license of its source (`license` column): MIT (64 families), CC-BY-4.0 (59), Apache-2.0 (19). Attribution belongs to the original authors of each source listed above. Our packaging, checkers and generators are released under the same terms as the corresponding source. diff --git a/data/construct.parquet b/data/construct.parquet new file mode 100644 index 0000000000000000000000000000000000000000..e51f8b38776c0e7761e2cdcfe8331b96c6df92e9 --- /dev/null +++ b/data/construct.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38b3c90ab1e11b267d5ee2c92939dbeb6958ab6fb3464cec95a4ce828e0624a7 +size 3195938 diff --git a/data/optimize.parquet b/data/optimize.parquet new file mode 100644 index 0000000000000000000000000000000000000000..02156e5dacb7f8c2ed5e17e7fe2938c33478901c --- /dev/null +++ b/data/optimize.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3c912b1d13d289de6b85cc381ecb0f5d13b55d4ec8cc5b8df8e0ec6d0da171c +size 1949811 diff --git a/families.csv b/families.csv new file mode 100644 index 0000000000000000000000000000000000000000..3875c156bf33d0282c91e0fc64277db963691396 --- /dev/null +++ b/families.csv @@ -0,0 +1,143 @@ +family,subset,tier,domain,source,license,problem_key,n_tasks,tags +ae_p10_kakeya_3d,optimize,research,geometry,AlphaEvolve-Repository-of-Problems/10-3d-kakeya,CC-BY-4.0,kakeya_needle_3d_prisms,1,exact_piecewise_integration;float_objective +ae_p16_gagliardo_nirenberg,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/16-gagliardo-nirenberg-special-case,CC-BY-4.0,nagy_gagliardo_nirenberg_sharp_constant,3,float_objective;known_optimum +ae_p17_young_convolution,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/17-young-convolution,CC-BY-4.0,young_convolution_sharp_constant,3,float_objective;known_optimum +ae_p18_hardy_littlewood_maximal,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/18-hardy-littlewood-maximal,CC-BY-4.0,centered_hardy_littlewood_weak11_constant_1d,1,exact_rational;known_optimum +ae_p1_ff_kakeya,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/1-finite-field-kakeya,CC-BY-4.0,finite_field_kakeya_min_size,10,exact_integer;finite_fields +ae_p1_ff_nikodym,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/1-finite-field-nikodym,CC-BY-4.0,finite_field_nikodym_min_size_d3,4,exact_integer;finite_fields +ae_p24_de_bruijn_sharma,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/24-de-bruijn-sharma,CC-BY-4.0,de_bruijn_sharma_x_intercept,4,float_objective;polynomials +ae_p29_block_stacking,optimize,competition,analysis,AlphaEvolve-Repository-of-Problems/29-block-stacking,CC-BY-4.0,block_stacking_overhang_one_per_level,3,agentic_trivial;exact_rational;known_optimum +ae_p30_arithmetic_kakeya,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/30-arithmetic-kakeya,CC-BY-4.0,arithmetic_kakeya_entropy_sum_difference,2,additive_combinatorics;entropy;float_objective +ae_p31_furstenberg_sarkozy,optimize,research,number_theory,AlphaEvolve-Repository-of-Problems/31-furstenberg-sarkozy,CC-BY-4.0,furstenberg_sarkozy_modular_exponent,2,additive_combinatorics;exact_integer +ae_p32_spherical_designs,construct,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/32-spherical-designs,CC-BY-4.0,spherical_t_design_s2,6,float_tolerance;numerical_design +ae_p35_cubes_in_cube,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/35-packing-in-a-dilate,CC-BY-4.0,unit_cubes_in_smallest_cube_n11,1,float_objective;packing +ae_p37_turan_tetrahedron,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/37-hypergraph-turan-tetrahedron,CC-BY-4.0,turan_density_K4_3,1,blow_up;extremal_hypergraph +ae_p38_factorial_factors,construct,research,number_theory,AlphaEvolve-Repository-of-Problems/38-factoring-N-factorial,CC-BY-4.0,factorial_into_n_large_factors_A034258,60,agentic_trivial;exact_integer;ilp_friendly;np_search +ae_p39_beat_the_average,optimize,research,probability,AlphaEvolve-Repository-of-Problems/39-beat-the-average,CC-BY-4.0,beat_the_average_X1X2X3_lt_2X4,1,discrete_measure;float_objective +ae_p40_erdos_discrepancy,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/40-erdos-discrepancy,CC-BY-4.0,erdos_discrepancy_C2_max_length,1,exact_integer;np_search;sat_friendly +ae_p41_sphere_max_volume,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/41-points-on-sphere-max-volume,CC-BY-4.0,max_volume_inscribed_polyhedron_n_vertices,7,float_objective +ae_p42_sum_difference_i,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/42-sum-difference-I,CC-BY-4.0,sum_difference_sumset_vs_diffset_exponent,1,additive_combinatorics;exact_integer +ae_p43_sum_difference_ii,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/43-sum-difference-II,CC-BY-4.0,sum_difference_diffset_vs_sumset_exponent,1,additive_combinatorics;exact_integer +ae_p44_sum_difference_iii,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/44-sum-difference-III,CC-BY-4.0,sum_difference_A_plus_B_vs_A_minus_B_exponent,1,additive_combinatorics;exact_integer +ae_p45_sum_product_fp,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/45-sum-product-finite-field,Apache-2.0,finite_field_sum_product_sqrt_p,3,additive_combinatorics;exact_integer +ae_p52_erdos_squarefree,construct,research,number_theory,AlphaEvolve-Repository-of-Problems/52-erdos-squarefree,CC-BY-4.0,erdos_ab_plus_1_never_squarefree,50,exact_integer +ae_p54_touching_cylinders,construct,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/54-pairwise-touching-cylinders,CC-BY-4.0,mutually_touching_infinite_cylinders,2,float_tolerance;nonlinear_system +ae_p58_happy_ending,construct,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/58-erdos-szekeres-happy-ending,CC-BY-4.0,erdos_szekeres_no_convex_k_gon_2pow_k_minus_2,5,exact_integer;np_search +ae_p59_isosceles_free_grid,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/59-no-isosceles-grid,CC-BY-4.0,isosceles_free_grid_subset,2,exact_integer;np_search +ae_p60_no5_on_sphere,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/60-no-5-on-a-sphere,CC-BY-4.0,no_five_cospherical_grid_subset,6,exact_integer;np_search +ae_p65_imo2025_p6_tiling,construct,competition,combinatorics,AlphaEvolve-Repository-of-Problems/65-imo-2025-p6,CC-BY-4.0,imo2025_p6_min_tiles,6,exact_integer +ea_circle_packing_26,optimize,research,discrete_geometry,EinsteinArena/circle-packing,MIT,circle_packing_square_sum_radii_n26,1,exact_check;float_objective +ea_circles_rectangle_21,optimize,research,discrete_geometry,EinsteinArena/circles-rectangle,MIT,circles_in_rectangle_perimeter4_sum_radii_n21,1,exact_check;float_objective +ea_difference_bases,optimize,research,number_theory,EinsteinArena/difference-bases,MIT,difference_basis_ratio,1,exact_check +ea_edges_vs_triangles,optimize,research,combinatorics,EinsteinArena/edges-vs-triangles,MIT,edges_vs_triangles_density_curve,1,float_objective +ea_erdos_min_overlap,optimize,research,analysis,EinsteinArena/erdos-min-overlap,MIT,erdos_minimum_overlap_upper,1,float_objective +ea_first_autocorrelation,optimize,research,analysis,EinsteinArena/first-autocorrelation-inequality,MIT,first_autocorrelation_inequality_upper,1,float_objective +ea_flat_polynomials_70,optimize,research,analysis,EinsteinArena/flat-polynomials,MIT,flat_littlewood_polynomial_n70,1,float_objective +ea_hadamard_det_51,optimize,research,combinatorics,EinsteinArena/hadamard-det-51,MIT,hadamard_maxdet_n51,1,ea_under_review;exact_check +ea_heilbronn_triangle_11,optimize,research,discrete_geometry,EinsteinArena/heilbronn-triangles,MIT,heilbronn_triangle_n11,1,exact_check;float_objective +ea_kakeya_needle_128,optimize,research,geometry,EinsteinArena/kakeya-needle-128,MIT,kakeya_needle_triangles_n128,1,ea_under_review;exact_check +ea_kissing_number,optimize,research,discrete_geometry,"EinsteinArena/kissing-number-d11,-d11-605,-d12",MIT,kissing_number_overlap_loss,3,best_known_uncertain;exact_check +ea_min_distance_ratio_16,optimize,research,discrete_geometry,EinsteinArena/min-distance-ratio-2d,MIT,max_min_distance_ratio_2d_n16,1,float_objective +ea_no_three_in_line_75,optimize,research,discrete_geometry,EinsteinArena/no-three-in-line-75,MIT,no_three_in_line_n75,1,ea_under_review;exact_check +ea_prime_number_theorem,optimize,research,number_theory,EinsteinArena/prime-number-theorem,MIT,pnt_chebyshev_certificate,1,float_objective;range_limited_certificate +ea_ring_loading_15,optimize,research,combinatorics,EinsteinArena/ring-loading-15,MIT,ring_loading_m15,1,ea_under_review;exact_check +ea_second_autocorrelation,optimize,research,analysis,EinsteinArena/second-autocorrelation-inequality,MIT,second_autocorrelation_inequality_lower,1,float_objective +ea_shannon_c7_5,optimize,research,graph_theory,EinsteinArena/shannon-capacity-c7-5,MIT,independent_set_c7_strong_power5,1,ea_under_review;exact_check +ea_sidon_45_set,optimize,research,number_theory,EinsteinArena/sidon-45-set,MIT,sidon_subsets_of_45_sets,1,ea_under_review;exact_check +ea_snake_in_the_box_13,optimize,research,graph_theory,EinsteinArena/snake-in-the-box-13,MIT,snake_in_the_box_d13,1,ea_under_review;exact_check +ea_sorting_network_16,optimize,research,combinatorics,EinsteinArena/sorting-network-16,MIT,sorting_network_size_n16,1,ea_under_review;exact_check +ea_spencer_discrepancy,optimize,research,combinatorics,EinsteinArena/spencer-discrepancy,MIT,spencer_discrepancy_square_n_le20,1,ea_under_review;exact_check +ea_tammes,optimize,research,discrete_geometry,EinsteinArena/tammes-problem,MIT,tammes_n50,1,float_objective +ea_third_autocorrelation,optimize,research,analysis,EinsteinArena/third-autocorrelation-inequality,MIT,third_autocorrelation_inequality_upper,1,float_objective +ea_thomson_282,optimize,research,discrete_geometry,EinsteinArena/thomson-problem,MIT,thomson_problem_n282,1,float_objective +ea_two_deletion_code_16,optimize,research,coding_theory,EinsteinArena/two-deletion-code-16,MIT,two_deletion_code_n16,1,ea_under_review;exact_check +ea_uncertainty_principle,optimize,research,analysis,EinsteinArena/uncertainty-principle,MIT,plus1_uncertainty_principle_upper,1,high_precision +finch_3ap_diffs_40,optimize,research,combinatorics,Finch-EFT/skydiscover/erdos_1097_3ap_diffs_n40,Apache-2.0,erdos1097_3ap_differences_n40_m400,1,best_known_uncertain;exact_check;np_search +finch_4subset_3dist_16,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_659_4subset_3dist_construction,Apache-2.0,erdos659_4sets_3dist_n16,1,best_known_uncertain;exact_check;np_search +finch_flat_poly_32,optimize,research,analysis,Finch-EFT/skydiscover/erdos_flat_polynomials_n32,Apache-2.0,flat_littlewood_polynomial_n32,1,best_known_uncertain;float_objective;np_search +finch_heilbronn_disk_12,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_507_heilbronn_disk_n12,Apache-2.0,heilbronn_disk_n12,1,best_known_uncertain;exact_check;float_objective +finch_isosceles_free_grid_8,optimize,competition,discrete_geometry,Finch-EFT/skydiscover/erdos_isosceles_free_grid,Apache-2.0,isosceles_free_grid_subset,1,exact_check;exact_optimum_known;np_search +finch_lcm_chain_10000,optimize,competition,number_theory,Finch-EFT/skydiscover/erdos_440_lcm_density,Apache-2.0,erdos440_lcm_consecutive_x10000,1,exact_check;exact_optimum_known +finch_newman_200,optimize,research,number_theory,Finch-EFT/skydiscover/erdos_480_newman_density,Apache-2.0,erdos480_newman_finite_n200,1,best_known_uncertain;float_objective +finch_no4_concyclic_12,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_654_no_four_concyclic_distances,Apache-2.0,erdos654_no4_concyclic_n12,1,best_known_uncertain;exact_check;np_search +finch_sidon_pair_100,optimize,research,number_theory,Finch-EFT/skydiscover/erdos_43_sidon_pair,Apache-2.0,erdos43_sidon_pair_n100,1,best_known_uncertain;exact_check;np_search +finch_sidon_set_121,optimize,competition,number_theory,Finch-EFT/skydiscover/erdos_difference_bases_N121,Apache-2.0,max_sidon_set_0_120,1,exact_check;exact_optimum_known +finch_square_packing_12,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_106_square_packing,Apache-2.0,erdos106_squares_in_square_n12,1,exact_check +finch_udg_girth_30,optimize,research,graph_theory,Finch-EFT/skydiscover/erdos_705_unit_distance_high_girth,Apache-2.0,erdos705_udg_chi4_girth_n30,1,best_known_uncertain;exact_check +fs_admissible_set,optimize,research,combinatorics,FunSearch/admissible_set,Apache-2.0,admissible_set_constant_weight,2,integer_objective +fs_cap_set,optimize,research,combinatorics,FunSearch/cap_set,Apache-2.0,cap_set_f3n,6,integer_objective +fs_cycle_independent_set,optimize,research,graph_theory,FunSearch/cyclic_graphs,Apache-2.0,independent_set_strong_power_odd_cycle,7,integer_objective +mc_all_interval,construct,competition,combinatorics,MathConstraint/all_interval,CC-BY-4.0,all_interval_series,40,agentic_trivial +mc_antimagic_square,construct,competition,combinatorics,MathConstraint/antimagic_square,CC-BY-4.0,antimagic_square,6,np_search +mc_bibd,construct,competition,combinatorics,MathConstraint/bibd,CC-BY-4.0,bibd,28,np_search +mc_costas_array,construct,competition,combinatorics,MathConstraint/costas_array,CC-BY-4.0,costas_array,23,np_search +mc_debruijn,construct,competition,combinatorics,MathConstraint/debruijn,CC-BY-4.0,de_bruijn_sequence,22,agentic_trivial +mc_golomb,construct,competition,combinatorics,MathConstraint/golomb,CC-BY-4.0,golomb_ruler,18,np_search +mc_graceful_graph,construct,competition,graph_theory,MathConstraint/graceful_graph,CC-BY-4.0,graceful_labeling,17,np_search +mc_graph_k_coloring,construct,competition,graph_theory,MathConstraint/graph_k_coloring,CC-BY-4.0,graph_k_coloring,48,np_search +mc_hadamard,construct,competition,combinatorics,MathConstraint/hadamard,CC-BY-4.0,legendre_pair,30,np_search +mc_langford,construct,competition,combinatorics,MathConstraint/langford,CC-BY-4.0,langford_pairing,27,agentic_trivial;np_search +mc_low_autocorrelation,construct,competition,combinatorics,MathConstraint/low_autocorrelation,CC-BY-4.0,low_autocorrelation_binary_sequence,31,np_search +mc_magic_sequence,construct,competition,combinatorics,MathConstraint/magic_sequence,CC-BY-4.0,magic_sequence,30,agentic_trivial +mc_max_clique,construct,competition,graph_theory,MathConstraint/max_clique,CC-BY-4.0,graph_clique,55,np_search +mc_max_independent_set,construct,competition,graph_theory,MathConstraint/max_independent_set,CC-BY-4.0,graph_independent_set,60,np_search +mc_non_transitive_dice,construct,competition,probability,MathConstraint/non_transitive_dice,CC-BY-4.0,intransitive_dice,15,agentic_trivial;np_search +mc_number_partitioning,construct,competition,number_theory,MathConstraint/number_partitioning,CC-BY-4.0,equal_sum_partition_1_to_n,59,agentic_trivial +mc_ortholatin,construct,competition,combinatorics,MathConstraint/ortholatin,CC-BY-4.0,orthogonal_latin_squares,21,np_search +mc_pysms_chromatic_girth,construct,competition,graph_theory,MathConstraint/pysms_chromatic_girth,CC-BY-4.0,graph_existence_chromatic_girth,25,np_search +mc_pysms_clique_coloring,construct,competition,graph_theory,MathConstraint/pysms_clique_coloring,CC-BY-4.0,graph_existence_clique_coloring,16,np_search +mc_pysms_degree_bounds,construct,competition,graph_theory,MathConstraint/pysms_degree_bounds,CC-BY-4.0,graph_existence_degree_bounds,11,agentic_trivial;np_search +mc_pysms_girth_degree,construct,competition,graph_theory,MathConstraint/pysms_girth_degree,CC-BY-4.0,graph_existence_girth_degree,18,np_search +mc_pysms_graph_builder,construct,competition,graph_theory,MathConstraint/pysms_graph_builder,CC-BY-4.0,graph_existence_graph_builder,8,np_search +mc_pysms_independent_connectivity,construct,competition,graph_theory,MathConstraint/pysms_independent_connectivity,CC-BY-4.0,graph_existence_independent_connectivity,15,np_search +mc_pysms_min_connectivity,construct,competition,graph_theory,MathConstraint/pysms_min_connectivity,CC-BY-4.0,graph_existence_min_connectivity,12,agentic_trivial;np_search +mc_pysms_min_degree,construct,competition,graph_theory,MathConstraint/pysms_min_degree,CC-BY-4.0,graph_existence_min_degree,12,agentic_trivial;np_search +mc_pysms_min_girth,construct,competition,graph_theory,MathConstraint/pysms_min_girth,CC-BY-4.0,graph_existence_min_girth,13,agentic_trivial;np_search +mc_pysms_mtf,construct,competition,graph_theory,MathConstraint/pysms_mtf,CC-BY-4.0,maximal_triangle_free_graph,12,agentic_trivial;np_search +mc_pysms_num_edges_bounds,construct,competition,graph_theory,MathConstraint/pysms_num_edges_bounds,CC-BY-4.0,graph_existence_num_edges_bounds,12,agentic_trivial;np_search +mc_quasigroup_idempotent,construct,competition,algebra,MathConstraint/quasigroup_idempotent,CC-BY-4.0,idempotent_qg3_quasigroup,12,np_search +mc_ramsey,construct,competition,combinatorics,MathConstraint/ramsey,CC-BY-4.0,ramsey_two_colouring,54,np_search +mc_social_golfers,construct,competition,combinatorics,MathConstraint/social_golfers,CC-BY-4.0,social_golfer,23,np_search +mc_van_der_waerden,construct,competition,combinatorics,MathConstraint/van_der_waerden,CC-BY-4.0,van_der_waerden_colouring,42,np_search +mc_vertex_cover,construct,competition,graph_theory,MathConstraint/vertex_cover,CC-BY-4.0,graph_vertex_cover,60,np_search +nppc_bandwidth,construct,competition,graph_theory,NPPC/bandwidth,MIT,graph_bandwidth,60,agentic_trivial;np_search +nppc_clique,construct,competition,graph_theory,NPPC/clique,MIT,graph_clique,60,agentic_trivial;np_search +nppc_dominating_set,construct,competition,graph_theory,NPPC/dominating_set,MIT,graph_dominating_set,60,agentic_trivial;np_search +nppc_independent_set,construct,competition,graph_theory,NPPC/independent_set,MIT,graph_independent_set,60,agentic_trivial;np_search +nppc_quad_diophantine,construct,competition,number_theory,NPPC/quad_diop_equ,MIT,quadratic_diophantine_ax2_by_c,60,agentic_trivial;np_search +nppc_quadratic_congruence,construct,competition,number_theory,NPPC/quadratic_congruence,MIT,quadratic_congruence_bounded,60,agentic_trivial;np_search +nppc_three_coloring,construct,competition,graph_theory,NPPC/graph_three_colorability,MIT,graph_3_coloring,60,agentic_trivial;np_search +nppc_vertex_cover,construct,competition,graph_theory,NPPC/vertex_cover,MIT,graph_vertex_cover,60,agentic_trivial;np_search +rg_graph_color,construct,competition,graph_theory,ReasoningGym/graph_color,Apache-2.0,graph_k_coloring,60,agentic_trivial;np_search +rg_intermediate_integration,construct,competition,analysis,ReasoningGym/intermediate_integration,Apache-2.0,symbolic_antiderivative,60,symbolic +rg_simple_integration,construct,competition,analysis,ReasoningGym/simple_integration,Apache-2.0,symbolic_antiderivative_polynomial,60,symbolic +rlve_antiderivative,construct,competition,analysis,RLVE-Gym/integral,MIT,symbolic_antiderivative,60, +rlve_bezout_identity,construct,competition,number_theory,RLVE-Gym/bezout_identity,MIT,bezout_coefficients,60,agentic_trivial +rlve_construct_hack_interval,construct,competition,number_theory,RLVE-Gym/construct_hack_interval,MIT,cf468c_hack_interval,60, +rlve_crt,construct,competition,number_theory,RLVE-Gym/crt,MIT,generalized_crt,60,agentic_trivial +rlve_distinct_subset_sum_permutation,construct,competition,combinatorics,RLVE-Gym/distinct_array_permutation,MIT,cf892d_gluttony,60,agentic_trivial +rlve_even_degree_partition,construct,competition,graph_theory,RLVE-Gym/even_degree_graph_partitioning,MIT,gallai_even_partition,60,agentic_trivial +rlve_graph_isomorphism,construct,competition,graph_theory,RLVE-Gym/graph_isomorphism,MIT,graph_isomorphism,60,agentic_trivial;np_search +rlve_grid_parity_construction,construct,competition,algebra,RLVE-Gym/grid_parity_construction,MIT,lights_out_gf2,60,agentic_trivial +rlve_imp_party,construct,competition,graph_theory,RLVE-Gym/imp_party,MIT,poi_party_clique_3n,60,agentic_trivial +rlve_integer_linear_system,construct,competition,algebra,RLVE-Gym/gaussian_elimination,MIT,integer_linear_system,60,agentic_trivial +rlve_largest_convex_polygon,construct,competition,discrete_geometry,RLVE-Gym/largest_convex_polygon,MIT,largest_convex_subset,60,agentic_trivial +rlve_largest_rectangle,construct,competition,discrete_geometry,RLVE-Gym/largest_rectangle_among_points,MIT,largest_rectangle_in_point_set,60,agentic_trivial +rlve_matrix_permutation_equivalence,construct,competition,combinatorics,RLVE-Gym/matrix_permutation_equivalence,MIT,binary_matrix_permutation_equivalence,60,agentic_trivial;np_search +rlve_max_achromatic_coloring,construct,competition,graph_theory,RLVE-Gym/maximum_achromatic_number,MIT,achromatic_number,60,agentic_trivial;np_search +rlve_maximum_clique,construct,competition,graph_theory,RLVE-Gym/maximum_clique,MIT,maximum_clique,60,agentic_trivial;np_search +rlve_min_chromatic_number,construct,competition,graph_theory,RLVE-Gym/minimum_chromatic_number,MIT,graph_k_coloring_chromatic,60,agentic_trivial;np_search +rlve_min_harmonious_coloring,construct,competition,graph_theory,RLVE-Gym/minimum_harmonious_chromatic_number,MIT,harmonious_chromatic_number,60,agentic_trivial;np_search +rlve_pairwise_sums_recovery,construct,competition,combinatorics,RLVE-Gym/squ_squarks,MIT,poi_squarks_pairwise_sums,60,agentic_trivial +rlve_pan_solar_panels,construct,competition,number_theory,RLVE-Gym/pan_solar_panels,MIT,poi_solar_panels_max_gcd,60,agentic_trivial +rlve_polynomial_global_minimum,construct,competition,analysis,RLVE-Gym/polynomial_minimum,MIT,polynomial_global_minimum,60,agentic_trivial +rlve_polynomial_integer_roots,construct,competition,algebra,RLVE-Gym/polynomial_factorization,MIT,integer_root_factorization,60,agentic_trivial;unique_answer +rlve_polynomial_interpolation,construct,competition,algebra,RLVE-Gym/polynomial_interpolation,MIT,lagrange_interpolation_integer,60,agentic_trivial;unique_answer +rlve_prefix_product_permutation,construct,competition,number_theory,RLVE-Gym/prefix_product_mod_distinct_permutation,MIT,cf487c_prefix_product_sequence,60, +rlve_prefix_sum_permutation,construct,competition,number_theory,RLVE-Gym/prefix_sum_mod_distinct_permutation,MIT,prefix_sum_mod_distinct_permutation,60, +rlve_prime_graph_coloring,construct,competition,graph_theory,RLVE-Gym/prime_graph_minimum_chromatic_number,MIT,prime_distance_graph_coloring,60,agentic_trivial +rlve_recursive_sequence_sum,construct,competition,number_theory,RLVE-Gym/recursive_sequence_sum_construction,MIT,linear_recurrence_subset_sum,60,agentic_trivial +rlve_round_robin_scores,construct,competition,combinatorics,RLVE-Gym/round_robin,MIT,tournament_score_realisation_3_1_0,60,agentic_trivial +rlve_shortest_path_count,construct,competition,combinatorics,RLVE-Gym/shortest_path_count_construction,MIT,cf388b_shortest_path_count,60, +rlve_smallest_enclosing_circle,construct,competition,geometry,RLVE-Gym/smallest_circle,MIT,minimum_enclosing_circle,60,agentic_trivial +rlve_subgraph_isomorphism,construct,competition,graph_theory,RLVE-Gym/subgraph_isomorphism,MIT,induced_subgraph_isomorphism,60,agentic_trivial;np_search diff --git a/grade.py b/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..48ad992848ba61b1e60c8541c85609db5380a84f --- /dev/null +++ b/grade.py @@ -0,0 +1,41 @@ +"""Grade an answer for a row of the flat dataset, with no Docker and no LLM. + + from grade import grade + reward, details = grade(row, answer_dict) + +`row` is a dataset row (needs `family` and `instance`); `answer_dict` is the parsed JSON answer. +Construct tasks return 1.0 for any valid witness, else 0.0. Optimize tasks return 0 if invalid, +otherwise 0.1 + 0.9 * progress from a trivial baseline to the best known value (see graders/run.py). +Requires python>=3.10 with numpy, scipy, sympy, networkx. +""" +import importlib.util +import json +import sys +from pathlib import Path + +_HERE = Path(__file__).resolve().parent / "graders" +_cache = {} + + +def _load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +def _check_fn(family): + if family not in _cache: + if "run" not in sys.modules: + _load("run", _HERE / "run.py") + _cache[family] = _load(f"check_{family}", _HERE / family / "check.py").check + return _cache[family] + + +def grade(row, answer): + inst = row["instance"] + if isinstance(inst, str): + inst = json.loads(inst) + run = sys.modules.get("run") or _load("run", _HERE / "run.py") + return run.grade(inst, answer, _check_fn(row["family"])) diff --git a/graders/__pycache__/run.cpython-314.pyc b/graders/__pycache__/run.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3aa60a742eb0c0f543bfa70ce65f90844fe7c9f Binary files /dev/null and b/graders/__pycache__/run.cpython-314.pyc differ diff --git a/graders/ae_p10_kakeya_3d/__pycache__/check.cpython-314.pyc b/graders/ae_p10_kakeya_3d/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af357bec4266ae55c9376a5e477693fb5d35f40e Binary files /dev/null and b/graders/ae_p10_kakeya_3d/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p10_kakeya_3d/check.py b/graders/ae_p10_kakeya_3d/check.py new file mode 100644 index 0000000000000000000000000000000000000000..45f17d7cfefd0743db738977ebdde7080e8cd54e --- /dev/null +++ b/graders/ae_p10_kakeya_3d/check.py @@ -0,0 +1,59 @@ +"""3D Kakeya needle problem (AlphaEvolve problem 10): volume of a union of n^2 sheared square tubes. + +Tube (i, j) (0 <= i, j < n, answer index k = i*n + j) has horizontal cross-section at height z in [0, 1] + [x_k + i z/n, x_k + i z/n + 1/n] x [y_k + j z/n, y_k + j z/n + 1/n]. +The union's cross-sectional area A(z) is piecewise quadratic in z, with breakpoints only where two x-edges or two +y-edges cross; we integrate it exactly with Simpson's rule between consecutive breakpoints (float64 arithmetic). +Upstream (kakeya_needle_3d.ipynb) estimated the volume by Monte Carlo over a 2.5 x 2.5 x 1 box (which also +silently truncated tubes leaving that box); this deterministic computation replaces it. +""" +import numpy as np + +from run import Invalid, float_list + + +def _crossings(e0, sl): + d0 = e0[:, None] - e0[None, :] + ds = sl[None, :] - sl[:, None] + with np.errstate(divide="ignore", invalid="ignore"): + z = d0 / ds + z = z[(ds != 0) & np.isfinite(z)] + return z[(z > 0) & (z < 1)] + + +def _area(z, x, y, i, j, n): + lx = x + i * z / n + ly = y + j * z / n + xs = np.unique(np.concatenate([lx, lx + 1.0 / n])) + ys = np.unique(np.concatenate([ly, ly + 1.0 / n])) + a0, a1 = np.searchsorted(xs, lx), np.searchsorted(xs, lx + 1.0 / n) + b0, b1 = np.searchsorted(ys, ly), np.searchsorted(ys, ly + 1.0 / n) + D = np.zeros((len(xs) + 1, len(ys) + 1)) + np.add.at(D, (a0, b0), 1) + np.add.at(D, (a1, b0), -1) + np.add.at(D, (a0, b1), -1) + np.add.at(D, (a1, b1), 1) + C = D.cumsum(0).cumsum(1)[:-2, :-2] > 0.5 + return float((C * np.diff(xs)[:, None] * np.diff(ys)[None, :]).sum()) + + +def volume(x, y, n): + k = np.arange(n * n) + i, j = (k // n).astype(float), (k % n).astype(float) + zb = np.concatenate([[0.0, 1.0], + _crossings(np.concatenate([x, x + 1.0 / n]), np.concatenate([i, i]) / n), + _crossings(np.concatenate([y, y + 1.0 / n]), np.concatenate([j, j]) / n)]) + zb = np.unique(zb) + fa = np.array([_area(z, x, y, i, j, n) for z in zb]) + mids = (zb[:-1] + zb[1:]) / 2 + fm = np.array([_area(z, x, y, i, j, n) for z in mids]) + return float(np.sum(np.diff(zb) * (fa[:-1] + 4 * fm + fa[1:]) / 6)) + + +def check(inst, ans): + n = inst["n"] + x = np.array(float_list(ans.get("x"), n * n, "x")) + y = np.array(float_list(ans.get("y"), n * n, "y")) + if np.abs(x).max() > 100 or np.abs(y).max() > 100: + raise Invalid("offsets must satisfy |x|, |y| <= 100") + return volume(x, y, n), {} diff --git a/graders/ae_p16_gagliardo_nirenberg/__pycache__/check.cpython-314.pyc b/graders/ae_p16_gagliardo_nirenberg/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e754426a1d13cf253e6cef061629eb8deb0e8c9 Binary files /dev/null and b/graders/ae_p16_gagliardo_nirenberg/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p16_gagliardo_nirenberg/check.py b/graders/ae_p16_gagliardo_nirenberg/check.py new file mode 100644 index 0000000000000000000000000000000000000000..838f9f39aaa01ca7e91b20edcc51de765745cae1 --- /dev/null +++ b/graders/ae_p16_gagliardo_nirenberg/check.py @@ -0,0 +1,27 @@ +"""Nagy / Gagliardo-Nirenberg quotient Q(f) = ||f||_p^{4p} / (||f||_2^{2(p+2)} ||f'||_2^{2(p-2)}), integer p. + +f is the non-negative piecewise-linear function with f(0) = f(m+1) = 0 and f(k) = values[k-1] (unit spacing; +Q is invariant under dilation and scaling, and |f| has the same norms as f, so this is no restriction in the +limit). All three norms are integrated exactly (polynomials on each unit segment). Upstream +(classical_inequalities.ipynb) sampled a user-supplied callable on [-15, 15]; this closed form replaces it. +""" +import numpy as np + +from run import Invalid, float_list + + +def check(inst, ans): + p = inst["p"] + v = float_list(ans.get("values"), None, "values") + if not 1 <= len(v) <= inst["max_len"]: + raise Invalid(f"need 1 <= len(values) <= {inst['max_len']}") + f = np.array([0.0] + v + [0.0]) + if f.min() < 0 or f.max() > 1e6 or f.max() <= 0: + raise Invalid("values must be non-negative, at most 1e6, and not all zero") + f = f / f.max() + c0, c1 = f[:-1], f[1:] + lp = sum(float(np.sum(c0 ** k * c1 ** (p - k))) for k in range(p + 1)) / (p + 1) # int f^p + l2 = float(np.sum(c0 * c0 + c0 * c1 + c1 * c1)) / 3 # int f^2 + d2 = float(np.sum((c1 - c0) ** 2)) # int f'^2 + q = lp ** 4 / (l2 ** (p + 2) * d2 ** (p - 2)) + return q, {} diff --git a/graders/ae_p17_young_convolution/__pycache__/check.cpython-314.pyc b/graders/ae_p17_young_convolution/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6db457a0422e53029a9ac2c78846c0ff7fbbfaa4 Binary files /dev/null and b/graders/ae_p17_young_convolution/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p17_young_convolution/check.py b/graders/ae_p17_young_convolution/check.py new file mode 100644 index 0000000000000000000000000000000000000000..07bb4cd68383438009c25cbca2ce4027016a66bc --- /dev/null +++ b/graders/ae_p17_young_convolution/check.py @@ -0,0 +1,45 @@ +"""Young's convolution inequality quotient ||f*g||_r / (||f||_p ||g||_q) for non-negative step functions. + +f = sum_i a_i 1_[i, i+1), g = sum_j b_j 1_[j, j+1); then f*g is piecewise linear with knot values +(f*g)(k) = sum_{i+j=k-1} a_i b_j, so all three norms are integrated exactly (up to float64 rounding). +Upstream (classical_inequalities.ipynb) used np.convolve(mode="same") on samples of user callables, which +truncates the convolution's support; this closed form replaces it. +""" +import numpy as np + +from run import Invalid, float_list + + +def _seg_power_integral(c0, c1, r): + """int_0^1 ((1-s) c0 + s c1)^r ds for non-negative c0, c1 (vectorised, cancellation-free).""" + hi, lo = np.maximum(c0, c1), np.minimum(c0, c1) + out = np.zeros_like(hi) + pos = hi > 0 + t = lo[pos] / hi[pos] + with np.errstate(divide="ignore"): + u = np.log(t) + num, den = np.expm1((r + 1) * u), np.expm1(u) + ratio = np.where(u == 0, r + 1, num / np.where(u == 0, 1.0, den)) # (1 - t^{r+1}) / (1 - t) + out[pos] = hi[pos] ** r * ratio / (r + 1) + return out + + +def _vec(v, name, max_len): + a = np.array(float_list(v, None, name)) + if not 1 <= len(a) <= max_len: + raise Invalid(f"need 1 <= len({name}) <= {max_len}") + if a.min() < 0 or a.max() > 1e6 or a.max() <= 0: + raise Invalid(f"{name}: entries must be in [0, 1e6] and not all zero") + return a / a.max() + + +def check(inst, ans): + p, q = inst["p"], inst["q"] + r = 1.0 / (1.0 / p + 1.0 / q - 1.0) + a = _vec(ans.get("f"), "f", inst["max_len"]) + b = _vec(ans.get("g"), "g", inst["max_len"]) + c = np.concatenate([[0.0], np.convolve(a, b), [0.0]]) + conv_r = float(np.sum(_seg_power_integral(c[:-1], c[1:], r))) ** (1.0 / r) + fp = float(np.sum(a ** p)) ** (1.0 / p) + gq = float(np.sum(b ** q)) ** (1.0 / q) + return conv_r / (fp * gq), {"r": r} diff --git a/graders/ae_p18_hardy_littlewood_maximal/__pycache__/check.cpython-314.pyc b/graders/ae_p18_hardy_littlewood_maximal/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9b59e002808649e60cd593923b87ec0033dc9d8 Binary files /dev/null and b/graders/ae_p18_hardy_littlewood_maximal/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p18_hardy_littlewood_maximal/check.py b/graders/ae_p18_hardy_littlewood_maximal/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d4c8d4c4711aa48e3d7996e8c2c3ebf44ea57d60 --- /dev/null +++ b/graders/ae_p18_hardy_littlewood_maximal/check.py @@ -0,0 +1,45 @@ +"""Weak (1,1) constant of the centred Hardy-Littlewood maximal operator on R, via finite point-mass measures. + +For mu = sum_i w_i delta_{a_i}, M mu(x) >= 1 iff x lies in some [a_j - S_ij/2, a_i + S_ij/2] (i <= j in sorted +order, S_ij = w_i + ... + w_j): the sup over h is attained when [x-h, x+h] just covers a contiguous block of +atoms. The level set is a finite union of intervals whose length is computed exactly in rationals. +(Upstream classical_inequalities.ipynb sampled functions on a grid; this exact formulation replaces it.) +""" +from fractions import Fraction + +from run import Invalid, float_list + + +def check(inst, ans): + a = float_list(ans.get("positions"), None, "positions") + w = float_list(ans.get("weights"), None, "weights") + n = len(a) + if not 1 <= n <= inst["max_atoms"] or len(w) != n: + raise Invalid(f"need 1 <= #atoms <= {inst['max_atoms']} and one weight per position") + if any(abs(x) > 1e6 for x in a) or any(not 1e-9 <= x <= 1e6 for x in w): + raise Invalid("positions must satisfy |a| <= 1e6 and weights must lie in [1e-9, 1e6]") + if len(set(a)) != n: + raise Invalid("positions must be distinct") + atoms = sorted(zip(map(Fraction, a), map(Fraction, w))) + pos = [p for p, _ in atoms] + cum = [Fraction(0)] + for _, x in atoms: + cum.append(cum[-1] + x) + iv = [] + for i in range(n): + for j in range(i, n): + half = (cum[j + 1] - cum[i]) / 2 + lo, hi = pos[j] - half, pos[i] + half + if lo <= hi: + iv.append((lo, hi)) + iv.sort() + total = Fraction(0) + cl, cr = iv[0] + for lo, hi in iv[1:]: + if lo > cr: + total += cr - cl + cl, cr = lo, hi + elif hi > cr: + cr = hi + total += cr - cl + return float(total / cum[-1]), {"level_set_length": float(total), "mass": float(cum[-1])} diff --git a/graders/ae_p1_ff_kakeya/__pycache__/check.cpython-314.pyc b/graders/ae_p1_ff_kakeya/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f9a901acd7f228f5f03512b98c05877f93eaca8 Binary files /dev/null and b/graders/ae_p1_ff_kakeya/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p1_ff_kakeya/check.py b/graders/ae_p1_ff_kakeya/check.py new file mode 100644 index 0000000000000000000000000000000000000000..dac5049b59a505ff843bc5e086d0c1c303695b2a --- /dev/null +++ b/graders/ae_p1_ff_kakeya/check.py @@ -0,0 +1,32 @@ +"""Finite-field Kakeya set in F_p^d: every direction contains a full line. Score = |K| (minimize). + +Upstream (AlphaEvolve notebook `finite_field_kakeya.ipynb`) silently deduplicated points and only checked +d in {3, 4}; here duplicates, out-of-range or non-integer coordinates are rejected and every projective +direction (first non-zero coordinate = 1) is checked for any d. +""" +import itertools + +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + p, d = inst["p"], inst["d"] + pts = ans.get("points") + if not isinstance(pts, list) or not pts: + raise Invalid("points must be a non-empty list") + if len(pts) > p ** d: + raise Invalid("more points than the whole space") + K = np.array([int_list(x, d, 0, p - 1, "point") for x in pts], dtype=np.int64) + w = p ** np.arange(d - 1, -1, -1, dtype=np.int64) + codes = K @ w + if len(np.unique(codes)) != len(codes): + raise Invalid("duplicate points") + for i in range(d): # directions v = (0,..,0,1,*,..,*) with the 1 in position i + for tail in itertools.product(range(p), repeat=d - 1 - i): + v = np.array([0] * i + [1] + list(tail), dtype=np.int64) + base = (K - K[:, i:i + 1] * v) % p # canonical point of the line through x with direction v + if np.bincount(base @ w, minlength=p ** d).max() < p: + raise Invalid(f"no full line in direction {v.tolist()}") + return len(pts), {"size": len(pts)} diff --git a/graders/ae_p1_ff_nikodym/__pycache__/check.cpython-314.pyc b/graders/ae_p1_ff_nikodym/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53c64e22edde55c373703bc87295bc9dced4dca3 Binary files /dev/null and b/graders/ae_p1_ff_nikodym/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p1_ff_nikodym/check.py b/graders/ae_p1_ff_nikodym/check.py new file mode 100644 index 0000000000000000000000000000000000000000..6345846c9b9114bf209db5350d6863485823b433 --- /dev/null +++ b/graders/ae_p1_ff_nikodym/check.py @@ -0,0 +1,47 @@ +"""Finite-field Nikodym set N in F_p^3, submitted as its complement. Score = |N| (minimize). + +Every point x of F_p^3 needs a direction v != 0 with x + t v in N for all t != 0 (x itself may lie outside N). +Upstream (AlphaEvolve `finite_field_nikodym.ipynb`) deduplicated silently; here the complement list must be +duplicate-free and in range. All p^2 + p + 1 projective directions are checked, vectorised over all points. +""" +import itertools + +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + p, d = inst["p"], 3 + rem = ans.get("removed") + if not isinstance(rem, list): + raise Invalid("removed must be a list") + if len(rem) >= p ** d: + raise Invalid("cannot remove every point") + w = np.array([p * p, p, 1], dtype=np.int64) + R = np.array([int_list(x, d, 0, p - 1, "point") for x in rem], dtype=np.int64).reshape(-1, d) + codes_r = R @ w + if len(np.unique(codes_r)) != len(codes_r): + raise Invalid("duplicate removed points") + in_n = np.ones(p ** d, dtype=bool) + in_n[codes_r] = False + X = np.stack(np.unravel_index(np.arange(p ** d), (p,) * d), axis=1).astype(np.int64) + good = np.zeros(p ** d, dtype=bool) + need = p - 1 + in_n.astype(np.int64) # points of N on the line through x, other than x, must number p-1 + done = False + for i in range(d): + for tail in itertools.product(range(p), repeat=d - 1 - i): + v = np.array([0] * i + [1] + list(tail), dtype=np.int64) + lid = ((X - X[:, i:i + 1] * v) % p) @ w + cnt = np.bincount(lid[in_n], minlength=p ** d) + good |= cnt[lid] == need + if good.all(): + done = True + break + if done: + break + if not done: + x = np.flatnonzero(~good)[0] + raise Invalid(f"point {X[x].tolist()} lies on no punctured line inside N") + size = p ** d - len(rem) + return size, {"size": size} diff --git a/graders/ae_p24_de_bruijn_sharma/__pycache__/check.cpython-314.pyc b/graders/ae_p24_de_bruijn_sharma/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c689932df36f7edad81046d436fa6dcedfd0c4c6 Binary files /dev/null and b/graders/ae_p24_de_bruijn_sharma/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p24_de_bruijn_sharma/check.py b/graders/ae_p24_de_bruijn_sharma/check.py new file mode 100644 index 0000000000000000000000000000000000000000..c56dd69deab535ec10e4eef53515f04c7dfea583 --- /dev/null +++ b/graders/ae_p24_de_bruijn_sharma/check.py @@ -0,0 +1,29 @@ +"""de Bruijn-Sharma problem, x-intercept: maximise sum |xi|^4 / sum |z|^4 over degree-n polynomials with +zeros summing to 0 (xi = critical points). Each polynomial P excludes all (alpha, 0) with alpha below its ratio. + +Upstream (de_bruijn_sharma_problem.ipynb) rejected |sum z| > 1e-9 in absolute terms (not scale invariant) and +scored a region area; here the zero-sum condition is relative and the roots are re-centred before scoring. +Critical points come from numpy's companion-matrix eigenvalues (float64). +""" +import numpy as np + +from run import Invalid, float_matrix + + +def check(inst, ans): + n = inst["n"] + Z = np.array(float_matrix(ans.get("roots"), n, 2, "roots")) + z = Z[:, 0] + 1j * Z[:, 1] + if np.abs(z).max() > 1e3: + raise Invalid("roots must satisfy |z| <= 1000") + s1 = np.abs(z).sum() + if s1 < 1e-6: + raise Invalid("all roots are (nearly) zero") + if abs(z.sum()) > 1e-9 * s1: + raise Invalid("the roots must sum to zero (|sum z| <= 1e-9 * sum |z|)") + z = z - z.mean() + xi = np.roots(np.polyder(np.poly(z))) + if len(xi) != n - 1 or not np.all(np.isfinite(xi)): + raise Invalid("could not compute the critical points") + c4 = float(np.sum(np.abs(z) ** 4)) + return float(np.sum(np.abs(xi) ** 4)) / c4, {} diff --git a/graders/ae_p29_block_stacking/__pycache__/check.cpython-314.pyc b/graders/ae_p29_block_stacking/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fce8ca721232492d1a9a4ee6fcada7fe0453378 Binary files /dev/null and b/graders/ae_p29_block_stacking/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p29_block_stacking/check.py b/graders/ae_p29_block_stacking/check.py new file mode 100644 index 0000000000000000000000000000000000000000..0936f9a12cbe14efd9acc0331b8d8feef14c7ad6 --- /dev/null +++ b/graders/ae_p29_block_stacking/check.py @@ -0,0 +1,23 @@ +"""Block stacking (overhang) problem, closed form of the constraints; checked in exact rational arithmetic. + +Upstream (block_stacking_problem.ipynb) used a float tolerance of 100*eps on every constraint, which lets a +submission exceed the true optimum H_n/2 by accumulated slack; here all constraints are exact (non-strict). +""" +from fractions import Fraction + +from run import Invalid, float_list + + +def check(inst, ans): + n = inst["n"] + x = [Fraction(v) for v in float_list(ans.get("x"), n, "x")] + xs = [Fraction(0)] + x # x_0 = 0 + for i in range(n): + if xs[i + 1] < xs[i]: + raise Invalid(f"need x_{i} <= x_{i + 1}") + tail = Fraction(0) + for i in range(n - 1, -1, -1): # tail = x_{i+1} + ... + x_n + tail += xs[i + 1] + if tail > (n - i) * (xs[i] + Fraction(1, 2)): + raise Invalid(f"stability constraint violated at i = {i}") + return float(xs[n]), {} diff --git a/graders/ae_p30_arithmetic_kakeya/__pycache__/check.cpython-314.pyc b/graders/ae_p30_arithmetic_kakeya/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af0b89740d36eb3f3223c2457a155cc9e423b9ce Binary files /dev/null and b/graders/ae_p30_arithmetic_kakeya/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p30_arithmetic_kakeya/check.py b/graders/ae_p30_arithmetic_kakeya/check.py new file mode 100644 index 0000000000000000000000000000000000000000..25d41f480456248b93d0a441deabeddfa9340f52 --- /dev/null +++ b/graders/ae_p30_arithmetic_kakeya/check.py @@ -0,0 +1,38 @@ +"""Arithmetic Kakeya / entropic sum-difference ratio H(X - Y) / max_r H(X + r Y) for an integer-valued (X, Y). + +Upstream (arithmetic_kakeya_conjecture.ipynb) silently clipped negative entries, re-normalised, and "repaired" +colliding differences by moving probability mass (so the scored distribution was not the submitted one), and one +variant put the JOINT entropy in the numerator. Here the submitted distribution is scored as is. +""" +import math +from collections import defaultdict + +from run import Invalid, float_list, int_list + + +def _entropy(keys, p): + acc = defaultdict(float) + for k, v in zip(keys, p): + acc[k] += v + return -sum(v * math.log(v) for v in acc.values() if v > 0) + + +def check(inst, ans): + sup = ans.get("support") + if not isinstance(sup, list) or not 2 <= len(sup) <= inst["max_support"]: + raise Invalid(f"support must be a list of 2..{inst['max_support']} points") + pts = [tuple(int_list(s, 2, -10 ** 6, 10 ** 6, "support point")) for s in sup] + if len(set(pts)) != len(pts): + raise Invalid("support points must be distinct") + w = float_list(ans.get("weights"), len(pts), "weights") + if min(w) < 0 or max(w) > 1e300: + raise Invalid("weights must be non-negative") + tot = math.fsum(w) + if not tot > 0: + raise Invalid("weights must not all vanish") + p = [v / tot for v in w] + num = _entropy([x - y for x, y in pts], p) + den = max(_entropy([y if r == "inf" else x + r * y for x, y in pts], p) for r in inst["slopes"]) + if den < 1e-12: + raise Invalid("degenerate distribution (all projections constant)") + return num / den, {"H_diff": num, "H_max": den} diff --git a/graders/ae_p31_furstenberg_sarkozy/__pycache__/check.cpython-314.pyc b/graders/ae_p31_furstenberg_sarkozy/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..697502b5dee429918ce5caa88ea3901f9bc96160 Binary files /dev/null and b/graders/ae_p31_furstenberg_sarkozy/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p31_furstenberg_sarkozy/check.py b/graders/ae_p31_furstenberg_sarkozy/check.py new file mode 100644 index 0000000000000000000000000000000000000000..296ac248623e85e3ff5e54bab1732a30c7889e1a --- /dev/null +++ b/graders/ae_p31_furstenberg_sarkozy/check.py @@ -0,0 +1,47 @@ +"""Ruzsa-type modular construction for the Furstenberg-Sarkozy problem. + +A subset A of Z/mZ (m square-free) with no two distinct elements differing by a non-zero k-th power residue +gives subsets of {1..N} with no k-th power differences of size N^{(k-1)/k + log|A|/(k log m)} (Ruzsa 1984). +Score = that exponent. Mirrors upstream `get_score` (furstenberg_sarkozy_problem.ipynb), which silently +reduced/deduplicated the list; here entries must be distinct residues in [0, m). +""" +import math + +import numpy as np + +from run import Invalid, as_int, int_list + + +def squarefree(m): + d = 2 + while d * d <= m: + if m % (d * d) == 0: + return False + d += 1 + return True + + +def check(inst, ans): + k = inst["k"] + m = as_int(ans.get("m"), "m", 2, inst["max_m"]) + if not squarefree(m): + raise Invalid("m must be square-free") + A = int_list(ans.get("residues"), None, 0, m - 1, "residues") + if not 1 <= len(A) <= inst["max_size"]: + raise Invalid(f"need 1 <= |A| <= {inst['max_size']}") + if len(set(A)) != len(A): + raise Invalid("duplicate residues") + y = np.arange(1, m, dtype=np.int64) + r = y % m + for _ in range(k - 1): + r = (r * y) % m + forb = np.zeros(m, dtype=bool) + forb[r] = True + forb[0] = False + a = np.array(A, dtype=np.int64) + diff = (a[:, None] - a[None, :]) % m + np.fill_diagonal(diff, 0) + if forb[diff].any(): + i, j = np.argwhere(forb[diff])[0] + raise Invalid(f"{A[i]} - {A[j]} is a non-zero k-th power residue mod {m} (k = {k})") + return (k - 1) / k + math.log(len(A)) / (k * math.log(m)), {"m": m, "size": len(A)} diff --git a/graders/ae_p32_spherical_designs/__pycache__/check.cpython-314.pyc b/graders/ae_p32_spherical_designs/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d8ab9a703437ce75dc8b62867d6bbbf40cbe4e9 Binary files /dev/null and b/graders/ae_p32_spherical_designs/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p32_spherical_designs/check.py b/graders/ae_p32_spherical_designs/check.py new file mode 100644 index 0000000000000000000000000000000000000000..5973c15b3df2d6228d713d9b186ced8e47dcbb48 --- /dev/null +++ b/graders/ae_p32_spherical_designs/check.py @@ -0,0 +1,53 @@ +"""Spherical t-design with N points on S^2 (numerical, tolerance 1e-10 on every harmonic average). + +Upstream (AlphaEvolve `spherical_t_designs.ipynb`) scored sum_k dim_k/C_k(1) * sum_{i,j} C_k(), whose +pair sums cancel to ~1e-10 in float64 and can even go negative; its printed acceptance test +`calculate_design_score(...) < 1e-8` compares the NEGATED error and is therefore always true (bug). Here we +evaluate the point averages of an orthonormal real spherical-harmonic basis directly (no cancellation). +""" +import numpy as np + +from run import Invalid, float_matrix + +TOL = 1e-10 + + +def harmonics(X, t): + """Rows: real spherical harmonics Y_lm (1 <= l <= t) normalised so that their mean square on S^2 is 1.""" + ct = np.clip(X[:, 2], -1.0, 1.0) + st = np.sqrt(np.maximum(0.0, 1.0 - ct * ct)) + ph = np.arctan2(X[:, 1], X[:, 0]) + P = {(0, 0): np.ones_like(ct)} + for m in range(1, t + 1): + P[(m, m)] = (np.sqrt(3.0) if m == 1 else np.sqrt((2 * m + 1) / (2 * m))) * st * P[(m - 1, m - 1)] + for m in range(0, t): + P[(m + 1, m)] = np.sqrt(2 * m + 3) * ct * P[(m, m)] + for m in range(0, t + 1): + for l in range(m + 2, t + 1): + a = np.sqrt((4 * l * l - 1) / (l * l - m * m)) + b = np.sqrt(((l - 1) ** 2 - m * m) / (4 * (l - 1) ** 2 - 1)) + P[(l, m)] = a * (ct * P[(l - 1, m)] - b * P[(l - 2, m)]) + rows = [] + for l in range(1, t + 1): + rows.append(P[(l, 0)]) + for m in range(1, l + 1): + rows.append(P[(l, m)] * np.cos(m * ph)) + rows.append(P[(l, m)] * np.sin(m * ph)) + return np.array(rows) + + +def check(inst, ans): + t, n = inst["t"], inst["N"] + X = np.array(float_matrix(ans.get("points"), n, 3, "points")) + nr = np.linalg.norm(X, axis=1) + if nr.min() < 0.5 or nr.max() > 2.0: + raise Invalid("points must be (approximately) unit vectors") + X = X / nr[:, None] + G = X @ X.T + np.fill_diagonal(G, -1.0) + if G.max() > 1.0 - 1e-8: + raise Invalid("two points coincide (or nearly: distance < 1.4e-4)") + dev = np.abs(harmonics(X, t).mean(axis=1)).max() + if not dev <= TOL: + raise Invalid(f"not a {t}-design: some harmonic of degree <= {t} has point average {dev:.3e} > {TOL}") + return None, {"max_harmonic_average": float(dev)} diff --git a/graders/ae_p35_cubes_in_cube/__pycache__/check.cpython-314.pyc b/graders/ae_p35_cubes_in_cube/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfdc2a17662859f52eae528dfbd3ec16e94cbe46 Binary files /dev/null and b/graders/ae_p35_cubes_in_cube/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p35_cubes_in_cube/check.py b/graders/ae_p35_cubes_in_cube/check.py new file mode 100644 index 0000000000000000000000000000000000000000..385bbee4f715ce70a2fb41197a6955e11d4ac10a --- /dev/null +++ b/graders/ae_p35_cubes_in_cube/check.py @@ -0,0 +1,51 @@ +"""Packing n unit cubes (arbitrary orientation) in the smallest axis-aligned cube (AlphaEvolve problem 35). + +Cube = centre + Euler angles in degrees, R = Rz(rz) Ry(ry) Rx(rx) (upstream convention). Disjoint interiors are +checked with the separating-axis theorem over the 15 candidate axes; projections may overlap by at most +inst["tol"] (floating-point slack). Score = largest side of the axis-aligned bounding box (minimize).""" +import itertools +import math + +import numpy as np + +from run import Invalid, float_matrix + + +def rot(rx, ry, rz): + x, y, z = map(math.radians, (rx, ry, rz)) + cx, sx, cy, sy, cz, sz = math.cos(x), math.sin(x), math.cos(y), math.sin(y), math.cos(z), math.sin(z) + mx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]]) + my = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]]) + mz = np.array([[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]]) + return mz @ my @ mx + + +LOCAL = np.array(list(itertools.product((-0.5, 0.5), repeat=3))) + + +def check(inst, ans): + n, tol = inst["n"], inst["tol"] + rows = float_matrix(ans.get("cubes"), n, 6, "cubes") + cubes = [] + for r in rows: + if max(abs(v) for v in r[:3]) > 1e3 or max(abs(v) for v in r[3:]) > 1e4: + raise Invalid("coordinates or angles out of range") + m = rot(*r[3:]) + cubes.append((m, LOCAL @ m.T + np.array(r[:3]))) + for (m1, v1), (m2, v2) in itertools.combinations(cubes, 2): + axes = [m1[:, i] for i in range(3)] + [m2[:, i] for i in range(3)] + axes += [np.cross(m1[:, i], m2[:, j]) for i in range(3) for j in range(3)] + separated = False + for a in axes: + na = np.linalg.norm(a) + if na < 1e-9: + continue + a = a / na + p1, p2 = v1 @ a, v2 @ a + if min(p1.max(), p2.max()) - max(p1.min(), p2.min()) <= tol: + separated = True + break + if not separated: + raise Invalid("two cubes overlap") + allv = np.vstack([v for _, v in cubes]) + return float((allv.max(0) - allv.min(0)).max()), {} diff --git a/graders/ae_p37_turan_tetrahedron/__pycache__/check.cpython-314.pyc b/graders/ae_p37_turan_tetrahedron/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c71a04dfc2c184f5d3378922e07433848e23a226 Binary files /dev/null and b/graders/ae_p37_turan_tetrahedron/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p37_turan_tetrahedron/check.py b/graders/ae_p37_turan_tetrahedron/check.py new file mode 100644 index 0000000000000000000000000000000000000000..6b0e9cbadd3166c810c19a79b01915ab1a5989c0 --- /dev/null +++ b/graders/ae_p37_turan_tetrahedron/check.py @@ -0,0 +1,39 @@ +"""Hypergraph Turan density of the tetrahedron K_4^(3) via weighted blow-up patterns (AlphaEvolve problem 37). + +Upstream silently *deleted* edges to repair K4 copies; we instead reject any pattern whose blow-up contains a +K_4^(3), and check it exactly (combinatorial condition on 4-multisets of classes).""" +import itertools + +from run import Invalid, float_list, int_list + + +def check(inst, ans): + w = float_list(ans.get("weights"), None, "weights") + k = len(w) + if not 1 <= k <= inst["max_classes"]: + raise Invalid(f"need 1..{inst['max_classes']} classes") + if any(x < 0 for x in w) or sum(w) <= 0: + raise Invalid("weights must be non-negative with positive sum") + edges = ans.get("edges") + if not isinstance(edges, list): + raise Invalid("edges must be a list") + es = set() + for e in edges: + int_list(e, 3, 0, k - 1, "edge") + if not (e[0] <= e[1] <= e[2]): + raise Invalid("each edge type must be sorted: [a, b, c] with a <= b <= c") + if e[0] == e[2]: + raise Invalid("edge type [a, a, a] is not allowed (its blow-up contains K_4^(3))") + if tuple(e) in es: + raise Invalid("duplicate edge type") + es.add(tuple(e)) + for m in itertools.combinations_with_replacement(range(k), 4): + subs = {tuple(sorted(m[:i] + m[i + 1:])) for i in range(4)} + if subs <= es: + raise Invalid(f"blow-up contains a tetrahedron on classes {list(m)}") + t = sum(w) + p = [x / t for x in w] + dens = 0.0 + for a, b, c in es: + dens += (6.0 if len({a, b, c}) == 3 else 3.0) * p[a] * p[b] * p[c] + return dens, {"classes": k, "edge_types": len(es)} diff --git a/graders/ae_p38_factorial_factors/__pycache__/check.cpython-314.pyc b/graders/ae_p38_factorial_factors/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f72d6009558b7a1a0b65e42698062843bb304a96 Binary files /dev/null and b/graders/ae_p38_factorial_factors/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p38_factorial_factors/check.py b/graders/ae_p38_factorial_factors/check.py new file mode 100644 index 0000000000000000000000000000000000000000..93ec67a19039afa8b4ce6e39811691b802132562 --- /dev/null +++ b/graders/ae_p38_factorial_factors/check.py @@ -0,0 +1,12 @@ +"""Factor N! into N factors, each >= t (AlphaEvolve problem 38 / OEIS A034258). Exact big-integer check.""" +import math + +from run import Invalid, int_list + + +def check(inst, ans): + n, t = inst["N"], inst["t"] + f = int_list(ans.get("factors"), n, t, None, "factors") + if math.prod(f) != math.factorial(n): + raise Invalid(f"the product of the factors is not {n}!") + return None, {"min_factor": min(f)} diff --git a/graders/ae_p39_beat_the_average/__pycache__/check.cpython-314.pyc b/graders/ae_p39_beat_the_average/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..122795cfb06020006ecdd65a39d1f66559c8ee3b Binary files /dev/null and b/graders/ae_p39_beat_the_average/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p39_beat_the_average/check.py b/graders/ae_p39_beat_the_average/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d263a6c1292a91bebac4f75022e9e65d6038ea5b --- /dev/null +++ b/graders/ae_p39_beat_the_average/check.py @@ -0,0 +1,31 @@ +"""Beat-the-average game (AlphaEvolve problem 39): maximize P[X1+X2+X3 < 2 X4] for iid X on the integers. + +Sparse re-implementation of the upstream convolution score; ties (X1+X2+X3 = 2 X4) are decided exactly +because the support is integral.""" +import numpy as np + +from run import Invalid, float_list, int_list + + +def check(inst, ans): + s = ans.get("support") + w = ans.get("weights") + if not isinstance(s, list) or not (1 <= len(s) <= inst["max_support"]): + raise Invalid(f"support must be a list of 1..{inst['max_support']} integers") + int_list(s, None, 0, inst["max_value"], "support") + if len(set(s)) != len(s): + raise Invalid("support values must be distinct") + w = float_list(w, len(s), "weights") + if any(x < 0 for x in w) or sum(w) <= 1e-12: + raise Invalid("weights must be non-negative with positive sum") + x = np.array(s, dtype=np.int64) + p = np.array(w, dtype=np.float64) + p = p / p.sum() + z = np.add.outer(x, x).ravel() # X1 + X2 + pz = np.multiply.outer(p, p).ravel() + order = np.argsort(z, kind="stable") + z, cz = z[order], np.concatenate([[0.0], np.cumsum(pz[order])]) + t = (2 * x[None, :] - x[:, None]).ravel() # need X1+X2 < 2 X4 - X3; rows X3, cols X4 + pt = np.multiply.outer(p, p).ravel() + prob = float(np.dot(pt, cz[np.searchsorted(z, t, side="left")])) + return prob, {"support_size": len(s)} diff --git a/graders/ae_p40_erdos_discrepancy/__pycache__/check.cpython-314.pyc b/graders/ae_p40_erdos_discrepancy/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7b9f61909ba5f279ce54dc1d16c01d39f59842a Binary files /dev/null and b/graders/ae_p40_erdos_discrepancy/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p40_erdos_discrepancy/check.py b/graders/ae_p40_erdos_discrepancy/check.py new file mode 100644 index 0000000000000000000000000000000000000000..6681bdc6534e00aecae90a5ea822b730e135caac --- /dev/null +++ b/graders/ae_p40_erdos_discrepancy/check.py @@ -0,0 +1,25 @@ +"""Erdos discrepancy problem, C = 2 (AlphaEvolve problem 40): longest +-1 sequence with discrepancy <= 2. + +Upstream scored the longest good prefix (plus a fractional bonus); we require the whole submitted sequence to +have discrepancy <= C and score its length (exact integer check).""" +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + x = ans.get("sequence") + if not isinstance(x, list) or not (1 <= len(x) <= inst["max_length"]): + raise Invalid(f"sequence must be a list of 1..{inst['max_length']} entries") + int_list(x, None, -1, 1, "sequence") + if 0 in x: + raise Invalid("entries must be +1 or -1") + a = np.array(x, dtype=np.int64) + n, c = len(x), inst["C"] + for d in range(1, n + 1): + ps = np.cumsum(a[d - 1::d]) + m = int(np.abs(ps).max()) + if m > c: + k = int(np.argmax(np.abs(ps) > c)) + 1 + raise Invalid(f"|x_{d} + x_{2*d} + ... + x_{k*d}| = {abs(int(ps[k-1]))} > {c}") + return float(n), {"length": n} diff --git a/graders/ae_p41_sphere_max_volume/__pycache__/check.cpython-314.pyc b/graders/ae_p41_sphere_max_volume/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..846f8fba37a0ec59eb8fd5e2175a4756db413642 Binary files /dev/null and b/graders/ae_p41_sphere_max_volume/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p41_sphere_max_volume/check.py b/graders/ae_p41_sphere_max_volume/check.py new file mode 100644 index 0000000000000000000000000000000000000000..58b6521809868700c39ccbae7ef07cd7c99c8d83 --- /dev/null +++ b/graders/ae_p41_sphere_max_volume/check.py @@ -0,0 +1,23 @@ +"""n points on the unit sphere maximizing the volume of their convex hull (AlphaEvolve problem 41). + +Upstream bug fixed: the notebook summed |det|/6 of origin-pyramids over (QJ-joggled) hull facets, which +over-counts whenever the origin lies outside the hull (e.g. all points in one hemisphere). We use the exact +hull volume (scipy ConvexHull.volume) of the normalized points, without joggling.""" +import numpy as np +from scipy.spatial import ConvexHull + +from run import Invalid, float_matrix + + +def check(inst, ans): + n = inst["n"] + p = np.array(float_matrix(ans.get("points"), n, 3, "points")) + nr = np.linalg.norm(p, axis=1) + if (nr < 1e-9).any() or (nr > 1e9).any(): + raise Invalid("every point needs a non-zero, finite norm (it is projected to the unit sphere)") + p = p / nr[:, None] + try: + v = ConvexHull(p).volume + except Exception as e: # degenerate (coplanar) input + raise Invalid(f"degenerate hull: {type(e).__name__}") + return float(v), {} diff --git a/graders/ae_p42_sum_difference_i/__pycache__/check.cpython-314.pyc b/graders/ae_p42_sum_difference_i/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbb3e530676057acffc7bda21fef0c9808169e94 Binary files /dev/null and b/graders/ae_p42_sum_difference_i/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p42_sum_difference_i/check.py b/graders/ae_p42_sum_difference_i/check.py new file mode 100644 index 0000000000000000000000000000000000000000..3189e36f895e4008e38eae3e94d0f3ce813d5022 --- /dev/null +++ b/graders/ae_p42_sum_difference_i/check.py @@ -0,0 +1,23 @@ +"""Sum-difference problem I (AlphaEvolve problem 42): maximize log(|A+A|/|A|) / log(|A-A|/|A|).""" +import math + +import numpy as np + +from run import Invalid, int_list + + +def sizes(ans, max_size, max_abs): + a = ans.get("A") + if not isinstance(a, list) or not (2 <= len(a) <= max_size): + raise Invalid(f"A must be a list of 2..{max_size} integers") + int_list(a, None, -max_abs, max_abs, "A") + if len(set(a)) != len(a): + raise Invalid("A must consist of distinct integers") + x = np.array(a, dtype=np.int64) + return len(a), int(np.unique(np.add.outer(x, x)).size), int(np.unique(np.subtract.outer(x, x)).size) + + +def check(inst, ans): + n, s, d = sizes(ans, inst["max_size"], inst["max_abs"]) + # |A-A| >= 2|A|-1 > |A| for |A| >= 2, so the denominator is positive + return math.log(s / n) / math.log(d / n), {"size": n, "sumset": s, "diffset": d} diff --git a/graders/ae_p43_sum_difference_ii/__pycache__/check.cpython-314.pyc b/graders/ae_p43_sum_difference_ii/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c27dae7814b871c4176a8a43861d9b0f9428bd6 Binary files /dev/null and b/graders/ae_p43_sum_difference_ii/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p43_sum_difference_ii/check.py b/graders/ae_p43_sum_difference_ii/check.py new file mode 100644 index 0000000000000000000000000000000000000000..53fecc1f859bd56537d71d11c68516f5da3b854e --- /dev/null +++ b/graders/ae_p43_sum_difference_ii/check.py @@ -0,0 +1,19 @@ +"""Sum-difference problem II (AlphaEvolve problem 43): maximize log|A-A| / log|A+A|.""" +import math + +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + a = ans.get("A") + if not isinstance(a, list) or not (2 <= len(a) <= inst["max_size"]): + raise Invalid(f"A must be a list of 2..{inst['max_size']} integers") + int_list(a, None, -inst["max_abs"], inst["max_abs"], "A") + if len(set(a)) != len(a): + raise Invalid("A must consist of distinct integers") + x = np.array(a, dtype=np.int64) + s = int(np.unique(np.add.outer(x, x)).size) + d = int(np.unique(np.subtract.outer(x, x)).size) + return math.log(d) / math.log(s), {"size": len(a), "sumset": s, "diffset": d} diff --git a/graders/ae_p44_sum_difference_iii/__pycache__/check.cpython-314.pyc b/graders/ae_p44_sum_difference_iii/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6afa8a4e4bf3c14e70d5eb21db070f21a8714615 Binary files /dev/null and b/graders/ae_p44_sum_difference_iii/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p44_sum_difference_iii/check.py b/graders/ae_p44_sum_difference_iii/check.py new file mode 100644 index 0000000000000000000000000000000000000000..5a8cdb3909aaceb2dcffa5c3aff899a69b2e946c --- /dev/null +++ b/graders/ae_p44_sum_difference_iii/check.py @@ -0,0 +1,41 @@ +"""Sum-difference problem III (AlphaEvolve problem 44). + +A set U of non-negative integers with min U = 0 gives the lower bound + C >= 1 + log(|U-U| / |U+U|) / log(2 max U + 1) +(AlphaEvolve's compute_lower_bound). Upstream checked |U-U| <= 2 max U + 1, which always holds when +U is inside [0, max U]; we check the hypotheses (integers, distinct, min 0) instead. +""" +import math + +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + u = ans.get("U") + if not isinstance(u, list) or not (2 <= len(u) <= inst["max_size"]): + raise Invalid(f"U must be a list of 2..{inst['max_size']} integers") + int_list(u, None, 0, inst["max_value"], "U") + if min(u) != 0: + raise Invalid("U must contain 0 and be non-negative") + if len(set(u)) != len(u): + raise Invalid("U must consist of distinct integers") + x = np.array(sorted(u), dtype=np.int64) + m = int(x[-1]) + # bitmap sweeps with a buffer of m+1 bytes: U-U is symmetric, so count non-negative differences; + # U+U lies in [0, 2m], handled as two windows [0, m] and [m+1, 2m] (x sorted -> contiguous slices) + buf = np.zeros(m + 1, dtype=bool) + for i, v in enumerate(x): + buf[v - x[:i + 1]] = True + d = 2 * int(buf.sum()) - 1 + s = 0 + for lo in (0, m + 1): + buf[:] = False + for v in x: + t = v + x + a, b = np.searchsorted(t, lo), np.searchsorted(t, lo + m, side="right") + buf[t[a:b] - lo] = True + s += int(buf.sum()) + del buf + return 1.0 + math.log(d / s) / math.log(2 * m + 1), {"size": len(u), "max": m, "diffset": d, "sumset": s} diff --git a/graders/ae_p45_sum_product_fp/__pycache__/check.cpython-314.pyc b/graders/ae_p45_sum_product_fp/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f97c5077699f216cbd5ab9dcd1d0cfdb049b121 Binary files /dev/null and b/graders/ae_p45_sum_product_fp/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p45_sum_product_fp/check.py b/graders/ae_p45_sum_product_fp/check.py new file mode 100644 index 0000000000000000000000000000000000000000..7184ef5e5926255a1a72ddf7fe632faebdd9012c --- /dev/null +++ b/graders/ae_p45_sum_product_fp/check.py @@ -0,0 +1,15 @@ +"""Finite-field sum-product problem (AlphaEvolve problem 45): minimize max(|X+X|, |X*X|) in F_p, |X| = floor(sqrt p).""" +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + p, k = inst["p"], inst["k"] + x = int_list(ans.get("X"), k, 0, p - 1, "X") + if len(set(x)) != k: + raise Invalid("X must consist of distinct residues") + a = np.array(sorted(x), dtype=np.int64) + s = int(np.unique(np.add.outer(a, a) % p).size) + q = int(np.unique(np.multiply.outer(a, a) % p).size) # products < p^2 < 2^63 + return float(max(s, q)), {"sumset": s, "productset": q} diff --git a/graders/ae_p52_erdos_squarefree/__pycache__/check.cpython-314.pyc b/graders/ae_p52_erdos_squarefree/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0edf376670c00047632abfdf07b9e431d826b0b0 Binary files /dev/null and b/graders/ae_p52_erdos_squarefree/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p52_erdos_squarefree/check.py b/graders/ae_p52_erdos_squarefree/check.py new file mode 100644 index 0000000000000000000000000000000000000000..87e15b242f211059193ba122baecdee9add99130 --- /dev/null +++ b/graders/ae_p52_erdos_squarefree/check.py @@ -0,0 +1,38 @@ +"""Erdos squarefree problem (AlphaEvolve problem 52): A in [1, N], |A| >= t, ab+1 NOT squarefree for all a, b in A +(a = b included). The repo's problem page says "square-free"; the notebook and the Erdos problem ask for +"never squarefree", which is what we check. Exact: for every pair we find a prime p with p^2 | ab+1.""" +import numpy as np + +from run import Invalid, int_list + + +def _primes(n): + s = np.ones(n + 1, dtype=bool) + s[:2] = False + for i in range(2, int(n ** .5) + 1): + if s[i]: + s[i * i::i] = False + return np.nonzero(s)[0] + + +def check(inst, ans): + n, t = inst["N"], inst["t"] + a = ans.get("A") + if not isinstance(a, list) or not (t <= len(a) <= 2 * t + 20): + raise Invalid(f"A must be a list of {t}..{2 * t + 20} integers") + int_list(a, None, 1, n, "A") + if len(set(a)) != len(a): + raise Invalid("A must consist of distinct integers") + x = np.array(sorted(a), dtype=np.int64) + iu, ju = np.triu_indices(len(x)) + va, vb = x[iu], x[ju] + left = np.ones(len(iu), dtype=bool) # pairs without a square divisor found yet + for p in _primes(int((n * n + 1) ** .5) + 1): + q = int(p) * int(p) + idx = np.nonzero(left)[0] + hit = ((va[idx] % q) * (vb[idx] % q) + 1) % q == 0 + left[idx[hit]] = False + if not left.any(): + return None, {"size": len(a)} + k = int(np.nonzero(left)[0][0]) + raise Invalid(f"{int(va[k])}*{int(vb[k])}+1 = {int(va[k]) * int(vb[k]) + 1} is squarefree") diff --git a/graders/ae_p54_touching_cylinders/__pycache__/check.cpython-314.pyc b/graders/ae_p54_touching_cylinders/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbe8d43380ad6f863afbfa2e1cb64cbfaea9cb50 Binary files /dev/null and b/graders/ae_p54_touching_cylinders/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p54_touching_cylinders/check.py b/graders/ae_p54_touching_cylinders/check.py new file mode 100644 index 0000000000000000000000000000000000000000..e962bc1c6d7d6cbc46f7da71f3af8200128b3b21 --- /dev/null +++ b/graders/ae_p54_touching_cylinders/check.py @@ -0,0 +1,62 @@ +"""Pairwise touching infinite cylinders (AlphaEvolve problem 54). + +Each cylinder: a point on its axis, an axis direction and a radius. Two cylinders touch (externally) when the +distance between their axes equals r_i + r_j. Checked in floating point with an absolute tolerance +(inst["tol"]); contact points (midpoints of closest approach) must lie in [-100, 100]^3 as upstream, which rules +out near-parallel pairs "touching at infinity".""" +import itertools +import math + +from run import Invalid, float_matrix + + +def _sub(a, b): + return [a[0] - b[0], a[1] - b[1], a[2] - b[2]] + + +def _dot(a, b): + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + + +def _cross(a, b): + return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] + + +def check(inst, ans): + n, unit, tol = inst["n"], inst["unit_radius"], inst["tol"] + rows = float_matrix(ans.get("cylinders"), n, 6 if unit else 7, "cylinders") + cyl = [] + for r in rows: + p, v = r[:3], r[3:6] + nv = math.sqrt(_dot(v, v)) + if nv < 1e-9: + raise Invalid("zero axis direction") + v = [c / nv for c in v] + rad = 1.0 if unit else r[6] + if not unit and not (inst["r_min"] <= rad <= inst["r_max"]): + raise Invalid(f"radius {rad} outside [{inst['r_min']}, {inst['r_max']}]") + if max(abs(c) for c in p) > 1000: + raise Invalid("axis point too far from the origin") + cyl.append((p, v, rad)) + worst = 0.0 + for (p1, v1, r1), (p2, v2, r2) in itertools.combinations(cyl, 2): + w = _sub(p2, p1) + c = _cross(v1, v2) + nc = math.sqrt(_dot(c, c)) + if nc < 1e-9: + d = math.sqrt(_dot(_cross(w, v1), _cross(w, v1))) + mid = [(p1[i] + p2[i]) / 2 for i in range(3)] + else: + d = abs(_dot(w, c)) / nc + b = _dot(v1, v2) + den = 1 - b * b + t1 = (_dot(w, v1) - b * _dot(w, v2)) / den + t2 = (b * _dot(w, v1) - _dot(w, v2)) / den + mid = [(p1[i] + t1 * v1[i] + p2[i] + t2 * v2[i]) / 2 for i in range(3)] + if max(abs(m) for m in mid) > 100: + raise Invalid("a contact point lies outside [-100, 100]^3") + err = abs(d - (r1 + r2)) + worst = max(worst, err) + if err > tol: + raise Invalid(f"axis distance {d:.12g} differs from r_i + r_j = {r1 + r2:.12g} by {err:.3g} > {tol}") + return None, {"max_error": worst} diff --git a/graders/ae_p58_happy_ending/__pycache__/check.cpython-314.pyc b/graders/ae_p58_happy_ending/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..154f69e8b696acca89b86a0071614f4439048437 Binary files /dev/null and b/graders/ae_p58_happy_ending/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p58_happy_ending/check.py b/graders/ae_p58_happy_ending/check.py new file mode 100644 index 0000000000000000000000000000000000000000..47e4606e109bc165111a8138a5a2f60870d563c8 --- /dev/null +++ b/graders/ae_p58_happy_ending/check.py @@ -0,0 +1,69 @@ +"""Erdos-Szekeres happy ending (AlphaEvolve problem 58): n = 2^(k-2) integer points in general position with no +k points in convex position. Exact integer orientation tests; the largest convex-position subset is computed by +the O(n^4) bottom-vertex / angular-order dynamic programme. + +Upstream bug: the notebook's verifier uses float orientations with a 1e-9 threshold (and numba fastmath); its +33- and 65-point sets (claimed to have "0 convex k-gons") contain a convex 7-gon / 8-gon under exact arithmetic.""" +import functools + +import numpy as np + +from run import Invalid, int_list + + +def orient_table(p): + n = len(p) + o = np.zeros((n, n, n), dtype=np.int8) + for i in range(n): + xi, yi = p[i] + for j in range(i + 1, n): + dx, dy = p[j][0] - xi, p[j][1] - yi + for k in range(j + 1, n): + c = dx * (p[k][1] - yi) - dy * (p[k][0] - xi) + if c == 0: + raise Invalid(f"points {p[i]}, {p[j]}, {p[k]} are collinear") + s = 1 if c > 0 else -1 + o[i, j, k] = o[j, k, i] = o[k, i, j] = s + o[i, k, j] = o[k, j, i] = o[j, i, k] = -s + return o + + +def max_convex(p, o): + n = len(p) + best = min(n, 3) + order = sorted(range(n), key=lambda i: (p[i][1], p[i][0])) + for bi, b in enumerate(order): + rest = order[bi + 1:] + m = len(rest) + if m < 2: + continue + rest = sorted(rest, key=functools.cmp_to_key(lambda u, v: -int(o[b, u, v]))) + r = np.array(rest) + chain = np.zeros((m, m), dtype=np.int32) # chain[i, j]: longest convex chain b .. r_i -> r_j + for j in range(1, m): + for i in range(j): + v = 3 + if i > 0: + ok = (chain[:i, i] > 0) & (o[r[:i], r[i], r[j]] > 0) + if ok.any(): + v = max(v, int(chain[:i, i][ok].max()) + 1) + chain[i, j] = v + close = o[r[:j], r[j], b] > 0 + if close.any(): + best = max(best, int(chain[:j, j][close].max())) + return best + + +def check(inst, ans): + n, k, lim = inst["n"], inst["k"], inst["max_abs"] + pts = ans.get("points") + if not isinstance(pts, list) or len(pts) != n: + raise Invalid(f"points must be a list of {n} [x, y] pairs") + p = [tuple(int_list(q, 2, -lim, lim, "point")) for q in pts] + if len(set(p)) != n: + raise Invalid("points must be distinct") + o = orient_table(p) + mc = max_convex(p, o) + if mc >= k: + raise Invalid(f"the set contains {mc} points in convex position (>= {k})") + return None, {"max_convex_subset": mc} diff --git a/graders/ae_p59_isosceles_free_grid/__pycache__/check.cpython-314.pyc b/graders/ae_p59_isosceles_free_grid/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da4a93271c2377e0178b80eb871b9e01e0195e67 Binary files /dev/null and b/graders/ae_p59_isosceles_free_grid/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p59_isosceles_free_grid/check.py b/graders/ae_p59_isosceles_free_grid/check.py new file mode 100644 index 0000000000000000000000000000000000000000..cfcfd7aba30ca03b3dccafd9ecd2dedab8e57a41 --- /dev/null +++ b/graders/ae_p59_isosceles_free_grid/check.py @@ -0,0 +1,25 @@ +"""Largest subset of the n x n grid with no (possibly flat) isosceles triangle (AlphaEvolve problem 59). +Exact: for every point b, the squared distances from b to all other chosen points must be pairwise distinct.""" +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + pts = ans.get("points") + if not isinstance(pts, list) or not (1 <= len(pts) <= 4 * n): + raise Invalid(f"points must be a list of 1..{4 * n} [x, y] pairs") + p = [tuple(int_list(q, 2, 0, n - 1, "point")) for q in pts] + if len(set(p)) != len(p): + raise Invalid("points must be distinct") + a = np.array(p, dtype=np.int64) + d = ((a[:, None, :] - a[None, :, :]) ** 2).sum(-1) + for i in range(len(p)): + row = np.delete(d[i], i) + vals, cnt = np.unique(row, return_counts=True) + if (cnt > 1).any(): + dup = vals[np.argmax(cnt > 1)] + a2 = [p[k] for k in range(len(p)) if k != i and d[i, k] == dup][:2] + raise Invalid(f"isosceles: {a2[0]} and {a2[1]} are equidistant from {p[i]}") + return float(len(p)), {"size": len(p)} diff --git a/graders/ae_p60_no5_on_sphere/__pycache__/check.cpython-314.pyc b/graders/ae_p60_no5_on_sphere/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3afd9e9f880c9ad286c965211371300697d0999 Binary files /dev/null and b/graders/ae_p60_no5_on_sphere/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p60_no5_on_sphere/check.py b/graders/ae_p60_no5_on_sphere/check.py new file mode 100644 index 0000000000000000000000000000000000000000..535715270fb95983b4b3896cda93a8746da1a961 --- /dev/null +++ b/graders/ae_p60_no5_on_sphere/check.py @@ -0,0 +1,53 @@ +"""No 5 points of an n x n x n grid subset on a common sphere or plane (AlphaEvolve problem 60). + +Exact int64 test: five points are co-spherical/co-planar iff det[x, y, z, x^2+y^2+z^2, 1] = 0, evaluated as the +4x4 determinant of differences (entries <= 3(n-1)^2, so |det| < 2^40). Upstream used float det + np.isclose.""" +import itertools + +import numpy as np + +from run import Invalid, int_list + + +def det4(m): + a, b, c, d = m[:, 0], m[:, 1], m[:, 2], m[:, 3] + + def det3(r0, r1, r2, i, j, k): + return (r0[:, i] * (r1[:, j] * r2[:, k] - r1[:, k] * r2[:, j]) + - r0[:, j] * (r1[:, i] * r2[:, k] - r1[:, k] * r2[:, i]) + + r0[:, k] * (r1[:, i] * r2[:, j] - r1[:, j] * r2[:, i])) + return (a[:, 0] * det3(b, c, d, 1, 2, 3) - a[:, 1] * det3(b, c, d, 0, 2, 3) + + a[:, 2] * det3(b, c, d, 0, 1, 3) - a[:, 3] * det3(b, c, d, 0, 1, 2)) + + +def lifted(p): + a = np.array(p, dtype=np.int64) + return np.concatenate([a, (a * a).sum(1, keepdims=True)], axis=1) + + +def bad_five(rows, combos): + """rows: (m, 4) lifted points; combos: (N, 5) index array. Returns mask of degenerate 5-sets.""" + base = rows[combos[:, 0]] + m = np.stack([rows[combos[:, i]] - base for i in range(1, 5)], axis=1) + return det4(m) == 0 + + +def check(inst, ans): + n = inst["n"] + pts = ans.get("points") + if not isinstance(pts, list) or not (1 <= len(pts) <= inst["max_points"]): + raise Invalid(f"points must be a list of 1..{inst['max_points']} [x, y, z] triples") + p = [tuple(int_list(q, 3, 0, n - 1, "point")) for q in pts] + if len(set(p)) != len(p): + raise Invalid("points must be distinct") + rows = lifted(p) + it = itertools.combinations(range(len(p)), 5) + while True: + chunk = np.array(list(itertools.islice(it, 200000)), dtype=np.int64) + if len(chunk) == 0: + break + bad = bad_five(rows, chunk) + if bad.any(): + q = [p[i] for i in chunk[np.argmax(bad)]] + raise Invalid(f"points {q} lie on a common sphere or plane") + return float(len(p)), {"size": len(p)} diff --git a/graders/ae_p65_imo2025_p6_tiling/__pycache__/check.cpython-314.pyc b/graders/ae_p65_imo2025_p6_tiling/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..582520d7d974a094b8cbd169332b37b366c92943 Binary files /dev/null and b/graders/ae_p65_imo2025_p6_tiling/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ae_p65_imo2025_p6_tiling/check.py b/graders/ae_p65_imo2025_p6_tiling/check.py new file mode 100644 index 0000000000000000000000000000000000000000..401de49cfa895e6f1c47b996fa5e8bdc8fc609e4 --- /dev/null +++ b/graders/ae_p65_imo2025_p6_tiling/check.py @@ -0,0 +1,24 @@ +"""IMO 2025 Problem 6 variant (AlphaEvolve problem 65): at most T rectangular tiles on an n x n grid, no overlaps, +every row and every column has exactly one uncovered unit square.""" +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + n, cap = inst["n"], inst["max_tiles"] + tiles = ans.get("tiles") + if not isinstance(tiles, list) or not (1 <= len(tiles) <= cap): + raise Invalid(f"tiles must be a list of 1..{cap} [row, col, height, width] entries") + cover = np.zeros((n, n), dtype=np.int32) + for t in tiles: + r, c, h, w = int_list(t, 4, 0, n, "tile") + if h < 1 or w < 1 or r + h > n or c + w > n: + raise Invalid(f"tile {t} is empty or leaves the grid") + cover[r:r + h, c:c + w] += 1 + if cover.max() > 1: + raise Invalid("tiles overlap") + free = cover == 0 + if not (free.sum(axis=1) == 1).all() or not (free.sum(axis=0) == 1).all(): + raise Invalid("some row or column does not have exactly one uncovered square") + return None, {"tiles": len(tiles)} diff --git a/graders/ea_circle_packing_26/__pycache__/check.cpython-314.pyc b/graders/ea_circle_packing_26/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2dbbfa8784815db065c4330e68b19a114aac2b2 Binary files /dev/null and b/graders/ea_circle_packing_26/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_circle_packing_26/check.py b/graders/ea_circle_packing_26/check.py new file mode 100644 index 0000000000000000000000000000000000000000..018159b91112bc76f2410da3995e5cea7fd7b438 --- /dev/null +++ b/graders/ea_circle_packing_26/check.py @@ -0,0 +1,26 @@ +"""Circle packing in the unit square, n = 26, maximize the sum of radii (EinsteinArena circle-packing, MIT). + +Upstream bug fixed: containment and non-overlap were tested in float64 (sqrt of a float distance), so +configurations with overlaps of ~1e-16 were accepted (the AlphaEvolve seed itself overlaps by that much in +exact arithmetic). Here both constraints are checked exactly on the rational values of the floats.""" +from fractions import Fraction + +from run import Invalid, float_matrix + + +def check(inst, ans): + n = inst["n"] + c = float_matrix(ans.get("circles"), n, 3, "circles") + F = [tuple(Fraction(v) for v in row) for row in c] + for x, y, r in F: + if r <= 0: + raise Invalid("radii must be positive") + if not (r <= x <= 1 - r and r <= y <= 1 - r): + raise Invalid("a circle is not contained in the unit square") + for i in range(n): + xi, yi, ri = F[i] + for j in range(i + 1, n): + xj, yj, rj = F[j] + if (xi - xj) ** 2 + (yi - yj) ** 2 < (ri + rj) ** 2: + raise Invalid(f"circles {i} and {j} overlap") + return sum(r for _, _, r in c), {} diff --git a/graders/ea_circles_rectangle_21/__pycache__/check.cpython-314.pyc b/graders/ea_circles_rectangle_21/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d63d81745dd0aeea3f82412164c79b6b9d895bc6 Binary files /dev/null and b/graders/ea_circles_rectangle_21/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_circles_rectangle_21/check.py b/graders/ea_circles_rectangle_21/check.py new file mode 100644 index 0000000000000000000000000000000000000000..75f56da763151ed4490b1e352b0fa9409811ddf7 --- /dev/null +++ b/graders/ea_circles_rectangle_21/check.py @@ -0,0 +1,27 @@ +"""21 disjoint circles in a rectangle of perimeter 4, maximize the sum of radii +(EinsteinArena circles-rectangle, MIT). + +Upstream bug fixed: the perimeter test is exact (Fractions) upstream but the disjointness test compares +float sqrt distances; both are exact here.""" +from fractions import Fraction + +from run import Invalid, float_matrix + + +def check(inst, ans): + n = inst["n"] + c = float_matrix(ans.get("circles"), n, 3, "circles") + F = [tuple(Fraction(v) for v in row) for row in c] + if any(r <= 0 for _, _, r in F): + raise Invalid("radii must be positive") + w = max(x + r for x, _, r in F) - min(x - r for x, _, r in F) + h = max(y + r for _, y, r in F) - min(y - r for _, y, r in F) + if w + h > 2: + raise Invalid("bounding rectangle violates width + height <= 2") + for i in range(n): + xi, yi, ri = F[i] + for j in range(i + 1, n): + xj, yj, rj = F[j] + if (xi - xj) ** 2 + (yi - yj) ** 2 < (ri + rj) ** 2: + raise Invalid(f"circles {i} and {j} overlap") + return sum(r for _, _, r in c), {} diff --git a/graders/ea_difference_bases/__pycache__/check.cpython-314.pyc b/graders/ea_difference_bases/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f066be87574c802a3d725476f45aeb70ae490fe Binary files /dev/null and b/graders/ea_difference_bases/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_difference_bases/check.py b/graders/ea_difference_bases/check.py new file mode 100644 index 0000000000000000000000000000000000000000..3186c425937b161b437429067dda8651658928ac --- /dev/null +++ b/graders/ea_difference_bases/check.py @@ -0,0 +1,30 @@ +"""Difference bases: minimize |B|^2 / v (EinsteinArena difference-bases, MIT). + +v = largest integer such that 1..v are all differences of elements of B (0 is added to B if missing). +Ported from the upstream verifier. Changes: elements must be JSON integers in [0, inst["max_value"]] +(upstream cast with int(), so floats/strings were silently truncated) and distinct (upstream deduplicated); +at most inst["max_size"] elements after adding 0.""" +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + s = ans.get("set") + if not isinstance(s, list) or not 1 <= len(s) <= inst["max_size"]: + raise Invalid(f"set must be a list of 1..{inst['max_size']} integers") + int_list(s, None, 0, inst["max_value"], "set") + if len(set(s)) != len(s): + raise Invalid("elements must be distinct") + B = sorted(set(s) | {0}) + if len(B) > inst["max_size"]: + raise Invalid(f"at most {inst['max_size']} elements including 0") + a = np.array(B, dtype=np.int64) + d = (a[None, :] - a[:, None])[np.triu_indices(len(a), 1)] + present = np.zeros(int(a[-1]) + 2, dtype=bool) + present[d] = True + present[0] = True + v = int(np.argmin(present)) - 1 # first missing positive difference minus one + if v < 1: + raise Invalid("1 is not a difference of the set") + return len(B) ** 2 / v, {"size": len(B), "v": v} diff --git a/graders/ea_edges_vs_triangles/__pycache__/check.cpython-314.pyc b/graders/ea_edges_vs_triangles/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bd91a615d24c2d01413866c1cd8e38b4431025f Binary files /dev/null and b/graders/ea_edges_vs_triangles/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_edges_vs_triangles/check.py b/graders/ea_edges_vs_triangles/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d666f7e136894b7e7831bc4abe8ddf4e24160fea --- /dev/null +++ b/graders/ea_edges_vs_triangles/check.py @@ -0,0 +1,68 @@ +"""Edges vs triangles (Razborov) upper-bound curve (EinsteinArena edges-vs-triangles, MIT). + +Each row is a probability vector over 20 parts (a complete 20-partite graphon); edge density +1 - sum w^2 ... (upstream uses S1^2 - S2 and S1^3 - 3 S1 S2 + 2 S3). Score = -(area under the slope-3 +envelope + 10 * max gap) (maximize). Ported verbatim from the upstream verifier. Changes: at most +inst["max_rows"] rows (the description says m <= 500 but upstream did not enforce it); NaN/inf rejected.""" +import numpy as np + +from run import Invalid, float_matrix + + +def _densities(A): + S1 = A.sum(1) + S2 = (A ** 2).sum(1) + S3 = (A ** 3).sum(1) + return S1 ** 2 - S2, S1 ** 3 - 3 * S1 * S2 + 2 * S3 + + +def _curve(ex, ty): + slope = 3.0 + o = np.argsort(ex) + fx = np.concatenate(([0.0], ex[o], [1.0])) + fy = np.concatenate(([0.0], ty[o], [1.0])) + ux, inv = np.unique(fx, return_inverse=True) + my = np.full(len(ux), np.inf) + np.minimum.at(my, inv, fy) + fx, fy = ux, my + if len(fx) < 2: + return 5.0 / 6.0, 1.0 + left = np.minimum.accumulate(fy - slope * fx) + right = np.minimum.accumulate(fy[::-1])[::-1] + area = 0.0 + for i in range(len(fx) - 1): + x0, x1 = fx[i], fx[i + 1] + w = x1 - x0 + if w <= 0: + continue + cap = min(float(right[i + 1]), 1.0) + yl, yr = slope * x0 + left[i], slope * x1 + left[i] + if yl >= cap: + area += cap * w + elif yr <= cap: + area += (yl + yr) * w / 2.0 + else: + xh = (cap - left[i]) / slope + area += (yl + cap) * (xh - x0) / 2.0 + cap * (x1 - xh) + gaps = np.diff(fx) + idx = np.where((fx[:-1] >= 0.0) & (fx[:-1] < 1.0))[0] + return area, float(np.max(gaps[idx])) if idx.size else 0.0 + + +def check(inst, ans): + w = ans.get("weights") + if not isinstance(w, list) or not 1 <= len(w) <= inst["max_rows"]: + raise Invalid(f"weights must be a list of 1..{inst['max_rows']} rows") + A = np.array(float_matrix(w, None, inst["parts"], "weights")) + if np.any(A < 0): + raise Invalid("weights must be non-negative") + s = A.sum(1) + if np.any(s < 1e-7): + raise Invalid("a row sums to (nearly) zero") + A = A / s[:, None] + e, t = _densities(A) + area, gap = _curve(e, t) + val = -(area + 10 * gap) + if not np.isfinite(val): + raise Invalid("non-finite score") + return float(val), {"area": float(area), "max_gap": gap} diff --git a/graders/ea_erdos_min_overlap/__pycache__/check.cpython-314.pyc b/graders/ea_erdos_min_overlap/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bd16376a7ffd913e75496b0edd46ce84491b25f Binary files /dev/null and b/graders/ea_erdos_min_overlap/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_erdos_min_overlap/check.py b/graders/ea_erdos_min_overlap/check.py new file mode 100644 index 0000000000000000000000000000000000000000..7950d6b8538a72b387252a20c04e276c1fd9be08 --- /dev/null +++ b/graders/ea_erdos_min_overlap/check.py @@ -0,0 +1,27 @@ +"""Erdos minimum overlap, upper bound (EinsteinArena erdos-min-overlap, MIT). + +h sampled at n points on [0, 2], values in [0, 1]; h is rescaled so that sum(h) = n/2; score +C = max(np.correlate(h, 1 - h, 'full')) * 2 / n (minimize). Ported from the upstream verifier. +Change: length capped at inst["max_len"] (upstream: no cap); NaN/inf rejected explicitly.""" +import numpy as np + +from run import Invalid, float_list + + +def check(inst, ans): + v = ans.get("values") + if not isinstance(v, list) or not 1 <= len(v) <= inst["max_len"]: + raise Invalid(f"values must be a list of 1..{inst['max_len']} numbers") + h = np.array(float_list(v, None, "values")) + if np.any(h < 0) or np.any(h > 1): + raise Invalid("all values must lie in [0, 1]") + s = float(np.sum(h)) + if s == 0: + raise Invalid("cannot normalise an all-zero sequence") + t = len(h) / 2.0 + if s != t: + h = h * (t / s) + if np.any(h < 0) or np.any(h > 1): + raise Invalid("after normalisation to sum n/2 some value exceeds 1") + c = float(np.max(np.correlate(h, 1 - h, mode="full")) / len(h) * 2) + return c, {} diff --git a/graders/ea_first_autocorrelation/__pycache__/check.cpython-314.pyc b/graders/ea_first_autocorrelation/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14ee42c7b8456b8630ec90b00fa62ea3a93f62d6 Binary files /dev/null and b/graders/ea_first_autocorrelation/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_first_autocorrelation/check.py b/graders/ea_first_autocorrelation/check.py new file mode 100644 index 0000000000000000000000000000000000000000..2c08b4ef2afb69e7113612f5da3fe62d83576de9 --- /dev/null +++ b/graders/ea_first_autocorrelation/check.py @@ -0,0 +1,24 @@ +"""First autocorrelation inequality, upper bound (EinsteinArena first-autocorrelation-inequality, MIT). + +C = max(conv(f, f) * dx) / (sum(f) * dx)^2 with dx = 0.5 / n, f >= 0 (minimize). Ported from the upstream +verifier (np.convolve). Change: the length is capped at inst["max_len"] so grading stays fast (upstream +has no cap), and NaN/inf are rejected explicitly.""" +import numpy as np + +from run import Invalid, float_list + + +def check(inst, ans): + v = ans.get("values") + if not isinstance(v, list) or not 1 <= len(v) <= inst["max_len"]: + raise Invalid(f"values must be a list of 1..{inst['max_len']} numbers") + f = np.array(float_list(v, None, "values")) + if np.any(f < 0): + raise Invalid("all values must be non-negative") + if np.sum(f) <= 0: + raise Invalid("the integral of f must be positive") + dx = 0.5 / len(f) + c = float(np.max(np.convolve(f, f) * dx) / (np.sum(f) * dx) ** 2) + if not np.isfinite(c): + raise Invalid("non-finite score") + return c, {} diff --git a/graders/ea_flat_polynomials_70/__pycache__/check.cpython-314.pyc b/graders/ea_flat_polynomials_70/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df9d5c7e180d047b6fe51c2f11eb68a0206c1486 Binary files /dev/null and b/graders/ea_flat_polynomials_70/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_flat_polynomials_70/check.py b/graders/ea_flat_polynomials_70/check.py new file mode 100644 index 0000000000000000000000000000000000000000..af293bdd4aa98117c053859850e2d938f39dabe3 --- /dev/null +++ b/graders/ea_flat_polynomials_70/check.py @@ -0,0 +1,18 @@ +"""Flat Littlewood polynomial of degree 69 (EinsteinArena flat-polynomials, MIT). + +Score = max_{z in grid} |g(z)| / sqrt(71) over 10^6 equally spaced points of the unit circle (minimize), +exactly as the upstream verifier (np.poly1d, np.linspace(0, 2pi, 10^6)). Change: coefficients must be the +JSON integers 1/-1 (upstream cast to float first, so 1.0 and true were accepted).""" +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n_coeffs"] + c = int_list(ans.get("coefficients"), n, -1, 1, "coefficients") + if any(x == 0 for x in c): + raise Invalid("coefficients must be +1 or -1") + zs = np.exp(1j * np.linspace(0, 2 * np.pi, inst["grid"])) + vals = np.abs(np.poly1d(np.array(c, dtype=np.float64))(zs)) + return float(np.max(vals) / np.sqrt(n + 1)), {} diff --git a/graders/ea_hadamard_det_51/__pycache__/check.cpython-314.pyc b/graders/ea_hadamard_det_51/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd4a00486d8673e49af99a7e8a4c24195584514f Binary files /dev/null and b/graders/ea_hadamard_det_51/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_hadamard_det_51/check.py b/graders/ea_hadamard_det_51/check.py new file mode 100644 index 0000000000000000000000000000000000000000..6a99b17f74a9b1cf69051abae394fa0d82d1aaef --- /dev/null +++ b/graders/ea_hadamard_det_51/check.py @@ -0,0 +1,48 @@ +"""Hadamard maximal determinant, order 51 (EinsteinArena hadamard-det-51, MIT). + +Score = log10 |det A| computed from the exact integer determinant (fraction-free Bareiss). +Audit of the upstream verifier (sympy det_bareis, exact): sound. Change: a singular matrix is +rejected as invalid instead of scoring 0.0 (log10 of 0 is undefined). +""" +import math + +from run import Invalid, int_list + + +def _det_bareiss(m): + a = [row[:] for row in m] + n = len(a) + sign, prev = 1, 1 + for k in range(n - 1): + if a[k][k] == 0: + for r in range(k + 1, n): + if a[r][k] != 0: + a[k], a[r] = a[r], a[k] + sign = -sign + break + else: + return 0 + akk, rowk = a[k][k], a[k] + for i in range(k + 1, n): + aik, rowi = a[i][k], a[i] + a[i] = rowi[:k + 1] + [(rowi[j] * akk - aik * rowk[j]) // prev for j in range(k + 1, n)] + prev = akk + return sign * a[n - 1][n - 1] + + +def check(inst, ans): + n = inst["n"] + m = ans.get("matrix") + if not isinstance(m, list) or len(m) != n: + raise Invalid(f"matrix must be a list of {n} rows") + rows = [] + for r in m: + int_list(r, n, -1, 1, "matrix row") + if any(x == 0 for x in r): + raise Invalid("entries must be exactly 1 or -1") + rows.append(list(r)) + d = abs(_det_bareiss(rows)) + if d == 0: + raise Invalid("matrix is singular") + e = len(str(d)) - 1 + return e + math.log10(d / 10 ** e), {"det_over_2^50": str(d >> 50) if d % (1 << 50) == 0 else None} diff --git a/graders/ea_heilbronn_triangle_11/__pycache__/check.cpython-314.pyc b/graders/ea_heilbronn_triangle_11/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddd2a3ee4ceefbe71d39ac92ceaf88d18886724b Binary files /dev/null and b/graders/ea_heilbronn_triangle_11/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_heilbronn_triangle_11/check.py b/graders/ea_heilbronn_triangle_11/check.py new file mode 100644 index 0000000000000000000000000000000000000000..bec363ff8110410dc65b11937058857ce9d80d3a --- /dev/null +++ b/graders/ea_heilbronn_triangle_11/check.py @@ -0,0 +1,23 @@ +"""Heilbronn problem in the unit equilateral triangle, n = 11 (EinsteinArena heilbronn-triangles, MIT). + +Upstream bug fixed: containment in the triangle with vertices (0,0), (1,0), (1/2, sqrt3/2) was tested in +float64 against a rounded sqrt(3); here it is exact (y >= 0, y^2 <= 3x^2, y^2 <= 3(1-x)^2 with x, 1-x >= 0, +on the rational values of the floats). The minimum triangle area is computed exactly, then divided by +sqrt(3)/4 in floating point.""" +import itertools +import math +from fractions import Fraction + +from run import Invalid, float_matrix + + +def check(inst, ans): + n = inst["n"] + p = float_matrix(ans.get("points"), n, 2, "points") + P = [(Fraction(x), Fraction(y)) for x, y in p] + for x, y in P: + if not (y >= 0 and x >= 0 and x <= 1 and y * y <= 3 * x * x and y * y <= 3 * (1 - x) ** 2): + raise Invalid(f"point ({float(x)}, {float(y)}) is outside the triangle") + m = min(abs(a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1])) + for a, b, c in itertools.combinations(P, 3)) / 2 + return float(m) / (math.sqrt(3) / 4), {} diff --git a/graders/ea_kakeya_needle_128/__pycache__/check.cpython-314.pyc b/graders/ea_kakeya_needle_128/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d51290604f6eefe1e50053a8bff3432ff86876b7 Binary files /dev/null and b/graders/ea_kakeya_needle_128/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_kakeya_needle_128/check.py b/graders/ea_kakeya_needle_128/check.py new file mode 100644 index 0000000000000000000000000000000000000000..299c29010cdd3d99985c024395ba3014c9515fa8 --- /dev/null +++ b/graders/ea_kakeya_needle_128/check.py @@ -0,0 +1,95 @@ +"""Discretized Kakeya needle problem, N = 128 (EinsteinArena kakeya-needle-128, MIT). + +Union area of the triangles T_j = conv{(x_j,0), (x_j+1/N,0), (x_j+j/N,1)} (minimize), computed exactly. +Audit: the upstream verifier is already exact rational arithmetic (slab-wise integration between all +crossings of the 2N section-endpoint lines, where the union length is affine), with the upstream +Station tolerance removed; I found no exploit. Ported with the same parsing rules.""" +import math +from fractions import Fraction + +from run import Invalid + +MAX_FRAC, MAX_INT = 25, 4 + + +def _parse(s): + if not isinstance(s, str): + raise Invalid("each offset must be a base-10 decimal string") + t = s.strip() + neg = t.startswith("-") + if neg or t.startswith("+"): + t = t[1:] + if t.count(".") > 1: + raise Invalid(f"malformed decimal string {s!r}") + ip, _, fp = t.partition(".") + digits = ip + fp + if digits == "" or not digits.isdigit() or not digits.isascii(): + raise Invalid(f"malformed decimal string {s!r}") + if len(fp) > MAX_FRAC or len(ip) > MAX_INT: + raise Invalid(f"offset {s!r} has too many digits") + v = Fraction(int(digits), 10 ** len(fp)) + return -v if neg else v + + +def _union(iv): + iv.sort() + tot, (cl, cr) = 0, iv[0] + for l, r in iv[1:]: + if l > cr: + tot += cr - cl + cl, cr = l, r + elif r > cr: + cr = r + return tot + cr - cl + + +def area(xs, N): + den = 1 + for x in xs: + den = den // math.gcd(den, x.denominator) * x.denominator + sx = [int(x * den) for x in xs] + lines = [] + for j, x in enumerate(sx, start=1): + lines.append((den * j, N * x)) + lines.append((den * (j - 1), N * x + den)) + pts = set() + m = len(lines) + for a in range(m): + sa, ia = lines[a] + for b in range(a + 1, m): + q = sa - lines[b][0] + if q == 0: + continue + p = lines[b][1] - ia + if q < 0: + p, q = -p, -q + if 0 < p < q: + g = math.gcd(p, q) + pts.add((p // g, q // g)) + bps = sorted(pts, key=lambda t: Fraction(t[0], t[1])) + [(1, 1)] + scale = N * den + + def ulen(p, q): + return _union([(lines[k][1] * q + lines[k][0] * p, lines[k + 1][1] * q + lines[k + 1][0] * p) + for k in range(0, m, 2)]) + + tot, py, pu = Fraction(0), Fraction(0), Fraction(ulen(0, 1), scale) + for p, q in bps: + y = Fraction(p, q) + u = Fraction(ulen(p, q), q * scale) + tot += (pu + u) * (y - py) / 2 + py, pu = y, u + return tot + + +def check(inst, ans): + N = inst["N"] + off = ans.get("offsets") + if not isinstance(off, list) or len(off) != N: + raise Invalid(f"offsets must be a list of exactly {N} strings") + xs = [_parse(s) for s in off] + x0 = xs[0] + a = area([x - x0 for x in xs], N) + if a <= 0 or a > Fraction(1, 2): + raise Invalid("internal area check failed") + return float(a), {} diff --git a/graders/ea_kissing_number/__pycache__/check.cpython-314.pyc b/graders/ea_kissing_number/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7f6c8f67853a15555a2c06feb03a953767ce10f Binary files /dev/null and b/graders/ea_kissing_number/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_kissing_number/check.py b/graders/ea_kissing_number/check.py new file mode 100644 index 0000000000000000000000000000000000000000..e67c43884a1e3216148fc027eaa31c36e4ff51a4 --- /dev/null +++ b/graders/ea_kissing_number/check.py @@ -0,0 +1,70 @@ +"""Kissing configurations with an overlap loss (EinsteinArena kissing-number-d11 / -d11-605 / -d12, MIT). + +Sphere centres c_i = 2 v_i / |v_i|; loss = sum_{i= max |v_i|^2 (in 30-80 digit Decimal arithmetic, so huge integer inputs can round) and +otherwise sums float-ish Decimal overlaps. Here every number is read as an exact rational (floats via their +shortest decimal repr), and a pair is overlapping iff > 0 and 4 ^2 > |v_i|^2 |v_j|^2, +decided in exact integer arithmetic (necessary and sufficient). The loss is 0 exactly for valid +configurations, and every overlapping pair contributes a strictly positive amount computed from the exact +excess 4^2 - |v_i|^2|v_j|^2 (so an invalid configuration can never round to 0).""" +import math +import re +from fractions import Fraction + +from run import Invalid + +DEC = re.compile(r"^[+-]?\d{1,40}(\.\d{1,80})?$") + + +def _rat(x): + if isinstance(x, bool): + raise Invalid("coordinates must be numbers") + if isinstance(x, int): + return Fraction(x) + if isinstance(x, float): + if not math.isfinite(x): + raise Invalid("non-finite coordinate") + return Fraction(repr(x)) + if isinstance(x, str) and DEC.fullmatch(x): + return Fraction(x) + raise Invalid("coordinates must be numbers or decimal strings") + + +def check(inst, ans): + n, d = inst["n"], inst["dim"] + vs = ans.get("vectors") + if not isinstance(vs, list) or len(vs) != n: + raise Invalid(f"vectors must be a list of exactly {n} vectors") + rows = [] + for v in vs: + if not isinstance(v, list) or len(v) != d: + raise Invalid(f"each vector must have exactly {d} coordinates") + rows.append([_rat(x) for x in v]) + den = 1 + for r in rows: + for q in r: + den = den * q.denominator // math.gcd(den, q.denominator) + R = [[int(q * den) for q in r] for r in rows] + N = [sum(x * x for x in r) for r in R] + if min(N) == 0: + raise Invalid("all vectors must be non-zero") + loss, bad = 0.0, 0 + for i in range(n): + ri, Ni = R[i], N[i] + for j in range(i + 1, n): + p = sum(a * b for a, b in zip(ri, R[j])) + if p <= 0: + continue + NN = Ni * N[j] + ex = 4 * p * p - NN + if ex <= 0: + continue + bad += 1 + q = float(Fraction(ex, NN)) # 4 cos^2 - 1 > 0 + c = min(1.0, float(Fraction(p * p, NN)) ** 0.5) + ov = 2.0 * (q / (2 * c + 1)) / (1.0 + math.sqrt(max(0.0, 2 - 2 * c))) + loss += max(ov, 1e-300) + return loss, {"overlapping_pairs": bad} diff --git a/graders/ea_min_distance_ratio_16/__pycache__/check.cpython-314.pyc b/graders/ea_min_distance_ratio_16/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3dee7420bb3b8465ecda01db1f1164f557719a96 Binary files /dev/null and b/graders/ea_min_distance_ratio_16/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_min_distance_ratio_16/check.py b/graders/ea_min_distance_ratio_16/check.py new file mode 100644 index 0000000000000000000000000000000000000000..85f09ce2dd1be5ced4e978559511eb501b10dffa --- /dev/null +++ b/graders/ea_min_distance_ratio_16/check.py @@ -0,0 +1,18 @@ +"""Minimize (max distance / min distance)^2 for 16 points in the plane (EinsteinArena min-distance-ratio-2d, MIT). + +Float objective, ported from the upstream verifier (distinctness: min distance > 1e-12).""" +import numpy as np + +from run import Invalid, float_matrix + + +def check(inst, ans): + n = inst["n"] + v = np.array(float_matrix(ans.get("vectors"), n, 2, "vectors")) + d = np.sqrt(((v[:, None, :] - v[None, :, :]) ** 2).sum(-1))[np.triu_indices(n, 1)] + if d.min() < 1e-12: + raise Invalid("points must be distinct (min distance < 1e-12)") + r = float((d.max() / d.min()) ** 2) + if not np.isfinite(r): + raise Invalid("non-finite ratio") + return r, {} diff --git a/graders/ea_no_three_in_line_75/__pycache__/check.cpython-314.pyc b/graders/ea_no_three_in_line_75/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0dbb56ecc3cb8cbe6150f462404f406f4f991b0 Binary files /dev/null and b/graders/ea_no_three_in_line_75/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_no_three_in_line_75/check.py b/graders/ea_no_three_in_line_75/check.py new file mode 100644 index 0000000000000000000000000000000000000000..5c7878ef4268634632328aae2c655529ed7426c2 --- /dev/null +++ b/graders/ea_no_three_in_line_75/check.py @@ -0,0 +1,31 @@ +"""No-three-in-line on the 75x75 grid (EinsteinArena no-three-in-line-75, MIT). + +Audit: upstream verifier is exact integer arithmetic over all triples; sound. Re-implemented with a +slope-hash per anchor point (same result, O(n^2) instead of O(n^3)).""" +import math + +from run import Invalid, int_list + + +def check(inst, ans): + g, cap = inst["grid"], inst["max_points"] + pts = ans.get("points") + if not isinstance(pts, list) or not 1 <= len(pts) <= cap: + raise Invalid(f"points must be a list of 1..{cap} pairs") + P = [tuple(int_list(p, 2, 0, g - 1, "point")) for p in pts] + if len(set(P)) != len(P): + raise Invalid("points must be distinct") + for i, (x1, y1) in enumerate(P): + seen = set() + for j, (x2, y2) in enumerate(P): + if j == i: + continue + dx, dy = x2 - x1, y2 - y1 + d = math.gcd(dx, dy) + dx, dy = dx // d, dy // d + if dx < 0 or (dx == 0 and dy < 0): + dx, dy = -dx, -dy + if (dx, dy) in seen: + raise Invalid(f"three collinear points including {P[i]}") + seen.add((dx, dy)) + return float(len(P)), {} diff --git a/graders/ea_prime_number_theorem/__pycache__/check.cpython-314.pyc b/graders/ea_prime_number_theorem/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df4263877f6fba712664c3538545e5837ae97c62 Binary files /dev/null and b/graders/ea_prime_number_theorem/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_prime_number_theorem/check.py b/graders/ea_prime_number_theorem/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d102c8e6d2d57cee4c45d23d1ce1004d5d45f260 --- /dev/null +++ b/graders/ea_prime_number_theorem/check.py @@ -0,0 +1,44 @@ +"""Prime number theorem certificate (EinsteinArena prime-number-theorem, MIT). + +f: finite partial function on positive integers; f(1) is adjusted so that sum f(k)/k = 0; the constraint is +F(x) = sum_k f(k) floor(x/k) <= 1; score S = -sum f(k) log(k)/k (maximize). + +Upstream weakness fixed: the constraint was checked on 10^7 Monte-Carlo samples x ~ U(1, 10 max k) with +tolerance 1e-4, so narrow violations could slip through. F is a step function that only changes at +integers, so here it is checked at EVERY integer 1 <= x <= 10 max k (sieve + cumulative sum), with +tolerance 1e-9 (float round-off of the f(1) normalisation). Other changes: values must lie in [-10, 10] +(upstream silently clipped), keys must be canonical decimal strings <= inst["max_key"].""" +import math + +import numpy as np + +from run import Invalid, num + + +def check(inst, ans): + pf = ans.get("partial_function") + if not isinstance(pf, dict) or not 1 <= len(pf) <= inst["max_keys"]: + raise Invalid(f"partial_function must be an object with 1..{inst['max_keys']} keys") + f = {} + for k, v in pf.items(): + if not (isinstance(k, str) and k.isascii() and k.isdigit() and k[0] != "0"): + raise Invalid(f"key {k!r} is not a canonical positive integer string") + kk = int(k) + if kk > inst["max_key"]: + raise Invalid(f"keys must be at most {inst['max_key']}") + x = num(v, "value") + if abs(x) > 10: + raise Invalid("values must lie in [-10, 10]") + f[kk] = x + f[1] = f.get(1, 0.0) - sum(v / k for k, v in f.items()) + X = 10 * max(f) + g = np.zeros(X + 1) + for k, v in f.items(): + g[k::k] += v + F = np.cumsum(g) + worst = float(F[1:].max()) + if worst > 1 + inst["tol"]: + n = int(np.argmax(F[1:])) + 1 + raise Invalid(f"constraint violated: sum f(k) floor(x/k) = {worst:.12g} > 1 at x = {n}") + s = -sum(v * math.log(k) / k for k, v in f.items()) + return float(s), {"max_F": worst, "checked_up_to": X} diff --git a/graders/ea_ring_loading_15/__pycache__/check.cpython-314.pyc b/graders/ea_ring_loading_15/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..897490be28c458320322d9b6e1b9b2b1c2bf4485 Binary files /dev/null and b/graders/ea_ring_loading_15/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_ring_loading_15/check.py b/graders/ea_ring_loading_15/check.py new file mode 100644 index 0000000000000000000000000000000000000000..df8d98093f8e743e0e107cfa81dc20d09a34b880 --- /dev/null +++ b/graders/ea_ring_loading_15/check.py @@ -0,0 +1,53 @@ +"""Ring loading problem with 15 pairs (EinsteinArena ring-loading-15, MIT). + +A(u, v) = min over z_i in {v_i, -u_i} of max_k |sum_{i<=k} z_i - sum_{i>k} z_i| (maximize). +Audit: upstream verifier parses exact rationals and enumerates all 2^15 adversary choices; sound. +Re-implemented over a common denominator with Python integers (same exact value, faster).""" +import math +import re +from fractions import Fraction + +from run import Invalid + +PAT = re.compile(r"^(?:0|[1-9]\d*)(?:(?:\.\d+)|(?:/[1-9]\d*))?$") + + +def _rat(s): + if not isinstance(s, str) or not 1 <= len(s) <= 80 or PAT.fullmatch(s) is None: + raise Invalid("values must be nonnegative decimal or fraction strings such as '0.25' or '3/7'") + r = Fraction(s) + if r.numerator.bit_length() > 64 or r.denominator.bit_length() > 64: + raise Invalid("reduced numerator and denominator must fit in 64 bits") + return r + + +def check(inst, ans): + k = inst["pairs"] + p = ans.get("pairs") + if not isinstance(p, list) or len(p) != k: + raise Invalid(f"pairs must be a list of exactly {k} pairs") + uv = [] + for q in p: + if not isinstance(q, list) or len(q) != 2: + raise Invalid("each entry must be a pair [u, v]") + u, v = _rat(q[0]), _rat(q[1]) + if u + v > 1: + raise Invalid("every pair must satisfy u + v <= 1") + uv.append((u, v)) + den = 1 + for u, v in uv: + for r in (u, v): + den = den * r.denominator // math.gcd(den, r.denominator) + U = [int(u * den) for u, _ in uv] + V = [int(v * den) for _, v in uv] + best = None + for mask in range(1 << k): + z = [-U[i] if mask >> i & 1 else V[i] for i in range(k)] + tot = sum(z) + pre, worst = 0, 0 + for x in z: + pre += x + worst = max(worst, abs(2 * pre - tot)) + if best is None or worst < best: + best = worst + return float(Fraction(best, den)), {"exact": str(Fraction(best, den))} diff --git a/graders/ea_second_autocorrelation/__pycache__/check.cpython-314.pyc b/graders/ea_second_autocorrelation/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..370be692780c3622332ea2d72657dafd9d5d0153 Binary files /dev/null and b/graders/ea_second_autocorrelation/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_second_autocorrelation/check.py b/graders/ea_second_autocorrelation/check.py new file mode 100644 index 0000000000000000000000000000000000000000..42e9d498741d37ed998d81f42ce6402fe0f87a3d --- /dev/null +++ b/graders/ea_second_autocorrelation/check.py @@ -0,0 +1,32 @@ +"""Second autocorrelation inequality, lower bound (EinsteinArena second-autocorrelation-inequality, MIT). + +C = ||f*f||_2^2 / (||f*f||_1 ||f*f||_inf) with the upstream discretisation (scipy oaconvolve, piecewise +linear L2, discrete L1/Linf); maximize. Ported from the upstream verifier. Changes: values must be >= 0 +exactly (upstream tolerated >= -1e-6 and clipped), length capped at inst["max_len"] (upstream 2,000,000).""" +import numpy as np +from scipy.signal import oaconvolve + +from run import Invalid, float_list + + +def check(inst, ans): + v = ans.get("values") + if not isinstance(v, list) or not 1 <= len(v) <= inst["max_len"]: + raise Invalid(f"values must be a list of 1..{inst['max_len']} numbers") + f = np.array(float_list(v, None, "values")) + if np.any(f < 0): + raise Invalid("all values must be non-negative") + if np.sum(f) <= 0: + raise Invalid("f must have positive integral") + conv = oaconvolve(f, f, mode="full") + m = len(conv) + xi = np.diff(np.linspace(-0.5, 0.5, m + 2)) + y = np.concatenate(([0], conv, [0])) + y1, y2 = y[:-1], y[1:] + l2 = float(np.sum((xi / 3) * (y1 ** 2 + y1 * y2 + y2 ** 2))) + l1 = np.sum(np.abs(conv)) / (m + 1) + li = np.max(np.abs(conv)) + c = float(l2 / (l1 * li)) + if not np.isfinite(c): + raise Invalid("non-finite score") + return c, {} diff --git a/graders/ea_shannon_c7_5/__pycache__/check.cpython-314.pyc b/graders/ea_shannon_c7_5/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..810e9d154dad0d34cc615cf121dccff57d5127fa Binary files /dev/null and b/graders/ea_shannon_c7_5/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_shannon_c7_5/check.py b/graders/ea_shannon_c7_5/check.py new file mode 100644 index 0000000000000000000000000000000000000000..bc6997de6577585e013c5aa8125423294d971776 --- /dev/null +++ b/graders/ea_shannon_c7_5/check.py @@ -0,0 +1,22 @@ +"""Independent set in the 5th strong power of C_7 (EinsteinArena shannon-capacity-c7-5, MIT). + +Audit: upstream verifier is exact (pairwise check); sound. Same check re-implemented.""" +from run import Invalid, int_list + + +def check(inst, ans): + w = ans.get("words") + cap, L, q = inst["max_words"], inst["length"], inst["q"] + if not isinstance(w, list) or not 1 <= len(w) <= cap: + raise Invalid(f"words must be a list of 1..{cap} words") + W = [tuple(int_list(x, L, 0, q - 1, "word")) for x in w] + if len(set(W)) != len(W): + raise Invalid("words must be distinct") + close = {0, 1, q - 1} + for i in range(len(W)): + a = W[i] + for j in range(i + 1, len(W)): + b = W[j] + if all((x - y) % q in close for x, y in zip(a, b)): + raise Invalid(f"words {a} and {b} are adjacent") + return float(len(W)), {} diff --git a/graders/ea_sidon_45_set/__pycache__/check.cpython-314.pyc b/graders/ea_sidon_45_set/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25a6a7145311178102960f7bd72efdb2836b8e02 Binary files /dev/null and b/graders/ea_sidon_45_set/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_sidon_45_set/check.py b/graders/ea_sidon_45_set/check.py new file mode 100644 index 0000000000000000000000000000000000000000..e49bea61dabe094f78326b2c4f7e5b4844a19c10 --- /dev/null +++ b/graders/ea_sidon_45_set/check.py @@ -0,0 +1,44 @@ +"""Sidon subsets of (4,5)-sets (EinsteinArena sidon-45-set, MIT). Score h(A)/|A| (minimize). + +Audit: upstream verifier is exact (all 4-subsets, exhaustive search for the largest Sidon subset); sound. +Re-implemented with a branch-and-bound for h(A) (same value).""" +from itertools import combinations + +from run import Invalid, int_list + + +def _max_sidon(a): + # largest Sidon subset (all sums x+y, x<=y distinct) by DFS with pruning + n = len(a) + best = [0] + + def rec(i, chosen, sums): + if len(chosen) + (n - i) <= best[0]: + return + if i == n: + best[0] = max(best[0], len(chosen)) + return + x = a[i] + new = [x + y for y in chosen] + [2 * x] + if len(set(new)) == len(new) and not any(s in sums for s in new): + rec(i + 1, chosen + [x], sums | set(new)) + rec(i + 1, chosen, sums) + + rec(0, [], frozenset()) + return best[0] + + +def check(inst, ans): + e = ans.get("elements") + lo, hi, bound = inst["min_size"], inst["max_size"], inst["max_abs"] + if not isinstance(e, list) or not lo <= len(e) <= hi: + raise Invalid(f"elements must be a list of {lo}..{hi} integers") + int_list(e, None, -bound, bound, "elements") + if len(set(e)) != len(e): + raise Invalid("elements must be distinct") + a = sorted(e) + for four in combinations(a, 4): + if len({four[j] - four[i] for i in range(4) for j in range(i + 1, 4)}) < 5: + raise Invalid(f"{four} has fewer than 5 distinct differences: not a (4,5)-set") + h = _max_sidon(a) + return h / len(a), {"h": h, "size": len(a)} diff --git a/graders/ea_snake_in_the_box_13/__pycache__/check.cpython-314.pyc b/graders/ea_snake_in_the_box_13/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd16b9ef6da35bc7be0bcfdc47fe85bd4afd8639 Binary files /dev/null and b/graders/ea_snake_in_the_box_13/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_snake_in_the_box_13/check.py b/graders/ea_snake_in_the_box_13/check.py new file mode 100644 index 0000000000000000000000000000000000000000..336a27a6b968ba39bf52cbfb1b25306985ec08fd --- /dev/null +++ b/graders/ea_snake_in_the_box_13/check.py @@ -0,0 +1,25 @@ +"""Snake-in-the-box in Q_13 (EinsteinArena snake-in-the-box-13, MIT). + +Audit: upstream verifier (XOR walk; a new vertex may have only its predecessor as a visited +neighbour) is an exact induced-path check; sound. Same check re-implemented.""" +from run import Invalid, int_list + + +def check(inst, ans): + d = inst["dim"] + a = ans.get("actions") + if not isinstance(a, list) or not 1 <= len(a) <= (1 << d) - 1: + raise Invalid(f"actions must be a list of 1..{(1 << d) - 1} integers") + int_list(a, None, 0, d - 1, "actions") + cur, seen = 0, {0} + for t in a: + nxt = cur ^ (1 << t) + if nxt in seen: + raise Invalid("the path repeats a vertex") + for c in range(d): + nb = nxt ^ (1 << c) + if nb != cur and nb in seen: + raise Invalid("the path has a chord (non-consecutive adjacent vertices)") + seen.add(nxt) + cur = nxt + return float(len(a)), {} diff --git a/graders/ea_sorting_network_16/__pycache__/check.cpython-314.pyc b/graders/ea_sorting_network_16/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0a50afa84a61135740c7ff823b6ad5292fdb111 Binary files /dev/null and b/graders/ea_sorting_network_16/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_sorting_network_16/check.py b/graders/ea_sorting_network_16/check.py new file mode 100644 index 0000000000000000000000000000000000000000..2038a73c3ede49044852e0c759472dea31ff0bc0 --- /dev/null +++ b/graders/ea_sorting_network_16/check.py @@ -0,0 +1,29 @@ +"""Sorting network on 16 wires, minimize comparators (EinsteinArena sorting-network-16, MIT). + +Audit: upstream verifier applies the network to all 2^16 binary inputs (0-1 principle): exact and sound. +Change: upstream caps submissions at 60 comparators (the record), which leaves no room for a +weaker-than-record baseline; here the cap is inst["max_comparators"] (200).""" +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + n, cap = inst["wires"], inst["max_comparators"] + c = ans.get("comparators") + if not isinstance(c, list) or not 1 <= len(c) <= cap: + raise Invalid(f"comparators must be a list of 1..{cap} pairs") + pairs = [] + for p in c: + i, j = int_list(p, 2, 0, n - 1, "comparator") + if not i < j: + raise Invalid("each comparator [i, j] needs i < j") + pairs.append((i, j)) + v = ((np.arange(1 << n, dtype=np.uint32)[:, None] >> np.arange(n, dtype=np.uint32)) & 1).astype(np.uint8) + for i, j in pairs: + a, b = v[:, i].copy(), v[:, j].copy() + v[:, i] = np.minimum(a, b) + v[:, j] = np.maximum(a, b) + if np.any(v[:, :-1] > v[:, 1:]): + raise Invalid("the network does not sort every 0/1 input") + return float(len(pairs)), {} diff --git a/graders/ea_spencer_discrepancy/__pycache__/check.cpython-314.pyc b/graders/ea_spencer_discrepancy/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e88da7669a3fc11704532f553f9d41853341053 Binary files /dev/null and b/graders/ea_spencer_discrepancy/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_spencer_discrepancy/check.py b/graders/ea_spencer_discrepancy/check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b5b2016ea7084a3d98b8cb89dadb432e60d0ce5 --- /dev/null +++ b/graders/ea_spencer_discrepancy/check.py @@ -0,0 +1,42 @@ +"""Spencer discrepancy constant witness (EinsteinArena spencer-discrepancy, MIT). +Score disc(A)/sqrt(n) with disc(A) = min_{x in {-1,1}^n} ||Ax||_inf (maximize). + +Audit: upstream verifier enumerates all 2^n sign vectors exactly; sound. Re-implemented with numpy +(vectorised popcounts; x and -x give the same value so half the vectors suffice).""" +import math + +import numpy as np + +from run import Invalid, int_list + + +def _popcount(a): + a = a - ((a >> 1) & 0x55555555) + a = (a & 0x33333333) + ((a >> 2) & 0x33333333) + a = (a + (a >> 4)) & 0x0F0F0F0F + return (a * 0x01010101 & 0xFFFFFFFF) >> 24 + + +def check(inst, ans): + m = ans.get("matrix") + cap = inst["max_order"] + if not isinstance(m, list) or not 1 <= len(m) <= cap: + raise Invalid(f"matrix order must be between 1 and {cap}") + n = len(m) + masks = [] + for row in m: + int_list(row, n, -1, 1, "matrix row") + if any(v == 0 for v in row): + raise Invalid("entries must be exactly -1 or 1") + masks.append(sum(1 << j for j, v in enumerate(row) if v == -1)) + disc = n + total = 1 << max(n - 1, 0) # fix the top sign (x ~ -x) + step = 1 << 18 + for s0 in range(0, total, step): + x = np.arange(s0, min(total, s0 + step), dtype=np.uint64) + worst = np.zeros(len(x), dtype=np.int64) + for r in masks: + pc = _popcount((x ^ np.uint64(r)) & np.uint64(0xFFFFFFFF)).astype(np.int64) + worst = np.maximum(worst, np.abs(n - 2 * pc)) + disc = min(disc, int(worst.min())) + return disc / math.sqrt(n), {"disc": disc, "order": n} diff --git a/graders/ea_tammes/__pycache__/check.cpython-314.pyc b/graders/ea_tammes/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15365be16eec8e4e9c7bdbd9a7f932b964f21673 Binary files /dev/null and b/graders/ea_tammes/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_tammes/check.py b/graders/ea_tammes/check.py new file mode 100644 index 0000000000000000000000000000000000000000..af79b2b1d2f6be5bb2dd07edd8d10ad91ffc3e4b --- /dev/null +++ b/graders/ea_tammes/check.py @@ -0,0 +1,16 @@ +"""Tammes problem: n points on S^2, maximize the minimum pairwise distance (EinsteinArena verifier, MIT).""" +import itertools +import math + +from run import Invalid, float_matrix + + +def check(inst, ans): + v = float_matrix(ans.get("vectors"), inst["n"], 3, "vectors") + u = [] + for x in v: + nr = math.sqrt(sum(t * t for t in x)) + if nr < 1e-12: + raise Invalid("zero vector") + u.append([t / nr for t in x]) + return min(math.dist(a, b) for a, b in itertools.combinations(u, 2)), {} diff --git a/graders/ea_third_autocorrelation/__pycache__/check.cpython-314.pyc b/graders/ea_third_autocorrelation/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35783825204e7cec35b506616a4beba58b5c3282 Binary files /dev/null and b/graders/ea_third_autocorrelation/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_third_autocorrelation/check.py b/graders/ea_third_autocorrelation/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1998a6ffaf74a7aaf2af5e3a3a1df28903e415a0 --- /dev/null +++ b/graders/ea_third_autocorrelation/check.py @@ -0,0 +1,23 @@ +"""Third autocorrelation inequality, upper bound (EinsteinArena third-autocorrelation-inequality, MIT). + +C = |max(conv(f, f) * dx)| / (sum(f) * dx)^2, dx = 0.5 / n, f may be negative (minimize). Ported from the +upstream verifier (np.convolve; the squared integral must be >= 1e-9). Change: length capped at +inst["max_len"]; NaN/inf rejected.""" +import numpy as np + +from run import Invalid, float_list + + +def check(inst, ans): + v = ans.get("values") + if not isinstance(v, list) or not 1 <= len(v) <= inst["max_len"]: + raise Invalid(f"values must be a list of 1..{inst['max_len']} numbers") + f = np.array(float_list(v, None, "values")) + dx = 0.5 / len(f) + i2 = (np.sum(f) * dx) ** 2 + if not i2 >= 1e-9: + raise Invalid("(integral of f)^2 must be at least 1e-9") + c = float(abs(np.max(np.convolve(f, f) * dx)) / i2) + if not np.isfinite(c): + raise Invalid("non-finite score") + return c, {} diff --git a/graders/ea_thomson_282/__pycache__/check.cpython-314.pyc b/graders/ea_thomson_282/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3f8f5af360477b825860428093f67bb61abdb40 Binary files /dev/null and b/graders/ea_thomson_282/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_thomson_282/check.py b/graders/ea_thomson_282/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d2fd582b7b621d54b3d49552494d073d031fc492 --- /dev/null +++ b/graders/ea_thomson_282/check.py @@ -0,0 +1,22 @@ +"""Thomson problem, n = 282: minimize the Coulomb energy of points on S^2 (EinsteinArena thomson-problem, MIT). + +Ported from the upstream verifier (points are normalized onto the sphere). Change: a (near-)zero vector is +rejected instead of being silently clamped to norm 1e-12.""" +import numpy as np + +from run import Invalid, float_matrix + + +def check(inst, ans): + n = inst["n"] + v = np.array(float_matrix(ans.get("vectors"), n, 3, "vectors")) + nr = np.linalg.norm(v, axis=1, keepdims=True) + if np.any(nr < 1e-12): + raise Invalid("zero vector") + v = v / nr + d = np.sqrt(((v[:, None, :] - v[None, :, :]) ** 2).sum(-1))[np.triu_indices(n, 1)] + d[d < 1e-12] = 1e-12 + e = float(np.sum(1.0 / d)) + if not np.isfinite(e): + raise Invalid("non-finite energy") + return e, {} diff --git a/graders/ea_two_deletion_code_16/__pycache__/check.cpython-314.pyc b/graders/ea_two_deletion_code_16/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b54268dee9b7e6d13be9d08c8120f363e319ed71 Binary files /dev/null and b/graders/ea_two_deletion_code_16/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_two_deletion_code_16/check.py b/graders/ea_two_deletion_code_16/check.py new file mode 100644 index 0000000000000000000000000000000000000000..8259bab2ac57ef62d4b41d965b91d357c71a9c9c --- /dev/null +++ b/graders/ea_two_deletion_code_16/check.py @@ -0,0 +1,28 @@ +"""Binary two-deletion-correcting code of length 16 (EinsteinArena two-deletion-code-16, MIT). + +Audit: upstream verifier (disjointness of the sets of length-14 subsequences) is exact; sound. +Same check re-implemented.""" +from run import Invalid + + +def _desc(w, L): + return {w[:i] + w[i + 1:j] + w[j + 1:] for i in range(L - 1) for j in range(i + 1, L)} + + +def check(inst, ans): + L, cap = inst["length"], inst["max_words"] + words = ans.get("words") + if not isinstance(words, list) or not 1 <= len(words) <= cap: + raise Invalid(f"words must be a list of 1..{cap} strings") + seen, used = set(), set() + for w in words: + if not isinstance(w, str) or len(w) != L or any(c not in "01" for c in w): + raise Invalid(f"every codeword must be a string of exactly {L} characters 0/1") + if w in seen: + raise Invalid("codewords must be distinct") + seen.add(w) + d = _desc(w, L) + if not used.isdisjoint(d): + raise Invalid(f"codeword {w} shares a two-deletion subsequence with an earlier codeword") + used |= d + return float(len(words)), {} diff --git a/graders/ea_uncertainty_principle/__pycache__/check.cpython-314.pyc b/graders/ea_uncertainty_principle/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a231c64c81602b09efc420fca4832cab522f5403 Binary files /dev/null and b/graders/ea_uncertainty_principle/__pycache__/check.cpython-314.pyc differ diff --git a/graders/ea_uncertainty_principle/check.py b/graders/ea_uncertainty_principle/check.py new file mode 100644 index 0000000000000000000000000000000000000000..8333ef5642f3cf52e0eefca66545e021b9c9fb8d --- /dev/null +++ b/graders/ea_uncertainty_principle/check.py @@ -0,0 +1,151 @@ +"""Uncertainty principle upper bound via Laguerre double roots (EinsteinArena uncertainty-principle, MIT). + +Given double-root positions z_1..z_m, g = sum_{j=0}^{2m+1} c_j L_{2j}^{(-1/2)} with g(0)=0, g'(0)=1, +g(z_i)=g'(z_i)=0; h = g / (x prod (x-z_i)^2) is a polynomial and the score is r/(2 pi), r = largest +positive root of h of odd multiplicity (last sign change) (minimize). + +Changes vs the upstream verifier (float64 / mpmath linear solve, 200k-point float grid scan + brentq): +* the linear system is solved in 400- and 600-digit decimal arithmetic, h is formed by exact synthetic + division, and the last sign change is found by exact real-root isolation (sympy) of h with + coefficients rounded to 60 significant digits -- no grid, so close root pairs and roots beyond the + upstream scan window (1.5 max z + 100) cannot be missed; the two precisions must agree; +* NEW validity check (upstream omission): the test function -g(2 pi x^2) e^{-pi x^2} must be eventually + non-negative, i.e. the leading coefficient of h must be negative; otherwise the bound is not valid; +* mpmath is not used (not in the allowed runtime set).""" +import math +from decimal import Decimal, localcontext +from fractions import Fraction + +import sympy as sp + +from run import Invalid, num + +SIG = 60 + + +def _laguerre(nmax): + al = Fraction(-1, 2) + L = [[Fraction(1)], [1 + al, Fraction(-1)]] + for k in range(1, nmax): + a, b = L[k], L[k - 1] + nxt = [Fraction(0)] * (k + 2) + for i, c in enumerate(a): + nxt[i] += (2 * k + 1 + al) * c + nxt[i + 1] -= c + for i, c in enumerate(b): + nxt[i] -= (k + al) * c + L.append([c / (k + 1) for c in nxt]) + return L + + +def _h_coeffs(zs, prec): + """Coefficients (high -> low) of h, as exact rationals rounded to SIG significant digits.""" + m = len(zs) + degs = list(range(0, 4 * m + 4, 2)) + L = _laguerre(degs[-1]) + with localcontext() as ctx: + ctx.prec = prec + + def D(q): + return Decimal(q.numerator) / Decimal(q.denominator) + + P = [[D(c) for c in L[d]] for d in degs] + Pd = [[i * c for i, c in enumerate(p)][1:] for p in P] + Pd[0] = [Decimal(0)] + + def ev(p, x): + r = Decimal(0) + for c in reversed(p): + r = r * x + c + return r + + zd = [D(z) for z in zs] + A = [[ev(p, Decimal(0)) for p in P] + [Decimal(0)], [ev(p, Decimal(0)) for p in Pd] + [Decimal(1)]] + for z in zd: + A.append([ev(p, z) for p in P] + [Decimal(0)]) + A.append([ev(p, z) for p in Pd] + [Decimal(0)]) + n = len(A) + for col in range(n): + piv = max(range(col, n), key=lambda r: abs(A[r][col])) + if A[piv][col] == 0: + raise Invalid("singular interpolation system") + A[col], A[piv] = A[piv], A[col] + pv = A[col][col] + for r in range(col + 1, n): + f = A[r][col] / pv + if f: + A[r] = [x - f * y for x, y in zip(A[r], A[col])] + c = [Decimal(0)] * n + for r in range(n - 1, -1, -1): + c[r] = (A[r][n] - sum(A[r][k] * c[k] for k in range(r + 1, n))) / A[r][r] + g = [Decimal(0)] * (degs[-1] + 1) + for cj, p in zip(c, P): + for i, v in enumerate(p): + g[i] += cj * v + poly = list(reversed(g)) + rems = [] + + def synth(pl, z): + out = [pl[0]] + for co in pl[1:]: + out.append(co + out[-1] * z) + return out[:-1], out[-1] + + poly, rm = synth(poly, Decimal(0)) + rems.append(rm) + for z in zd: + for _ in range(2): + poly, rm = synth(poly, z) + rems.append(rm) + scale = max(abs(x) for x in poly) + if scale == 0 or max(abs(r) for r in rems) > scale * Decimal(10) ** (-(prec // 3)): + raise Invalid("numerically unstable root configuration") + out = [] + for x in poly: + if x == 0: + out.append(sp.Integer(0)) + continue + q = x.adjusted() - SIG + out.append(sp.Integer(int(x.scaleb(-q).to_integral_value())) * sp.Rational(10) ** q) + return out + + +def _last_sign_change(coeffs): + x = sp.Symbol("x") + h = sp.Poly(coeffs, x, domain="QQ") + if not h.LC() < 0: + raise Invalid("the test function is not eventually of the right sign (leading coefficient of h >= 0)") + best = None + for fac, mult in h.sqf_list()[1]: + if mult % 2 == 0: + continue + for (lo, hi), _ in fac.intervals(): + if best is None or hi > best[2]: + best = (fac, lo, hi) + if best is None: + raise Invalid("no sign change") + fac, lo, hi = best + lo, hi = fac.refine_root(lo, hi, eps=sp.Rational(1, 10 ** 16)) + r = (lo + hi) / 2 + if not r > 0: + raise Invalid("no positive sign change") + return float(r) + + +def check(inst, ans): + zs = ans.get("laguerre_double_roots") + if not isinstance(zs, list) or not 1 <= len(zs) <= inst["max_roots"]: + raise Invalid(f"laguerre_double_roots must be a list of 1..{inst['max_roots']} numbers") + Z = [] + for z in zs: + v = num(z, "root") + if not 0 < v <= inst["max_root"]: + raise Invalid(f"roots must lie in (0, {inst['max_root']}]") + Z.append(Fraction(repr(v))) + if len(set(Z)) != len(Z): + raise Invalid("duplicate roots") + r1 = _last_sign_change(_h_coeffs(Z, 400)) + r2 = _last_sign_change(_h_coeffs(Z, 600)) + if abs(r1 - r2) > 1e-12 * max(1.0, abs(r2)): + raise Invalid("numerically unstable root configuration") + return r2 / (2 * math.pi), {"r": r2} diff --git a/graders/finch_3ap_diffs_40/__pycache__/check.cpython-314.pyc b/graders/finch_3ap_diffs_40/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..000468ecf0daf7c5ccde633c2047cb832ad660eb Binary files /dev/null and b/graders/finch_3ap_diffs_40/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_3ap_diffs_40/check.py b/graders/finch_3ap_diffs_40/check.py new file mode 100644 index 0000000000000000000000000000000000000000..ac30a01a909fcbd25818ff1325c71ecc5d13f84c --- /dev/null +++ b/graders/finch_3ap_diffs_40/check.py @@ -0,0 +1,14 @@ +"""Erdos #1097: number of distinct common differences of 3-term APs in a 40-element set A of [0, 400) +(Finch/EFT skydiscover erdos_1097_3ap_diffs_n40, Apache-2.0). Exact integer count, as upstream. Change: +entries must be JSON integers (upstream cast with int()).""" +from run import Invalid, int_list + + +def check(inst, ans): + n, M = inst["n"], inst["M"] + A = int_list(ans.get("A"), n, 0, M - 1, "A") + if len(set(A)) != n: + raise Invalid("elements must be distinct") + S, L = set(A), sorted(A) + ds = {L[j] - L[i] for i in range(n) for j in range(i + 1, n) if 2 * L[j] - L[i] in S} + return float(len(ds)), {} diff --git a/graders/finch_4subset_3dist_16/__pycache__/check.cpython-314.pyc b/graders/finch_4subset_3dist_16/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa05b2d9a2703e3549162d140ef221ae8f053519 Binary files /dev/null and b/graders/finch_4subset_3dist_16/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_4subset_3dist_16/check.py b/graders/finch_4subset_3dist_16/check.py new file mode 100644 index 0000000000000000000000000000000000000000..bc93325cc8cb26a11bde0b73b15ad88bec05f735 --- /dev/null +++ b/graders/finch_4subset_3dist_16/check.py @@ -0,0 +1,50 @@ +"""Erdos #659, n = 16: every 4 points determine at least 3 distinct distances; minimize the total +number of distinct distances (Finch/EFT skydiscover erdos_659_4subset_3dist_construction, Apache-2.0). + +Upstream bug fixed: distances were grouped by a chained relative tolerance 1e-9 over the sorted list, so +many slightly different distances could be merged into one class. Here coordinates are exact rationals +and squared distances are compared exactly.""" +import itertools +import math +import re +from fractions import Fraction + +from run import Invalid + +RAT = re.compile(r"^[+-]?\d{1,30}(\.\d{1,30})?(/[1-9]\d{0,29})?$") + + +def rat(x): + if isinstance(x, bool): + raise Invalid("coordinates must be numbers or rational strings") + if isinstance(x, int): + return Fraction(x) + if isinstance(x, float): + if not math.isfinite(x): + raise Invalid("non-finite number") + return Fraction(x) + if isinstance(x, str) and RAT.fullmatch(x.strip()): + return Fraction(x.strip()) + raise Invalid("coordinates must be numbers or rational strings such as '1/3'") + + +def check(inst, ans): + n = inst["n"] + pts = ans.get("points") + if not isinstance(pts, list) or len(pts) != n: + raise Invalid(f"points must be a list of exactly {n} pairs") + P = [] + for q in pts: + if not isinstance(q, list) or len(q) != 2: + raise Invalid("each point is [x, y]") + P.append((rat(q[0]), rat(q[1]))) + if len(set(P)) != n: + raise Invalid("points must be distinct") + D = {} + for i in range(n): + for j in range(i + 1, n): + D[i, j] = (P[i][0] - P[j][0]) ** 2 + (P[i][1] - P[j][1]) ** 2 + for q in itertools.combinations(range(n), 4): + if len({D[a, b] for a, b in itertools.combinations(q, 2)}) < 3: + raise Invalid(f"points {list(q)} determine fewer than 3 distinct distances") + return float(len(set(D.values()))), {} diff --git a/graders/finch_flat_poly_32/__pycache__/check.cpython-314.pyc b/graders/finch_flat_poly_32/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f354e747f3d28c51a7ba48e949d81dc10ce9637 Binary files /dev/null and b/graders/finch_flat_poly_32/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_flat_poly_32/check.py b/graders/finch_flat_poly_32/check.py new file mode 100644 index 0000000000000000000000000000000000000000..2e620938175201eca84154d4e1ca8a458a1f6bb6 --- /dev/null +++ b/graders/finch_flat_poly_32/check.py @@ -0,0 +1,17 @@ +"""Erdos-Littlewood flat polynomial, n = 32 +-1 coefficients: minimize max |p| on the unit circle, +evaluated on the 16384-point FFT grid as in the upstream evaluator (Finch/EFT skydiscover +erdos_flat_polynomials_n32, Apache-2.0; grid error is below 0.002% for degree 31). Changes: the raw max +modulus is the score (upstream: sqrt(n)/max); coefficients must be the JSON integers 1/-1.""" +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + n, M = inst["n"], inst["grid"] + c = int_list(ans.get("coefficients"), n, -1, 1, "coefficients") + if any(x == 0 for x in c): + raise Invalid("coefficients must be +1 or -1") + p = np.zeros(M, dtype=np.complex128) + p[:n] = c + return float(np.max(np.abs(np.fft.fft(p)))), {} diff --git a/graders/finch_heilbronn_disk_12/__pycache__/check.cpython-314.pyc b/graders/finch_heilbronn_disk_12/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3425fd0fb25e713bc1b3d41763b2209e25ae90da Binary files /dev/null and b/graders/finch_heilbronn_disk_12/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_heilbronn_disk_12/check.py b/graders/finch_heilbronn_disk_12/check.py new file mode 100644 index 0000000000000000000000000000000000000000..352b9ad2c236456a8fe6008df319b766e30031c5 --- /dev/null +++ b/graders/finch_heilbronn_disk_12/check.py @@ -0,0 +1,23 @@ +"""Erdos #507 Heilbronn problem in the unit disk, n = 12: maximize the minimum triangle area +(Finch/EFT skydiscover erdos_507_heilbronn_disk_n12, Apache-2.0). + +Upstream bug fixed: containment used a 1e-9 slack (x^2 + y^2 <= 1 + 1e-9), letting points sit slightly +outside the disk; duplicates were detected after rounding to 12 decimals. Here containment, distinctness +and the minimum area are exact on the rational values of the floats.""" +import itertools +from fractions import Fraction + +from run import Invalid, float_matrix + + +def check(inst, ans): + n = inst["n"] + p = float_matrix(ans.get("points"), n, 2, "points") + P = [(Fraction(x), Fraction(y)) for x, y in p] + if any(x * x + y * y > 1 for x, y in P): + raise Invalid("all points must lie in the closed unit disk") + if len(set(P)) != n: + raise Invalid("points must be distinct") + m = min(abs((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])) + for a, b, c in itertools.combinations(P, 3)) / 2 + return float(m), {} diff --git a/graders/finch_isosceles_free_grid_8/__pycache__/check.cpython-314.pyc b/graders/finch_isosceles_free_grid_8/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..617a63bc2965e74ed420fb638e1647edde1f0986 Binary files /dev/null and b/graders/finch_isosceles_free_grid_8/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_isosceles_free_grid_8/check.py b/graders/finch_isosceles_free_grid_8/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1bb564fdfaf4e0d4f6319c735b06ef1361ad4a8b --- /dev/null +++ b/graders/finch_isosceles_free_grid_8/check.py @@ -0,0 +1,25 @@ +"""No isosceles triangle (including degenerate collinear ones) in the 8x8 grid (Finch/EFT skydiscover +erdos_isosceles_free_grid, Apache-2.0). Exact integer check of all triples, as upstream. Change: upstream +returned early for |S| < 3 without checking range/duplicates (fixed); points must be JSON integers.""" +import itertools + +from run import Invalid, int_list + + +def check(inst, ans): + N = inst["N"] + pts = ans.get("points") + if not isinstance(pts, list) or not 1 <= len(pts) <= N * N: + raise Invalid(f"points must be a list of 1..{N * N} integer pairs") + P = [tuple(int_list(p, 2, 0, N - 1, "point")) for p in pts] + if len(set(P)) != len(P): + raise Invalid("points must be distinct") + + def d(a, b): + return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + + for a, b, c in itertools.combinations(P, 3): + x, y, z = d(a, b), d(a, c), d(b, c) + if x == y or x == z or y == z: + raise Invalid(f"{a}, {b}, {c} form an isosceles (possibly degenerate) triangle") + return float(len(P)), {} diff --git a/graders/finch_lcm_chain_10000/__pycache__/check.cpython-314.pyc b/graders/finch_lcm_chain_10000/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bfadeac39c6f711389c7dcf9a79a24a6cff29ea Binary files /dev/null and b/graders/finch_lcm_chain_10000/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_lcm_chain_10000/check.py b/graders/finch_lcm_chain_10000/check.py new file mode 100644 index 0000000000000000000000000000000000000000..5ab38960f0d8348ee15c89ca9a46a7fbff15f87c --- /dev/null +++ b/graders/finch_lcm_chain_10000/check.py @@ -0,0 +1,21 @@ +"""Erdos #440 finite analogue: strictly increasing sequence, count indices with lcm(a_i, a_{i+1}) <= 10000 +(Finch/EFT skydiscover erdos_440_lcm_density, Apache-2.0). Exact integer check, same count as upstream +(invalid consecutive pairs are simply not counted). Changes: entries must be JSON integers (upstream +accepted integral floats), length and size are capped.""" +import math + +from run import Invalid, int_list + + +def check(inst, ans): + a = ans.get("sequence") + if not isinstance(a, list) or not 2 <= len(a) <= inst["max_len"]: + raise Invalid(f"sequence must be a list of 2..{inst['max_len']} integers") + int_list(a, None, 1, inst["max_value"], "sequence") + if any(y <= x for x, y in zip(a, a[1:])): + raise Invalid("sequence must be strictly increasing") + X = inst["x"] + cnt = sum(1 for x, y in zip(a, a[1:]) if x // math.gcd(x, y) * y <= X) + if cnt < 1: + raise Invalid("no consecutive pair has lcm <= x") + return float(cnt), {} diff --git a/graders/finch_newman_200/__pycache__/check.cpython-314.pyc b/graders/finch_newman_200/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fcefd133b9a3288344da2ef278251274baad0b0 Binary files /dev/null and b/graders/finch_newman_200/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_newman_200/check.py b/graders/finch_newman_200/check.py new file mode 100644 index 0000000000000000000000000000000000000000..82b1fa7c191ddae1c98bc318742e6cca87ed7d73 --- /dev/null +++ b/graders/finch_newman_200/check.py @@ -0,0 +1,16 @@ +"""Erdos #480 (Newman / Chung-Graham) finite version: x_1..x_200 in [0,1], maximize +g = min_{1<=n<=100} min_m n |x_{m+n} - x_m| (Finch/EFT skydiscover erdos_480_newman_density, Apache-2.0). +Ported from the upstream evaluator. Change: values must lie in [0, 1] exactly (upstream allowed a 1e-6 +slack and then clipped).""" +import numpy as np + +from run import Invalid, float_list + + +def check(inst, ans): + N, H = inst["N"], inst["n_max"] + x = np.array(float_list(ans.get("x"), N, "x")) + if np.any(x < 0) or np.any(x > 1): + raise Invalid("all values must lie in [0, 1]") + g = min(n * float(np.min(np.abs(x[n:] - x[:-n]))) for n in range(1, H + 1)) + return g, {} diff --git a/graders/finch_no4_concyclic_12/__pycache__/check.cpython-314.pyc b/graders/finch_no4_concyclic_12/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a41de04917991764921094d9b553267e5b198f53 Binary files /dev/null and b/graders/finch_no4_concyclic_12/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_no4_concyclic_12/check.py b/graders/finch_no4_concyclic_12/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d0022c55d7ca334ca057fbb7e383c8d943b2486a --- /dev/null +++ b/graders/finch_no4_concyclic_12/check.py @@ -0,0 +1,62 @@ +"""Erdos #654, n = 12: points with no four on a circle (or line); minimize max_i d(i), d(i) = number of +distinct distances from point i (Finch/EFT skydiscover erdos_654_no_four_concyclic_distances, Apache-2.0). + +Upstream bugs fixed: distance equality used a chained relative tolerance 1e-9 over sorted values (so a +chain of slightly different distances could collapse into one "distinct distance") and cocircularity a +float determinant with an absolute threshold. Here coordinates are exact rationals and both tests are +exact.""" +import itertools +import math +import re +from fractions import Fraction + +from run import Invalid + +RAT = re.compile(r"^[+-]?\d{1,30}(\.\d{1,30})?(/[1-9]\d{0,29})?$") + + +def rat(x): + if isinstance(x, bool): + raise Invalid("coordinates must be numbers or rational strings") + if isinstance(x, int): + return Fraction(x) + if isinstance(x, float): + if not math.isfinite(x): + raise Invalid("non-finite number") + return Fraction(x) + if isinstance(x, str) and RAT.fullmatch(x.strip()): + return Fraction(x.strip()) + raise Invalid("coordinates must be numbers or rational strings such as '1/3'") + + +def points(inst, ans): + n = inst["n"] + pts = ans.get("points") + if not isinstance(pts, list) or len(pts) != n: + raise Invalid(f"points must be a list of exactly {n} pairs") + P = [] + for q in pts: + if not isinstance(q, list) or len(q) != 2: + raise Invalid("each point is [x, y]") + P.append((rat(q[0]), rat(q[1]))) + if len(set(P)) != n: + raise Invalid("points must be distinct") + return P + + +def cocircular(a, b, c, d): + m = [(x - a[0], y - a[1]) for x, y in (b, c, d)] + m = [(x, y, x * x + y * y) for x, y in m] + return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) + - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])) == 0 + + +def check(inst, ans): + P = points(inst, ans) + for q in itertools.combinations(P, 4): + if cocircular(*q): + raise Invalid(f"four points {[(str(x), str(y)) for x, y in q]} lie on a common circle or line") + n = len(P) + d = [len({(P[i][0] - P[j][0]) ** 2 + (P[i][1] - P[j][1]) ** 2 for j in range(n) if j != i}) for i in range(n)] + return float(max(d)), {"d": d} diff --git a/graders/finch_sidon_pair_100/__pycache__/check.cpython-314.pyc b/graders/finch_sidon_pair_100/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3abceab8418e2bad3baf68768cb8bcbcdb96182 Binary files /dev/null and b/graders/finch_sidon_pair_100/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_sidon_pair_100/check.py b/graders/finch_sidon_pair_100/check.py new file mode 100644 index 0000000000000000000000000000000000000000..62e6b728e79ca222aa21046cb95dd2fec81db08c --- /dev/null +++ b/graders/finch_sidon_pair_100/check.py @@ -0,0 +1,35 @@ +"""Erdos #43: Sidon sets A, B in {1..100} with (A-A) and (B-B) meeting only in 0; maximize +C(|A|,2) + C(|B|,2) (Finch/EFT skydiscover erdos_43_sidon_pair, Apache-2.0). Exact integer check, as +upstream. Change: entries must be JSON integers (upstream cast with int()).""" +from run import Invalid, int_list + + +def _sidon(S): + seen = set() + for i in range(len(S)): + for j in range(i, len(S)): + s = S[i] + S[j] + if s in seen: + return False + seen.add(s) + return True + + +def check(inst, ans): + N = inst["N"] + A = int_list(ans.get("A"), None, 1, N, "A") + B = int_list(ans.get("B"), None, 1, N, "B") + if len(A) > N or len(B) > N: + raise Invalid("sets too large") + if len(set(A)) != len(A) or len(set(B)) != len(B): + raise Invalid("elements must be distinct within each set") + if not _sidon(A): + raise Invalid("A is not a Sidon set") + if not _sidon(B): + raise Invalid("B is not a Sidon set") + dA = {a - b for a in A for b in A if a != b} + dB = {a - b for a in B for b in B if a != b} + if dA & dB: + raise Invalid(f"(A-A) and (B-B) share the nonzero difference {min(abs(d) for d in dA & dB)}") + na, nb = len(A), len(B) + return float(na * (na - 1) // 2 + nb * (nb - 1) // 2), {"size_A": na, "size_B": nb} diff --git a/graders/finch_sidon_set_121/__pycache__/check.cpython-314.pyc b/graders/finch_sidon_set_121/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff5f7a3e27000ace1ec5f668f89027e5802dc0ed Binary files /dev/null and b/graders/finch_sidon_set_121/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_sidon_set_121/check.py b/graders/finch_sidon_set_121/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1de835ec9dc6dee0499e53d1c31cae499811a8ac --- /dev/null +++ b/graders/finch_sidon_set_121/check.py @@ -0,0 +1,22 @@ +"""Largest Sidon set in {0,...,120} (Finch/EFT skydiscover erdos_difference_bases_N121, Apache-2.0). +Exact integer check (all pairwise sums a+a', a<=a', distinct), as upstream. Change: entries must be JSON +integers (upstream cast with int()).""" +from run import Invalid, int_list + + +def check(inst, ans): + a = ans.get("set") + N = inst["N"] + if not isinstance(a, list) or not 1 <= len(a) <= N: + raise Invalid(f"set must be a list of 1..{N} integers") + int_list(a, None, 0, N - 1, "set") + if len(set(a)) != len(a): + raise Invalid("elements must be distinct") + sums = set() + for i in range(len(a)): + for j in range(i, len(a)): + s = a[i] + a[j] + if s in sums: + raise Invalid(f"not a Sidon set: the sum {s} occurs twice") + sums.add(s) + return float(len(a)), {} diff --git a/graders/finch_square_packing_12/__pycache__/check.cpython-314.pyc b/graders/finch_square_packing_12/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75ece94848f2fa28f3ee225691576eaf4410dd26 Binary files /dev/null and b/graders/finch_square_packing_12/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_square_packing_12/check.py b/graders/finch_square_packing_12/check.py new file mode 100644 index 0000000000000000000000000000000000000000..89efc6680e2ea8158a06da5b036a6cd781d684be --- /dev/null +++ b/graders/finch_square_packing_12/check.py @@ -0,0 +1,52 @@ +"""Erdos #106 square packing, n = 12 axis-parallel squares in [0,1]^2, maximize the sum of side lengths +(Finch/EFT skydiscover erdos_106_square_packing, Apache-2.0). + +Upstream bug fixed: containment and overlap were checked with an absolute tolerance 1e-9 (overlap area up +to 1e-9 per pair, 1e-9 slack at the border), so slightly enlarged squares could beat the conjectured +optimum 10/3. Here everything is exact rational arithmetic; touching boundaries are allowed.""" +import math +import re +from fractions import Fraction + +from run import Invalid + +RAT = re.compile(r"^[+-]?\d{1,30}(\.\d{1,30})?(/[1-9]\d{0,29})?$") + + +def rat(x): + if isinstance(x, bool): + raise Invalid("coordinates must be numbers or rational strings") + if isinstance(x, int): + return Fraction(x) + if isinstance(x, float): + if not math.isfinite(x): + raise Invalid("non-finite number") + return Fraction(x) + if isinstance(x, str) and RAT.fullmatch(x.strip()): + return Fraction(x.strip()) + raise Invalid("coordinates must be numbers or rational strings such as '1/3'") + + +def check(inst, ans): + n = inst["n"] + sq = ans.get("squares") + if not isinstance(sq, list) or len(sq) != n: + raise Invalid(f"squares must be a list of exactly {n} triples") + S = [] + for t in sq: + if not isinstance(t, list) or len(t) != 3: + raise Invalid("each square is [x, y, s]") + x, y, s = (rat(v) for v in t) + if s <= 0: + raise Invalid("side lengths must be positive") + if x < 0 or y < 0 or x + s > 1 or y + s > 1: + raise Invalid("a square is not inside the unit square") + S.append((x, y, s)) + for i in range(n): + x1, y1, s1 = S[i] + for j in range(i + 1, n): + x2, y2, s2 = S[j] + if min(x1 + s1, x2 + s2) > max(x1, x2) and min(y1 + s1, y2 + s2) > max(y1, y2): + raise Invalid(f"squares {i} and {j} overlap") + total = sum(s for _, _, s in S) + return float(total), {"exact": str(total)} diff --git a/graders/finch_udg_girth_30/__pycache__/check.cpython-314.pyc b/graders/finch_udg_girth_30/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..100d830244cf376eb6cbc72c7b4fc831616c1f28 Binary files /dev/null and b/graders/finch_udg_girth_30/__pycache__/check.cpython-314.pyc differ diff --git a/graders/finch_udg_girth_30/check.py b/graders/finch_udg_girth_30/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d13a1b2900cd4570249465104956f57af9929f7e --- /dev/null +++ b/graders/finch_udg_girth_30/check.py @@ -0,0 +1,198 @@ +"""Erdos #705: 4-chromatic unit-distance graph on 30 points with large girth (Finch/EFT skydiscover +erdos_705_unit_distance_high_girth, Apache-2.0). + +Upstream bugs fixed: (1) edges were |d - 1| < 1e-6 in float64, so near-unit "fake" edges produced graphs +that are not unit-distance graphs; here coordinates are exact real algebraic numbers (integers, rationals, ++ - * /, integer powers, sqrt; or JSON numbers taken at their exact binary value) and a pair is an edge +iff its distance is exactly 1 (numerical 60-digit screen, then an exact minimal-polynomial test); +(2) non-3-colourability was decided by a backtracking search with a 5 s wall-clock deadline (result +depended on machine speed); here the search is exact (DSatur branch and bound, no deadline).""" +import math +import re +from collections import deque + +import sympy as sp + +from run import Invalid + +TOK = re.compile(r"\s*(?:(\d+(?:\.\d+)?)|(sqrt)|([-+*/^()]))") +MAXLEN, MAXSQRT = 160, 3 + + +def _parse(s): + if not isinstance(s, str) or not 1 <= len(s) <= MAXLEN: + raise Invalid(f"coordinate expressions must be strings of 1..{MAXLEN} characters") + toks, pos = [], 0 + s = s.strip() + while pos < len(s): + m = TOK.match(s, pos) + if not m or m.end() == pos: + raise Invalid(f"cannot parse coordinate {s!r}") + toks.append(m.group(1) and ("num", m.group(1)) or m.group(2) and ("sqrt", None) or ("op", m.group(3))) + pos = m.end() + toks.append(("end", None)) + i = [0] + nsqrt = [0] + + def peek(): + return toks[i[0]] + + def take(kind, val=None): + t = toks[i[0]] + if t[0] != kind or (val is not None and t[1] != val): + raise Invalid(f"cannot parse coordinate {s!r}") + i[0] += 1 + return t + + def expr(): + v = term() + while peek() in (("op", "+"), ("op", "-")): + op = take("op")[1] + w = term() + v = v + w if op == "+" else v - w + return v + + def term(): + v = factor() + while peek() in (("op", "*"), ("op", "/")): + op = take("op")[1] + w = factor() + if op == "/": + if w == 0: + raise Invalid("division by zero") + v = v / w + else: + v = v * w + return v + + def factor(): + if peek() in (("op", "-"), ("op", "+")): + op = take("op")[1] + v = factor() + return -v if op == "-" else v + v = atom() + if peek() == ("op", "^"): + take("op", "^") + t = take("num")[1] + if "." in t or int(t) > 8: + raise Invalid("exponents must be integers 0..8") + v = v ** int(t) + return v + + def atom(): + t = peek() + if t[0] == "num": + take("num") + return sp.Rational(t[1]) + if t[0] == "sqrt": + take("sqrt") + nsqrt[0] += 1 + if nsqrt[0] > MAXSQRT: + raise Invalid(f"at most {MAXSQRT} sqrt per coordinate") + take("op", "(") + a = expr() + take("op", ")") + av = sp.N(a, 60) + if av < -sp.Rational(1, 10 ** 40): + raise Invalid("sqrt of a negative number") + if abs(av) < sp.Rational(1, 10 ** 40) and _is_zero(a): + return sp.Integer(0) + if av < 0: + raise Invalid("sqrt of a negative number") + return sp.sqrt(a) + if t == ("op", "("): + take("op", "(") + v = expr() + take("op", ")") + return v + raise Invalid(f"cannot parse coordinate {s!r}") + + v = expr() + take("end") + return v + + +def _is_zero(e): + x = sp.Symbol("x") + return sp.minimal_polynomial(e, x) == x + + +def _coord(c): + if isinstance(c, bool): + raise Invalid("coordinates must be numbers or expression strings") + if isinstance(c, int): + return sp.Integer(c) + if isinstance(c, float): + if not math.isfinite(c): + raise Invalid("non-finite coordinate") + return sp.Rational(c) + return _parse(c) + + +def _three_colourable(adj): + n = len(adj) + col = [-1] * n + + def rec(k): + if k == n: + return True + # DSatur: most constrained uncoloured vertex + v = max((u for u in range(n) if col[u] < 0), + key=lambda u: (len({col[w] for w in adj[u] if col[w] >= 0}), len(adj[u]))) + used = {col[w] for w in adj[v] if col[w] >= 0} + for c in range(3): + if c not in used: + col[v] = c + if rec(k + 1): + return True + col[v] = -1 + return False + + return rec(0) + + +def _girth(adj): + n, best = len(adj), math.inf + for s in range(n): + dist, par = [-1] * n, [-1] * n + dist[s] = 0 + q = deque([s]) + while q: + u = q.popleft() + for v in adj[u]: + if dist[v] < 0: + dist[v], par[v] = dist[u] + 1, u + q.append(v) + elif par[u] != v: + best = min(best, dist[u] + dist[v] + 1) + return best + + +def check(inst, ans): + n = inst["n"] + pts = ans.get("points") + if not isinstance(pts, list) or len(pts) != n: + raise Invalid(f"points must be a list of exactly {n} pairs") + P = [] + for p in pts: + if not isinstance(p, list) or len(p) != 2: + raise Invalid("each point is [x, y]") + P.append((_coord(p[0]), _coord(p[1]))) + num = [(sp.N(x, 60), sp.N(y, 60)) for x, y in P] + adj = [set() for _ in range(n)] + tiny = sp.Rational(1, 10 ** 25) + for i in range(n): + for j in range(i + 1, n): + d2n = (num[i][0] - num[j][0]) ** 2 + (num[i][1] - num[j][1]) ** 2 + if abs(d2n) < tiny and _is_zero((P[i][0] - P[j][0]) ** 2 + (P[i][1] - P[j][1]) ** 2): + raise Invalid(f"points {i} and {j} coincide") + if abs(d2n - 1) < tiny and _is_zero(sp.expand((P[i][0] - P[j][0]) ** 2 + (P[i][1] - P[j][1]) ** 2 - 1)): + adj[i].add(j) + adj[j].add(i) + edges = sum(len(a) for a in adj) // 2 + if edges == 0: + raise Invalid("the unit-distance graph has no edges") + if _three_colourable(adj): + raise Invalid("the unit-distance graph is 3-colourable (chromatic number <= 3)") + g = _girth(adj) + return float(g), {"edges": edges} diff --git a/graders/fs_admissible_set/__pycache__/check.cpython-314.pyc b/graders/fs_admissible_set/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0925ddb1151910bfb21c4b7c2d888a823ac24ea7 Binary files /dev/null and b/graders/fs_admissible_set/__pycache__/check.cpython-314.pyc differ diff --git a/graders/fs_admissible_set/check.py b/graders/fs_admissible_set/check.py new file mode 100644 index 0000000000000000000000000000000000000000..6eaa074538d9d4504dfa5d25e028ba7b477ba196 --- /dev/null +++ b/graders/fs_admissible_set/check.py @@ -0,0 +1,56 @@ +"""Constant-weight admissible set A(n, w) (FunSearch / Tyrrell 2022). Score = number of vectors. + +A subset of {0,1,2}^n is admissible (with weight w) if every vector has exactly w nonzero entries, no two +vectors have the same support, and every three distinct vectors u, v, x have a coordinate i where the +multiset {u_i, v_i, x_i} is {0,0,1}, {0,0,2} or {0,1,2}. + +Triple check: for a pair (u, v) the set of "blocking" third vectors is a product set (per coordinate the +values that do NOT complete a good multiset; table from the FunSearch skeleton's block_children). We AND +per-coordinate bitsets over the answer's vectors, so a check is O(N^2 * n * N/64) word ops (3003 vectors: +~3 s). Given constant weight and distinct supports, u and v are never in their own blocking set. +""" +import math + +import numpy as np + +from run import Invalid, int_list + +INVALID = {(0, 0): (0,), (0, 1): (1,), (0, 2): (2,), (1, 0): (1,), (1, 1): (0, 1, 2), (1, 2): (1, 2), + (2, 0): (2,), (2, 1): (1, 2), (2, 2): (0, 1, 2)} + + +def check(inst, ans): + n, w = inst["n"], inst["w"] + vecs = ans.get("vectors") + if not isinstance(vecs, list) or not vecs or len(vecs) > math.comb(n, w): + raise Invalid(f"vectors must be a non-empty list of at most C({n},{w}) vectors") + sups = set() + for v in vecs: + int_list(v, n, 0, 2, "vector") + s = tuple(i for i in range(n) if v[i]) + if len(s) != w: + raise Invalid(f"vector {v} does not have weight {w}") + if s in sups: + raise Invalid(f"two vectors share the support {list(s)}") + sups.add(s) + A = np.array(vecs, dtype=np.int64) + N = len(A) + W = (N + 63) // 64 + + def pack(mask): + b = np.packbits(mask, bitorder="little") + return np.concatenate([b, np.zeros(W * 8 - len(b), np.uint8)]).view(np.uint64) + + U = np.zeros((n, 3, 3, W), np.uint64) + for i in range(n): + for (p, q), vals in INVALID.items(): + U[i, p, q] = pack(np.isin(A[:, i], vals)) + for a in range(N - 1): + B = A[a + 1:] + acc = U[0, A[a, 0]][B[:, 0]] + for i in range(1, n): + acc &= U[i, A[a, i]][B[:, i]] + if acc.any(): + b = a + 1 + int(np.nonzero(acc.any(axis=1))[0][0]) + raise Invalid(f"vectors {vecs[a]} and {vecs[b]} form a bad triple with another vector") + return float(N), {"size": N} diff --git a/graders/fs_cap_set/__pycache__/check.cpython-314.pyc b/graders/fs_cap_set/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ccf15cd9edb45849163b3defada503411bcb240 Binary files /dev/null and b/graders/fs_cap_set/__pycache__/check.cpython-314.pyc differ diff --git a/graders/fs_cap_set/check.py b/graders/fs_cap_set/check.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b4309ffc9678bb5a2f8e30718868e5c68b1874 --- /dev/null +++ b/graders/fs_cap_set/check.py @@ -0,0 +1,21 @@ +"""Cap set in F_3^n: no three distinct vectors x, y, z with x + y + z = 0 (mod 3). Score = size.""" +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + vecs = ans.get("vectors") + if not isinstance(vecs, list) or not vecs or len(vecs) > 3 ** n: + raise Invalid(f"vectors must be a non-empty list of at most 3^{n} vectors") + pts = [tuple(int_list(v, n, 0, 2, "vector")) for v in vecs] + if len(set(pts)) != len(pts): + raise Invalid("duplicate vectors") + # incremental check (as in the FunSearch notebook's is_cap_set): a point may not be the third point of a + # line through two earlier points; O(c^2 n) and stops at the first violation + blocked = set() + for i, p in enumerate(pts): + if p in blocked: + raise Invalid(f"vector {list(p)} completes a line with two earlier vectors") + for q in pts[:i]: + blocked.add(tuple((-a - b) % 3 for a, b in zip(p, q))) + return float(len(pts)), {"size": len(pts)} diff --git a/graders/fs_cycle_independent_set/__pycache__/check.cpython-314.pyc b/graders/fs_cycle_independent_set/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2375d7ce817a00bf2fb0cb12047b58f47a1842ae Binary files /dev/null and b/graders/fs_cycle_independent_set/__pycache__/check.cpython-314.pyc differ diff --git a/graders/fs_cycle_independent_set/check.py b/graders/fs_cycle_independent_set/check.py new file mode 100644 index 0000000000000000000000000000000000000000..18467766f4b39df02d00aad7ae384bd83e857320 --- /dev/null +++ b/graders/fs_cycle_independent_set/check.py @@ -0,0 +1,38 @@ +"""Independent set in the strong product C_m^{⊠n}. Score = size. + +Two distinct vertices x, y of C_m^{⊠n} (n-tuples over Z_m) are adjacent iff x_i - y_i ∈ {-1, 0, 1} (mod m) +for every i. Check: mark the answer in a boolean table of size m^n and look up all 3^n - 1 neighbours of +every answer vertex (vectorised; 26244 vertices of C_9^7 take ~1 s). +""" +import itertools + +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + m, n = inst["m"], inst["n"] + vecs = ans.get("vertices") + # alpha(C_m^{⊠n}) <= (m/2)^n (fractional independence number is multiplicative under strong products), + # so longer lists are invalid; rejecting them early also bounds grading time + if not isinstance(vecs, list) or not vecs or 2 ** n * len(vecs) > m ** n: + raise Invalid(f"vertices must be a non-empty list of at most ({m}/2)^{n} tuples") + for v in vecs: + int_list(v, n, 0, m - 1, "vertex") + A = np.array(vecs, dtype=np.int64) + pw = m ** np.arange(n - 1, -1, -1, dtype=np.int64) + codes = A @ pw + if len(np.unique(codes)) != len(codes): + raise Invalid("duplicate vertices") + table = np.zeros(m ** n, bool) + table[codes] = True + for off in itertools.product((-1, 0, 1), repeat=n): + if not any(off): + continue + nb = ((A + np.array(off)) % m) @ pw + hit = table[nb] + if hit.any(): + k = int(np.nonzero(hit)[0][0]) + raise Invalid(f"vertices {vecs[k]} and {[(x + o) % m for x, o in zip(vecs[k], off)]} are adjacent") + return float(len(vecs)), {"size": len(vecs)} diff --git a/graders/mc_all_interval/__pycache__/check.cpython-314.pyc b/graders/mc_all_interval/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5ce06f8182faa23d4f6227be59db6266fc43a8b Binary files /dev/null and b/graders/mc_all_interval/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_all_interval/check.py b/graders/mc_all_interval/check.py new file mode 100644 index 0000000000000000000000000000000000000000..2e39eec264b6422a47e35921b8cdbe1fa1748307 --- /dev/null +++ b/graders/mc_all_interval/check.py @@ -0,0 +1,17 @@ +"""All-interval series of size n (MathConstraint all_interval, CC-BY-4.0). Accepts any valid series.""" +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + x = int_list(ans.get("x"), n, 0, n - 1, "x") + if sorted(x) != list(range(n)): + raise Invalid("x is not a permutation of 0..n-1") + d = [abs(x[i + 1] - x[i]) for i in range(n - 1)] + if sorted(d) != list(range(1, n)): + raise Invalid("consecutive differences are not a permutation of 1..n-1") + seqs = {"x": x, "d": d} + for name, i, v in inst.get("fixed", []): + if seqs[name][i] != v: + raise Invalid(f"fixed value {name}[{i}] = {v} not respected") + return None, {} diff --git a/graders/mc_antimagic_square/__pycache__/check.cpython-314.pyc b/graders/mc_antimagic_square/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b525526db7194357e8a094a9945a37b7052bc6ec Binary files /dev/null and b/graders/mc_antimagic_square/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_antimagic_square/check.py b/graders/mc_antimagic_square/check.py new file mode 100644 index 0000000000000000000000000000000000000000..9c86a40bef203632c61a8ba237cae03eb53251a6 --- /dev/null +++ b/graders/mc_antimagic_square/check.py @@ -0,0 +1,20 @@ +"""Antimagic square of order n (MathConstraint antimagic_square, CC-BY-4.0): the numbers 1..n^2 in an +n x n grid whose 2n+2 line sums (rows, columns, both main diagonals) are 2n+2 consecutive integers.""" +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + g = ans.get("grid") + if not isinstance(g, list) or len(g) != n: + raise Invalid(f"grid must be a list of {n} rows") + g = [int_list(r, n, 1, n * n, "grid row") for r in g] + flat = [v for r in g for v in r] + if sorted(flat) != list(range(1, n * n + 1)): + raise Invalid(f"grid must contain each of 1..{n * n} exactly once") + sums = [sum(r) for r in g] + [sum(g[i][j] for i in range(n)) for j in range(n)] + sums += [sum(g[i][i] for i in range(n)), sum(g[i][n - 1 - i] for i in range(n))] + s = sorted(sums) + if any(s[i + 1] != s[i] + 1 for i in range(len(s) - 1)): + raise Invalid(f"line sums {sums} are not {2 * n + 2} consecutive integers") + return None, {} diff --git a/graders/mc_bibd/__pycache__/check.cpython-314.pyc b/graders/mc_bibd/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be3bfdddf77076217fd6ce2192df1ded080486ee Binary files /dev/null and b/graders/mc_bibd/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_bibd/check.py b/graders/mc_bibd/check.py new file mode 100644 index 0000000000000000000000000000000000000000..c4b5da62477026f27ff9869fe33602fcc41e2ea9 --- /dev/null +++ b/graders/mc_bibd/check.py @@ -0,0 +1,25 @@ +"""Balanced incomplete block design BIBD(v, k, lambda) (MathConstraint bibd, CC-BY-4.0). +Answer = list of b blocks; every block is a k-subset of {0..v-1}, every pair of points lies in exactly +lambda blocks (which forces every point to lie in r blocks). Repeated blocks are allowed, as upstream +(its 0/1 incidence-matrix model does not forbid equal columns).""" +import itertools + +from run import Invalid, int_list + + +def check(inst, ans): + v, k, lam, b = inst["v"], inst["k"], inst["lambda"], inst["b"] + blocks = ans.get("blocks") + if not isinstance(blocks, list) or len(blocks) != b: + raise Invalid(f"blocks must be a list of exactly {b} blocks") + pair = {} + for B in blocks: + B = int_list(B, k, 0, v - 1, "block") + if len(set(B)) != k: + raise Invalid("a block contains a repeated point") + for p in itertools.combinations(sorted(B), 2): + pair[p] = pair.get(p, 0) + 1 + for p in itertools.combinations(range(v), 2): + if pair.get(p, 0) != lam: + raise Invalid(f"points {p} lie together in {pair.get(p, 0)} blocks, need {lam}") + return None, {} diff --git a/graders/mc_costas_array/__pycache__/check.cpython-314.pyc b/graders/mc_costas_array/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64ff0846da0e73f2bbfc35794d290e50bb3cde9e Binary files /dev/null and b/graders/mc_costas_array/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_costas_array/check.py b/graders/mc_costas_array/check.py new file mode 100644 index 0000000000000000000000000000000000000000..c86323a5b639b23787ecd4d5f358b986bbd91b6c --- /dev/null +++ b/graders/mc_costas_array/check.py @@ -0,0 +1,22 @@ +"""Costas array of order n (MathConstraint costas_array, CC-BY-4.0). Accepts any valid array. +Adapted from pilot/grader.py check_costas; adds the optional fixed entries (upstream partial assignment).""" +import itertools + +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + x = int_list(ans.get("x"), n, 0, n - 1, "x") + if sorted(x) != list(range(n)): + raise Invalid("x is not a permutation of 0..n-1") + for name, i, v in inst.get("fixed", []): + if x[i] != v: + raise Invalid(f"fixed value {name}[{i}] = {v} not respected") + vecs = set() + for i, j in itertools.combinations(range(n), 2): + d = (j - i, x[j] - x[i]) + if d in vecs: + raise Invalid(f"repeated displacement vector {d}") + vecs.add(d) + return None, {} diff --git a/graders/mc_debruijn/__pycache__/check.cpython-314.pyc b/graders/mc_debruijn/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f91211270309cc4cf6f87ad41f2cde8cf8b77ab5 Binary files /dev/null and b/graders/mc_debruijn/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_debruijn/check.py b/graders/mc_debruijn/check.py new file mode 100644 index 0000000000000000000000000000000000000000..c9d6f0177d2b3bde8306d74939ee9704c1501a23 --- /dev/null +++ b/graders/mc_debruijn/check.py @@ -0,0 +1,15 @@ +"""De Bruijn sequence B(b, n) (MathConstraint debruijn, CC-BY-4.0). Accepts any valid cyclic sequence.""" +from run import Invalid, int_list + + +def check(inst, ans): + b, n = inst["b"], inst["n"] + m = b ** n + x = int_list(ans.get("seq"), m, 0, b - 1, "seq") + seen = set() + for i in range(m): + w = tuple(x[(i + k) % m] for k in range(n)) + if w in seen: + raise Invalid(f"window {w} occurs twice") + seen.add(w) + return None, {} diff --git a/graders/mc_golomb/__pycache__/check.cpython-314.pyc b/graders/mc_golomb/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d353aed4cc38fb2cab4c4228e3233946da0decda Binary files /dev/null and b/graders/mc_golomb/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_golomb/check.py b/graders/mc_golomb/check.py new file mode 100644 index 0000000000000000000000000000000000000000..84aedd6e33fee7271543bfa49ab05128e23c31ee --- /dev/null +++ b/graders/mc_golomb/check.py @@ -0,0 +1,27 @@ +"""Golomb ruler with n marks and length <= L (MathConstraint golomb, CC-BY-4.0, reframed as a decision +problem with the target length stated). Accepts any valid ruler. +Upstream note: the upstream prompt states no length bound and its verifier re-solves the optimisation +model with the marks fixed, which returns OPTIMUM for any Golomb ruler, so any ruler (e.g. 0,1,3,7,15,..) +was accepted. Here the length bound is part of the instance and enforced.""" +import itertools + +from run import Invalid, int_list + + +def check(inst, ans): + n, L = inst["n"], inst["max_length"] + a = int_list(ans.get("marks"), n, 0, L, "marks") + if a[0] != 0: + raise Invalid("first mark must be 0") + if any(a[i] >= a[i + 1] for i in range(n - 1)): + raise Invalid("marks must be strictly increasing") + for name, i, v in inst.get("fixed", []): + if a[i] != v: + raise Invalid(f"fixed value {name}[{i}] = {v} not respected") + seen = set() + for i, j in itertools.combinations(range(n), 2): + d = a[j] - a[i] + if d in seen: + raise Invalid(f"difference {d} occurs twice") + seen.add(d) + return None, {"length": a[-1]} diff --git a/graders/mc_graceful_graph/__pycache__/check.cpython-314.pyc b/graders/mc_graceful_graph/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a23d3377586fa856729ec6507b3c952026f6674b Binary files /dev/null and b/graders/mc_graceful_graph/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_graceful_graph/check.py b/graders/mc_graceful_graph/check.py new file mode 100644 index 0000000000000000000000000000000000000000..f4d33af1d63c0495c3b32d34db6ae10f0fb45923 --- /dev/null +++ b/graders/mc_graceful_graph/check.py @@ -0,0 +1,19 @@ +"""Graceful labelling of K_k x P_p (MathConstraint graceful_graph, CC-BY-4.0): distinct vertex labels in +0..m (m = number of edges) whose edge differences |l(u) - l(v)| are all distinct.""" +from run import Invalid, int_list + + +def check(inst, ans): + nv, edges = inst["num_vertices"], inst["edges"] + m = len(edges) + x = int_list(ans.get("labels"), nv, 0, m, "labels") + if len(set(x)) != nv: + raise Invalid("vertex labels must be distinct") + d = [abs(x[u] - x[v]) for u, v in edges] + if len(set(d)) != m: + raise Invalid("edge labels are not distinct") + seqs = {"labels": x, "d": d} + for name, i, v in inst.get("fixed", []): + if seqs[name][i] != v: + raise Invalid(f"fixed value {name}[{i}] = {v} not respected") + return None, {} diff --git a/graders/mc_graph_k_coloring/__pycache__/check.cpython-314.pyc b/graders/mc_graph_k_coloring/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..672e0657d4079c39607918294db3c4c975f777eb Binary files /dev/null and b/graders/mc_graph_k_coloring/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_graph_k_coloring/check.py b/graders/mc_graph_k_coloring/check.py new file mode 100644 index 0000000000000000000000000000000000000000..2b5f38cd0c22ac1b4ba37c0d3ff0a34635f08854 --- /dev/null +++ b/graders/mc_graph_k_coloring/check.py @@ -0,0 +1,11 @@ +"""Proper k-colouring of a given graph (MathConstraint graph_k_coloring, CC-BY-4.0). Any valid colouring.""" +from run import Invalid, int_list + + +def check(inst, ans): + n, k = inst["n"], inst["k"] + c = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in inst["edges"]: + if c[u] == c[v]: + raise Invalid(f"edge ({u},{v}) is monochromatic") + return None, {} diff --git a/graders/mc_hadamard/__pycache__/check.cpython-314.pyc b/graders/mc_hadamard/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9940faf38a8f9a81119ba7c18a881ed1fc1b7f71 Binary files /dev/null and b/graders/mc_hadamard/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_hadamard/check.py b/graders/mc_hadamard/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fc4b93160fd7473dd14935db9d712e52abdd00c2 --- /dev/null +++ b/graders/mc_hadamard/check.py @@ -0,0 +1,18 @@ +"""Legendre pair of odd length n (MathConstraint hadamard, CC-BY-4.0): x, y in {-1,+1}^n with +sum(x) = sum(y) = 1 and PAF_x(k) + PAF_y(k) = -2 for k = 1..(n-1)/2 (periodic autocorrelation).""" +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + x = int_list(ans.get("x"), n, -1, 1, "x") + y = int_list(ans.get("y"), n, -1, 1, "y") + if 0 in x or 0 in y: + raise Invalid("entries must be -1 or +1") + if sum(x) != 1 or sum(y) != 1: + raise Invalid("sum(x) and sum(y) must both equal 1") + for k in range(1, (n - 1) // 2 + 1): + p = sum(x[i] * x[(i + k) % n] for i in range(n)) + sum(y[i] * y[(i + k) % n] for i in range(n)) + if p != -2: + raise Invalid(f"PAF_x({k}) + PAF_y({k}) = {p}, need -2") + return None, {} diff --git a/graders/mc_langford/__pycache__/check.cpython-314.pyc b/graders/mc_langford/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87c0846240f0930d18373343ffded855b2093453 Binary files /dev/null and b/graders/mc_langford/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_langford/check.py b/graders/mc_langford/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4672d7eacf321991933cb280d6c940f1c4a67935 --- /dev/null +++ b/graders/mc_langford/check.py @@ -0,0 +1,17 @@ +"""Langford sequence L(2, n) (MathConstraint langford, CC-BY-4.0). Accepts any valid sequence.""" +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + seq = int_list(ans.get("seq"), 2 * n, 1, n, "seq") + for v in range(1, n + 1): + pos = [i for i, s in enumerate(seq) if s == v] + if len(pos) != 2: + raise Invalid(f"value {v} occurs {len(pos)} times (need exactly 2)") + if pos[1] - pos[0] != v + 1: + raise Invalid(f"the two copies of {v} are {pos[1] - pos[0]} positions apart (need {v + 1})") + for name, i, v in inst.get("fixed", []): + if seq[i] != v: + raise Invalid(f"fixed value {name}[{i}] = {v} not respected") + return None, {} diff --git a/graders/mc_low_autocorrelation/__pycache__/check.cpython-314.pyc b/graders/mc_low_autocorrelation/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fe3072b8bf62f295ba49504a6e31f1a46608379 Binary files /dev/null and b/graders/mc_low_autocorrelation/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_low_autocorrelation/check.py b/graders/mc_low_autocorrelation/check.py new file mode 100644 index 0000000000000000000000000000000000000000..8456f7b1c0ff0c9fb4bc9ae5a49074c8afa7d1aa --- /dev/null +++ b/graders/mc_low_autocorrelation/check.py @@ -0,0 +1,20 @@ +"""+-1 sequence of length n with aperiodic autocorrelation energy sum_k C_k^2 <= bound +(MathConstraint low_autocorrelation, CC-BY-4.0). Exact integer arithmetic.""" +from run import Invalid, int_list + + +def check(inst, ans): + n, bound = inst["n"], inst["bound"] + s = int_list(ans.get("seq"), n, -1, 1, "seq") + if any(v == 0 for v in s): + raise Invalid("entries must be -1 or +1") + c = [sum(s[i] * s[i + k] for i in range(n - k)) for k in range(1, n)] + e = sum(v * v for v in c) + # fixed values: seq[i] or c[k] (c[k] is the autocorrelation at shift k+1, as upstream) + seqs = {"seq": s, "c": c} + for name, i, v in inst.get("fixed", []): + if seqs[name][i] != v: + raise Invalid(f"fixed value {name}[{i}] = {v} not respected") + if e > bound: + raise Invalid(f"energy {e} exceeds the bound {bound}") + return None, {"energy": e} diff --git a/graders/mc_magic_sequence/__pycache__/check.cpython-314.pyc b/graders/mc_magic_sequence/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba4aff5990599a5fdd80e63a5856a8946c162cba Binary files /dev/null and b/graders/mc_magic_sequence/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_magic_sequence/check.py b/graders/mc_magic_sequence/check.py new file mode 100644 index 0000000000000000000000000000000000000000..27f636ddd6cfe523924ae01c6b9f37ee392f0332 --- /dev/null +++ b/graders/mc_magic_sequence/check.py @@ -0,0 +1,18 @@ +"""Magic sequence of length n: x[i] = number of occurrences of i in x (MathConstraint magic_sequence, +CC-BY-4.0). The property itself is checked (no stored answer).""" +from collections import Counter + +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + x = int_list(ans.get("x"), n, 0, n, "x") + cnt = Counter(x) + for i in range(n): + if x[i] != cnt.get(i, 0): + raise Invalid(f"x[{i}] = {x[i]} but {i} occurs {cnt.get(i, 0)} times") + for name, i, v in inst.get("fixed", []): + if x[i] != v: + raise Invalid(f"fixed value {name}[{i}] = {v} not respected") + return None, {} diff --git a/graders/mc_max_clique/__pycache__/check.cpython-314.pyc b/graders/mc_max_clique/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d278b3891a54f37087b16cf5a7476b0080beb14 Binary files /dev/null and b/graders/mc_max_clique/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_max_clique/check.py b/graders/mc_max_clique/check.py new file mode 100644 index 0000000000000000000000000000000000000000..e3f70dbd5b155a3514c2102aa4ad460201495210 --- /dev/null +++ b/graders/mc_max_clique/check.py @@ -0,0 +1,18 @@ +"""Clique of size >= k in a given graph (MathConstraint max_clique decision version, CC-BY-4.0).""" +import itertools + +from run import Invalid, int_list + + +def check(inst, ans): + n, k = inst["n"], inst["k"] + S = int_list(ans.get("clique"), None, 0, n - 1, "clique") + if len(set(S)) != len(S): + raise Invalid("repeated vertex") + if len(S) < k: + raise Invalid(f"clique has {len(S)} vertices, need at least {k}") + E = {(u, v) for u, v in inst["edges"]} + for u, v in itertools.combinations(sorted(S), 2): + if (u, v) not in E: + raise Invalid(f"vertices {u} and {v} are not adjacent") + return None, {"size": len(S)} diff --git a/graders/mc_max_independent_set/__pycache__/check.cpython-314.pyc b/graders/mc_max_independent_set/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ade7a344a9cbb469ad006b4e82ba718a04b01b25 Binary files /dev/null and b/graders/mc_max_independent_set/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_max_independent_set/check.py b/graders/mc_max_independent_set/check.py new file mode 100644 index 0000000000000000000000000000000000000000..adce413e8578d996549583b990e4ff559f38ed41 --- /dev/null +++ b/graders/mc_max_independent_set/check.py @@ -0,0 +1,18 @@ +"""Independent set of size >= k in a given graph (MathConstraint max_independent_set, CC-BY-4.0).""" +import itertools + +from run import Invalid, int_list + + +def check(inst, ans): + n, k = inst["n"], inst["k"] + S = int_list(ans.get("independent_set"), None, 0, n - 1, "independent_set") + if len(set(S)) != len(S): + raise Invalid("repeated vertex") + if len(S) < k: + raise Invalid(f"set has {len(S)} vertices, need at least {k}") + E = {(u, v) for u, v in inst["edges"]} + for u, v in itertools.combinations(sorted(S), 2): + if (u, v) in E: + raise Invalid(f"vertices {u} and {v} are adjacent") + return None, {"size": len(S)} diff --git a/graders/mc_non_transitive_dice/__pycache__/check.cpython-314.pyc b/graders/mc_non_transitive_dice/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c32e1addf4db2784bacae9217d38d3d8cf7be240 Binary files /dev/null and b/graders/mc_non_transitive_dice/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_non_transitive_dice/check.py b/graders/mc_non_transitive_dice/check.py new file mode 100644 index 0000000000000000000000000000000000000000..e3d5c04fa6e2819bf32f34fafe13a383437dc62a --- /dev/null +++ b/graders/mc_non_transitive_dice/check.py @@ -0,0 +1,18 @@ +"""Cyclically intransitive dice (MathConstraint non_transitive_dice, CC-BY-4.0): n dice with m faces in +0..2m-1; die i beats die (i+1) mod n, i.e. #{(a, b): face_i(a) > face_{i+1}(b)} > floor(m^2 / 2). +Face order is irrelevant (upstream additionally demanded sorted faces as a symmetry break; not required).""" +from run import Invalid, int_list + + +def check(inst, ans): + n, m = inst["n"], inst["m"] + D = ans.get("dice") + if not isinstance(D, list) or len(D) != n: + raise Invalid(f"dice must be a list of {n} dice") + D = [int_list(d, m, 0, 2 * m - 1, "die") for d in D] + for i in range(n): + A, B = D[i], D[(i + 1) % n] + w = sum(1 for a in A for b in B if a > b) + if w <= m * m // 2: + raise Invalid(f"die {i} wins only {w} of {m * m} face pairs against die {(i + 1) % n}") + return None, {} diff --git a/graders/mc_number_partitioning/__pycache__/check.cpython-314.pyc b/graders/mc_number_partitioning/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee219c733ed67bca93d94bf216b8ade03272f1f9 Binary files /dev/null and b/graders/mc_number_partitioning/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_number_partitioning/check.py b/graders/mc_number_partitioning/check.py new file mode 100644 index 0000000000000000000000000000000000000000..67793721db8ba7d3c3979ea0e1e07091491ffa7e --- /dev/null +++ b/graders/mc_number_partitioning/check.py @@ -0,0 +1,14 @@ +"""Partition {1..n} into k subsets of equal sum (MathConstraint number_partitioning, CC-BY-4.0).""" +from run import Invalid, int_list + + +def check(inst, ans): + n, k = inst["n"], inst["k"] + x = int_list(ans.get("x"), n, 0, k - 1, "x") + target = n * (n + 1) // 2 // k + sums = [0] * k + for i, s in enumerate(x): + sums[s] += i + 1 + if any(t != target for t in sums): + raise Invalid(f"subset sums {sums} are not all {target}") + return None, {} diff --git a/graders/mc_ortholatin/__pycache__/check.cpython-314.pyc b/graders/mc_ortholatin/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cbc0267c7d40c85b46c97d07bccde2cb2777721 Binary files /dev/null and b/graders/mc_ortholatin/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_ortholatin/check.py b/graders/mc_ortholatin/check.py new file mode 100644 index 0000000000000000000000000000000000000000..a5418a59fae1c86318eee903e90d75b36d8a3306 --- /dev/null +++ b/graders/mc_ortholatin/check.py @@ -0,0 +1,25 @@ +"""Pair of orthogonal Latin squares of order n (MathConstraint ortholatin, CC-BY-4.0).""" +from run import Invalid, int_list + + +def _square(v, n, name): + if not isinstance(v, list) or len(v) != n: + raise Invalid(f"{name} must be a list of {n} rows") + S = [int_list(r, n, 0, n - 1, f"{name} row") for r in v] + full = list(range(n)) + for i in range(n): + if sorted(S[i]) != full: + raise Invalid(f"{name}: row {i} is not a permutation of 0..{n - 1}") + if sorted(S[r][i] for r in range(n)) != full: + raise Invalid(f"{name}: column {i} is not a permutation of 0..{n - 1}") + return S + + +def check(inst, ans): + n = inst["n"] + X = _square(ans.get("X"), n, "X") + Y = _square(ans.get("Y"), n, "Y") + pairs = {(X[i][j], Y[i][j]) for i in range(n) for j in range(n)} + if len(pairs) != n * n: + raise Invalid("X and Y are not orthogonal (some ordered pair repeats)") + return None, {} diff --git a/graders/mc_pysms_chromatic_girth/__pycache__/check.cpython-314.pyc b/graders/mc_pysms_chromatic_girth/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1609043107341130c6519acc5260014f70fdc0e0 Binary files /dev/null and b/graders/mc_pysms_chromatic_girth/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_pysms_chromatic_girth/check.py b/graders/mc_pysms_chromatic_girth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0b12508cf59b733f007a9d1f50831aec9efdf --- /dev/null +++ b/graders/mc_pysms_chromatic_girth/check.py @@ -0,0 +1,151 @@ +"""Graph-existence constraints (MathConstraint pysms_* problem types, CC-BY-4.0). The answer is a graph on +the stated vertex set, plus a proper colouring when a chromatic-number upper bound is asked for. Every +constraint present in the instance is checked exactly (no stored answer is compared). + +Upstream note: upstream verifies by fixing the edge variables in the pysms CNF and calling CaDiCaL; the +min-chromatic-number bound of pysms_graph_builder is only a raw smsg solver parameter, not a clause, so the +upstream verifier ignored it. It is enforced here. Edge endpoints are also type-checked (upstream accepted +floats/bools that compare in range).""" +import itertools + +from run import Invalid, int_list + + +def _has_clique(adj, n, k): + def rec(cand, size): + if size == k: + return True + while cand: + if size + bin(cand).count("1") < k: + return False + v = cand.bit_length() - 1 + cand &= ~(1 << v) + if rec(cand & adj[v], size + 1): + return True + return False + return rec((1 << n) - 1, 0) + + +def _connected(adj, n, removed): + alive = [v for v in range(n) if not removed >> v & 1] + if len(alive) <= 1: + return True + mask = sum(1 << v for v in alive) + seen = 1 << alive[0] + stack = [alive[0]] + while stack: + v = stack.pop() + new = adj[v] & mask & ~seen + seen |= new + while new: + u = new.bit_length() - 1 + new &= ~(1 << u) + stack.append(u) + return seen == mask + + +def _girth(adj, n): + best = None + for r in range(n): + dist, par, q = {r: 0}, {r: -1}, [r] + for v in q: + nb = adj[v] + while nb: + u = nb.bit_length() - 1 + nb &= ~(1 << u) + if u not in dist: + dist[u], par[u] = dist[v] + 1, v + q.append(u) + elif par[v] != u: + c = dist[u] + dist[v] + 1 + best = c if best is None else min(best, c) + return best # None = acyclic + + +def _colourable(adj, n, k): + col = [-1] * n + order = sorted(range(n), key=lambda v: -bin(adj[v]).count("1")) + + def rec(i): + if i == n: + return True + v = order[i] + used = {col[u] for u in range(n) if adj[v] >> u & 1 and col[u] >= 0} + for c in range(k): + if c not in used: + col[v] = c + if rec(i + 1): + return True + col[v] = -1 + return False + return rec(0) + + +def check(inst, ans): + n = inst["vertices"] + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list of [u, v] pairs") + edges = set() + for e in E: + u, v = int_list(e, 2, 0, n - 1, "edge") + if u == v: + raise Invalid(f"self-loop at {u}") + e2 = (min(u, v), max(u, v)) + if e2 in edges: + raise Invalid(f"duplicate edge {e2}") + edges.add(e2) + adj = [0] * n + for u, v in edges: + adj[u] |= 1 << v + adj[v] |= 1 << u + deg = [bin(a).count("1") for a in adj] + for u, v in inst.get("required_edges", []): + if (min(u, v), max(u, v)) not in edges: + raise Invalid(f"required edge ({u},{v}) is missing") + c = inst.get + if c("min_degree") is not None and min(deg) < c("min_degree"): + raise Invalid(f"minimum degree {min(deg)} < {c('min_degree')}") + if c("max_degree") is not None and max(deg) > c("max_degree"): + raise Invalid(f"maximum degree {max(deg)} > {c('max_degree')}") + if c("min_edges") is not None and len(edges) < c("min_edges"): + raise Invalid(f"{len(edges)} edges < {c('min_edges')}") + if c("max_edges") is not None and len(edges) > c("max_edges"): + raise Invalid(f"{len(edges)} edges > {c('max_edges')}") + if c("max_clique") is not None and _has_clique(adj, n, c("max_clique") + 1): + raise Invalid(f"graph contains a clique of size {c('max_clique') + 1}") + if c("max_independent_set") is not None: + full = (1 << n) - 1 + comp = [full & ~adj[v] & ~(1 << v) for v in range(n)] + if _has_clique(comp, n, c("max_independent_set") + 1): + raise Invalid(f"graph contains an independent set of size {c('max_independent_set') + 1}") + if c("min_girth") is not None: + g = _girth(adj, n) + if g is not None and g < c("min_girth"): + raise Invalid(f"graph has a cycle of length {g} < {c('min_girth')}") + if c("min_connectivity") is not None: + k = c("min_connectivity") + if n <= k: + raise Invalid("too few vertices for this connectivity") + for s in range(k): + for I in itertools.combinations(range(n), s): + if not _connected(adj, n, sum(1 << v for v in I)): + raise Invalid(f"deleting vertices {list(I)} disconnects the graph") + if c("mtf"): + for u, v in itertools.combinations(range(n), 2): + if adj[u] >> v & 1: + if adj[u] & adj[v]: + raise Invalid(f"triangle on edge ({u},{v})") + elif not adj[u] & adj[v]: + raise Invalid(f"non-adjacent {u}, {v} have no common neighbour (edge could be added)") + if c("max_chromatic_number") is not None: + k = c("max_chromatic_number") + col = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in edges: + if col[u] == col[v]: + raise Invalid(f"coloring: edge ({u},{v}) is monochromatic") + if c("min_chromatic_number") is not None and c("min_chromatic_number") >= 2: + m = c("min_chromatic_number") + if not edges or _colourable(adj, n, m - 1): + raise Invalid(f"graph is {m - 1}-colourable, chromatic number must be at least {m}") + return None, {"num_edges": len(edges)} diff --git a/graders/mc_pysms_clique_coloring/__pycache__/check.cpython-314.pyc b/graders/mc_pysms_clique_coloring/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04a537776827ceaaed357fdf67059ca9071525d4 Binary files /dev/null and b/graders/mc_pysms_clique_coloring/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_pysms_clique_coloring/check.py b/graders/mc_pysms_clique_coloring/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0b12508cf59b733f007a9d1f50831aec9efdf --- /dev/null +++ b/graders/mc_pysms_clique_coloring/check.py @@ -0,0 +1,151 @@ +"""Graph-existence constraints (MathConstraint pysms_* problem types, CC-BY-4.0). The answer is a graph on +the stated vertex set, plus a proper colouring when a chromatic-number upper bound is asked for. Every +constraint present in the instance is checked exactly (no stored answer is compared). + +Upstream note: upstream verifies by fixing the edge variables in the pysms CNF and calling CaDiCaL; the +min-chromatic-number bound of pysms_graph_builder is only a raw smsg solver parameter, not a clause, so the +upstream verifier ignored it. It is enforced here. Edge endpoints are also type-checked (upstream accepted +floats/bools that compare in range).""" +import itertools + +from run import Invalid, int_list + + +def _has_clique(adj, n, k): + def rec(cand, size): + if size == k: + return True + while cand: + if size + bin(cand).count("1") < k: + return False + v = cand.bit_length() - 1 + cand &= ~(1 << v) + if rec(cand & adj[v], size + 1): + return True + return False + return rec((1 << n) - 1, 0) + + +def _connected(adj, n, removed): + alive = [v for v in range(n) if not removed >> v & 1] + if len(alive) <= 1: + return True + mask = sum(1 << v for v in alive) + seen = 1 << alive[0] + stack = [alive[0]] + while stack: + v = stack.pop() + new = adj[v] & mask & ~seen + seen |= new + while new: + u = new.bit_length() - 1 + new &= ~(1 << u) + stack.append(u) + return seen == mask + + +def _girth(adj, n): + best = None + for r in range(n): + dist, par, q = {r: 0}, {r: -1}, [r] + for v in q: + nb = adj[v] + while nb: + u = nb.bit_length() - 1 + nb &= ~(1 << u) + if u not in dist: + dist[u], par[u] = dist[v] + 1, v + q.append(u) + elif par[v] != u: + c = dist[u] + dist[v] + 1 + best = c if best is None else min(best, c) + return best # None = acyclic + + +def _colourable(adj, n, k): + col = [-1] * n + order = sorted(range(n), key=lambda v: -bin(adj[v]).count("1")) + + def rec(i): + if i == n: + return True + v = order[i] + used = {col[u] for u in range(n) if adj[v] >> u & 1 and col[u] >= 0} + for c in range(k): + if c not in used: + col[v] = c + if rec(i + 1): + return True + col[v] = -1 + return False + return rec(0) + + +def check(inst, ans): + n = inst["vertices"] + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list of [u, v] pairs") + edges = set() + for e in E: + u, v = int_list(e, 2, 0, n - 1, "edge") + if u == v: + raise Invalid(f"self-loop at {u}") + e2 = (min(u, v), max(u, v)) + if e2 in edges: + raise Invalid(f"duplicate edge {e2}") + edges.add(e2) + adj = [0] * n + for u, v in edges: + adj[u] |= 1 << v + adj[v] |= 1 << u + deg = [bin(a).count("1") for a in adj] + for u, v in inst.get("required_edges", []): + if (min(u, v), max(u, v)) not in edges: + raise Invalid(f"required edge ({u},{v}) is missing") + c = inst.get + if c("min_degree") is not None and min(deg) < c("min_degree"): + raise Invalid(f"minimum degree {min(deg)} < {c('min_degree')}") + if c("max_degree") is not None and max(deg) > c("max_degree"): + raise Invalid(f"maximum degree {max(deg)} > {c('max_degree')}") + if c("min_edges") is not None and len(edges) < c("min_edges"): + raise Invalid(f"{len(edges)} edges < {c('min_edges')}") + if c("max_edges") is not None and len(edges) > c("max_edges"): + raise Invalid(f"{len(edges)} edges > {c('max_edges')}") + if c("max_clique") is not None and _has_clique(adj, n, c("max_clique") + 1): + raise Invalid(f"graph contains a clique of size {c('max_clique') + 1}") + if c("max_independent_set") is not None: + full = (1 << n) - 1 + comp = [full & ~adj[v] & ~(1 << v) for v in range(n)] + if _has_clique(comp, n, c("max_independent_set") + 1): + raise Invalid(f"graph contains an independent set of size {c('max_independent_set') + 1}") + if c("min_girth") is not None: + g = _girth(adj, n) + if g is not None and g < c("min_girth"): + raise Invalid(f"graph has a cycle of length {g} < {c('min_girth')}") + if c("min_connectivity") is not None: + k = c("min_connectivity") + if n <= k: + raise Invalid("too few vertices for this connectivity") + for s in range(k): + for I in itertools.combinations(range(n), s): + if not _connected(adj, n, sum(1 << v for v in I)): + raise Invalid(f"deleting vertices {list(I)} disconnects the graph") + if c("mtf"): + for u, v in itertools.combinations(range(n), 2): + if adj[u] >> v & 1: + if adj[u] & adj[v]: + raise Invalid(f"triangle on edge ({u},{v})") + elif not adj[u] & adj[v]: + raise Invalid(f"non-adjacent {u}, {v} have no common neighbour (edge could be added)") + if c("max_chromatic_number") is not None: + k = c("max_chromatic_number") + col = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in edges: + if col[u] == col[v]: + raise Invalid(f"coloring: edge ({u},{v}) is monochromatic") + if c("min_chromatic_number") is not None and c("min_chromatic_number") >= 2: + m = c("min_chromatic_number") + if not edges or _colourable(adj, n, m - 1): + raise Invalid(f"graph is {m - 1}-colourable, chromatic number must be at least {m}") + return None, {"num_edges": len(edges)} diff --git a/graders/mc_pysms_degree_bounds/__pycache__/check.cpython-314.pyc b/graders/mc_pysms_degree_bounds/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ab0ae2e8acc713cd97ea99dab9105c37176450c Binary files /dev/null and b/graders/mc_pysms_degree_bounds/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_pysms_degree_bounds/check.py b/graders/mc_pysms_degree_bounds/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0b12508cf59b733f007a9d1f50831aec9efdf --- /dev/null +++ b/graders/mc_pysms_degree_bounds/check.py @@ -0,0 +1,151 @@ +"""Graph-existence constraints (MathConstraint pysms_* problem types, CC-BY-4.0). The answer is a graph on +the stated vertex set, plus a proper colouring when a chromatic-number upper bound is asked for. Every +constraint present in the instance is checked exactly (no stored answer is compared). + +Upstream note: upstream verifies by fixing the edge variables in the pysms CNF and calling CaDiCaL; the +min-chromatic-number bound of pysms_graph_builder is only a raw smsg solver parameter, not a clause, so the +upstream verifier ignored it. It is enforced here. Edge endpoints are also type-checked (upstream accepted +floats/bools that compare in range).""" +import itertools + +from run import Invalid, int_list + + +def _has_clique(adj, n, k): + def rec(cand, size): + if size == k: + return True + while cand: + if size + bin(cand).count("1") < k: + return False + v = cand.bit_length() - 1 + cand &= ~(1 << v) + if rec(cand & adj[v], size + 1): + return True + return False + return rec((1 << n) - 1, 0) + + +def _connected(adj, n, removed): + alive = [v for v in range(n) if not removed >> v & 1] + if len(alive) <= 1: + return True + mask = sum(1 << v for v in alive) + seen = 1 << alive[0] + stack = [alive[0]] + while stack: + v = stack.pop() + new = adj[v] & mask & ~seen + seen |= new + while new: + u = new.bit_length() - 1 + new &= ~(1 << u) + stack.append(u) + return seen == mask + + +def _girth(adj, n): + best = None + for r in range(n): + dist, par, q = {r: 0}, {r: -1}, [r] + for v in q: + nb = adj[v] + while nb: + u = nb.bit_length() - 1 + nb &= ~(1 << u) + if u not in dist: + dist[u], par[u] = dist[v] + 1, v + q.append(u) + elif par[v] != u: + c = dist[u] + dist[v] + 1 + best = c if best is None else min(best, c) + return best # None = acyclic + + +def _colourable(adj, n, k): + col = [-1] * n + order = sorted(range(n), key=lambda v: -bin(adj[v]).count("1")) + + def rec(i): + if i == n: + return True + v = order[i] + used = {col[u] for u in range(n) if adj[v] >> u & 1 and col[u] >= 0} + for c in range(k): + if c not in used: + col[v] = c + if rec(i + 1): + return True + col[v] = -1 + return False + return rec(0) + + +def check(inst, ans): + n = inst["vertices"] + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list of [u, v] pairs") + edges = set() + for e in E: + u, v = int_list(e, 2, 0, n - 1, "edge") + if u == v: + raise Invalid(f"self-loop at {u}") + e2 = (min(u, v), max(u, v)) + if e2 in edges: + raise Invalid(f"duplicate edge {e2}") + edges.add(e2) + adj = [0] * n + for u, v in edges: + adj[u] |= 1 << v + adj[v] |= 1 << u + deg = [bin(a).count("1") for a in adj] + for u, v in inst.get("required_edges", []): + if (min(u, v), max(u, v)) not in edges: + raise Invalid(f"required edge ({u},{v}) is missing") + c = inst.get + if c("min_degree") is not None and min(deg) < c("min_degree"): + raise Invalid(f"minimum degree {min(deg)} < {c('min_degree')}") + if c("max_degree") is not None and max(deg) > c("max_degree"): + raise Invalid(f"maximum degree {max(deg)} > {c('max_degree')}") + if c("min_edges") is not None and len(edges) < c("min_edges"): + raise Invalid(f"{len(edges)} edges < {c('min_edges')}") + if c("max_edges") is not None and len(edges) > c("max_edges"): + raise Invalid(f"{len(edges)} edges > {c('max_edges')}") + if c("max_clique") is not None and _has_clique(adj, n, c("max_clique") + 1): + raise Invalid(f"graph contains a clique of size {c('max_clique') + 1}") + if c("max_independent_set") is not None: + full = (1 << n) - 1 + comp = [full & ~adj[v] & ~(1 << v) for v in range(n)] + if _has_clique(comp, n, c("max_independent_set") + 1): + raise Invalid(f"graph contains an independent set of size {c('max_independent_set') + 1}") + if c("min_girth") is not None: + g = _girth(adj, n) + if g is not None and g < c("min_girth"): + raise Invalid(f"graph has a cycle of length {g} < {c('min_girth')}") + if c("min_connectivity") is not None: + k = c("min_connectivity") + if n <= k: + raise Invalid("too few vertices for this connectivity") + for s in range(k): + for I in itertools.combinations(range(n), s): + if not _connected(adj, n, sum(1 << v for v in I)): + raise Invalid(f"deleting vertices {list(I)} disconnects the graph") + if c("mtf"): + for u, v in itertools.combinations(range(n), 2): + if adj[u] >> v & 1: + if adj[u] & adj[v]: + raise Invalid(f"triangle on edge ({u},{v})") + elif not adj[u] & adj[v]: + raise Invalid(f"non-adjacent {u}, {v} have no common neighbour (edge could be added)") + if c("max_chromatic_number") is not None: + k = c("max_chromatic_number") + col = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in edges: + if col[u] == col[v]: + raise Invalid(f"coloring: edge ({u},{v}) is monochromatic") + if c("min_chromatic_number") is not None and c("min_chromatic_number") >= 2: + m = c("min_chromatic_number") + if not edges or _colourable(adj, n, m - 1): + raise Invalid(f"graph is {m - 1}-colourable, chromatic number must be at least {m}") + return None, {"num_edges": len(edges)} diff --git a/graders/mc_pysms_girth_degree/__pycache__/check.cpython-314.pyc b/graders/mc_pysms_girth_degree/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c382c0df61db508293278c2953b743befb308908 Binary files /dev/null and b/graders/mc_pysms_girth_degree/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_pysms_girth_degree/check.py b/graders/mc_pysms_girth_degree/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0b12508cf59b733f007a9d1f50831aec9efdf --- /dev/null +++ b/graders/mc_pysms_girth_degree/check.py @@ -0,0 +1,151 @@ +"""Graph-existence constraints (MathConstraint pysms_* problem types, CC-BY-4.0). The answer is a graph on +the stated vertex set, plus a proper colouring when a chromatic-number upper bound is asked for. Every +constraint present in the instance is checked exactly (no stored answer is compared). + +Upstream note: upstream verifies by fixing the edge variables in the pysms CNF and calling CaDiCaL; the +min-chromatic-number bound of pysms_graph_builder is only a raw smsg solver parameter, not a clause, so the +upstream verifier ignored it. It is enforced here. Edge endpoints are also type-checked (upstream accepted +floats/bools that compare in range).""" +import itertools + +from run import Invalid, int_list + + +def _has_clique(adj, n, k): + def rec(cand, size): + if size == k: + return True + while cand: + if size + bin(cand).count("1") < k: + return False + v = cand.bit_length() - 1 + cand &= ~(1 << v) + if rec(cand & adj[v], size + 1): + return True + return False + return rec((1 << n) - 1, 0) + + +def _connected(adj, n, removed): + alive = [v for v in range(n) if not removed >> v & 1] + if len(alive) <= 1: + return True + mask = sum(1 << v for v in alive) + seen = 1 << alive[0] + stack = [alive[0]] + while stack: + v = stack.pop() + new = adj[v] & mask & ~seen + seen |= new + while new: + u = new.bit_length() - 1 + new &= ~(1 << u) + stack.append(u) + return seen == mask + + +def _girth(adj, n): + best = None + for r in range(n): + dist, par, q = {r: 0}, {r: -1}, [r] + for v in q: + nb = adj[v] + while nb: + u = nb.bit_length() - 1 + nb &= ~(1 << u) + if u not in dist: + dist[u], par[u] = dist[v] + 1, v + q.append(u) + elif par[v] != u: + c = dist[u] + dist[v] + 1 + best = c if best is None else min(best, c) + return best # None = acyclic + + +def _colourable(adj, n, k): + col = [-1] * n + order = sorted(range(n), key=lambda v: -bin(adj[v]).count("1")) + + def rec(i): + if i == n: + return True + v = order[i] + used = {col[u] for u in range(n) if adj[v] >> u & 1 and col[u] >= 0} + for c in range(k): + if c not in used: + col[v] = c + if rec(i + 1): + return True + col[v] = -1 + return False + return rec(0) + + +def check(inst, ans): + n = inst["vertices"] + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list of [u, v] pairs") + edges = set() + for e in E: + u, v = int_list(e, 2, 0, n - 1, "edge") + if u == v: + raise Invalid(f"self-loop at {u}") + e2 = (min(u, v), max(u, v)) + if e2 in edges: + raise Invalid(f"duplicate edge {e2}") + edges.add(e2) + adj = [0] * n + for u, v in edges: + adj[u] |= 1 << v + adj[v] |= 1 << u + deg = [bin(a).count("1") for a in adj] + for u, v in inst.get("required_edges", []): + if (min(u, v), max(u, v)) not in edges: + raise Invalid(f"required edge ({u},{v}) is missing") + c = inst.get + if c("min_degree") is not None and min(deg) < c("min_degree"): + raise Invalid(f"minimum degree {min(deg)} < {c('min_degree')}") + if c("max_degree") is not None and max(deg) > c("max_degree"): + raise Invalid(f"maximum degree {max(deg)} > {c('max_degree')}") + if c("min_edges") is not None and len(edges) < c("min_edges"): + raise Invalid(f"{len(edges)} edges < {c('min_edges')}") + if c("max_edges") is not None and len(edges) > c("max_edges"): + raise Invalid(f"{len(edges)} edges > {c('max_edges')}") + if c("max_clique") is not None and _has_clique(adj, n, c("max_clique") + 1): + raise Invalid(f"graph contains a clique of size {c('max_clique') + 1}") + if c("max_independent_set") is not None: + full = (1 << n) - 1 + comp = [full & ~adj[v] & ~(1 << v) for v in range(n)] + if _has_clique(comp, n, c("max_independent_set") + 1): + raise Invalid(f"graph contains an independent set of size {c('max_independent_set') + 1}") + if c("min_girth") is not None: + g = _girth(adj, n) + if g is not None and g < c("min_girth"): + raise Invalid(f"graph has a cycle of length {g} < {c('min_girth')}") + if c("min_connectivity") is not None: + k = c("min_connectivity") + if n <= k: + raise Invalid("too few vertices for this connectivity") + for s in range(k): + for I in itertools.combinations(range(n), s): + if not _connected(adj, n, sum(1 << v for v in I)): + raise Invalid(f"deleting vertices {list(I)} disconnects the graph") + if c("mtf"): + for u, v in itertools.combinations(range(n), 2): + if adj[u] >> v & 1: + if adj[u] & adj[v]: + raise Invalid(f"triangle on edge ({u},{v})") + elif not adj[u] & adj[v]: + raise Invalid(f"non-adjacent {u}, {v} have no common neighbour (edge could be added)") + if c("max_chromatic_number") is not None: + k = c("max_chromatic_number") + col = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in edges: + if col[u] == col[v]: + raise Invalid(f"coloring: edge ({u},{v}) is monochromatic") + if c("min_chromatic_number") is not None and c("min_chromatic_number") >= 2: + m = c("min_chromatic_number") + if not edges or _colourable(adj, n, m - 1): + raise Invalid(f"graph is {m - 1}-colourable, chromatic number must be at least {m}") + return None, {"num_edges": len(edges)} diff --git a/graders/mc_pysms_graph_builder/__pycache__/check.cpython-314.pyc b/graders/mc_pysms_graph_builder/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71eb82993fa836877c25b54bcca46e7e9e8a1b45 Binary files /dev/null and b/graders/mc_pysms_graph_builder/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_pysms_graph_builder/check.py b/graders/mc_pysms_graph_builder/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0b12508cf59b733f007a9d1f50831aec9efdf --- /dev/null +++ b/graders/mc_pysms_graph_builder/check.py @@ -0,0 +1,151 @@ +"""Graph-existence constraints (MathConstraint pysms_* problem types, CC-BY-4.0). The answer is a graph on +the stated vertex set, plus a proper colouring when a chromatic-number upper bound is asked for. Every +constraint present in the instance is checked exactly (no stored answer is compared). + +Upstream note: upstream verifies by fixing the edge variables in the pysms CNF and calling CaDiCaL; the +min-chromatic-number bound of pysms_graph_builder is only a raw smsg solver parameter, not a clause, so the +upstream verifier ignored it. It is enforced here. Edge endpoints are also type-checked (upstream accepted +floats/bools that compare in range).""" +import itertools + +from run import Invalid, int_list + + +def _has_clique(adj, n, k): + def rec(cand, size): + if size == k: + return True + while cand: + if size + bin(cand).count("1") < k: + return False + v = cand.bit_length() - 1 + cand &= ~(1 << v) + if rec(cand & adj[v], size + 1): + return True + return False + return rec((1 << n) - 1, 0) + + +def _connected(adj, n, removed): + alive = [v for v in range(n) if not removed >> v & 1] + if len(alive) <= 1: + return True + mask = sum(1 << v for v in alive) + seen = 1 << alive[0] + stack = [alive[0]] + while stack: + v = stack.pop() + new = adj[v] & mask & ~seen + seen |= new + while new: + u = new.bit_length() - 1 + new &= ~(1 << u) + stack.append(u) + return seen == mask + + +def _girth(adj, n): + best = None + for r in range(n): + dist, par, q = {r: 0}, {r: -1}, [r] + for v in q: + nb = adj[v] + while nb: + u = nb.bit_length() - 1 + nb &= ~(1 << u) + if u not in dist: + dist[u], par[u] = dist[v] + 1, v + q.append(u) + elif par[v] != u: + c = dist[u] + dist[v] + 1 + best = c if best is None else min(best, c) + return best # None = acyclic + + +def _colourable(adj, n, k): + col = [-1] * n + order = sorted(range(n), key=lambda v: -bin(adj[v]).count("1")) + + def rec(i): + if i == n: + return True + v = order[i] + used = {col[u] for u in range(n) if adj[v] >> u & 1 and col[u] >= 0} + for c in range(k): + if c not in used: + col[v] = c + if rec(i + 1): + return True + col[v] = -1 + return False + return rec(0) + + +def check(inst, ans): + n = inst["vertices"] + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list of [u, v] pairs") + edges = set() + for e in E: + u, v = int_list(e, 2, 0, n - 1, "edge") + if u == v: + raise Invalid(f"self-loop at {u}") + e2 = (min(u, v), max(u, v)) + if e2 in edges: + raise Invalid(f"duplicate edge {e2}") + edges.add(e2) + adj = [0] * n + for u, v in edges: + adj[u] |= 1 << v + adj[v] |= 1 << u + deg = [bin(a).count("1") for a in adj] + for u, v in inst.get("required_edges", []): + if (min(u, v), max(u, v)) not in edges: + raise Invalid(f"required edge ({u},{v}) is missing") + c = inst.get + if c("min_degree") is not None and min(deg) < c("min_degree"): + raise Invalid(f"minimum degree {min(deg)} < {c('min_degree')}") + if c("max_degree") is not None and max(deg) > c("max_degree"): + raise Invalid(f"maximum degree {max(deg)} > {c('max_degree')}") + if c("min_edges") is not None and len(edges) < c("min_edges"): + raise Invalid(f"{len(edges)} edges < {c('min_edges')}") + if c("max_edges") is not None and len(edges) > c("max_edges"): + raise Invalid(f"{len(edges)} edges > {c('max_edges')}") + if c("max_clique") is not None and _has_clique(adj, n, c("max_clique") + 1): + raise Invalid(f"graph contains a clique of size {c('max_clique') + 1}") + if c("max_independent_set") is not None: + full = (1 << n) - 1 + comp = [full & ~adj[v] & ~(1 << v) for v in range(n)] + if _has_clique(comp, n, c("max_independent_set") + 1): + raise Invalid(f"graph contains an independent set of size {c('max_independent_set') + 1}") + if c("min_girth") is not None: + g = _girth(adj, n) + if g is not None and g < c("min_girth"): + raise Invalid(f"graph has a cycle of length {g} < {c('min_girth')}") + if c("min_connectivity") is not None: + k = c("min_connectivity") + if n <= k: + raise Invalid("too few vertices for this connectivity") + for s in range(k): + for I in itertools.combinations(range(n), s): + if not _connected(adj, n, sum(1 << v for v in I)): + raise Invalid(f"deleting vertices {list(I)} disconnects the graph") + if c("mtf"): + for u, v in itertools.combinations(range(n), 2): + if adj[u] >> v & 1: + if adj[u] & adj[v]: + raise Invalid(f"triangle on edge ({u},{v})") + elif not adj[u] & adj[v]: + raise Invalid(f"non-adjacent {u}, {v} have no common neighbour (edge could be added)") + if c("max_chromatic_number") is not None: + k = c("max_chromatic_number") + col = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in edges: + if col[u] == col[v]: + raise Invalid(f"coloring: edge ({u},{v}) is monochromatic") + if c("min_chromatic_number") is not None and c("min_chromatic_number") >= 2: + m = c("min_chromatic_number") + if not edges or _colourable(adj, n, m - 1): + raise Invalid(f"graph is {m - 1}-colourable, chromatic number must be at least {m}") + return None, {"num_edges": len(edges)} diff --git a/graders/mc_pysms_independent_connectivity/__pycache__/check.cpython-314.pyc b/graders/mc_pysms_independent_connectivity/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..beeda9def9ecbd0dda6c65355512017337694ae3 Binary files /dev/null and b/graders/mc_pysms_independent_connectivity/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_pysms_independent_connectivity/check.py b/graders/mc_pysms_independent_connectivity/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0b12508cf59b733f007a9d1f50831aec9efdf --- /dev/null +++ b/graders/mc_pysms_independent_connectivity/check.py @@ -0,0 +1,151 @@ +"""Graph-existence constraints (MathConstraint pysms_* problem types, CC-BY-4.0). The answer is a graph on +the stated vertex set, plus a proper colouring when a chromatic-number upper bound is asked for. Every +constraint present in the instance is checked exactly (no stored answer is compared). + +Upstream note: upstream verifies by fixing the edge variables in the pysms CNF and calling CaDiCaL; the +min-chromatic-number bound of pysms_graph_builder is only a raw smsg solver parameter, not a clause, so the +upstream verifier ignored it. It is enforced here. Edge endpoints are also type-checked (upstream accepted +floats/bools that compare in range).""" +import itertools + +from run import Invalid, int_list + + +def _has_clique(adj, n, k): + def rec(cand, size): + if size == k: + return True + while cand: + if size + bin(cand).count("1") < k: + return False + v = cand.bit_length() - 1 + cand &= ~(1 << v) + if rec(cand & adj[v], size + 1): + return True + return False + return rec((1 << n) - 1, 0) + + +def _connected(adj, n, removed): + alive = [v for v in range(n) if not removed >> v & 1] + if len(alive) <= 1: + return True + mask = sum(1 << v for v in alive) + seen = 1 << alive[0] + stack = [alive[0]] + while stack: + v = stack.pop() + new = adj[v] & mask & ~seen + seen |= new + while new: + u = new.bit_length() - 1 + new &= ~(1 << u) + stack.append(u) + return seen == mask + + +def _girth(adj, n): + best = None + for r in range(n): + dist, par, q = {r: 0}, {r: -1}, [r] + for v in q: + nb = adj[v] + while nb: + u = nb.bit_length() - 1 + nb &= ~(1 << u) + if u not in dist: + dist[u], par[u] = dist[v] + 1, v + q.append(u) + elif par[v] != u: + c = dist[u] + dist[v] + 1 + best = c if best is None else min(best, c) + return best # None = acyclic + + +def _colourable(adj, n, k): + col = [-1] * n + order = sorted(range(n), key=lambda v: -bin(adj[v]).count("1")) + + def rec(i): + if i == n: + return True + v = order[i] + used = {col[u] for u in range(n) if adj[v] >> u & 1 and col[u] >= 0} + for c in range(k): + if c not in used: + col[v] = c + if rec(i + 1): + return True + col[v] = -1 + return False + return rec(0) + + +def check(inst, ans): + n = inst["vertices"] + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list of [u, v] pairs") + edges = set() + for e in E: + u, v = int_list(e, 2, 0, n - 1, "edge") + if u == v: + raise Invalid(f"self-loop at {u}") + e2 = (min(u, v), max(u, v)) + if e2 in edges: + raise Invalid(f"duplicate edge {e2}") + edges.add(e2) + adj = [0] * n + for u, v in edges: + adj[u] |= 1 << v + adj[v] |= 1 << u + deg = [bin(a).count("1") for a in adj] + for u, v in inst.get("required_edges", []): + if (min(u, v), max(u, v)) not in edges: + raise Invalid(f"required edge ({u},{v}) is missing") + c = inst.get + if c("min_degree") is not None and min(deg) < c("min_degree"): + raise Invalid(f"minimum degree {min(deg)} < {c('min_degree')}") + if c("max_degree") is not None and max(deg) > c("max_degree"): + raise Invalid(f"maximum degree {max(deg)} > {c('max_degree')}") + if c("min_edges") is not None and len(edges) < c("min_edges"): + raise Invalid(f"{len(edges)} edges < {c('min_edges')}") + if c("max_edges") is not None and len(edges) > c("max_edges"): + raise Invalid(f"{len(edges)} edges > {c('max_edges')}") + if c("max_clique") is not None and _has_clique(adj, n, c("max_clique") + 1): + raise Invalid(f"graph contains a clique of size {c('max_clique') + 1}") + if c("max_independent_set") is not None: + full = (1 << n) - 1 + comp = [full & ~adj[v] & ~(1 << v) for v in range(n)] + if _has_clique(comp, n, c("max_independent_set") + 1): + raise Invalid(f"graph contains an independent set of size {c('max_independent_set') + 1}") + if c("min_girth") is not None: + g = _girth(adj, n) + if g is not None and g < c("min_girth"): + raise Invalid(f"graph has a cycle of length {g} < {c('min_girth')}") + if c("min_connectivity") is not None: + k = c("min_connectivity") + if n <= k: + raise Invalid("too few vertices for this connectivity") + for s in range(k): + for I in itertools.combinations(range(n), s): + if not _connected(adj, n, sum(1 << v for v in I)): + raise Invalid(f"deleting vertices {list(I)} disconnects the graph") + if c("mtf"): + for u, v in itertools.combinations(range(n), 2): + if adj[u] >> v & 1: + if adj[u] & adj[v]: + raise Invalid(f"triangle on edge ({u},{v})") + elif not adj[u] & adj[v]: + raise Invalid(f"non-adjacent {u}, {v} have no common neighbour (edge could be added)") + if c("max_chromatic_number") is not None: + k = c("max_chromatic_number") + col = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in edges: + if col[u] == col[v]: + raise Invalid(f"coloring: edge ({u},{v}) is monochromatic") + if c("min_chromatic_number") is not None and c("min_chromatic_number") >= 2: + m = c("min_chromatic_number") + if not edges or _colourable(adj, n, m - 1): + raise Invalid(f"graph is {m - 1}-colourable, chromatic number must be at least {m}") + return None, {"num_edges": len(edges)} diff --git a/graders/mc_pysms_min_connectivity/__pycache__/check.cpython-314.pyc b/graders/mc_pysms_min_connectivity/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96bc649eee1f72335bea48bb52a4b3c10386e8d2 Binary files /dev/null and b/graders/mc_pysms_min_connectivity/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_pysms_min_connectivity/check.py b/graders/mc_pysms_min_connectivity/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0b12508cf59b733f007a9d1f50831aec9efdf --- /dev/null +++ b/graders/mc_pysms_min_connectivity/check.py @@ -0,0 +1,151 @@ +"""Graph-existence constraints (MathConstraint pysms_* problem types, CC-BY-4.0). The answer is a graph on +the stated vertex set, plus a proper colouring when a chromatic-number upper bound is asked for. Every +constraint present in the instance is checked exactly (no stored answer is compared). + +Upstream note: upstream verifies by fixing the edge variables in the pysms CNF and calling CaDiCaL; the +min-chromatic-number bound of pysms_graph_builder is only a raw smsg solver parameter, not a clause, so the +upstream verifier ignored it. It is enforced here. Edge endpoints are also type-checked (upstream accepted +floats/bools that compare in range).""" +import itertools + +from run import Invalid, int_list + + +def _has_clique(adj, n, k): + def rec(cand, size): + if size == k: + return True + while cand: + if size + bin(cand).count("1") < k: + return False + v = cand.bit_length() - 1 + cand &= ~(1 << v) + if rec(cand & adj[v], size + 1): + return True + return False + return rec((1 << n) - 1, 0) + + +def _connected(adj, n, removed): + alive = [v for v in range(n) if not removed >> v & 1] + if len(alive) <= 1: + return True + mask = sum(1 << v for v in alive) + seen = 1 << alive[0] + stack = [alive[0]] + while stack: + v = stack.pop() + new = adj[v] & mask & ~seen + seen |= new + while new: + u = new.bit_length() - 1 + new &= ~(1 << u) + stack.append(u) + return seen == mask + + +def _girth(adj, n): + best = None + for r in range(n): + dist, par, q = {r: 0}, {r: -1}, [r] + for v in q: + nb = adj[v] + while nb: + u = nb.bit_length() - 1 + nb &= ~(1 << u) + if u not in dist: + dist[u], par[u] = dist[v] + 1, v + q.append(u) + elif par[v] != u: + c = dist[u] + dist[v] + 1 + best = c if best is None else min(best, c) + return best # None = acyclic + + +def _colourable(adj, n, k): + col = [-1] * n + order = sorted(range(n), key=lambda v: -bin(adj[v]).count("1")) + + def rec(i): + if i == n: + return True + v = order[i] + used = {col[u] for u in range(n) if adj[v] >> u & 1 and col[u] >= 0} + for c in range(k): + if c not in used: + col[v] = c + if rec(i + 1): + return True + col[v] = -1 + return False + return rec(0) + + +def check(inst, ans): + n = inst["vertices"] + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list of [u, v] pairs") + edges = set() + for e in E: + u, v = int_list(e, 2, 0, n - 1, "edge") + if u == v: + raise Invalid(f"self-loop at {u}") + e2 = (min(u, v), max(u, v)) + if e2 in edges: + raise Invalid(f"duplicate edge {e2}") + edges.add(e2) + adj = [0] * n + for u, v in edges: + adj[u] |= 1 << v + adj[v] |= 1 << u + deg = [bin(a).count("1") for a in adj] + for u, v in inst.get("required_edges", []): + if (min(u, v), max(u, v)) not in edges: + raise Invalid(f"required edge ({u},{v}) is missing") + c = inst.get + if c("min_degree") is not None and min(deg) < c("min_degree"): + raise Invalid(f"minimum degree {min(deg)} < {c('min_degree')}") + if c("max_degree") is not None and max(deg) > c("max_degree"): + raise Invalid(f"maximum degree {max(deg)} > {c('max_degree')}") + if c("min_edges") is not None and len(edges) < c("min_edges"): + raise Invalid(f"{len(edges)} edges < {c('min_edges')}") + if c("max_edges") is not None and len(edges) > c("max_edges"): + raise Invalid(f"{len(edges)} edges > {c('max_edges')}") + if c("max_clique") is not None and _has_clique(adj, n, c("max_clique") + 1): + raise Invalid(f"graph contains a clique of size {c('max_clique') + 1}") + if c("max_independent_set") is not None: + full = (1 << n) - 1 + comp = [full & ~adj[v] & ~(1 << v) for v in range(n)] + if _has_clique(comp, n, c("max_independent_set") + 1): + raise Invalid(f"graph contains an independent set of size {c('max_independent_set') + 1}") + if c("min_girth") is not None: + g = _girth(adj, n) + if g is not None and g < c("min_girth"): + raise Invalid(f"graph has a cycle of length {g} < {c('min_girth')}") + if c("min_connectivity") is not None: + k = c("min_connectivity") + if n <= k: + raise Invalid("too few vertices for this connectivity") + for s in range(k): + for I in itertools.combinations(range(n), s): + if not _connected(adj, n, sum(1 << v for v in I)): + raise Invalid(f"deleting vertices {list(I)} disconnects the graph") + if c("mtf"): + for u, v in itertools.combinations(range(n), 2): + if adj[u] >> v & 1: + if adj[u] & adj[v]: + raise Invalid(f"triangle on edge ({u},{v})") + elif not adj[u] & adj[v]: + raise Invalid(f"non-adjacent {u}, {v} have no common neighbour (edge could be added)") + if c("max_chromatic_number") is not None: + k = c("max_chromatic_number") + col = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in edges: + if col[u] == col[v]: + raise Invalid(f"coloring: edge ({u},{v}) is monochromatic") + if c("min_chromatic_number") is not None and c("min_chromatic_number") >= 2: + m = c("min_chromatic_number") + if not edges or _colourable(adj, n, m - 1): + raise Invalid(f"graph is {m - 1}-colourable, chromatic number must be at least {m}") + return None, {"num_edges": len(edges)} diff --git a/graders/mc_pysms_min_degree/__pycache__/check.cpython-314.pyc b/graders/mc_pysms_min_degree/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec11911665ac65c0ab2f6358b6d06917fa1a0b22 Binary files /dev/null and b/graders/mc_pysms_min_degree/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_pysms_min_degree/check.py b/graders/mc_pysms_min_degree/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0b12508cf59b733f007a9d1f50831aec9efdf --- /dev/null +++ b/graders/mc_pysms_min_degree/check.py @@ -0,0 +1,151 @@ +"""Graph-existence constraints (MathConstraint pysms_* problem types, CC-BY-4.0). The answer is a graph on +the stated vertex set, plus a proper colouring when a chromatic-number upper bound is asked for. Every +constraint present in the instance is checked exactly (no stored answer is compared). + +Upstream note: upstream verifies by fixing the edge variables in the pysms CNF and calling CaDiCaL; the +min-chromatic-number bound of pysms_graph_builder is only a raw smsg solver parameter, not a clause, so the +upstream verifier ignored it. It is enforced here. Edge endpoints are also type-checked (upstream accepted +floats/bools that compare in range).""" +import itertools + +from run import Invalid, int_list + + +def _has_clique(adj, n, k): + def rec(cand, size): + if size == k: + return True + while cand: + if size + bin(cand).count("1") < k: + return False + v = cand.bit_length() - 1 + cand &= ~(1 << v) + if rec(cand & adj[v], size + 1): + return True + return False + return rec((1 << n) - 1, 0) + + +def _connected(adj, n, removed): + alive = [v for v in range(n) if not removed >> v & 1] + if len(alive) <= 1: + return True + mask = sum(1 << v for v in alive) + seen = 1 << alive[0] + stack = [alive[0]] + while stack: + v = stack.pop() + new = adj[v] & mask & ~seen + seen |= new + while new: + u = new.bit_length() - 1 + new &= ~(1 << u) + stack.append(u) + return seen == mask + + +def _girth(adj, n): + best = None + for r in range(n): + dist, par, q = {r: 0}, {r: -1}, [r] + for v in q: + nb = adj[v] + while nb: + u = nb.bit_length() - 1 + nb &= ~(1 << u) + if u not in dist: + dist[u], par[u] = dist[v] + 1, v + q.append(u) + elif par[v] != u: + c = dist[u] + dist[v] + 1 + best = c if best is None else min(best, c) + return best # None = acyclic + + +def _colourable(adj, n, k): + col = [-1] * n + order = sorted(range(n), key=lambda v: -bin(adj[v]).count("1")) + + def rec(i): + if i == n: + return True + v = order[i] + used = {col[u] for u in range(n) if adj[v] >> u & 1 and col[u] >= 0} + for c in range(k): + if c not in used: + col[v] = c + if rec(i + 1): + return True + col[v] = -1 + return False + return rec(0) + + +def check(inst, ans): + n = inst["vertices"] + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list of [u, v] pairs") + edges = set() + for e in E: + u, v = int_list(e, 2, 0, n - 1, "edge") + if u == v: + raise Invalid(f"self-loop at {u}") + e2 = (min(u, v), max(u, v)) + if e2 in edges: + raise Invalid(f"duplicate edge {e2}") + edges.add(e2) + adj = [0] * n + for u, v in edges: + adj[u] |= 1 << v + adj[v] |= 1 << u + deg = [bin(a).count("1") for a in adj] + for u, v in inst.get("required_edges", []): + if (min(u, v), max(u, v)) not in edges: + raise Invalid(f"required edge ({u},{v}) is missing") + c = inst.get + if c("min_degree") is not None and min(deg) < c("min_degree"): + raise Invalid(f"minimum degree {min(deg)} < {c('min_degree')}") + if c("max_degree") is not None and max(deg) > c("max_degree"): + raise Invalid(f"maximum degree {max(deg)} > {c('max_degree')}") + if c("min_edges") is not None and len(edges) < c("min_edges"): + raise Invalid(f"{len(edges)} edges < {c('min_edges')}") + if c("max_edges") is not None and len(edges) > c("max_edges"): + raise Invalid(f"{len(edges)} edges > {c('max_edges')}") + if c("max_clique") is not None and _has_clique(adj, n, c("max_clique") + 1): + raise Invalid(f"graph contains a clique of size {c('max_clique') + 1}") + if c("max_independent_set") is not None: + full = (1 << n) - 1 + comp = [full & ~adj[v] & ~(1 << v) for v in range(n)] + if _has_clique(comp, n, c("max_independent_set") + 1): + raise Invalid(f"graph contains an independent set of size {c('max_independent_set') + 1}") + if c("min_girth") is not None: + g = _girth(adj, n) + if g is not None and g < c("min_girth"): + raise Invalid(f"graph has a cycle of length {g} < {c('min_girth')}") + if c("min_connectivity") is not None: + k = c("min_connectivity") + if n <= k: + raise Invalid("too few vertices for this connectivity") + for s in range(k): + for I in itertools.combinations(range(n), s): + if not _connected(adj, n, sum(1 << v for v in I)): + raise Invalid(f"deleting vertices {list(I)} disconnects the graph") + if c("mtf"): + for u, v in itertools.combinations(range(n), 2): + if adj[u] >> v & 1: + if adj[u] & adj[v]: + raise Invalid(f"triangle on edge ({u},{v})") + elif not adj[u] & adj[v]: + raise Invalid(f"non-adjacent {u}, {v} have no common neighbour (edge could be added)") + if c("max_chromatic_number") is not None: + k = c("max_chromatic_number") + col = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in edges: + if col[u] == col[v]: + raise Invalid(f"coloring: edge ({u},{v}) is monochromatic") + if c("min_chromatic_number") is not None and c("min_chromatic_number") >= 2: + m = c("min_chromatic_number") + if not edges or _colourable(adj, n, m - 1): + raise Invalid(f"graph is {m - 1}-colourable, chromatic number must be at least {m}") + return None, {"num_edges": len(edges)} diff --git a/graders/mc_pysms_min_girth/__pycache__/check.cpython-314.pyc b/graders/mc_pysms_min_girth/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32434c680fd60be070a0e1b2ffd8c38db435f6d4 Binary files /dev/null and b/graders/mc_pysms_min_girth/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_pysms_min_girth/check.py b/graders/mc_pysms_min_girth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0b12508cf59b733f007a9d1f50831aec9efdf --- /dev/null +++ b/graders/mc_pysms_min_girth/check.py @@ -0,0 +1,151 @@ +"""Graph-existence constraints (MathConstraint pysms_* problem types, CC-BY-4.0). The answer is a graph on +the stated vertex set, plus a proper colouring when a chromatic-number upper bound is asked for. Every +constraint present in the instance is checked exactly (no stored answer is compared). + +Upstream note: upstream verifies by fixing the edge variables in the pysms CNF and calling CaDiCaL; the +min-chromatic-number bound of pysms_graph_builder is only a raw smsg solver parameter, not a clause, so the +upstream verifier ignored it. It is enforced here. Edge endpoints are also type-checked (upstream accepted +floats/bools that compare in range).""" +import itertools + +from run import Invalid, int_list + + +def _has_clique(adj, n, k): + def rec(cand, size): + if size == k: + return True + while cand: + if size + bin(cand).count("1") < k: + return False + v = cand.bit_length() - 1 + cand &= ~(1 << v) + if rec(cand & adj[v], size + 1): + return True + return False + return rec((1 << n) - 1, 0) + + +def _connected(adj, n, removed): + alive = [v for v in range(n) if not removed >> v & 1] + if len(alive) <= 1: + return True + mask = sum(1 << v for v in alive) + seen = 1 << alive[0] + stack = [alive[0]] + while stack: + v = stack.pop() + new = adj[v] & mask & ~seen + seen |= new + while new: + u = new.bit_length() - 1 + new &= ~(1 << u) + stack.append(u) + return seen == mask + + +def _girth(adj, n): + best = None + for r in range(n): + dist, par, q = {r: 0}, {r: -1}, [r] + for v in q: + nb = adj[v] + while nb: + u = nb.bit_length() - 1 + nb &= ~(1 << u) + if u not in dist: + dist[u], par[u] = dist[v] + 1, v + q.append(u) + elif par[v] != u: + c = dist[u] + dist[v] + 1 + best = c if best is None else min(best, c) + return best # None = acyclic + + +def _colourable(adj, n, k): + col = [-1] * n + order = sorted(range(n), key=lambda v: -bin(adj[v]).count("1")) + + def rec(i): + if i == n: + return True + v = order[i] + used = {col[u] for u in range(n) if adj[v] >> u & 1 and col[u] >= 0} + for c in range(k): + if c not in used: + col[v] = c + if rec(i + 1): + return True + col[v] = -1 + return False + return rec(0) + + +def check(inst, ans): + n = inst["vertices"] + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list of [u, v] pairs") + edges = set() + for e in E: + u, v = int_list(e, 2, 0, n - 1, "edge") + if u == v: + raise Invalid(f"self-loop at {u}") + e2 = (min(u, v), max(u, v)) + if e2 in edges: + raise Invalid(f"duplicate edge {e2}") + edges.add(e2) + adj = [0] * n + for u, v in edges: + adj[u] |= 1 << v + adj[v] |= 1 << u + deg = [bin(a).count("1") for a in adj] + for u, v in inst.get("required_edges", []): + if (min(u, v), max(u, v)) not in edges: + raise Invalid(f"required edge ({u},{v}) is missing") + c = inst.get + if c("min_degree") is not None and min(deg) < c("min_degree"): + raise Invalid(f"minimum degree {min(deg)} < {c('min_degree')}") + if c("max_degree") is not None and max(deg) > c("max_degree"): + raise Invalid(f"maximum degree {max(deg)} > {c('max_degree')}") + if c("min_edges") is not None and len(edges) < c("min_edges"): + raise Invalid(f"{len(edges)} edges < {c('min_edges')}") + if c("max_edges") is not None and len(edges) > c("max_edges"): + raise Invalid(f"{len(edges)} edges > {c('max_edges')}") + if c("max_clique") is not None and _has_clique(adj, n, c("max_clique") + 1): + raise Invalid(f"graph contains a clique of size {c('max_clique') + 1}") + if c("max_independent_set") is not None: + full = (1 << n) - 1 + comp = [full & ~adj[v] & ~(1 << v) for v in range(n)] + if _has_clique(comp, n, c("max_independent_set") + 1): + raise Invalid(f"graph contains an independent set of size {c('max_independent_set') + 1}") + if c("min_girth") is not None: + g = _girth(adj, n) + if g is not None and g < c("min_girth"): + raise Invalid(f"graph has a cycle of length {g} < {c('min_girth')}") + if c("min_connectivity") is not None: + k = c("min_connectivity") + if n <= k: + raise Invalid("too few vertices for this connectivity") + for s in range(k): + for I in itertools.combinations(range(n), s): + if not _connected(adj, n, sum(1 << v for v in I)): + raise Invalid(f"deleting vertices {list(I)} disconnects the graph") + if c("mtf"): + for u, v in itertools.combinations(range(n), 2): + if adj[u] >> v & 1: + if adj[u] & adj[v]: + raise Invalid(f"triangle on edge ({u},{v})") + elif not adj[u] & adj[v]: + raise Invalid(f"non-adjacent {u}, {v} have no common neighbour (edge could be added)") + if c("max_chromatic_number") is not None: + k = c("max_chromatic_number") + col = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in edges: + if col[u] == col[v]: + raise Invalid(f"coloring: edge ({u},{v}) is monochromatic") + if c("min_chromatic_number") is not None and c("min_chromatic_number") >= 2: + m = c("min_chromatic_number") + if not edges or _colourable(adj, n, m - 1): + raise Invalid(f"graph is {m - 1}-colourable, chromatic number must be at least {m}") + return None, {"num_edges": len(edges)} diff --git a/graders/mc_pysms_mtf/__pycache__/check.cpython-314.pyc b/graders/mc_pysms_mtf/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3b4279a631eafed13a4348f7f1a34d4022fc5b5 Binary files /dev/null and b/graders/mc_pysms_mtf/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_pysms_mtf/check.py b/graders/mc_pysms_mtf/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0b12508cf59b733f007a9d1f50831aec9efdf --- /dev/null +++ b/graders/mc_pysms_mtf/check.py @@ -0,0 +1,151 @@ +"""Graph-existence constraints (MathConstraint pysms_* problem types, CC-BY-4.0). The answer is a graph on +the stated vertex set, plus a proper colouring when a chromatic-number upper bound is asked for. Every +constraint present in the instance is checked exactly (no stored answer is compared). + +Upstream note: upstream verifies by fixing the edge variables in the pysms CNF and calling CaDiCaL; the +min-chromatic-number bound of pysms_graph_builder is only a raw smsg solver parameter, not a clause, so the +upstream verifier ignored it. It is enforced here. Edge endpoints are also type-checked (upstream accepted +floats/bools that compare in range).""" +import itertools + +from run import Invalid, int_list + + +def _has_clique(adj, n, k): + def rec(cand, size): + if size == k: + return True + while cand: + if size + bin(cand).count("1") < k: + return False + v = cand.bit_length() - 1 + cand &= ~(1 << v) + if rec(cand & adj[v], size + 1): + return True + return False + return rec((1 << n) - 1, 0) + + +def _connected(adj, n, removed): + alive = [v for v in range(n) if not removed >> v & 1] + if len(alive) <= 1: + return True + mask = sum(1 << v for v in alive) + seen = 1 << alive[0] + stack = [alive[0]] + while stack: + v = stack.pop() + new = adj[v] & mask & ~seen + seen |= new + while new: + u = new.bit_length() - 1 + new &= ~(1 << u) + stack.append(u) + return seen == mask + + +def _girth(adj, n): + best = None + for r in range(n): + dist, par, q = {r: 0}, {r: -1}, [r] + for v in q: + nb = adj[v] + while nb: + u = nb.bit_length() - 1 + nb &= ~(1 << u) + if u not in dist: + dist[u], par[u] = dist[v] + 1, v + q.append(u) + elif par[v] != u: + c = dist[u] + dist[v] + 1 + best = c if best is None else min(best, c) + return best # None = acyclic + + +def _colourable(adj, n, k): + col = [-1] * n + order = sorted(range(n), key=lambda v: -bin(adj[v]).count("1")) + + def rec(i): + if i == n: + return True + v = order[i] + used = {col[u] for u in range(n) if adj[v] >> u & 1 and col[u] >= 0} + for c in range(k): + if c not in used: + col[v] = c + if rec(i + 1): + return True + col[v] = -1 + return False + return rec(0) + + +def check(inst, ans): + n = inst["vertices"] + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list of [u, v] pairs") + edges = set() + for e in E: + u, v = int_list(e, 2, 0, n - 1, "edge") + if u == v: + raise Invalid(f"self-loop at {u}") + e2 = (min(u, v), max(u, v)) + if e2 in edges: + raise Invalid(f"duplicate edge {e2}") + edges.add(e2) + adj = [0] * n + for u, v in edges: + adj[u] |= 1 << v + adj[v] |= 1 << u + deg = [bin(a).count("1") for a in adj] + for u, v in inst.get("required_edges", []): + if (min(u, v), max(u, v)) not in edges: + raise Invalid(f"required edge ({u},{v}) is missing") + c = inst.get + if c("min_degree") is not None and min(deg) < c("min_degree"): + raise Invalid(f"minimum degree {min(deg)} < {c('min_degree')}") + if c("max_degree") is not None and max(deg) > c("max_degree"): + raise Invalid(f"maximum degree {max(deg)} > {c('max_degree')}") + if c("min_edges") is not None and len(edges) < c("min_edges"): + raise Invalid(f"{len(edges)} edges < {c('min_edges')}") + if c("max_edges") is not None and len(edges) > c("max_edges"): + raise Invalid(f"{len(edges)} edges > {c('max_edges')}") + if c("max_clique") is not None and _has_clique(adj, n, c("max_clique") + 1): + raise Invalid(f"graph contains a clique of size {c('max_clique') + 1}") + if c("max_independent_set") is not None: + full = (1 << n) - 1 + comp = [full & ~adj[v] & ~(1 << v) for v in range(n)] + if _has_clique(comp, n, c("max_independent_set") + 1): + raise Invalid(f"graph contains an independent set of size {c('max_independent_set') + 1}") + if c("min_girth") is not None: + g = _girth(adj, n) + if g is not None and g < c("min_girth"): + raise Invalid(f"graph has a cycle of length {g} < {c('min_girth')}") + if c("min_connectivity") is not None: + k = c("min_connectivity") + if n <= k: + raise Invalid("too few vertices for this connectivity") + for s in range(k): + for I in itertools.combinations(range(n), s): + if not _connected(adj, n, sum(1 << v for v in I)): + raise Invalid(f"deleting vertices {list(I)} disconnects the graph") + if c("mtf"): + for u, v in itertools.combinations(range(n), 2): + if adj[u] >> v & 1: + if adj[u] & adj[v]: + raise Invalid(f"triangle on edge ({u},{v})") + elif not adj[u] & adj[v]: + raise Invalid(f"non-adjacent {u}, {v} have no common neighbour (edge could be added)") + if c("max_chromatic_number") is not None: + k = c("max_chromatic_number") + col = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in edges: + if col[u] == col[v]: + raise Invalid(f"coloring: edge ({u},{v}) is monochromatic") + if c("min_chromatic_number") is not None and c("min_chromatic_number") >= 2: + m = c("min_chromatic_number") + if not edges or _colourable(adj, n, m - 1): + raise Invalid(f"graph is {m - 1}-colourable, chromatic number must be at least {m}") + return None, {"num_edges": len(edges)} diff --git a/graders/mc_pysms_num_edges_bounds/__pycache__/check.cpython-314.pyc b/graders/mc_pysms_num_edges_bounds/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdb322fd7485c4e2c95b8df4b79bfbb7a631c7af Binary files /dev/null and b/graders/mc_pysms_num_edges_bounds/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_pysms_num_edges_bounds/check.py b/graders/mc_pysms_num_edges_bounds/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0b12508cf59b733f007a9d1f50831aec9efdf --- /dev/null +++ b/graders/mc_pysms_num_edges_bounds/check.py @@ -0,0 +1,151 @@ +"""Graph-existence constraints (MathConstraint pysms_* problem types, CC-BY-4.0). The answer is a graph on +the stated vertex set, plus a proper colouring when a chromatic-number upper bound is asked for. Every +constraint present in the instance is checked exactly (no stored answer is compared). + +Upstream note: upstream verifies by fixing the edge variables in the pysms CNF and calling CaDiCaL; the +min-chromatic-number bound of pysms_graph_builder is only a raw smsg solver parameter, not a clause, so the +upstream verifier ignored it. It is enforced here. Edge endpoints are also type-checked (upstream accepted +floats/bools that compare in range).""" +import itertools + +from run import Invalid, int_list + + +def _has_clique(adj, n, k): + def rec(cand, size): + if size == k: + return True + while cand: + if size + bin(cand).count("1") < k: + return False + v = cand.bit_length() - 1 + cand &= ~(1 << v) + if rec(cand & adj[v], size + 1): + return True + return False + return rec((1 << n) - 1, 0) + + +def _connected(adj, n, removed): + alive = [v for v in range(n) if not removed >> v & 1] + if len(alive) <= 1: + return True + mask = sum(1 << v for v in alive) + seen = 1 << alive[0] + stack = [alive[0]] + while stack: + v = stack.pop() + new = adj[v] & mask & ~seen + seen |= new + while new: + u = new.bit_length() - 1 + new &= ~(1 << u) + stack.append(u) + return seen == mask + + +def _girth(adj, n): + best = None + for r in range(n): + dist, par, q = {r: 0}, {r: -1}, [r] + for v in q: + nb = adj[v] + while nb: + u = nb.bit_length() - 1 + nb &= ~(1 << u) + if u not in dist: + dist[u], par[u] = dist[v] + 1, v + q.append(u) + elif par[v] != u: + c = dist[u] + dist[v] + 1 + best = c if best is None else min(best, c) + return best # None = acyclic + + +def _colourable(adj, n, k): + col = [-1] * n + order = sorted(range(n), key=lambda v: -bin(adj[v]).count("1")) + + def rec(i): + if i == n: + return True + v = order[i] + used = {col[u] for u in range(n) if adj[v] >> u & 1 and col[u] >= 0} + for c in range(k): + if c not in used: + col[v] = c + if rec(i + 1): + return True + col[v] = -1 + return False + return rec(0) + + +def check(inst, ans): + n = inst["vertices"] + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list of [u, v] pairs") + edges = set() + for e in E: + u, v = int_list(e, 2, 0, n - 1, "edge") + if u == v: + raise Invalid(f"self-loop at {u}") + e2 = (min(u, v), max(u, v)) + if e2 in edges: + raise Invalid(f"duplicate edge {e2}") + edges.add(e2) + adj = [0] * n + for u, v in edges: + adj[u] |= 1 << v + adj[v] |= 1 << u + deg = [bin(a).count("1") for a in adj] + for u, v in inst.get("required_edges", []): + if (min(u, v), max(u, v)) not in edges: + raise Invalid(f"required edge ({u},{v}) is missing") + c = inst.get + if c("min_degree") is not None and min(deg) < c("min_degree"): + raise Invalid(f"minimum degree {min(deg)} < {c('min_degree')}") + if c("max_degree") is not None and max(deg) > c("max_degree"): + raise Invalid(f"maximum degree {max(deg)} > {c('max_degree')}") + if c("min_edges") is not None and len(edges) < c("min_edges"): + raise Invalid(f"{len(edges)} edges < {c('min_edges')}") + if c("max_edges") is not None and len(edges) > c("max_edges"): + raise Invalid(f"{len(edges)} edges > {c('max_edges')}") + if c("max_clique") is not None and _has_clique(adj, n, c("max_clique") + 1): + raise Invalid(f"graph contains a clique of size {c('max_clique') + 1}") + if c("max_independent_set") is not None: + full = (1 << n) - 1 + comp = [full & ~adj[v] & ~(1 << v) for v in range(n)] + if _has_clique(comp, n, c("max_independent_set") + 1): + raise Invalid(f"graph contains an independent set of size {c('max_independent_set') + 1}") + if c("min_girth") is not None: + g = _girth(adj, n) + if g is not None and g < c("min_girth"): + raise Invalid(f"graph has a cycle of length {g} < {c('min_girth')}") + if c("min_connectivity") is not None: + k = c("min_connectivity") + if n <= k: + raise Invalid("too few vertices for this connectivity") + for s in range(k): + for I in itertools.combinations(range(n), s): + if not _connected(adj, n, sum(1 << v for v in I)): + raise Invalid(f"deleting vertices {list(I)} disconnects the graph") + if c("mtf"): + for u, v in itertools.combinations(range(n), 2): + if adj[u] >> v & 1: + if adj[u] & adj[v]: + raise Invalid(f"triangle on edge ({u},{v})") + elif not adj[u] & adj[v]: + raise Invalid(f"non-adjacent {u}, {v} have no common neighbour (edge could be added)") + if c("max_chromatic_number") is not None: + k = c("max_chromatic_number") + col = int_list(ans.get("coloring"), n, 0, k - 1, "coloring") + for u, v in edges: + if col[u] == col[v]: + raise Invalid(f"coloring: edge ({u},{v}) is monochromatic") + if c("min_chromatic_number") is not None and c("min_chromatic_number") >= 2: + m = c("min_chromatic_number") + if not edges or _colourable(adj, n, m - 1): + raise Invalid(f"graph is {m - 1}-colourable, chromatic number must be at least {m}") + return None, {"num_edges": len(edges)} diff --git a/graders/mc_quasigroup_idempotent/__pycache__/check.cpython-314.pyc b/graders/mc_quasigroup_idempotent/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87e35148b10322a25e9f38d19100398bc2202ff2 Binary files /dev/null and b/graders/mc_quasigroup_idempotent/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_quasigroup_idempotent/check.py b/graders/mc_quasigroup_idempotent/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4563f2e9a90050cdd7c56dfc33831acde74c9ef2 --- /dev/null +++ b/graders/mc_quasigroup_idempotent/check.py @@ -0,0 +1,21 @@ +"""Idempotent quasigroup satisfying QG3, (x*y)*(y*x) = x (MathConstraint quasigroup_idempotent, CC-BY-4.0).""" +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + T = ans.get("table") + if not isinstance(T, list) or len(T) != n: + raise Invalid(f"table must be a list of {n} rows") + T = [int_list(r, n, 0, n - 1, "table row") for r in T] + full = list(range(n)) + for i in range(n): + if sorted(T[i]) != full or sorted(T[r][i] for r in range(n)) != full: + raise Invalid(f"row/column {i} is not a permutation (not a Latin square)") + if T[i][i] != i: + raise Invalid(f"not idempotent: {i}*{i} = {T[i][i]}") + for i in range(n): + for j in range(n): + if T[T[i][j]][T[j][i]] != i: + raise Invalid(f"QG3 fails for (x, y) = ({i}, {j})") + return None, {} diff --git a/graders/mc_ramsey/__pycache__/check.cpython-314.pyc b/graders/mc_ramsey/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baed76ec78561703d3f06593575c5736c33d4190 Binary files /dev/null and b/graders/mc_ramsey/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_ramsey/check.py b/graders/mc_ramsey/check.py new file mode 100644 index 0000000000000000000000000000000000000000..53526c0bc87af6298219d3e1eac5f95f01b57541 --- /dev/null +++ b/graders/mc_ramsey/check.py @@ -0,0 +1,31 @@ +"""Two-colouring of the edges of K_n with no colour-0 K_r and no colour-1 K_s (MathConstraint ramsey, +CC-BY-4.0). Adapted from pilot/grader.py check_ramsey; adds the optional fixed edge colours.""" +import itertools + +from run import Invalid, int_list + + +def check(inst, ans): + n, r, s = inst["n"], inst["r"], inst["s"] + edges = list(itertools.combinations(range(n), 2)) + col = int_list(ans.get("colors"), len(edges), 0, 1, "colors") + for name, i, v in inst.get("fixed", []): + if col[i] != v: + raise Invalid(f"fixed value {name}[{i}] = {v} not respected") + c = {e: col[i] for i, e in enumerate(edges)} + for k, colour in ((r, 0), (s, 1)): + adj = {v: {u for u in range(n) if u != v and c[(min(u, v), max(u, v))] == colour} for v in range(n)} + + def grow(size, cand): + if size == k: + return True + if size + len(cand) < k: + return False + for v in sorted(cand): + if grow(size + 1, {u for u in cand if u > v} & adj[v]): + return True + return False + + if grow(0, set(range(n))): + raise Invalid(f"monochromatic K_{k} in colour {colour}") + return None, {} diff --git a/graders/mc_social_golfers/__pycache__/check.cpython-314.pyc b/graders/mc_social_golfers/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01c418105a4754946702a4350dd6c10cf711861e Binary files /dev/null and b/graders/mc_social_golfers/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_social_golfers/check.py b/graders/mc_social_golfers/check.py new file mode 100644 index 0000000000000000000000000000000000000000..73977815b7b6094a8491075b6dc2ae1293e44930 --- /dev/null +++ b/graders/mc_social_golfers/check.py @@ -0,0 +1,25 @@ +"""Social golfer problem (MathConstraint social_golfers, CSPLib prob010, CC-BY-4.0): each week partition +the g*s players into g groups of size s; no two players share a group in more than one week.""" +from run import Invalid, int_list + + +def check(inst, ans): + g, s, w = inst["n_groups"], inst["group_size"], inst["n_weeks"] + P = g * s + sched = ans.get("schedule") + if not isinstance(sched, list) or len(sched) != w: + raise Invalid(f"schedule must be a list of {w} weeks") + met = set() + for wk, row in enumerate(sched): + row = int_list(row, P, 0, g - 1, f"week {wk}") + groups = [[p for p in range(P) if row[p] == grp] for grp in range(g)] + for grp, mem in enumerate(groups): + if len(mem) != s: + raise Invalid(f"week {wk}: group {grp} has {len(mem)} players, need {s}") + for i in range(s): + for j in range(i + 1, s): + pr = (mem[i], mem[j]) + if pr in met: + raise Invalid(f"players {pr} play together in more than one week") + met.add(pr) + return None, {} diff --git a/graders/mc_van_der_waerden/__pycache__/check.cpython-314.pyc b/graders/mc_van_der_waerden/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27ee1cb706e39a611ff68f234e1db33d7530325e Binary files /dev/null and b/graders/mc_van_der_waerden/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_van_der_waerden/check.py b/graders/mc_van_der_waerden/check.py new file mode 100644 index 0000000000000000000000000000000000000000..9853b089b6ac1773d80eac8e9e02ceb4019ad41f --- /dev/null +++ b/graders/mc_van_der_waerden/check.py @@ -0,0 +1,15 @@ +"""k-colouring of {1..n} with no monochromatic L-term arithmetic progression (MathConstraint +van_der_waerden, CC-BY-4.0).""" +from run import Invalid, int_list + + +def check(inst, ans): + n, k, L = inst["n"], inst["k"], inst["L"] + c = int_list(ans.get("colors"), n, 0, k - 1, "colors") + for a in range(n): + for d in range(1, n): + if a + (L - 1) * d >= n: + break + if all(c[a + j * d] == c[a] for j in range(1, L)): + raise Invalid(f"monochromatic progression {[a + 1 + j * d for j in range(L)]}") + return None, {} diff --git a/graders/mc_vertex_cover/__pycache__/check.cpython-314.pyc b/graders/mc_vertex_cover/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1981c5bcb11d351cb8e4914599001413c10bde7c Binary files /dev/null and b/graders/mc_vertex_cover/__pycache__/check.cpython-314.pyc differ diff --git a/graders/mc_vertex_cover/check.py b/graders/mc_vertex_cover/check.py new file mode 100644 index 0000000000000000000000000000000000000000..e3accb3da1c773fd2126b8b5b0a97b099e29c83b --- /dev/null +++ b/graders/mc_vertex_cover/check.py @@ -0,0 +1,16 @@ +"""Vertex cover of size <= k in a given graph (MathConstraint vertex_cover, CC-BY-4.0).""" +from run import Invalid, int_list + + +def check(inst, ans): + n, k = inst["n"], inst["k"] + S = int_list(ans.get("cover"), None, 0, n - 1, "cover") + if len(set(S)) != len(S): + raise Invalid("repeated vertex") + if len(S) > k: + raise Invalid(f"cover has {len(S)} vertices, at most {k} allowed") + C = set(S) + for u, v in inst["edges"]: + if u not in C and v not in C: + raise Invalid(f"edge ({u},{v}) is not covered") + return None, {"size": len(S)} diff --git a/graders/nppc_bandwidth/__pycache__/check.cpython-314.pyc b/graders/nppc_bandwidth/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d187eb66cef031b4970f5037fb7a5835aa7beb3d Binary files /dev/null and b/graders/nppc_bandwidth/__pycache__/check.cpython-314.pyc differ diff --git a/graders/nppc_bandwidth/check.py b/graders/nppc_bandwidth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..0f847cded257e6c404063dfafde33fa44163afa2 --- /dev/null +++ b/graders/nppc_bandwidth/check.py @@ -0,0 +1,14 @@ +"""Bandwidth <= b: layout must be a permutation of 0..n-1 with |p[u]-p[v]| <= b on every edge.""" +from run import Invalid, int_list + + +def check(inst, ans): + n, b = inst["num_nodes"], inst["bandwidth"] + # upstream NPPC verifier compares sorted(layout) to range(n), which also accepts floats/bools + p = int_list(ans.get("layout"), n, 0, n - 1, "layout") + if len(set(p)) != n: + raise Invalid("layout is not a permutation of 0..n-1") + for u, v in inst["edges"]: + if abs(p[u] - p[v]) > b: + raise Invalid(f"edge ({u},{v}) has stretch {abs(p[u] - p[v])} > {b}") + return None, {} diff --git a/graders/nppc_clique/__pycache__/check.cpython-314.pyc b/graders/nppc_clique/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d2cae07c3faecd92a8010a2e325d8d7b899594a Binary files /dev/null and b/graders/nppc_clique/__pycache__/check.cpython-314.pyc differ diff --git a/graders/nppc_clique/check.py b/graders/nppc_clique/check.py new file mode 100644 index 0000000000000000000000000000000000000000..98eb4fc9097fcfa31988cf0a8b79280cec2b7980 --- /dev/null +++ b/graders/nppc_clique/check.py @@ -0,0 +1,19 @@ +"""Clique of size >= k. Accepts any valid clique.""" +import itertools + +from run import Invalid, int_list + + +def check(inst, ans): + n, k = inst["num_nodes"], inst["k"] + c = int_list(ans.get("clique"), None, 0, n - 1, "clique") + # upstream NPPC verifier checks len(list) >= k but only tests pairs u < v, so [v, v, ..., v] passed + if len(set(c)) != len(c): + raise Invalid("clique contains duplicates") + if len(c) < k: + raise Invalid(f"clique has {len(c)} < {k} vertices") + es = {(min(u, v), max(u, v)) for u, v in inst["edges"]} + for u, v in itertools.combinations(sorted(c), 2): + if (u, v) not in es: + raise Invalid(f"no edge between {u} and {v}") + return None, {"size": len(c)} diff --git a/graders/nppc_dominating_set/__pycache__/check.cpython-314.pyc b/graders/nppc_dominating_set/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..350a337066ceab91133123bb1b4af022ab88383b Binary files /dev/null and b/graders/nppc_dominating_set/__pycache__/check.cpython-314.pyc differ diff --git a/graders/nppc_dominating_set/check.py b/graders/nppc_dominating_set/check.py new file mode 100644 index 0000000000000000000000000000000000000000..0677a7bcbccb02297d022ffa4b5dd15da6371bff --- /dev/null +++ b/graders/nppc_dominating_set/check.py @@ -0,0 +1,23 @@ +"""Dominating set of size <= k. Accepts any valid dominating set.""" +from run import Invalid, int_list + + +def check(inst, ans): + n, k = inst["num_nodes"], inst["k"] + # upstream NPPC verifier has no type/range checks (out-of-range labels and floats are silently used) + d = int_list(ans.get("dominating_set"), None, 0, n - 1, "dominating_set") + if len(set(d)) != len(d): + raise Invalid("dominating_set contains duplicates") + if not d or len(d) > k: + raise Invalid(f"dominating_set must have 1..{k} vertices, got {len(d)}") + dom = set(d) + s = set(d) + for u, v in inst["edges"]: + if u in s: + dom.add(v) + if v in s: + dom.add(u) + if len(dom) != n: + miss = min(set(range(n)) - dom) + raise Invalid(f"vertex {miss} is not dominated") + return None, {"size": len(d)} diff --git a/graders/nppc_independent_set/__pycache__/check.cpython-314.pyc b/graders/nppc_independent_set/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94141745065d1ce57f492bc6a1202ac325064fec Binary files /dev/null and b/graders/nppc_independent_set/__pycache__/check.cpython-314.pyc differ diff --git a/graders/nppc_independent_set/check.py b/graders/nppc_independent_set/check.py new file mode 100644 index 0000000000000000000000000000000000000000..92279a931488c7f39c08a3b11162b3f54a9c662a --- /dev/null +++ b/graders/nppc_independent_set/check.py @@ -0,0 +1,19 @@ +"""Independent set of size >= k. Accepts any valid independent set.""" +import itertools + +from run import Invalid, int_list + + +def check(inst, ans): + n, k = inst["num_nodes"], inst["k"] + s = int_list(ans.get("independent_set"), None, 0, n - 1, "independent_set") + # upstream NPPC verifier checks len(list) >= size but only tests pairs u < v, so [v]*k passed + if len(set(s)) != len(s): + raise Invalid("independent_set contains duplicates") + if len(s) < k: + raise Invalid(f"independent_set has {len(s)} < {k} vertices") + es = {(min(u, v), max(u, v)) for u, v in inst["edges"]} + for u, v in itertools.combinations(sorted(s), 2): + if (u, v) in es: + raise Invalid(f"edge between {u} and {v}") + return None, {"size": len(s)} diff --git a/graders/nppc_quad_diophantine/__pycache__/check.cpython-314.pyc b/graders/nppc_quad_diophantine/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d95408f3e25a744f2621b44a4c5a862740e184d6 Binary files /dev/null and b/graders/nppc_quad_diophantine/__pycache__/check.cpython-314.pyc differ diff --git a/graders/nppc_quad_diophantine/check.py b/graders/nppc_quad_diophantine/check.py new file mode 100644 index 0000000000000000000000000000000000000000..88989d2a8839b089c9b07dd2d3c26c21bfdca58c --- /dev/null +++ b/graders/nppc_quad_diophantine/check.py @@ -0,0 +1,11 @@ +"""a*x^2 + b*y = c in positive integers. Accepts any solution (exact integer arithmetic).""" +from run import Invalid, as_int + + +def check(inst, ans): + # upstream NPPC verifier only checks x > 0 and y > 0, so non-integer (float) x, y were accepted + x = as_int(ans.get("x"), "x", lo=1) + y = as_int(ans.get("y"), "y", lo=1) + if inst["a"] * x * x + inst["b"] * y != inst["c"]: + raise Invalid("a*x^2 + b*y != c") + return None, {} diff --git a/graders/nppc_quadratic_congruence/__pycache__/check.cpython-314.pyc b/graders/nppc_quadratic_congruence/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad385fd71065e3c2a14a26879d94b36e718acd41 Binary files /dev/null and b/graders/nppc_quadratic_congruence/__pycache__/check.cpython-314.pyc differ diff --git a/graders/nppc_quadratic_congruence/check.py b/graders/nppc_quadratic_congruence/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1a751c071a276ca0aae7fb05bfdcd7b6e0c6d3a6 --- /dev/null +++ b/graders/nppc_quadratic_congruence/check.py @@ -0,0 +1,11 @@ +"""Quadratic congruence: integer x with 1 <= x < c and x^2 = a (mod b). Accepts any such x.""" +from run import Invalid, as_int + + +def check(inst, ans): + # upstream NPPC verifier did int(x) (accepting "12", 12.9 -> 12) and only checked x < c, so negative x + # (e.g. -r for any root r) and x = 0 passed and the bound c was meaningless + x = as_int(ans.get("x"), "x", lo=1, hi=inst["c"] - 1) + if x * x % inst["b"] != inst["a"]: + raise Invalid("x^2 mod b != a") + return None, {} diff --git a/graders/nppc_three_coloring/__pycache__/check.cpython-314.pyc b/graders/nppc_three_coloring/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0cec6d83430a3dd1db54a24b28fee17bfb6286d Binary files /dev/null and b/graders/nppc_three_coloring/__pycache__/check.cpython-314.pyc differ diff --git a/graders/nppc_three_coloring/check.py b/graders/nppc_three_coloring/check.py new file mode 100644 index 0000000000000000000000000000000000000000..72362ed9180250b6c53ce0c71867ca476ac2af20 --- /dev/null +++ b/graders/nppc_three_coloring/check.py @@ -0,0 +1,12 @@ +"""Proper 3-colouring of a given graph. Accepts any valid colouring.""" +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["num_nodes"] + # upstream NPPC verifier skips the range/length check, so an all-distinct colouring passed it + c = int_list(ans.get("coloring"), n, 0, 2, "coloring") + for u, v in inst["edges"]: + if c[u] == c[v]: + raise Invalid(f"edge ({u},{v}) is monochromatic") + return None, {} diff --git a/graders/nppc_vertex_cover/__pycache__/check.cpython-314.pyc b/graders/nppc_vertex_cover/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6cdb8be67e304b225e0f78dd8df7fe463d7c0f9 Binary files /dev/null and b/graders/nppc_vertex_cover/__pycache__/check.cpython-314.pyc differ diff --git a/graders/nppc_vertex_cover/check.py b/graders/nppc_vertex_cover/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d8ed740cc660c4837d941a8d70ea394c3bc9f69e --- /dev/null +++ b/graders/nppc_vertex_cover/check.py @@ -0,0 +1,18 @@ +"""Vertex cover of size <= k. Accepts any valid cover.""" +from run import Invalid, int_list + + +def check(inst, ans): + n, k = inst["num_nodes"], inst["k"] + # upstream NPPC verifier converts to a set without type checks (floats/bools slip through and + # duplicates are silently merged); here entries must be distinct ints in range + c = int_list(ans.get("cover"), None, 0, n - 1, "cover") + if len(set(c)) != len(c): + raise Invalid("cover contains duplicates") + if len(c) > k: + raise Invalid(f"cover has {len(c)} > {k} vertices") + s = set(c) + for u, v in inst["edges"]: + if u not in s and v not in s: + raise Invalid(f"edge ({u},{v}) not covered") + return None, {"size": len(c)} diff --git a/graders/rg_graph_color/__pycache__/check.cpython-314.pyc b/graders/rg_graph_color/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6889424ed1629514a421f3e78642b5f8c84aee4 Binary files /dev/null and b/graders/rg_graph_color/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rg_graph_color/check.py b/graders/rg_graph_color/check.py new file mode 100644 index 0000000000000000000000000000000000000000..e9328912405d1c894970c90415be62bf9556ed36 --- /dev/null +++ b/graders/rg_graph_color/check.py @@ -0,0 +1,13 @@ +"""Proper colouring with colours 1..k (Reasoning Gym graph_color, Apache-2.0). Any valid colouring. +Upstream note: its verifier checks `color in allowed_colors`, so True (== 1) and 1.0 were accepted as +colours, and extra keys were ignored. Here colours must be ints in 1..k, one per vertex.""" +from run import Invalid, int_list + + +def check(inst, ans): + n, k = inst["num_vertices"], inst["num_colors"] + c = int_list(ans.get("coloring"), n, 1, k, "coloring") + for u, v in inst["edges"]: + if c[u] == c[v]: + raise Invalid(f"adjacent vertices {u} and {v} share colour {c[u]}") + return None, {} diff --git a/graders/rg_intermediate_integration/__pycache__/check.cpython-314.pyc b/graders/rg_intermediate_integration/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..187fd9ea4e6941793a86fe48b53aff117bb8f8bd Binary files /dev/null and b/graders/rg_intermediate_integration/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rg_intermediate_integration/check.py b/graders/rg_intermediate_integration/check.py new file mode 100644 index 0000000000000000000000000000000000000000..a9e364a8ede6c8215a16a04ee6b0d3529adc647d --- /dev/null +++ b/graders/rg_intermediate_integration/check.py @@ -0,0 +1,158 @@ +"""Antiderivative check (Reasoning Gym simple_integration / intermediate_integration, Apache-2.0). + +The answer string is parsed with a whitelist AST walker (no eval), differentiated with SymPy and compared +with the integrand numerically (30-digit evaluation) at fixed points inside the integrand's real domain. +Any additive constant (e.g. "+ C") is allowed. + +Upstream notes: upstream scores with sympy.parse_expr, which calls eval() on the model's string (arbitrary +code execution), and it accepts an unevaluated "Integral(f, x)" since its derivative is f. Both are +rejected here: only arithmetic, whitelisted elementary functions, the variable, C, E and pi are allowed.""" +import ast +import math +import signal + +import sympy + +from run import Invalid + +MAX_LEN = 3000 +MAX_NODES = 600 +MAX_POW_NEST = 4 # nested powers with a variable exponent (x**x**x**...) blow up differentiation +TIME_LIMIT = 40 # seconds; a slower answer is rejected +FUNCS = {"sin": sympy.sin, "cos": sympy.cos, "tan": sympy.tan, "cot": sympy.cot, "sec": sympy.sec, + "csc": sympy.csc, "asin": sympy.asin, "acos": sympy.acos, "atan": sympy.atan, "acot": sympy.acot, + "arcsin": sympy.asin, "arccos": sympy.acos, "arctan": sympy.atan, "sinh": sympy.sinh, + "cosh": sympy.cosh, "tanh": sympy.tanh, "asinh": sympy.asinh, "acosh": sympy.acosh, + "atanh": sympy.atanh, "exp": sympy.exp, "log": sympy.log, "ln": sympy.log, "sqrt": sympy.sqrt, + "Abs": sympy.Abs, "abs": sympy.Abs} +POINTS = [0.3137, 0.5521, 0.8093, 1.1171, 1.4519, 1.9033, 2.3471, 2.8123, 3.3319, 3.9107, 4.6231, + -0.3547, -0.6529, -0.9511, -1.3027, -1.7519, -2.2013, -2.7131, -3.1397, -3.8203, -4.4111, + 0.1231, -0.1523, 0.2129, -0.2617, 0.0517, -0.0719, 5.4127, -5.3311, 6.3019, -6.2203, 7.2213, + -7.1117, 8.9021, -9.3107, 10.7129, -10.6337, 12.9011, -12.8231, 15.3113, -15.2719] +MIN_POINTS = 5 + + +def parse(s, var): + if not isinstance(s, str) or not s.strip(): + raise Invalid("antiderivative must be a non-empty string") + if len(s) > MAX_LEN: + raise Invalid("expression too long") + s = s.strip() + try: + tree = ast.parse(s, mode="eval") + except SyntaxError: + raise Invalid("expression does not parse (use ** for powers and * for products)") + if sum(1 for _ in ast.walk(tree)) > MAX_NODES: + raise Invalid("expression too large") + + def pow_nest(nd): + kids = [pow_nest(c) for c in ast.iter_child_nodes(nd)] + own = isinstance(nd, ast.BinOp) and isinstance(nd.op, ast.Pow) and any( + isinstance(c, ast.Name) and c.id == var for c in ast.walk(nd.right)) + return max(kids, default=0) + (1 if own else 0) + if pow_nest(tree) > MAX_POW_NEST: + raise Invalid("too many nested powers with a variable exponent") + x = sympy.Symbol(var, real=True) + names = {var: x, "C": sympy.Symbol("C"), "E": sympy.E, "pi": sympy.pi} + + def conv(nd): + if isinstance(nd, ast.Expression): + return conv(nd.body) + if isinstance(nd, ast.Constant): + v = nd.value + if isinstance(v, bool) or not isinstance(v, (int, float)): + raise Invalid(f"constant {v!r} not allowed") + if isinstance(v, int): + if abs(v) > 10 ** 18: + raise Invalid("integer constant too large") + return sympy.Integer(v) + if not math.isfinite(v): + raise Invalid("non-finite constant") + return sympy.Float(v, 30) + if isinstance(nd, ast.Name): + if nd.id not in names: + raise Invalid(f"unknown name {nd.id!r} (the variable is {var})") + return names[nd.id] + if isinstance(nd, ast.UnaryOp) and isinstance(nd.op, (ast.USub, ast.UAdd)): + a = conv(nd.operand) + return -a if isinstance(nd.op, ast.USub) else a + if isinstance(nd, ast.BinOp): + a, b = conv(nd.left), conv(nd.right) + if isinstance(nd.op, ast.Add): + return a + b + if isinstance(nd.op, ast.Sub): + return a - b + if isinstance(nd.op, ast.Mult): + return a * b + if isinstance(nd.op, ast.Div): + if b == 0: + raise Invalid("division by zero") + return a / b + if isinstance(nd.op, ast.Pow): + if not b.free_symbols: + bv = complex(b.evalf(20)) + if bv.imag != 0 or abs(bv.real) > 100: + raise Invalid("exponent too large") + if not a.free_symbols and abs(complex(a.evalf(20))) > 1e6: + raise Invalid("numeric power too large") + return a ** b + raise Invalid("only + - * / ** are allowed (use ** for powers)") + if isinstance(nd, ast.Call): + if not isinstance(nd.func, ast.Name) or nd.func.id not in FUNCS: + raise Invalid(f"function {ast.unparse(nd.func)!r} not allowed") + if nd.keywords or len(nd.args) != 1: + raise Invalid(f"{nd.func.id} takes exactly one argument") + return FUNCS[nd.func.id](conv(nd.args[0])) + raise Invalid(f"syntax element {type(nd).__name__} not allowed") + + return conv(tree), x + + +def value(expr, x, p): + v = expr.evalf(30, subs={x: sympy.Float(p, 30)}) + try: + z = complex(v) + except (TypeError, ValueError): + return None + if not (math.isfinite(z.real) and math.isfinite(z.imag)): + return None + return z + + +def _timeout(signum, frame): + raise Invalid(f"answer took more than {TIME_LIMIT} s to check") + + +def check(inst, ans): + if hasattr(signal, "SIGALRM"): + old = signal.signal(signal.SIGALRM, _timeout) + signal.alarm(TIME_LIMIT) + try: + return _check(inst, ans) + finally: + signal.alarm(0) + signal.signal(signal.SIGALRM, old) + return _check(inst, ans) + + +def _check(inst, ans): + var = inst["variable"] + F, x = parse(ans.get("antiderivative"), var) + f, x2 = parse(inst["integrand"], var) + if not F.has(x): + raise Invalid("antiderivative does not depend on the variable") + dF = sympy.diff(F, x) + used = 0 + for p in POINTS: + fv = value(f, x2, p) + if fv is None or abs(fv.imag) > 1e-20 * (1 + abs(fv.real)): + continue # outside the integrand's real domain + gv = value(dF, x, p) + if gv is None: + raise Invalid(f"derivative of the answer cannot be evaluated at {var} = {p}") + if abs(gv - fv) > 1e-9 * max(1.0, abs(fv)): + raise Invalid(f"derivative of the answer differs from the integrand at {var} = {p}") + used += 1 + if used < MIN_POINTS: + raise Invalid("too few evaluation points in the integrand's domain") + return None, {"points": used} diff --git a/graders/rg_simple_integration/__pycache__/check.cpython-314.pyc b/graders/rg_simple_integration/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..115d6f9b6bc5f2d1a98d86cdc6bd2964e823fed2 Binary files /dev/null and b/graders/rg_simple_integration/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rg_simple_integration/check.py b/graders/rg_simple_integration/check.py new file mode 100644 index 0000000000000000000000000000000000000000..a9e364a8ede6c8215a16a04ee6b0d3529adc647d --- /dev/null +++ b/graders/rg_simple_integration/check.py @@ -0,0 +1,158 @@ +"""Antiderivative check (Reasoning Gym simple_integration / intermediate_integration, Apache-2.0). + +The answer string is parsed with a whitelist AST walker (no eval), differentiated with SymPy and compared +with the integrand numerically (30-digit evaluation) at fixed points inside the integrand's real domain. +Any additive constant (e.g. "+ C") is allowed. + +Upstream notes: upstream scores with sympy.parse_expr, which calls eval() on the model's string (arbitrary +code execution), and it accepts an unevaluated "Integral(f, x)" since its derivative is f. Both are +rejected here: only arithmetic, whitelisted elementary functions, the variable, C, E and pi are allowed.""" +import ast +import math +import signal + +import sympy + +from run import Invalid + +MAX_LEN = 3000 +MAX_NODES = 600 +MAX_POW_NEST = 4 # nested powers with a variable exponent (x**x**x**...) blow up differentiation +TIME_LIMIT = 40 # seconds; a slower answer is rejected +FUNCS = {"sin": sympy.sin, "cos": sympy.cos, "tan": sympy.tan, "cot": sympy.cot, "sec": sympy.sec, + "csc": sympy.csc, "asin": sympy.asin, "acos": sympy.acos, "atan": sympy.atan, "acot": sympy.acot, + "arcsin": sympy.asin, "arccos": sympy.acos, "arctan": sympy.atan, "sinh": sympy.sinh, + "cosh": sympy.cosh, "tanh": sympy.tanh, "asinh": sympy.asinh, "acosh": sympy.acosh, + "atanh": sympy.atanh, "exp": sympy.exp, "log": sympy.log, "ln": sympy.log, "sqrt": sympy.sqrt, + "Abs": sympy.Abs, "abs": sympy.Abs} +POINTS = [0.3137, 0.5521, 0.8093, 1.1171, 1.4519, 1.9033, 2.3471, 2.8123, 3.3319, 3.9107, 4.6231, + -0.3547, -0.6529, -0.9511, -1.3027, -1.7519, -2.2013, -2.7131, -3.1397, -3.8203, -4.4111, + 0.1231, -0.1523, 0.2129, -0.2617, 0.0517, -0.0719, 5.4127, -5.3311, 6.3019, -6.2203, 7.2213, + -7.1117, 8.9021, -9.3107, 10.7129, -10.6337, 12.9011, -12.8231, 15.3113, -15.2719] +MIN_POINTS = 5 + + +def parse(s, var): + if not isinstance(s, str) or not s.strip(): + raise Invalid("antiderivative must be a non-empty string") + if len(s) > MAX_LEN: + raise Invalid("expression too long") + s = s.strip() + try: + tree = ast.parse(s, mode="eval") + except SyntaxError: + raise Invalid("expression does not parse (use ** for powers and * for products)") + if sum(1 for _ in ast.walk(tree)) > MAX_NODES: + raise Invalid("expression too large") + + def pow_nest(nd): + kids = [pow_nest(c) for c in ast.iter_child_nodes(nd)] + own = isinstance(nd, ast.BinOp) and isinstance(nd.op, ast.Pow) and any( + isinstance(c, ast.Name) and c.id == var for c in ast.walk(nd.right)) + return max(kids, default=0) + (1 if own else 0) + if pow_nest(tree) > MAX_POW_NEST: + raise Invalid("too many nested powers with a variable exponent") + x = sympy.Symbol(var, real=True) + names = {var: x, "C": sympy.Symbol("C"), "E": sympy.E, "pi": sympy.pi} + + def conv(nd): + if isinstance(nd, ast.Expression): + return conv(nd.body) + if isinstance(nd, ast.Constant): + v = nd.value + if isinstance(v, bool) or not isinstance(v, (int, float)): + raise Invalid(f"constant {v!r} not allowed") + if isinstance(v, int): + if abs(v) > 10 ** 18: + raise Invalid("integer constant too large") + return sympy.Integer(v) + if not math.isfinite(v): + raise Invalid("non-finite constant") + return sympy.Float(v, 30) + if isinstance(nd, ast.Name): + if nd.id not in names: + raise Invalid(f"unknown name {nd.id!r} (the variable is {var})") + return names[nd.id] + if isinstance(nd, ast.UnaryOp) and isinstance(nd.op, (ast.USub, ast.UAdd)): + a = conv(nd.operand) + return -a if isinstance(nd.op, ast.USub) else a + if isinstance(nd, ast.BinOp): + a, b = conv(nd.left), conv(nd.right) + if isinstance(nd.op, ast.Add): + return a + b + if isinstance(nd.op, ast.Sub): + return a - b + if isinstance(nd.op, ast.Mult): + return a * b + if isinstance(nd.op, ast.Div): + if b == 0: + raise Invalid("division by zero") + return a / b + if isinstance(nd.op, ast.Pow): + if not b.free_symbols: + bv = complex(b.evalf(20)) + if bv.imag != 0 or abs(bv.real) > 100: + raise Invalid("exponent too large") + if not a.free_symbols and abs(complex(a.evalf(20))) > 1e6: + raise Invalid("numeric power too large") + return a ** b + raise Invalid("only + - * / ** are allowed (use ** for powers)") + if isinstance(nd, ast.Call): + if not isinstance(nd.func, ast.Name) or nd.func.id not in FUNCS: + raise Invalid(f"function {ast.unparse(nd.func)!r} not allowed") + if nd.keywords or len(nd.args) != 1: + raise Invalid(f"{nd.func.id} takes exactly one argument") + return FUNCS[nd.func.id](conv(nd.args[0])) + raise Invalid(f"syntax element {type(nd).__name__} not allowed") + + return conv(tree), x + + +def value(expr, x, p): + v = expr.evalf(30, subs={x: sympy.Float(p, 30)}) + try: + z = complex(v) + except (TypeError, ValueError): + return None + if not (math.isfinite(z.real) and math.isfinite(z.imag)): + return None + return z + + +def _timeout(signum, frame): + raise Invalid(f"answer took more than {TIME_LIMIT} s to check") + + +def check(inst, ans): + if hasattr(signal, "SIGALRM"): + old = signal.signal(signal.SIGALRM, _timeout) + signal.alarm(TIME_LIMIT) + try: + return _check(inst, ans) + finally: + signal.alarm(0) + signal.signal(signal.SIGALRM, old) + return _check(inst, ans) + + +def _check(inst, ans): + var = inst["variable"] + F, x = parse(ans.get("antiderivative"), var) + f, x2 = parse(inst["integrand"], var) + if not F.has(x): + raise Invalid("antiderivative does not depend on the variable") + dF = sympy.diff(F, x) + used = 0 + for p in POINTS: + fv = value(f, x2, p) + if fv is None or abs(fv.imag) > 1e-20 * (1 + abs(fv.real)): + continue # outside the integrand's real domain + gv = value(dF, x, p) + if gv is None: + raise Invalid(f"derivative of the answer cannot be evaluated at {var} = {p}") + if abs(gv - fv) > 1e-9 * max(1.0, abs(fv)): + raise Invalid(f"derivative of the answer differs from the integrand at {var} = {p}") + used += 1 + if used < MIN_POINTS: + raise Invalid("too few evaluation points in the integrand's domain") + return None, {"points": used} diff --git a/graders/rlve_antiderivative/__pycache__/check.cpython-314.pyc b/graders/rlve_antiderivative/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fed9230405ce9b9a786ed7afba0f9e93c004f7bb Binary files /dev/null and b/graders/rlve_antiderivative/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rlve_antiderivative/check.py b/graders/rlve_antiderivative/check.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b30b93bbbb7795b54d973e43f25b23c82cb7fc --- /dev/null +++ b/graders/rlve_antiderivative/check.py @@ -0,0 +1,107 @@ +"""Antiderivative check. The answer string is tokenised against a whitelist (x, integers, + - * / ** ( ) and a few +elementary functions) before sympy parses it, so no Python eval of untrusted text and no `integrate`/`Integral`.""" +import re +import signal + +import sympy +from sympy.parsing.sympy_parser import auto_number, parse_expr + +from run import Invalid + +x = sympy.Symbol("x") +FUNCS = {"sin": sympy.sin, "cos": sympy.cos, "tan": sympy.tan, "exp": sympy.exp, "log": sympy.log, + "sqrt": sympy.sqrt, "asin": sympy.asin, "acos": sympy.acos, "atan": sympy.atan, "sinh": sympy.sinh, + "cosh": sympy.cosh, "tanh": sympy.tanh, "E": sympy.E, "pi": sympy.pi, "x": x} +TOK = re.compile(r"\s*(?:(\d+)|([A-Za-z]+)|(\*\*|[-+*/()]))") +NPTS = 40 + + +def safe_parse(s, max_len): + if not isinstance(s, str) or not s.strip(): + raise Invalid("F must be a non-empty string") + if len(s) > max_len: + raise Invalid("expression too long") + pos = 0 + while pos < len(s): + m = TOK.match(s, pos) + if not m or m.end() == pos: + if s[pos:].strip() == "": + break + raise Invalid(f"illegal character near position {pos}") + if m.group(1) and len(m.group(1)) > 12: + raise Invalid("integer literal too long") + if m.group(2) and m.group(2) not in FUNCS: + raise Invalid(f"unknown name {m.group(2)!r}") + pos = m.end() + try: + e = parse_expr(s, local_dict=dict(FUNCS), global_dict={"__builtins__": {}, "Integer": sympy.Integer}, + transformations=(auto_number,)) + except Invalid: + raise + except Exception as ex: + raise Invalid(f"cannot parse F: {type(ex).__name__}") + if not isinstance(e, sympy.Expr): + raise Invalid("F is not an expression") + if e.free_symbols - {x}: + raise Invalid("F may only contain the variable x") + return e + + +def _val(e, pt): + v = e.evalf(40, subs={x: pt}) + if not v.is_number or v.has(sympy.zoo, sympy.nan, sympy.oo, -sympy.oo): + return None + return v + + +class _Timeout(Exception): + pass + + +def _alarm(*_): + raise _Timeout() + + +def check(inst, ans): + old = None + try: + old = signal.signal(signal.SIGALRM, _alarm) + signal.alarm(40) + except ValueError: # not in main thread + old = None + try: + return _check(inst, ans) + except _Timeout: + raise Invalid("evaluation timed out") + except RecursionError: + raise Invalid("expression too deep") + finally: + if old is not None: + signal.alarm(0) + signal.signal(signal.SIGALRM, old) + + +def _check(inst, ans): + F = safe_parse(ans.get("F"), inst["max_len"]) + if sympy.count_ops(F) > inst["max_ops"]: + raise Invalid("expression too complex") + if any(isinstance(a, sympy.Rational) and max(abs(a.p), abs(a.q)) > 10 ** 12 for a in F.atoms(sympy.Rational)): + raise Invalid("numeric constants too large") + D = sympy.diff(F, x) + f = sympy.sympify(inst["f_prime"]) # trusted instance data + ok = 0 + for k in range(NPTS): + pt = sympy.Rational(2 * k + 1, NPTS // 2 * 2) * 2 - 2 + sympy.Rational(1, 997) + vf = _val(f, pt) + if vf is None: + continue + vd = _val(D, pt) + if vd is None: + continue + err = sympy.Abs(vd - vf).evalf(40) + if err > sympy.Float("1e-20", 40) * (1 + sympy.Abs(vf).evalf(40)): + raise Invalid(f"F'(x) != f(x) at x = {float(pt):.4f}") + ok += 1 + if ok < NPTS // 4: + raise Invalid("F' could not be compared with f on enough test points") + return None, {"points_checked": ok} diff --git a/graders/rlve_bezout_identity/__pycache__/check.cpython-314.pyc b/graders/rlve_bezout_identity/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5870e718aced5e2d5d188508c878920fce21803b Binary files /dev/null and b/graders/rlve_bezout_identity/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rlve_bezout_identity/check.py b/graders/rlve_bezout_identity/check.py new file mode 100644 index 0000000000000000000000000000000000000000..b4cb860ed36974a12b71adc9a0fa3f1ad85c814a --- /dev/null +++ b/graders/rlve_bezout_identity/check.py @@ -0,0 +1,10 @@ +from run import Invalid, int_list + + +def check(inst, ans): + A = inst["A"] + X = int_list(ans.get("X"), len(A), name="X") + S = sum(a * x for a, x in zip(A, X)) + if S != inst["target"]: + raise Invalid(f"S = {S}, required {inst['target']}") + return None, {} diff --git a/graders/rlve_construct_hack_interval/__pycache__/check.cpython-314.pyc b/graders/rlve_construct_hack_interval/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a83af0277cedd4a5b24b46a342c51e05d39fbb7c Binary files /dev/null and b/graders/rlve_construct_hack_interval/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rlve_construct_hack_interval/check.py b/graders/rlve_construct_hack_interval/check.py new file mode 100644 index 0000000000000000000000000000000000000000..34b46e9758e3a50ed16c9c2a29cfc0abe663926b --- /dev/null +++ b/graders/rlve_construct_hack_interval/check.py @@ -0,0 +1,30 @@ +from run import Invalid, as_int + + +def digit_sum_prefix(n): + """sum of digit sums of all integers in [0, n] (exact, digit DP).""" + if n <= 0: + return 0 + s = str(n) + total, prefix_sum = 0, 0 + k = len(s) + for i, ch in enumerate(s): + d = int(ch) + rest = k - i - 1 + p = 10 ** rest + # numbers with this digit < d, free suffix of `rest` digits + total += d * prefix_sum * p + (d * (d - 1) // 2) * p + d * (45 * rest * p // 10 if rest else 0) + prefix_sum += d + return total + prefix_sum # include n itself + + +def check(inst, ans): + mod = inst["mod"] + L = as_int(ans.get("L"), "L", lo=1) + R = as_int(ans.get("R"), "R", lo=1, hi=10 * mod) + if L > R: + raise Invalid("need L <= R") + total = digit_sum_prefix(R) - digit_sum_prefix(L - 1) + if total % mod: + raise Invalid(f"sum of digit sums over [L, R] is {total}, not divisible by {mod}") + return None, {} diff --git a/graders/rlve_crt/__pycache__/check.cpython-314.pyc b/graders/rlve_crt/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9e760c7e6be11cb711ecc14628f992c8385d8da Binary files /dev/null and b/graders/rlve_crt/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rlve_crt/check.py b/graders/rlve_crt/check.py new file mode 100644 index 0000000000000000000000000000000000000000..886d95606ef325930b24794c0959c2ba7b254ebd --- /dev/null +++ b/graders/rlve_crt/check.py @@ -0,0 +1,11 @@ +from run import Invalid, as_int + + +def check(inst, ans): + x = as_int(ans.get("x"), "x", lo=0) + if x.bit_length() > 20000: + raise Invalid("x is unreasonably large") + for a, b in zip(inst["residues"], inst["moduli"]): + if x % b != a: + raise Invalid(f"x mod {b} = {x % b}, need {a}") + return None, {} diff --git a/graders/rlve_distinct_subset_sum_permutation/__pycache__/check.cpython-314.pyc b/graders/rlve_distinct_subset_sum_permutation/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f57469446d73eab0058c149ec9b4cebeeb3bf21 Binary files /dev/null and b/graders/rlve_distinct_subset_sum_permutation/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rlve_distinct_subset_sum_permutation/check.py b/graders/rlve_distinct_subset_sum_permutation/check.py new file mode 100644 index 0000000000000000000000000000000000000000..06bbbcf872c2fca05785f40fdfdcf85a5e5a0e7c --- /dev/null +++ b/graders/rlve_distinct_subset_sum_permutation/check.py @@ -0,0 +1,22 @@ +from collections import Counter + +from run import Invalid, int_list + + +def check(inst, ans): + A = inst["A"] + n = len(A) + B = int_list(ans.get("B"), n, name="B") + if Counter(B) != Counter(A): + raise Invalid("B is not a permutation of A") + d = [a - b for a, b in zip(A, B)] + # count subsets (including empty and full) with sum 0; the empty and full sets always qualify + ways = Counter({0: 1}) + for x in d: + nxt = Counter(ways) + for s, c in ways.items(): + nxt[s + x] += c + ways = nxt + if ways[0] != 2: + raise Invalid(f"{ways[0] - 2} non-empty proper subsets have equal sums in A and B") + return None, {} diff --git a/graders/rlve_even_degree_partition/__pycache__/check.cpython-314.pyc b/graders/rlve_even_degree_partition/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72902e913ce4d2556efec85a094b9308458b1a3d Binary files /dev/null and b/graders/rlve_even_degree_partition/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rlve_even_degree_partition/check.py b/graders/rlve_even_degree_partition/check.py new file mode 100644 index 0000000000000000000000000000000000000000..9c7f0f71ea6d10264ececcc933b97a4a0e6eaf8e --- /dev/null +++ b/graders/rlve_even_degree_partition/check.py @@ -0,0 +1,15 @@ +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + g = int_list(ans.get("groups"), n, 1, 2, "groups") + deg = [0] * n + for u, v in inst["edges"]: + if g[u] == g[v]: + deg[u] += 1 + deg[v] += 1 + for v in range(n): + if deg[v] % 2: + raise Invalid(f"vertex {v} has {deg[v]} same-group neighbours") + return None, {} diff --git a/graders/rlve_graph_isomorphism/__pycache__/check.cpython-314.pyc b/graders/rlve_graph_isomorphism/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd07c7d17ff8827149fe73b9e211147bc8d93e75 Binary files /dev/null and b/graders/rlve_graph_isomorphism/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rlve_graph_isomorphism/check.py b/graders/rlve_graph_isomorphism/check.py new file mode 100644 index 0000000000000000000000000000000000000000..64b755f5ab12e7270811ccfc2f02d104715517b7 --- /dev/null +++ b/graders/rlve_graph_isomorphism/check.py @@ -0,0 +1,13 @@ +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + p = int_list(ans.get("p"), n, 0, n - 1, "p") + if len(set(p)) != n: + raise Invalid("p is not a permutation") + e2 = {(min(u, v), max(u, v)) for u, v in inst["edges2"]} + img = {(min(p[u], p[v]), max(p[u], p[v])) for u, v in inst["edges1"]} + if img != e2: + raise Invalid(f"{len(img - e2)} edges of G1 are not mapped onto edges of G2") + return None, {} diff --git a/graders/rlve_grid_parity_construction/__pycache__/check.cpython-314.pyc b/graders/rlve_grid_parity_construction/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7c87d5e452428fefb73413f2769d41809207064 Binary files /dev/null and b/graders/rlve_grid_parity_construction/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rlve_grid_parity_construction/check.py b/graders/rlve_grid_parity_construction/check.py new file mode 100644 index 0000000000000000000000000000000000000000..89d5d286593348d0000ac10db74e1c6242be6c97 --- /dev/null +++ b/graders/rlve_grid_parity_construction/check.py @@ -0,0 +1,22 @@ +from run import Invalid + + +def check(inst, ans): + P = inst["parity"] + N, M = len(P), len(P[0]) + G = ans.get("grid") + if not isinstance(G, list) or len(G) != N: + raise Invalid(f"grid must be a list of {N} strings") + for r in G: + if not isinstance(r, str) or len(r) != M or set(r) - {"0", "1"}: + raise Invalid(f"each row must be a string of {M} characters '0'/'1'") + for i in range(N): + for j in range(M): + v = int(G[i][j]) + for di, dj in ((-1, 0), (1, 0), (0, -1), (0, 1)): + a, b = i + di, j + dj + if 0 <= a < N and 0 <= b < M: + v ^= int(G[a][b]) + if v != int(P[i][j]): + raise Invalid(f"parity mismatch at ({i}, {j})") + return None, {} diff --git a/graders/rlve_imp_party/__pycache__/check.cpython-314.pyc b/graders/rlve_imp_party/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7827232c6eede7e3710490079deb98cef56fd38b Binary files /dev/null and b/graders/rlve_imp_party/__pycache__/check.cpython-314.pyc differ diff --git a/graders/rlve_imp_party/check.py b/graders/rlve_imp_party/check.py new file mode 100644 index 0000000000000000000000000000000000000000..97b5a037a2ba8bf4495cf87cc074d1c60b11311c --- /dev/null +++ b/graders/rlve_imp_party/check.py @@ -0,0 +1,14 @@ +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + c = int_list(ans.get("clique"), n, 0, 3 * n - 1, "clique") + if len(set(c)) != n: + raise Invalid("vertices must be distinct") + es = {(min(u, v), max(u, v)) for u, v in inst["edges"]} + for i in range(n): + for j in range(i + 1, n): + if (min(c[i], c[j]), max(c[i], c[j])) not in es: + raise Invalid(f"{c[i]} and {c[j]} are not adjacent") + return None, {} diff --git a/graders/rlve_integer_linear_system/__pycache__/check.cpython-314.pyc b/graders/rlve_integer_linear_system/__pycache__/check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce67dc3c036acee1e871deca4a284ad9d25f9ed8 Binary files /dev/null and b/graders/rlve_integer_linear_system/__pycache__/check.cpython-314.pyc differ