← 返回 Skills 市场
aipoch-ai

Code Refactor for Reproducibility

作者 AIpoch · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ 安全检测通过
113
总下载
0
收藏
0
当前安装
1
版本数
在 OpenClaw 中安装
/install code-refactor-for-reproducibility-1
功能描述
Use when refactoring research code for publication, adding documentation to existing analysis scripts, creating reproducible computational workflows, or prep...
使用说明 (SKILL.md)

\r

Research Code Reproducibility Refactoring Tool\r

\r

When to Use\r

\r

  • Use this skill when the task needs Use when refactoring research code for publication, adding documentation to existing analysis scripts, creating reproducible computational workflows, or preparing code for sharing with collaborators. Transforms research code into publication-ready, reproducible workflows. Adds documentation, implements error handling, creates environment specifications, and ensures computational reproducibility for scientific publications.\r
  • Use this skill for data analysis tasks that require explicit assumptions, bounded scope, and a reproducible output format.\r
  • Use this skill when you need a documented fallback path for missing inputs, execution errors, or partial evidence.\r \r

Key Features\r

\r

  • Scope-focused workflow aligned to: Use when refactoring research code for publication, adding documentation to existing analysis scripts, creating reproducible computational workflows, or preparing code for sharing with collaborators. Transforms research code into publication-ready, reproducible workflows. Adds documentation, implements error handling, creates environment specifications, and ensures computational reproducibility for scientific publications.\r
  • Packaged executable path(s): scripts/main.py.\r
  • Structured execution path designed to keep outputs consistent and reviewable.\r \r

Dependencies\r

\r

  • Python: 3.10+. Repository baseline for current packaged skills.\r
  • numpy: unspecified. Declared in requirements.txt.\r
  • pandas: unspecified. Declared in requirements.txt.\r
  • pytest: unspecified. Declared in requirements.txt.\r
  • scipy: unspecified. Declared in requirements.txt.\r
  • src: unspecified. Declared in requirements.txt.\r \r

Example Usage\r

\r

cd "20260318/scientific-skills/Data Analytics/code-refactor-for-reproducibility"\r
python -m py_compile scripts/main.py\r
python scripts/main.py --help\r
```\r
\r
Example run plan:\r
1. Confirm the user input, output path, and any required config values.\r
2. Edit the in-file `CONFIG` block or documented parameters if the script uses fixed settings.\r
3. Run `python scripts/main.py` with the validated inputs.\r
4. Review the generated output and return the final artifact with any assumptions called out.\r
\r
## Implementation Details\r
\r
See `## Workflow` above for related details.\r
\r
- Execution model: validate the request, choose the packaged workflow, and produce a bounded deliverable.\r
- Input controls: confirm the source files, scope limits, output format, and acceptance criteria before running any script.\r
- Primary implementation surface: `scripts/main.py`.\r
- Parameters to clarify first: input path, output path, scope filters, thresholds, and any domain-specific constraints.\r
- Output discipline: keep results reproducible, identify assumptions explicitly, and avoid undocumented side effects.\r
\r
## Quick Check\r
\r
Use this command to verify that the packaged script entry point can be parsed before deeper execution.\r
\r
```bash\r
python -m py_compile scripts/main.py\r
```\r
\r
## Audit-Ready Commands\r
\r
Use these concrete commands for validation. They are intentionally self-contained and avoid placeholder paths.\r
\r
```bash\r
python -m py_compile scripts/main.py\r
python scripts/main.py --help\r
```\r
\r
## Workflow\r
\r
1. Confirm the user objective, required inputs, and non-negotiable constraints before doing detailed work.\r
2. Validate that the request matches the documented scope and stop early if the task would require unsupported assumptions.\r
3. Use the packaged script path or the documented reasoning path with only the inputs that are actually available.\r
4. Return a structured result that separates assumptions, deliverables, risks, and unresolved items.\r
5. If execution fails or inputs are incomplete, switch to the fallback path and state exactly what blocked full completion.\r
\r
## Workflow Overview\r
\r
Follow this sequence when refactoring a research codebase:\r
\r
1. **Analyze** — identify reproducibility issues in existing code\r
2. **Refactor** — apply documentation, parameterization, and error handling\r
3. **Specify environment** — pin dependencies and create environment files\r
4. **Validate** — run tests and verify behaviour is unchanged\r
\r
---\r
\r
## Step 1: Analyze Code for Reproducibility Issues\r
\r
Read each source file and check for the following problems. Document findings before making any changes.\r
\r
**Checklist:** missing docstrings · hardcoded absolute paths · missing random seeds · bare `except:` clauses · unpinned imports · unexplained magic numbers\r
\r
**Example — detecting issues manually:**\r
\r
```python\r
import ast, pathlib\r
\r
def find_hardcoded_paths(source: str) -> list[str]:\r
    """Return string literals that look like absolute paths."""\r
    tree = ast.parse(source)\r
    return [\r
        node.s for node in ast.walk(tree)\r
        if isinstance(node, ast.Constant)\r
        and isinstance(node.s, str)\r
        and node.s.startswith("/")\r
    ]\r
\r
source = pathlib.Path("analysis.py").read_text()\r
print(find_hardcoded_paths(source))\r
```\r
\r
---\r
\r
## Step 2: Refactor for Best Practices\r
\r
Apply improvements in place. Always back up originals first.\r
\r
### 2a. Add docstrings\r
\r
```python\r
\r
# Before\r
def load_data(path):\r
    import pandas as pd\r
    return pd.read_csv(path)\r
\r
# After\r
def load_data(path: str) -> "pd.DataFrame":\r
    """Load a CSV dataset from disk.\r
\r
    Parameters\r
    ----------\r
    path : str\r
        Path to the CSV file (relative to project root).\r
\r
    Returns\r
    -------\r
    pd.DataFrame\r
        Raw dataset with original column names preserved.\r
    """\r
    import pandas as pd\r
    return pd.read_csv(path)\r
```\r
\r
### 2b. Parameterize hardcoded values\r
\r
```python\r
from pathlib import Path\r
import argparse\r
\r
def parse_args():\r
    parser = argparse.ArgumentParser()\r
    parser.add_argument("--data", type=Path, default=Path("data/raw.csv"))\r
    parser.add_argument("--output", type=Path, default=Path("results/"))\r
    return parser.parse_args()\r
\r
args = parse_args()\r
df = pd.read_csv(args.data)\r
args.output.mkdir(parents=True, exist_ok=True)\r
```\r
\r
### 2c. Set random seeds\r
\r
```python\r
import random\r
import numpy as np\r
\r
SEED = 42  # document this constant at module level\r
\r
random.seed(SEED)\r
np.random.seed(SEED)\r
\r
# scikit-learn\r
from sklearn.ensemble import RandomForestClassifier\r
clf = RandomForestClassifier(random_state=SEED)\r
\r
# PyTorch\r
import torch\r
torch.manual_seed(SEED)\r
torch.backends.cudnn.deterministic = True\r
```\r
\r
### 2d. Add error handling and logging\r
\r
```python\r
import logging\r
from pathlib import Path\r
\r
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")\r
logger = logging.getLogger(__name__)\r
\r
def load_data(path: Path) -> "pd.DataFrame":\r
    """Load dataset with validation."""\r
    import pandas as pd\r
    if not path.exists():\r
        raise FileNotFoundError(f"Data file not found: {path}")\r
    logger.info("Loading data from %s", path)\r
    df = pd.read_csv(path)\r
    if df.empty:\r
        raise ValueError(f"Loaded dataframe is empty: {path}")\r
    logger.info("Loaded %d rows, %d columns", *df.shape)\r
    return df\r
```\r
\r
---\r
\r
## Step 3: Generate Environment Specifications\r
\r
See `references/environment-setup.md` for full Dockerfile and Conda environment templates.\r
\r
### requirements.txt (pip)\r
\r
```text\r
pip install pipreqs\r
pipreqs src/ --output requirements.txt --force\r
```\r
\r
Verify resolution:\r
```text\r
python -m venv .venv_test && source .venv_test/bin/activate\r
pip install -r requirements.txt\r
python -c "import pandas, numpy, sklearn"\r
deactivate && rm -rf .venv_test\r
```\r
\r
### environment.yml (Conda)\r
\r
```yaml\r
name: my-research-env\r
channels:\r
  - conda-forge\r
  - defaults\r
dependencies:\r
  - python=3.9\r
  - numpy=1.24.3\r
  - pandas=2.0.1\r
  - scikit-learn=1.2.2\r
  - matplotlib=3.7.1\r
  - pip:\r
    - some-pip-only-package==0.5.0\r
```\r
\r
```text\r
conda env create -f environment.yml\r
conda activate my-research-env\r
```\r
\r
---\r
\r
## Step 4: Create Documentation\r
\r
### README structure\r
\r
Generate a `README.md` containing at minimum:\r
\r
```markdown\r
\r
## Requirements\r
\x3C!-- List Python version and key packages with versions -->\r
\r
## Installation\r
```text\r
conda env create -f environment.yml\r
conda activate my-research-env\r
```\r
\r
## Data\r
\x3C!-- Describe input data format, source, and where to place files -->\r
\r
## Running the Analysis\r
```text\r
python main.py --data data/raw.csv --output results/\r
```\r
\r
## Expected Outputs\r
\x3C!-- Describe files created and how to interpret them -->\r
\r
## Reproducing Results\r
- Random seed: 42 (set in `config.py`)\r
- Hardware: results validated on CPU; GPU results may differ slightly\r
```\r
\r
---\r
\r
## Step 5: Validate Reproducibility\r
\r
After all changes, verify that behaviour is unchanged:\r
\r
```text\r
\r
# 1. Run the full pipeline and capture output checksums\r
python main.py --data data/raw.csv --output results/\r
md5sum results/*.csv > checksums_refactored.md5\r
diff checksums_original.md5 checksums_refactored.md5\r
\r
# 2. Run unit tests\r
pytest tests/ -v --tb=short\r
\r
# 3. Confirm determinism across two clean runs\r
python main.py --output results_run1/\r
python main.py --output results_run2/\r
diff -r results_run1/ results_run2/\r
```\r
\r
**Reproducibility verification checklist:**\r
- [ ] Output checksums match pre-refactor baseline\r
- [ ] All tests pass\r
- [ ] Pipeline runs twice and produces identical outputs\r
- [ ] `requirements.txt` / `environment.yml` installs cleanly in a fresh environment\r
- [ ] No absolute paths remain in source files\r
- [ ] Random seeds are set and documented\r
- [ ] All public functions have docstrings\r
- [ ] README contains complete reproduction instructions\r
\r
---\r
\r
## Best Practices Summary\r
\r
| Practice |\r
|---|\r
| Relative paths only |\r
| Pin dependency versions |\r
| Set random seeds |\r
| Docstrings on all public functions |\r
| Validate outputs against a baseline |\r
| Automate environment setup |\r
\r
## References\r
\r
- `references/guide.md` — Comprehensive user guide\r
- `references/environment-setup.md` — Dockerfile and full environment templates\r
- `references/examples/` — Working code examples\r
- `references/api-docs/` — Complete API documentation\r
\r
---\r
\r
**Skill ID**: 455 | **Version**: 1.0 | **License**: MIT\r
\r
## Output Requirements\r
\r
Every final response should make these items explicit when they are relevant:\r
\r
- Objective or requested deliverable\r
- Inputs used and assumptions introduced\r
- Workflow or decision path\r
- Core result, recommendation, or artifact\r
- Constraints, risks, caveats, or validation needs\r
- Unresolved items and next-step checks\r
\r
## Error Handling\r
\r
- If required inputs are missing, state exactly which fields are missing and request only the minimum additional information.\r
- If the task goes outside the documented scope, stop instead of guessing or silently widening the assignment.\r
- If `scripts/main.py` fails, report the failure point, summarize what still can be completed safely, and provide a manual fallback.\r
- Do not fabricate files, citations, data, search results, or execution outcomes.\r
\r
## Input Validation\r
\r
This skill accepts requests that match the documented purpose of `code-refactor-for-reproducibility` and include enough context to complete the workflow safely.\r
\r
Do not continue the workflow when the request is out of scope, missing a critical input, or would require unsupported assumptions. Instead respond:\r
\r
> `code-refactor-for-reproducibility` only handles its documented workflow. Please provide the missing required inputs or switch to a more suitable skill.\r
\r
## Response Template\r
\r
Use the following fixed structure for non-trivial requests:\r
\r
1. Objective\r
2. Inputs Received\r
3. Assumptions\r
4. Workflow\r
5. Deliverable\r
6. Risks and Limits\r
7. Next Checks\r
\r
If the request is simple, you may compress the structure, but still keep assumptions and limits explicit when they affect correctness.\r
安全使用建议
This skill appears coherent and self-contained, but it executes a local Python script that will read source files and write a project structure. Before running: (1) inspect scripts/main.py locally (search for network calls or subprocess.exec if you want extra assurance), (2) run python -m py_compile scripts/main.py and python scripts/main.py --help as suggested, (3) run it in an isolated directory or sandbox and back up originals to avoid accidental overwrites, and (4) note requirements.txt includes a 'src' entry which may reference a local package—verify your environment before pip/conda installs. If you will allow autonomous agent invocation, remember the agent could run the script; only grant that if you trust automated runs.
能力评估
Purpose & Capability
Name/description describe refactoring research code. The package contains an analysis/refactor entrypoint (scripts/main.py) and README/template generation consistent with that purpose. No unrelated binaries, services, or credentials are requested.
Instruction Scope
SKILL.md instructs the agent to analyze source files, confirm inputs/outputs, run the packaged Python script, and produce reproducible outputs. Those instructions remain within the stated scope and explicitly recommend backups and scope confirmation before running.
Install Mechanism
There is no install specification — instruction-only skill with an included Python script. No external downloads, package installs, or extraction from arbitrary URLs are present in the metadata.
Credentials
The skill requests no environment variables or credentials. The included requirements.txt lists common scientific packages; one entry 'src' is unusual (may reference a local package) but not a credential or unrelated secret.
Persistence & Privilege
always is false and the skill does not request persistent platform privileges. The script will create files/directories in the chosen output path (expected for this purpose) but does not modify other skills or system-wide agent settings.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install code-refactor-for-reproducibility-1
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /code-refactor-for-reproducibility-1 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
Initial release of the research code reproducibility refactoring tool. - Provides a structured workflow for refactoring research code into reproducible, publication-ready scripts. - Adds thorough documentation, error handling, and environment specification guidance. - Details steps for analyzing code, refactoring, setting random seeds, and parameterizing hardcoded values. - Includes audit-ready commands and quick checks for validation. - Offers practical code snippets and real-world usage instructions. - Emphasizes reproducibility, explicit assumptions, and clear workflow boundaries.
元数据
Slug code-refactor-for-reproducibility-1
版本 1.0.0
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 1
常见问题

Code Refactor for Reproducibility 是什么?

Use when refactoring research code for publication, adding documentation to existing analysis scripts, creating reproducible computational workflows, or prep... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 113 次。

如何安装 Code Refactor for Reproducibility?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install code-refactor-for-reproducibility-1」即可一键安装,无需额外配置。

Code Refactor for Reproducibility 是免费的吗?

是的,Code Refactor for Reproducibility 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Code Refactor for Reproducibility 支持哪些平台?

Code Refactor for Reproducibility 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Code Refactor for Reproducibility?

由 AIpoch(@aipoch-ai)开发并维护,当前版本 v1.0.0。

💬 留言讨论