Coding SOP — Research Experiments & Data Analysis
1. Experiment Execution SOP
1.1 Hypothesis → Code → Execute → Verify
- Hypothesize: state what you expect and why
- Design: define variables, controls, sample size / iteration count
- Code:
workspace_save to outputs/scripts/; include docstring (hypothesis,
expected outcome, dependencies)
- Execute:
exec in workspace (safe commands — see §5); capture stdout + stderr
- Verify: compare against hypothesis; check for NaN/Inf/warnings; save to
outputs/reports/
- Iterate: if contradicted, revise (do NOT cherry-pick); if confirmed, document
1.2 Script Template
Every script must include: shebang, docstring (experiment title, hypothesis,
dependencies, date), seed setting (see §6), and four sections: loading,
processing, analysis, output.
2. Data Processing SOP
2.1 Pipeline: Clean → Transform → Analyze
- Inspect:
df.info(), df.describe(), df.head() — check dtypes, nulls, duplicates
- Clean: handle missing values (drop/impute/flag — document choice), fix dtypes,
remove duplicates, detect outliers (IQR, z-score, domain rules)
- Transform: normalize/standardize, encode categoricals, feature engineering,
reshape (pivot, melt, merge)
- Validate: assert expected shape, sanity-check stats, save cleaned data via
workspace_save("sources/data/<name>_clean.csv")
2.2 Common Libraries
Python: pandas/polars (DataFrames), numpy (numerics), dask (large files),
spaCy (text). R: dplyr/tidyr (wrangling), data.table/arrow (large files),
stringr/tidytext (text).
Browse analysis/wrangling/ for 10 deep-dive skills (pandas, missing data, survey, text mining).
3. Statistical Analysis Guide
3.1 Test Selection Tree
What is your research question?
│
├── Comparing groups?
│ ├── 2 groups
│ │ ├── Continuous DV, normal → Independent t-test
│ │ ├── Continuous DV, non-normal → Mann-Whitney U
│ │ ├── Paired/matched → Paired t-test / Wilcoxon signed-rank
│ │ └── Categorical DV → Chi-square / Fisher's exact
│ ├── 3+ groups
│ │ ├── 1 factor, normal → One-way ANOVA → post-hoc (Tukey/Bonferroni)
│ │ ├── 1 factor, non-normal → Kruskal-Wallis → post-hoc (Dunn)
│ │ ├── 2+ factors → Two-way / N-way ANOVA (check interactions)
│ │ └── Repeated measures → Repeated-measures ANOVA / Friedman
│ └── Pre/post with control → Mixed ANOVA / DiD
│
├── Predicting an outcome?
│ ├── Continuous outcome → Linear regression (OLS)
│ │ ├── Multiple predictors → Multiple regression
│ │ ├── Non-linear → Polynomial / GAM / splines
│ │ └── Endogeneity → IV / 2SLS (see econometrics skills)
│ ├── Binary outcome → Logistic regression
│ ├── Count/ordinal → Poisson / Ordinal logistic
│ ├── Time-to-event → Cox proportional hazards
│ └── Panel data → Fixed/random effects (see econometrics skills)
│
├── Exploring relationships?
│ ├── 2 continuous vars → Pearson r (normal) / Spearman rho (non-normal)
│ ├── 2 categorical vars → Chi-square test of independence
│ ├── Latent constructs → Factor analysis / SEM
│ └── Dimensionality → PCA / t-SNE
│
└── Estimating causal effects?
├── Randomized experiment → t-test / ANOVA with random assignment
├── Natural experiment → DiD, RDD, IV
└── Observational → Propensity score matching, synthetic control
3.2 Reporting Checklist
Every test must report: test name, statistic value (t/F/chi-sq/U/z), df, exact
p-value, effect size (Cohen's d / eta-sq / Cramer's V / OR), 95% CI, assumptions
checked (normality, homoscedasticity, independence), sample size per group.
3.3 Common Pitfalls
- Multiple comparisons: Bonferroni, Holm, or FDR correction
- p-hacking: pre-register hypotheses; never fish for p < 0.05
- Small samples: exact tests or bootstrap over asymptotic tests
- Normality: Shapiro-Wilk (n < 50) or Q-Q plot + KS test
- Confounders: include as covariates or stratify
Deep-dive skills: browse analysis/statistics/ (10 skills: Bayesian, meta-analysis,
SEM, survival, power analysis, nonparametric) and analysis/econometrics/ (12 skills:
causal inference, panel data, IV, time series).
4. Visualization SOP
4.1 Chart Type Selection
| Data pattern |
Chart type |
| Distribution (1 var) |
Histogram, KDE, box/violin plot |
| Comparison (categories) |
Bar chart, grouped bar, dot plot |
| Trend over time |
Line chart, area chart |
| Relationship (2 vars) |
Scatter plot, regression plot |
| Correlation matrix |
Heatmap |
| Composition |
Stacked bar, treemap |
| Geographic |
Choropleth, point map |
| Network / graph |
Force-directed, adjacency matrix |
| High-dimensional |
PCA biplot, t-SNE, UMAP |
4.2 Publication-Quality Standards
Set plt.rcParams for journal figures: figure.dpi: 300, font.family: serif,
font.size: 10, savefig.bbox: tight. Key rules:
- Resolution: 300 DPI minimum (600 DPI for line art)
- Format: PDF/SVG for vector; PNG/TIFF for raster (avoid JPEG)
- Color: colorblind-safe palettes (viridis, cividis, Set2)
- Labels: every axis labeled with units; legend outside if crowded
- Font: 8-12pt, match journal spec (serif or sans-serif)
- Size: single column ~3.5in, double column ~7in width
- Save:
workspace_save("outputs/figures/fig-<desc>.pdf", content)
Deep-dive skills: browse analysis/dataviz/ (14 skills: matplotlib, plotly, D3,
publication figures, color accessibility, geospatial, network viz).
5. exec Safety & Patterns
Safe (no approval): python3, Rscript, xelatex, pandoc, jq, wc, grep, find.
Requires approval_card: pip install, brew install, curl, wget, anything outside workspace.
Full safety rules in Workspace SOP.
Common patterns:
exec("python3 outputs/scripts/experiment.py") — run analysis
exec("Rscript outputs/scripts/analysis.R") — R script
exec("python3 -c \"import pandas; ...\"") — quick inspection
Output paths: All script outputs (figures, data, reports) MUST use
workspace-relative paths. Set the working directory to workspace root before
execution, and use paths like outputs/figures/, outputs/reports/.
Template for Python:
import os
os.chdir(os.environ.get('WORKSPACE_ROOT', '.'))
6. Reproducibility Protocol
6.1 Environment Recording
At analysis start, capture Python version, platform, and key package versions
(numpy, pandas, scipy, matplotlib, sklearn). Save via
workspace_save("outputs/reports/env-snapshot-<date>.json").
6.2 Reproducibility Checklist
- Random seeds: Set at script top for numpy, random, torch, tensorflow
- Version locking: Record exact versions (pip freeze / conda list)
- Data provenance: Source URL, download date, SHA-256 for raw data
- Execution order: Scripts must run independently (no notebook-state dependency)
- Relative paths: Use workspace-relative paths, not absolute
- For ML: log hyperparams, track metrics per step, save checkpoints, record hardware
7. Coding Complexity Delegation
Before writing code, assess complexity:
Simple task (single file, stdlib only, no iteration)
→ RC handles directly via exec
Complex task (multi-file, dependencies, iterative debugging)
→ Check MEMORY.md Environment for installed CLIs (codex, claude, opencode)
→ CLI found → inform user, suggest delegating via exec
→ User agrees → exec the CLI (read claude-code / codex-cli / opencode-cli skill)
→ User wants RC → proceed with RC's own capabilities
→ No CLI → recommend installation, wait for user decision
→ User insists → RC proceeds via repeated workspace_save + exec (slower)
Boundary: "complex coding" = multi-file projects, dependency management, iterative
debugging, beamer/multi-chapter LaTeX, interactive visualizations. For these, the
Claude Code, Codex CLI, and OpenCode CLI skills provide delegation guidance.
8. RC Local Tools Reference
- workspace_save: persist code to
outputs/scripts/ (or outputs/notebooks/),
figures to outputs/figures/, processed data to sources/data/.
Commit message prefix: Add: / Update:.
- workspace_append: add results to an existing report or data file without
overwriting. Preferred over read + save for incremental updates.
- workspace_download: save binary outputs (plots, exports) from URLs.
- exec: run scripts from workspace root. Default timeout 120s (increase for
long-running). Always inspect both stdout and stderr. On failure: fix code,
workspace_save again, re-run.
Related Research-Plugins Skills
For detailed methodology beyond this SOP, browse these RP skill indexes:
| Index path |
Skills |
Covers |
tools/code-exec/ |
7 |
Jupyter, Colab, Kaggle, reproducibility (Python/R) |
analysis/statistics/ |
10 |
Hypothesis testing, Bayesian, meta-analysis, SEM, survival |
analysis/econometrics/ |
12 |
Causal inference, panel data, IV, DiD, time series, Stata |
analysis/wrangling/ |
10 |
pandas, data cleaning, missing data, survey, text mining |
analysis/dataviz/ |
14 |
matplotlib, plotly, D3, publication figures, geospatial, networks |
domains/ai-ml/ |
27 |
PyTorch, TensorFlow, LLM eval, experiment tracking, ML pipelines |
tools/diagram/ |
9 |
Mermaid, PlantUML, GraphViz, flowcharts, scientific diagrams |
domains/ |
147 |
16 disciplines — browse domains/{field}/ for domain-specific analysis methods |
1---
2name: coding-sop
3description: >-
4 Standard operating procedure for research experiments, data analysis,
5 and visualization. Covers Python/R script execution, statistical analysis,
6 data wrangling (pandas/tidyverse), publication-quality figures
7 (matplotlib/plotly/ggplot2), and experiment reproducibility.
8---
9
10<!-- MAINTENANCE NOTES:
11 Scope: research code (experiments, data, viz, stats). NOT software engineering
12 (→ claude-code/codex-cli). Boundaries: workspace-sop (files/versions),
13 search-sop (literature), writing-sop (prose/LaTeX), output-cards (card schemas).
14 Sources: AGENTS.md §4 (exec safety) + new content. Size budget: ≤10K bytes.
15-->
16
17# Coding SOP — Research Experiments & Data Analysis
18
19## 1. Experiment Execution SOP
20
21### 1.1 Hypothesis → Code → Execute → Verify
22
231. **Hypothesize**: state what you expect and why
242. **Design**: define variables, controls, sample size / iteration count
253. **Code**: `workspace_save` to `outputs/scripts/`; include docstring (hypothesis,
26 expected outcome, dependencies)
274. **Execute**: `exec` in workspace (safe commands — see §5); capture stdout + stderr
285. **Verify**: compare against hypothesis; check for NaN/Inf/warnings; save to
29 `outputs/reports/`
306. **Iterate**: if contradicted, revise (do NOT cherry-pick); if confirmed, document
31
32### 1.2 Script Template
33
34Every script must include: shebang, docstring (experiment title, hypothesis,
35dependencies, date), seed setting (see §6), and four sections: loading,
36processing, analysis, output.
37
38## 2. Data Processing SOP
39
40### 2.1 Pipeline: Clean → Transform → Analyze
41
421. **Inspect**: `df.info()`, `df.describe()`, `df.head()` — check dtypes, nulls, duplicates
432. **Clean**: handle missing values (drop/impute/flag — document choice), fix dtypes,
44 remove duplicates, detect outliers (IQR, z-score, domain rules)
453. **Transform**: normalize/standardize, encode categoricals, feature engineering,
46 reshape (pivot, melt, merge)
474. **Validate**: assert expected shape, sanity-check stats, save cleaned data via
48 `workspace_save("sources/data/<name>_clean.csv")`
49
50### 2.2 Common Libraries
51
52**Python**: pandas/polars (DataFrames), numpy (numerics), dask (large files),
53spaCy (text). **R**: dplyr/tidyr (wrangling), data.table/arrow (large files),
54stringr/tidytext (text).
55
56Browse `analysis/wrangling/` for 10 deep-dive skills (pandas, missing data, survey, text mining).
57
58## 3. Statistical Analysis Guide
59
60### 3.1 Test Selection Tree
61
62```
63What is your research question?
64│
65├── Comparing groups?
66│ ├── 2 groups
67│ │ ├── Continuous DV, normal → Independent t-test
68│ │ ├── Continuous DV, non-normal → Mann-Whitney U
69│ │ ├── Paired/matched → Paired t-test / Wilcoxon signed-rank
70│ │ └── Categorical DV → Chi-square / Fisher's exact
71│ ├── 3+ groups
72│ │ ├── 1 factor, normal → One-way ANOVA → post-hoc (Tukey/Bonferroni)
73│ │ ├── 1 factor, non-normal → Kruskal-Wallis → post-hoc (Dunn)
74│ │ ├── 2+ factors → Two-way / N-way ANOVA (check interactions)
75│ │ └── Repeated measures → Repeated-measures ANOVA / Friedman
76│ └── Pre/post with control → Mixed ANOVA / DiD
77│
78├── Predicting an outcome?
79│ ├── Continuous outcome → Linear regression (OLS)
80│ │ ├── Multiple predictors → Multiple regression
81│ │ ├── Non-linear → Polynomial / GAM / splines
82│ │ └── Endogeneity → IV / 2SLS (see econometrics skills)
83│ ├── Binary outcome → Logistic regression
84│ ├── Count/ordinal → Poisson / Ordinal logistic
85│ ├── Time-to-event → Cox proportional hazards
86│ └── Panel data → Fixed/random effects (see econometrics skills)
87│
88├── Exploring relationships?
89│ ├── 2 continuous vars → Pearson r (normal) / Spearman rho (non-normal)
90│ ├── 2 categorical vars → Chi-square test of independence
91│ ├── Latent constructs → Factor analysis / SEM
92│ └── Dimensionality → PCA / t-SNE
93│
94└── Estimating causal effects?
95 ├── Randomized experiment → t-test / ANOVA with random assignment
96 ├── Natural experiment → DiD, RDD, IV
97 └── Observational → Propensity score matching, synthetic control
98```
99
100### 3.2 Reporting Checklist
101
102Every test must report: test name, statistic value (t/F/chi-sq/U/z), df, exact
103p-value, effect size (Cohen's d / eta-sq / Cramer's V / OR), 95% CI, assumptions
104checked (normality, homoscedasticity, independence), sample size per group.
105
106### 3.3 Common Pitfalls
107
108- **Multiple comparisons**: Bonferroni, Holm, or FDR correction
109- **p-hacking**: pre-register hypotheses; never fish for p < 0.05
110- **Small samples**: exact tests or bootstrap over asymptotic tests
111- **Normality**: Shapiro-Wilk (n < 50) or Q-Q plot + KS test
112- **Confounders**: include as covariates or stratify
113
114**Deep-dive skills**: browse `analysis/statistics/` (10 skills: Bayesian, meta-analysis,
115SEM, survival, power analysis, nonparametric) and `analysis/econometrics/` (12 skills:
116causal inference, panel data, IV, time series).
117
118## 4. Visualization SOP
119
120### 4.1 Chart Type Selection
121
122| Data pattern | Chart type |
123|:-------------|:-----------|
124| Distribution (1 var) | Histogram, KDE, box/violin plot |
125| Comparison (categories) | Bar chart, grouped bar, dot plot |
126| Trend over time | Line chart, area chart |
127| Relationship (2 vars) | Scatter plot, regression plot |
128| Correlation matrix | Heatmap |
129| Composition | Stacked bar, treemap |
130| Geographic | Choropleth, point map |
131| Network / graph | Force-directed, adjacency matrix |
132| High-dimensional | PCA biplot, t-SNE, UMAP |
133
134### 4.2 Publication-Quality Standards
135
136Set `plt.rcParams` for journal figures: `figure.dpi: 300`, `font.family: serif`,
137`font.size: 10`, `savefig.bbox: tight`. Key rules:
138
1391. **Resolution**: 300 DPI minimum (600 DPI for line art)
1402. **Format**: PDF/SVG for vector; PNG/TIFF for raster (avoid JPEG)
1413. **Color**: colorblind-safe palettes (viridis, cividis, Set2)
1424. **Labels**: every axis labeled with units; legend outside if crowded
1435. **Font**: 8-12pt, match journal spec (serif or sans-serif)
1446. **Size**: single column ~3.5in, double column ~7in width
1457. **Save**: `workspace_save("outputs/figures/fig-<desc>.pdf", content)`
146
147**Deep-dive skills**: browse `analysis/dataviz/` (14 skills: matplotlib, plotly, D3,
148publication figures, color accessibility, geospatial, network viz).
149
150## 5. exec Safety & Patterns
151
152**Safe** (no approval): `python3`, `Rscript`, `xelatex`, `pandoc`, `jq`, `wc`, `grep`, `find`.
153**Requires approval_card**: `pip install`, `brew install`, `curl`, `wget`, anything outside workspace.
154Full safety rules in **Workspace SOP**.
155
156Common patterns:
157- `exec("python3 outputs/scripts/experiment.py")` — run analysis
158- `exec("Rscript outputs/scripts/analysis.R")` — R script
159- `exec("python3 -c \"import pandas; ...\"")` — quick inspection
160
161**Output paths**: All script outputs (figures, data, reports) MUST use
162workspace-relative paths. Set the working directory to workspace root before
163execution, and use paths like `outputs/figures/`, `outputs/reports/`.
164Template for Python:
165```python
166import os
167os.chdir(os.environ.get('WORKSPACE_ROOT', '.'))
168```
169
170## 6. Reproducibility Protocol
171
172### 6.1 Environment Recording
173
174At analysis start, capture Python version, platform, and key package versions
175(numpy, pandas, scipy, matplotlib, sklearn). Save via
176`workspace_save("outputs/reports/env-snapshot-<date>.json")`.
177
178### 6.2 Reproducibility Checklist
179
180- **Random seeds**: Set at script top for numpy, random, torch, tensorflow
181- **Version locking**: Record exact versions (pip freeze / conda list)
182- **Data provenance**: Source URL, download date, SHA-256 for raw data
183- **Execution order**: Scripts must run independently (no notebook-state dependency)
184- **Relative paths**: Use workspace-relative paths, not absolute
185- For ML: log hyperparams, track metrics per step, save checkpoints, record hardware
186
187## 7. Coding Complexity Delegation
188
189Before writing code, assess complexity:
190
191```
192Simple task (single file, stdlib only, no iteration)
193 → RC handles directly via exec
194Complex task (multi-file, dependencies, iterative debugging)
195 → Check MEMORY.md Environment for installed CLIs (codex, claude, opencode)
196 → CLI found → inform user, suggest delegating via exec
197 → User agrees → exec the CLI (read claude-code / codex-cli / opencode-cli skill)
198 → User wants RC → proceed with RC's own capabilities
199 → No CLI → recommend installation, wait for user decision
200 → User insists → RC proceeds via repeated workspace_save + exec (slower)
201```
202
203**Boundary**: "complex coding" = multi-file projects, dependency management, iterative
204debugging, beamer/multi-chapter LaTeX, interactive visualizations. For these, the
205**Claude Code**, **Codex CLI**, and **OpenCode CLI** skills provide delegation guidance.
206
207## 8. RC Local Tools Reference
208
209- **workspace_save**: persist code to `outputs/scripts/` (or `outputs/notebooks/`),
210 figures to `outputs/figures/`, processed data to `sources/data/`.
211 Commit message prefix: `Add:` / `Update:`.
212- **workspace_append**: add results to an existing report or data file without
213 overwriting. Preferred over read + save for incremental updates.
214- **workspace_download**: save binary outputs (plots, exports) from URLs.
215- **exec**: run scripts from workspace root. Default timeout 120s (increase for
216 long-running). Always inspect both stdout and stderr. On failure: fix code,
217 `workspace_save` again, re-run.
218
219## Related Research-Plugins Skills
220
221For detailed methodology beyond this SOP, browse these RP skill indexes:
222
223| Index path | Skills | Covers |
224|:-----------|:-------|:-------|
225| `tools/code-exec/` | 7 | Jupyter, Colab, Kaggle, reproducibility (Python/R) |
226| `analysis/statistics/` | 10 | Hypothesis testing, Bayesian, meta-analysis, SEM, survival |
227| `analysis/econometrics/` | 12 | Causal inference, panel data, IV, DiD, time series, Stata |
228| `analysis/wrangling/` | 10 | pandas, data cleaning, missing data, survey, text mining |
229| `analysis/dataviz/` | 14 | matplotlib, plotly, D3, publication figures, geospatial, networks |
230| `domains/ai-ml/` | 27 | PyTorch, TensorFlow, LLM eval, experiment tracking, ML pipelines |
231| `tools/diagram/` | 9 | Mermaid, PlantUML, GraphViz, flowcharts, scientific diagrams |
232| `domains/` | 147 | 16 disciplines — browse `domains/{field}/` for domain-specific analysis methods |