← Back to Skills Marketplace
aipoch-ai

Code Refactor for Reproducibility

by AIpoch · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ Security Clean
113
Downloads
0
Stars
0
Active Installs
1
Versions
Install in OpenClaw
/install code-refactor-for-reproducibility-1
Description
Use when refactoring research code for publication, adding documentation to existing analysis scripts, creating reproducible computational workflows, or prep...
README (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
Usage Guidance
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.
Capability Assessment
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.
How to Use
  1. Make sure OpenClaw is installed (local or Docker)
  2. Run the install command in chat: /install code-refactor-for-reproducibility-1
  3. After installation, invoke the skill by name or use /code-refactor-for-reproducibility-1
  4. Provide required inputs per the skill's parameter spec and get structured output
Version History
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.
Metadata
Slug code-refactor-for-reproducibility-1
Version 1.0.0
License MIT-0
All-time Installs 0
Active Installs 0
Total Versions 1
Frequently Asked Questions

What is Code Refactor for Reproducibility?

Use when refactoring research code for publication, adding documentation to existing analysis scripts, creating reproducible computational workflows, or prep... It is an AI Agent Skill for Claude Code / OpenClaw, with 113 downloads so far.

How do I install Code Refactor for Reproducibility?

Run "/install code-refactor-for-reproducibility-1" in the OpenClaw or Claude Code chat to install it in one step — no extra setup required.

Is Code Refactor for Reproducibility free?

Yes, Code Refactor for Reproducibility is completely free, licensed under MIT-0. You can download, install and use it at no cost.

Which platforms does Code Refactor for Reproducibility support?

Code Refactor for Reproducibility is cross-platform and runs anywhere OpenClaw / Claude Code is available (cross-platform).

Who created Code Refactor for Reproducibility?

It is built and maintained by AIpoch (@aipoch-ai); the current version is v1.0.0.

💬 Comments