微算力 · API 导航与自营网关
API 接入 EN
未登录登录
🔬

科研代码可复现性重构专家

Code Refactor For Reproducibility · v0.1.0
入口已确认,内容待校验 文件树里有 SKILL.md,但正文还没采回,frontmatter 未核对。
效率 安全 A 级 作者 ewankeynes 公开目录收录
808 下载 0 安装 2.9k 收藏 0 浏览

简介

MIT开源的科研代码重构工具,将杂乱分析脚本转化为符合学术出版标准的可复现工作流,自动生成文档与环境配置,确保研究结果的科学可信度。

原始描述

Use when refactoring research code for publication, adding documentation to existing analysis scripts, creating reproducible computational workflows, or prep...

通过你的 Agent 添加

安装目录:code-refactor-for-reproducibility-162496/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/code-refactor-for-reproducibility-162496/
Codex CLI~/.codex/skills/code-refactor-for-reproducibility-162496/
DeepSeek Harness~/.agents/skills/code-refactor-for-reproducibility-162496/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

中文使用说明 来自收录源

核心用法

本技能专为科研场景设计,通过系统化五步工作流将杂乱的研究代码转化为符合学术出版标准的可复现工作流。用户首先使用 Analyze 阶段识别代码中的可复现性问题,包括硬编码路径、缺失随机种子、裸异常捕获等常见问题;随后在 Refactor 阶段应用最佳实践,添加标准化文档字符串、参数化配置、统一的错误处理与日志记录机制;Specify environment 阶段自动生成精确的依赖锁定文件(requirements.txt/environment.yml),消除"在我的电脑上能跑"的复现噩梦;Create documentation 阶段构建符合学术规范的README模板;最终通过 Validate 阶段执行严格的回归测试与确定性验证,确保重构前后行为完全一致。

技能深度集成Python科研生态,对NumPy、Pandas、scikit-learn、PyTorch等主流库提供针对性的随机种子设置方案,并包含完整的Conda环境管理与Docker容器化指引。

显著优点

学术规范导向:严格遵循FAIR原则(可发现、可访问、可互操作、可复用),输出直接满足Nature/Science等顶刊代码审查要求,大幅降低论文被拒或读者无法复现的风险。

零侵入式重构:采用备份-修改-验证的安全模式,通过AST静态分析自动检测问题而非强制重写,保留原有代码逻辑的同时渐进式提升质量。

生态完整性:覆盖从代码层(类型注解、日志)、环境层(依赖锁定、容器化)到文档层(API文档、复现指南)的全栈解决方案,避免用户拼凑多个工具的碎片化成本。

确定性保障:提供双轨验证机制(checksum比对+单元测试+跨运行一致性检测),特别针对机器学习研究中常见的GPU非确定性问题给出明确提示与缓解策略。

潜在缺点与局限性

语言单一性:当前版本仅深度支持Python科研代码,R、Julia、MATLAB等语言的科研用户无法直接受益,需手动适配工作流逻辑。

规模边界:针对单分析脚本或中小型项目(百级文件规模)设计,面对超大规模基因组学、气候模拟等涉及TB级数据与分布式计算的复杂流水线时,仍需配合Snakemake、Nextflow等专业工作流引擎。

领域假设:内置模板默认面向表格数据与常规机器学习任务,对计算机视觉特有的数据加载器优化、NLP的Tokenizer版本管理等细分领域支持有限。

自动化程度:环境生成依赖pipreqs等第三方工具,对动态导入、cython扩展等边缘情况的解析可能不完整,仍需人工审查。

适合的目标群体

  • 准备投稿的研究人员:即将向要求代码公开的期刊(如PLOS、Nature Research)提交论文,需快速满足可复现性审查标准
  • 实验室代码维护者:继承遗留分析脚本并需要建立可持续维护的代码库规范
  • 跨机构协作者:与外部团队共享计算流程,消除环境差异导致的沟通成本
  • 研究生与博士后:系统学习科研软件工程最佳实践,建立职业化的代码开发习惯
  • 教学场景导师:为计算生物学、数据科学课程提供标准化的代码评审与重构示范

常规使用风险

性能退化风险:添加的类型检查、日志I/O与参数解析可能引入微小开销,对单次运行秒级的轻量分析影响可忽略,但在百万次迭代的模拟中需关注profile验证。

依赖漂移风险:严格锁定的依赖版本可能滞后于安全补丁,建议配合Dependabot等自动化工具建立更新策略,而非永久冻结。

过度工程风险:针对探索性数据分析(EDA)阶段的一次性脚本强制应用完整规范可能适得其反,技能文档已明确建议根据项目成熟度选择性地应用子集规则。

验证盲区:checksum比对仅能检测输出差异,无法捕获逻辑等价的实现变化(如算法优化导致数值精度差异),需结合领域知识人工判断。

技能正文


name: code-refactor-for-reproducibility description: 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. allowed-tools: "Read Write Bash Edit" license: MIT metadata: skill-author: AIPOCH version: "1.0"

Research Code Reproducibility Refactoring Tool

Workflow Overview

Follow this sequence when refactoring a research codebase:

  1. Analyze — identify reproducibility issues in existing code
  2. Refactor — apply documentation, parameterization, and error handling
  3. Specify environment — pin dependencies and create environment files
  4. Validate — run tests and verify behaviour is unchanged

Step 1: Analyze Code for Reproducibility Issues

Read each source file and check for the following problems. Document findings before making any changes.

Checklist: missing docstrings · hardcoded absolute paths · missing random seeds · bare except: clauses · unpinned imports · unexplained magic numbers

Example — detecting issues manually:

import ast, pathlib

def find_hardcoded_paths(source: str) -> list[str]:
    """Return string literals that look like absolute paths."""
    tree = ast.parse(source)
    return [
        node.s for node in ast.walk(tree)
        if isinstance(node, ast.Constant)
        and isinstance(node.s, str)
        and node.s.startswith("/")
    ]

source = pathlib.Path("analysis.py").read_text()
print(find_hardcoded_paths(source))

Step 2: Refactor for Best Practices

Apply improvements in place. Always back up originals first.

2a. Add docstrings

# Before
def load_data(path):
    import pandas as pd
    return pd.read_csv(path)

# After
def load_data(path: str) -> "pd.DataFrame":
    """Load a CSV dataset from disk.

    Parameters
    ----------
    path : str
        Path to the CSV file (relative to project root).

    Returns
    -------
    pd.DataFrame
        Raw dataset with original column names preserved.
    """
    import pandas as pd
    return pd.read_csv(path)

2b. Parameterize hardcoded values

from pathlib import Path
import argparse

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--data", type=Path, default=Path("data/raw.csv"))
    parser.add_argument("--output", type=Path, default=Path("results/"))
    return parser.parse_args()

args = parse_args()
df = pd.read_csv(args.data)
args.output.mkdir(parents=True, exist_ok=True)

2c. Set random seeds

import random
import numpy as np

SEED = 42  # document this constant at module level

random.seed(SEED)
np.random.seed(SEED)

# scikit-learn
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(random_state=SEED)

# PyTorch
import torch
torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = True

2d. Add error handling and logging

import logging
from pathlib import Path

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

def load_data(path: Path) -> "pd.DataFrame":
    """Load dataset with validation."""
    import pandas as pd
    if not path.exists():
        raise FileNotFoundError(f"Data file not found: {path}")
    logger.info("Loading data from %s", path)
    df = pd.read_csv(path)
    if df.empty:
        raise ValueError(f"Loaded dataframe is empty: {path}")
    logger.info("Loaded %d rows, %d columns", *df.shape)
    return df

Step 3: Generate Environment Specifications

See references/environment-setup.md for full Dockerfile and Conda environment templates.

requirements.txt (pip)

pip install pipreqs
pipreqs src/ --output requirements.txt --force

Verify resolution:

python -m venv .venv_test && source .venv_test/bin/activate
pip install -r requirements.txt
python -c "import pandas, numpy, sklearn"
deactivate && rm -rf .venv_test

environment.yml (Conda)

name: my-research-env
channels:
  - conda-forge
  - defaults
dependencies:
  - python=3.9
  - numpy=1.24.3
  - pandas=2.0.1
  - scikit-learn=1.2.2
  - matplotlib=3.7.1
  - pip:
    - some-pip-only-package==0.5.0
conda env create -f environment.yml
conda activate my-research-env

Step 4: Create Documentation

README structure

Generate a README.md containing at minimum:

## Requirements
<!-- List Python version and key packages with versions -->

## Installation
```bash
conda env create -f environment.yml
conda activate my-research-env

Data

Running the Analysis

python main.py --data data/raw.csv --output results/

Expected Outputs

Reproducing Results

  • Random seed: 42 (set in config.py)
  • Hardware: results validated on CPU; GPU results may differ slightly

---

## Step 5: Validate Reproducibility

After all changes, verify that behaviour is unchanged:

```bash
# 1. Run the full pipeline and capture output checksums
python main.py --data data/raw.csv --output results/
md5sum results/*.csv > checksums_refactored.md5
diff checksums_original.md5 checksums_refactored.md5

# 2. Run unit tests
pytest tests/ -v --tb=short

# 3. Confirm determinism across two clean runs
python main.py --output results_run1/
python main.py --output results_run2/
diff -r results_run1/ results_run2/

Reproducibility verification checklist:

  • Output checksums match pre-refactor baseline
  • All tests pass
  • Pipeline runs twice and produces identical outputs
  • requirements.txt / environment.yml installs cleanly in a fresh environment
  • No absolute paths remain in source files
  • Random seeds are set and documented
  • All public functions have docstrings
  • README contains complete reproduction instructions

Best Practices Summary

Practice
Relative paths only
Pin dependency versions
Set random seeds
Docstrings on all public functions
Validate outputs against a baseline
Automate environment setup

References

  • references/guide.md — Comprehensive user guide
  • references/environment-setup.md — Dockerfile and full environment templates
  • references/examples/ — Working code examples
  • references/api-docs/ — Complete API documentation

Skill ID: 455 | Version: 1.0 | License: MIT

正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。

标签

education-researchdevelopment-engineeringdata-analyticsautomationdocsgittesting

同类 Skill