feat: 任务书 05,runner 与 tasks 两个模块
runner 用 Docker 跑一条命令并交回结局和资源用量;tasks 读 task.json、准备运行目录、给出正式运行/校验器/轻量检查的运行定义,并从原始产物独立判分。任务目录从参考项目搬到 tasks/circle_packing/,新增 task.json;vocab 的 VERDICTS 删掉"判不了",ProcessResult 的 cancelled 改为"容器从外面被杀了"。 全新上下文审阅后的两处修复:计量 shell 以容器内 root 运行,命令经 setpriv 降权,结果写在容器自己的文件层、结束后 docker cp 取出,并加 no-new-privileges,候选无法伪造计量结果把超时记成正常退出;harness 开跑前删掉旧的 solution.json、metrics.json,旧产物不会被当成本次的值。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2025 Sakana AI
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,34 @@
|
||||
# 官方基线来源声明
|
||||
|
||||
本目录文件来自 SakanaAI/ShinkaEvolve,Apache-2.0 许可(见同目录 `LICENSE`)。
|
||||
|
||||
- 固定提交:`9912af12d423504b8d580f4179fd15f5f88b8c50`
|
||||
- 固定日期:2026-09-17(由项目负责人原字节下载并哈希固定在 `/tmp/rivalbits2-shinka-18k23a46/manifest.json`)
|
||||
|
||||
| 文件 | 原始 URL | sha256 | 修改 |
|
||||
| --- | --- | --- | --- |
|
||||
| `initial.py` | <https://raw.githubusercontent.com/SakanaAI/ShinkaEvolve/9912af12d423504b8d580f4179fd15f5f88b8c50/examples/circle_packing/initial.py> | `09da8428a85792a94a9c6cc2193b6a0db1090ce598a17b75bc0db48d0953d098` | 无(逐字节复制) |
|
||||
| `evaluate.py` | <https://raw.githubusercontent.com/SakanaAI/ShinkaEvolve/9912af12d423504b8d580f4179fd15f5f88b8c50/examples/circle_packing/evaluate.py> | `eb8b9787dc25dee24a5f5305d1e3bd876e5c336cded1c9bab7fb204612928b4d` | 无(逐字节复制) |
|
||||
| `LICENSE` | <https://raw.githubusercontent.com/SakanaAI/ShinkaEvolve/9912af12d423504b8d580f4179fd15f5f88b8c50/LICENSE> | `c3e5b1c26607caf7208d5a105c113fe240630bb873fdb8ca5b4c2e32c721ddaf` | 无 |
|
||||
|
||||
上表三个 sha256 是基线"没被改过"的唯一判据,由本项目的 `tests/tasks.test.ts`
|
||||
("基线三个文件的 sha256 等于 SOURCES.md 表上的值")逐个断言。
|
||||
|
||||
它防的是**别的测试看不见的改动**:给 `initial.py` 加一行注释、或者动一个字节的
|
||||
`evaluate.py` / `LICENSE`,成绩一位不变,别的测试都不会挂。`evaluate.py` 和 `LICENSE`
|
||||
根本不在运行路径上。
|
||||
|
||||
一个实测过的事实(参考项目里跑出来的):把 `compute_max_radii` 那个白跑 105625 次的冗余双循环删掉,
|
||||
半径和一位不差(都是 0.9597642169962064),但第 (7, 8) 对圆会重叠 2.7755575615628914e-17,
|
||||
容差 0 下判不合法,要经合法化才收下。那个冗余循环仍然是本研究的改进起点。
|
||||
|
||||
## 已知的基线事实(刻意保留,不是缺陷)
|
||||
|
||||
- `initial.py` 的 `compute_max_radii` 含嵌套的冗余缩半径循环(外层 `for i/for j`
|
||||
包了一层重复的 `for i/for j`),且外环布局(0.7 半径环经 clip 到 0.99)是退化布局;
|
||||
圆心 clip 后可能出现零半径。这些是官方基线的原样事实,是本研究的改进起点,
|
||||
**不得“修复”**——任何改进必须作为正式候选经过研究流程。
|
||||
- `evaluate.py` 依赖 `shinka.core.run_shinka_eval`(ShinkaEvolve 框架内部),
|
||||
且其聚合以候选自报的 `reported_sum` 作为 `combined_score`。本项目**不信任**
|
||||
自报分数:独立校验器 `../validate.py` 不 import 本文件,自行重算半径和。
|
||||
本文件仅作为官方协议参考保留,不在本项目的运行路径上执行。
|
||||
@@ -0,0 +1,197 @@
|
||||
"""
|
||||
Evaluator for circle packing example (n=26) with improved timeout handling
|
||||
"""
|
||||
|
||||
import os
|
||||
import argparse
|
||||
import numpy as np
|
||||
from typing import Tuple, Optional, List, Dict, Any
|
||||
|
||||
from shinka.core import run_shinka_eval
|
||||
|
||||
|
||||
def format_centers_string(centers: np.ndarray) -> str:
|
||||
"""Formats circle centers into a multi-line string for display."""
|
||||
return "\n".join(
|
||||
[
|
||||
f" centers[{i}] = ({x_coord:.4f}, {y_coord:.4f})"
|
||||
for i, (x_coord, y_coord) in enumerate(centers)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def adapted_validate_packing(
|
||||
run_output: Tuple[np.ndarray, np.ndarray, float],
|
||||
atol=0.0,
|
||||
) -> Tuple[bool, Optional[str]]:
|
||||
"""
|
||||
Validates circle packing results based on the output of 'run_packing'.
|
||||
|
||||
Args:
|
||||
run_output: Tuple (centers, radii, reported_sum) from run_packing.
|
||||
|
||||
Returns:
|
||||
(is_valid: bool, error_message: Optional[str])
|
||||
"""
|
||||
centers, radii, reported_sum = run_output
|
||||
msg = "The circles are placed correctly. There are no overlaps or any circles outside the unit square."
|
||||
if not isinstance(centers, np.ndarray):
|
||||
centers = np.array(centers)
|
||||
if not isinstance(radii, np.ndarray):
|
||||
radii = np.array(radii)
|
||||
|
||||
n_expected = 26
|
||||
if centers.shape != (n_expected, 2):
|
||||
msg = (
|
||||
f"Centers shape incorrect. Expected ({n_expected}, 2), got {centers.shape}"
|
||||
)
|
||||
return False, msg
|
||||
if radii.shape != (n_expected,):
|
||||
msg = f"Radii shape incorrect. Expected ({n_expected},), got {radii.shape}"
|
||||
return False, msg
|
||||
|
||||
if (
|
||||
not np.all(np.isfinite(centers))
|
||||
or not np.all(np.isfinite(radii))
|
||||
or not np.isfinite(reported_sum)
|
||||
):
|
||||
msg = "Non-finite values found in centers, radii, or reported_sum."
|
||||
return False, msg
|
||||
|
||||
if np.any(radii < 0):
|
||||
negative_indices = np.where(radii < 0)[0]
|
||||
msg = f"Negative radii found for circles at indices: {negative_indices}"
|
||||
return False, msg
|
||||
|
||||
if not np.isclose(np.sum(radii), reported_sum, atol=atol):
|
||||
msg = (
|
||||
f"Sum of radii ({np.sum(radii):.6f}) does not match "
|
||||
f"reported ({reported_sum:.6f})"
|
||||
)
|
||||
return False, msg
|
||||
|
||||
for i in range(n_expected):
|
||||
x, y = centers[i]
|
||||
r = radii[i]
|
||||
is_outside = (
|
||||
x - r < -atol or x + r > 1 + atol or y - r < -atol or y + r > 1 + atol
|
||||
)
|
||||
if is_outside:
|
||||
msg = (
|
||||
f"Circle {i} (x={x:.4f}, y={y:.4f}, r={r:.4f}) is outside unit square."
|
||||
)
|
||||
return False, msg
|
||||
|
||||
for i in range(n_expected):
|
||||
for j in range(i + 1, n_expected):
|
||||
dist = np.sqrt(np.sum((centers[i] - centers[j]) ** 2))
|
||||
if dist < radii[i] + radii[j] - atol:
|
||||
msg = (
|
||||
f"Circles {i} & {j} overlap. Dist: {dist:.4f}, "
|
||||
f"Sum Radii: {(radii[i] + radii[j]):.4f}"
|
||||
)
|
||||
return False, msg
|
||||
return True, msg
|
||||
|
||||
|
||||
def get_circle_packing_kwargs(run_index: int) -> Dict[str, Any]:
|
||||
"""Provides keyword arguments for circle packing runs (none needed)."""
|
||||
return {}
|
||||
|
||||
|
||||
def aggregate_circle_packing_metrics(
|
||||
results: List[Tuple[np.ndarray, np.ndarray, float]], results_dir: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Aggregates metrics for circle packing. Assumes num_runs=1.
|
||||
Saves extra.npz with detailed packing information.
|
||||
"""
|
||||
if not results:
|
||||
return {"combined_score": 0.0, "error": "No results to aggregate"}
|
||||
|
||||
centers, radii, reported_sum = results[0]
|
||||
|
||||
public_metrics = {
|
||||
"centers_str": format_centers_string(centers),
|
||||
"num_circles": centers.shape[0],
|
||||
}
|
||||
private_metrics = {
|
||||
"reported_sum_of_radii": float(reported_sum),
|
||||
}
|
||||
metrics = {
|
||||
"combined_score": float(reported_sum),
|
||||
"public": public_metrics,
|
||||
"private": private_metrics,
|
||||
}
|
||||
|
||||
extra_file = os.path.join(results_dir, "extra.npz")
|
||||
try:
|
||||
np.savez(
|
||||
extra_file,
|
||||
centers=centers,
|
||||
radii=radii,
|
||||
reported_sum=reported_sum,
|
||||
)
|
||||
print(f"Detailed packing data saved to {extra_file}")
|
||||
except Exception as e:
|
||||
print(f"Error saving extra.npz: {e}")
|
||||
metrics["extra_npz_save_error"] = str(e)
|
||||
|
||||
return metrics
|
||||
|
||||
|
||||
def main(program_path: str, results_dir: str):
|
||||
"""Runs the circle packing evaluation using shinka.eval."""
|
||||
print(f"Evaluating program: {program_path}")
|
||||
print(f"Saving results to: {results_dir}")
|
||||
os.makedirs(results_dir, exist_ok=True)
|
||||
|
||||
num_experiment_runs = 1
|
||||
|
||||
# Define a nested function to pass results_dir to the aggregator
|
||||
def _aggregator_with_context(
|
||||
r: List[Tuple[np.ndarray, np.ndarray, float]],
|
||||
) -> Dict[str, Any]:
|
||||
return aggregate_circle_packing_metrics(r, results_dir)
|
||||
|
||||
metrics, correct, error_msg = run_shinka_eval(
|
||||
program_path=program_path,
|
||||
results_dir=results_dir,
|
||||
experiment_fn_name="run_packing",
|
||||
num_runs=num_experiment_runs,
|
||||
get_experiment_kwargs=get_circle_packing_kwargs,
|
||||
validate_fn=adapted_validate_packing,
|
||||
aggregate_metrics_fn=_aggregator_with_context,
|
||||
)
|
||||
|
||||
if correct:
|
||||
print("Evaluation and Validation completed successfully.")
|
||||
else:
|
||||
print(f"Evaluation or Validation failed: {error_msg}")
|
||||
|
||||
print("Metrics:")
|
||||
for key, value in metrics.items():
|
||||
if isinstance(value, str) and len(value) > 100:
|
||||
print(f" {key}: <string_too_long_to_display>")
|
||||
else:
|
||||
print(f" {key}: {value}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Circle packing evaluator using shinka.eval"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--program_path",
|
||||
type=str,
|
||||
default="initial.py",
|
||||
help="Path to program to evaluate (must contain 'run_packing')",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--results_dir",
|
||||
type=str,
|
||||
default="results",
|
||||
help="Dir to save results (metrics.json, correct.json, extra.npz)",
|
||||
)
|
||||
parsed_args = parser.parse_args()
|
||||
main(parsed_args.program_path, parsed_args.results_dir)
|
||||
@@ -0,0 +1,100 @@
|
||||
# EVOLVE-BLOCK-START
|
||||
"""Constructor-based circle packing for n=26 circles"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def construct_packing():
|
||||
"""
|
||||
Construct a specific arrangement of 26 circles in a unit square
|
||||
that attempts to maximize the sum of their radii.
|
||||
|
||||
Returns:
|
||||
Tuple of (centers, radii, sum_of_radii)
|
||||
centers: np.array of shape (26, 2) with (x, y) coordinates
|
||||
radii: np.array of shape (26) with radius of each circle
|
||||
sum_of_radii: Sum of all radii
|
||||
"""
|
||||
# Initialize arrays for 26 circles
|
||||
n = 26
|
||||
centers = np.zeros((n, 2))
|
||||
|
||||
# Place circles in a structured pattern
|
||||
# This is a simple pattern - evolution will improve this
|
||||
|
||||
# First, place a large circle in the center
|
||||
centers[0] = [0.5, 0.5]
|
||||
|
||||
# Place 8 circles around it in a ring
|
||||
for i in range(8):
|
||||
angle = 2 * np.pi * i / 8
|
||||
centers[i + 1] = [0.5 + 0.3 * np.cos(angle), 0.5 + 0.3 * np.sin(angle)]
|
||||
|
||||
# Place 16 more circles in an outer ring
|
||||
for i in range(16):
|
||||
angle = 2 * np.pi * i / 16
|
||||
centers[i + 9] = [0.5 + 0.7 * np.cos(angle), 0.5 + 0.7 * np.sin(angle)]
|
||||
|
||||
# Additional positioning adjustment to make sure all circles
|
||||
# are inside the square and don't overlap
|
||||
# Clip to ensure everything is inside the unit square
|
||||
centers = np.clip(centers, 0.01, 0.99)
|
||||
|
||||
# Compute maximum valid radii for this configuration
|
||||
radii = compute_max_radii(centers)
|
||||
return centers, radii
|
||||
|
||||
|
||||
def compute_max_radii(centers):
|
||||
"""
|
||||
Compute the maximum possible radii for each circle position
|
||||
such that they don't overlap and stay within the unit square.
|
||||
|
||||
Args:
|
||||
centers: np.array of shape (n, 2) with (x, y) coordinates
|
||||
|
||||
Returns:
|
||||
np.array of shape (n) with radius of each circle
|
||||
"""
|
||||
n = centers.shape[0]
|
||||
radii = np.ones(n)
|
||||
|
||||
# First, limit by distance to square borders
|
||||
for i in range(n):
|
||||
x, y = centers[i]
|
||||
# Distance to borders
|
||||
radii[i] = min(x, y, 1 - x, 1 - y)
|
||||
|
||||
for i in range(n):
|
||||
for j in range(i + 1, n):
|
||||
dist = np.sqrt(np.sum((centers[i] - centers[j]) ** 2))
|
||||
|
||||
# Then, limit by distance to other circles
|
||||
# Each pair of circles with centers at distance d can have
|
||||
# sum of radii at most d to avoid overlap
|
||||
for i in range(n):
|
||||
for j in range(i + 1, n):
|
||||
dist = np.sqrt(np.sum((centers[i] - centers[j]) ** 2))
|
||||
|
||||
# If current radii would cause overlap
|
||||
if radii[i] + radii[j] > dist:
|
||||
# Scale both radii proportionally
|
||||
scale = dist / (radii[i] + radii[j])
|
||||
radii[i] *= scale
|
||||
radii[j] *= scale
|
||||
|
||||
# Ensure no negative radii due to numerical issues
|
||||
radii = np.maximum(radii, 0.0)
|
||||
return radii
|
||||
|
||||
|
||||
# EVOLVE-BLOCK-END
|
||||
|
||||
|
||||
# This part remains fixed (not evolved)
|
||||
def run_packing():
|
||||
"""Run the circle packing constructor for n=26"""
|
||||
centers, radii = construct_packing()
|
||||
# Calculate the sum of radii
|
||||
sum_radii = np.sum(radii)
|
||||
return centers, radii, sum_radii
|
||||
Reference in New Issue
Block a user