[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7390F1T0MCC7E0RT2R4D5DM":3,"skill-same:01M7390F1T0MCC7E0RT2R4D5DM":65},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":6,"ownerHtmlUrl":42,"ownerBlogUrl":43,"ownerDescription":6,"updatedAt":44,"install":45,"resources":58},"01M7390F1T0MCC7E0RT2R4D5DM","fit-drift-diffusion-model",null,"Fit cognitive drift-diffusion models (Ratcliff DDM) to reaction time and accuracy data with parameter estimation (drift rate, boundary separation, non-decision time), model comparison, and parameter recovery validation. Use when modeling binary decision-making with reaction time data, estimating cognitive parameters from experimental data, comparing sequential sampling model variants, or decomposing speed-accuracy tradeoff effects into latent cognitive components.","roohe\u002Fagentic-super-skills","roohe","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99054084?v=4","01M734WCDFP6RZVT5CNM00QR26","01M734WCE4BD0T4NZS5PCV9V5F",10,"MIT","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Ffit-drift-diffusion-model\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: fit-drift-diffusion-model\nlocale: caveman-lite\nsource_locale: en\nsource_commit: 82c77053\ntranslator: \"Julius Brussee homage — caveman\"\ntranslation_date: \"2026-04-24\"\ndescription: >\n  Fit cognitive drift-diffusion models (Ratcliff DDM) to reaction time and\n  accuracy data with parameter estimation (drift rate, boundary separation,\n  non-decision time), model comparison, and parameter recovery validation.\n  Use when modeling binary decision-making with reaction time data, estimating\n  cognitive parameters from experimental data, comparing sequential sampling\n  model variants, or decomposing speed-accuracy tradeoff effects into\n  latent cognitive components.\nlicense: MIT\nallowed-tools: Read Write Edit Bash Grep Glob\nmetadata:\n  author: Philipp Thoss\n  version: \"1.0\"\n  domain: diffusion\n  complexity: advanced\n  language: multi\n  tags: diffusion, ddm, drift-diffusion, cognitive, reaction-time, estimation\n---\n\n# Fit a Drift-Diffusion Model\n\nEstimate the parameters of a drift-diffusion model (DDM) from reaction time and accuracy data, evaluate model fit against observed quantiles, compare candidate model variants, and validate estimation quality through parameter recovery simulation.\n\n## When to Use\n\n- Modeling binary decision-making with reaction time data\n- Estimating cognitive parameters (drift rate, boundary separation, non-decision time) from experimental data\n- Comparing sequential sampling model variants for a decision task\n- Validating that a DDM fitting pipeline recovers known parameter values\n- Decomposing speed-accuracy tradeoff effects into latent cognitive components\n\n## Inputs\n\n- **Required**: Reaction time data with accuracy labels (correct\u002Ferror) per trial\n- **Required**: Subject and condition identifiers for each trial\n- **Required**: Choice of DDM variant (basic 3-parameter, full 7-parameter, or hierarchical)\n- **Optional**: Prior distributions for Bayesian estimation (default: weakly informative)\n- **Optional**: Number of simulated datasets for parameter recovery (default: 100)\n- **Optional**: RT filtering bounds in seconds (default: 0.1 to 5.0)\n\n## Procedure\n\n### Step 1: Prepare Reaction Time Data\n\nClean and format the raw behavioral data for DDM fitting.\n\n1. Load the dataset and inspect columns for subject ID, condition, RT, and accuracy:\n\n```python\nimport pandas as pd\n\ndata = pd.read_csv(\"behavioral_data.csv\")\nrequired_columns = [\"subject_id\", \"condition\", \"rt\", \"accuracy\"]\nassert all(col in data.columns for col in required_columns), \\\n    f\"Missing columns: {set(required_columns) - set(data.columns)}\"\n```\n\n2. Filter outlier RTs using configurable bounds:\n\n```python\nrt_lower = 0.1  # seconds\nrt_upper = 5.0  # seconds\n\nn_before = len(data)\ndata = data[(data[\"rt\"] >= rt_lower) & (data[\"rt\"] \u003C= rt_upper)]\nn_removed = n_before - len(data)\nprint(f\"Removed {n_removed} trials ({100*n_removed\u002Fn_before:.1f}%) outside [{rt_lower}, {rt_upper}]s\")\n```\n\n3. Compute summary statistics per subject and condition:\n\n```python\nsummary = data.groupby([\"subject_id\", \"condition\"]).agg(\n    n_trials=(\"rt\", \"count\"),\n    mean_rt=(\"rt\", \"mean\"),\n    accuracy=(\"accuracy\", \"mean\")\n).reset_index()\nprint(summary.describe())\n```\n\n4. Verify minimum trial counts (DDM needs sufficient data per cell):\n\n```python\nmin_trials = summary[\"n_trials\"].min()\nassert min_trials >= 40, f\"Minimum trials per cell is {min_trials}; need at least 40 for stable estimation\"\n```\n\n**Got:** Cleaned dataframe with no RT outliers, at least 40 trials per subject-condition cell, and accuracy rates between 0.50 and 0.99.\n\n**If fail:** If trial counts are too low, consider collapsing conditions or removing subjects with excessive missing data. If accuracy is at ceiling (>0.99) or floor (\u003C0.55), the DDM may not be identifiable -- check task difficulty.\n\n### Step 2: Select DDM Variant\n\nChoose the appropriate model complexity based on the research question.\n\n1. Define the candidate model variants:\n\n```python\nmodel_variants = {\n    \"basic\": {\n        \"params\": [\"v\", \"a\", \"t\"],\n        \"description\": \"Drift rate, boundary separation, non-decision time\",\n        \"free_params\": 3\n    },\n    \"full\": {\n        \"params\": [\"v\", \"a\", \"t\", \"z\", \"sv\", \"sz\", \"st\"],\n        \"description\": \"Basic + starting point bias, cross-trial variability\",\n        \"free_params\": 7\n    },\n    \"hddm\": {\n        \"params\": [\"v\", \"a\", \"t\", \"z\"],\n        \"description\": \"Hierarchical with group-level and subject-level parameters\",\n        \"free_params\": \"4 per subject + 8 group-level\"\n    }\n}\n```\n\n2. Select based on data characteristics:\n\n| Criterion | Basic (3-param) | Full (7-param) | Hierarchical |\n|-----------|-----------------|-----------------|--------------|\n| Trials per cell | 40-100 | 200+ | 40+ (pooled) |\n| Subjects | Any | Any | 10+ |\n| Research goal | Group effects | Individual fits | Both levels |\n| Error RT shape | Symmetric | Asymmetric | Either |\n\n3. Configure the selected variant:\n\n```python\nselected_variant = \"basic\"  # adjust based on criteria above\nmodel_config = model_variants[selected_variant]\nprint(f\"Selected: {selected_variant} ({model_config['free_params']} free parameters)\")\nprint(f\"Parameters: {', '.join(model_config['params'])}\")\n```\n\n**Got:** A model variant selected with justification based on trial counts, subject count, and research question.\n\n**If fail:** If unsure between variants, start with the basic model and add complexity only if residual diagnostics indicate systematic misfit (e.g., error RT distribution mismatch).\n\n### Step 3: Estimate Parameters\n\nFit the DDM to data using maximum likelihood or Bayesian estimation.\n\n1. For MLE fitting using the `fast-dm` or Python `pyddm` approach:\n\n```python\nimport pyddm\n\nmodel = pyddm.Model(\n    drift=pyddm.DriftConstant(drift=pyddm.Fittable(minval=0, maxval=5)),\n    bound=pyddm.BoundConstant(B=pyddm.Fittable(minval=0.3, maxval=3.0)),\n    nondecision=pyddm.NonDecisionConstant(t=pyddm.Fittable(minval=0.1, maxval=0.5)),\n    overlay=pyddm.OverlayNonDecision(nondectime=pyddm.Fittable(minval=0.1, maxval=0.5)),\n    T_dur=5.0,\n    dt=0.001,\n    dx=0.001\n)\n```\n\n2. For Bayesian estimation using HDDM:\n\n```python\nimport hddm\n\nhddm_model = hddm.HDDM(data, depends_on={\"v\": \"condition\"})\nhddm_model.find_starting_values()\nhddm_model.sample(5000, burn=1000, thin=2, dbname=\"traces.db\", db=\"pickle\")\n```\n\n3. Extract and store estimated parameters:\n\n```python\nparams = hddm_model.get_group_estimates()\nprint(\"Group-level parameter estimates:\")\nfor param_name, stats in params.items():\n    print(f\"  {param_name}: {stats['mean']:.3f} [{stats['2.5q']:.3f}, {stats['97.5q']:.3f}]\")\n```\n\n4. Check convergence (Bayesian only):\n\n```python\nfrom kabuki.analyze import gelman_rubin\n\nconvergence = gelman_rubin(hddm_model)\nmax_rhat = max(convergence.values())\nprint(f\"Max Gelman-Rubin R-hat: {max_rhat:.3f}\")\nassert max_rhat \u003C 1.1, f\"Chains have not converged (R-hat = {max_rhat:.3f})\"\n```\n\n**Got:** Parameter estimates with standard errors or credible intervals. For Bayesian fits, Gelman-Rubin R-hat \u003C 1.1 for all parameters. Drift rate typically 0.5-4.0, boundary 0.5-2.5, non-decision time 0.15-0.50s.\n\n**If fail:** If estimation fails to converge, try: (a) tighter parameter bounds, (b) better starting values via grid search, (c) longer chains with more burn-in. If MLE hits boundary values, the model may be misspecified.\n\n### Step 4: Evaluate Model Fit\n\nCompare predicted and observed RT distributions using quantile-based diagnostics.\n\n1. Generate predicted RT quantiles from the fitted model:\n\n```python\nimport numpy as np\n\nquantiles = [0.1, 0.3, 0.5, 0.7, 0.9]\n\npredicted_rts = model.simulate(n_trials=10000)\npred_quantiles = np.quantile(predicted_rts[predicted_rts > 0], quantiles)  # correct\npred_quantiles_err = np.quantile(np.abs(predicted_rts[predicted_rts \u003C 0]), quantiles)  # error\n```\n\n2. Compute observed RT quantiles:\n\n```python\nobs_correct = data[data[\"accuracy\"] == 1][\"rt\"]\nobs_error = data[data[\"accuracy\"] == 0][\"rt\"]\n\nobs_quantiles = np.quantile(obs_correct, quantiles)\nobs_quantiles_err = np.quantile(obs_error, quantiles) if len(obs_error) > 10 else None\n```\n\n3. Create a quantile-probability plot (QP plot):\n\n```python\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1, 1, figsize=(8, 6))\nax.scatter(obs_quantiles, quantiles, marker=\"o\", label=\"Observed (correct)\")\nax.scatter(pred_quantiles, quantiles, marker=\"x\", label=\"Predicted (correct)\")\nif obs_quantiles_err is not None:\n    ax.scatter(obs_quantiles_err, quantiles, marker=\"o\", facecolors=\"none\", label=\"Observed (error)\")\n    ax.scatter(pred_quantiles_err, quantiles, marker=\"x\", label=\"Predicted (error)\")\nax.set_xlabel(\"RT (s)\")\nax.set_ylabel(\"Quantile\")\nax.legend()\nax.set_title(\"Quantile-Probability Plot\")\nfig.savefig(\"qp_plot.png\", dpi=150)\n```\n\n4. Compute fit statistic (chi-square on quantile bins):\n\n```python\nfrom scipy.stats import chisquare\n\nobserved_proportions = np.diff(np.concatenate([[0], quantiles, [1]]))\npredicted_proportions = np.diff(np.concatenate([[0], quantiles, [1]]))\nchi2, p_value = chisquare(observed_proportions, predicted_proportions)\nprint(f\"Chi-square fit: chi2={chi2:.3f}, p={p_value:.3f}\")\n```\n\n**Got:** QP plot shows predicted quantiles closely tracking observed quantiles for both correct and error RTs. Chi-square test is non-significant (p > 0.05), indicating adequate fit.\n\n**If fail:** If the model systematically misses fast or slow quantiles, consider adding cross-trial variability parameters (sv, st). If error RT shape is wrong, add starting point variability (sz). Refit with the extended model.\n\n### Step 5: Compare Models\n\nUse information criteria to select among candidate DDM variants.\n\n1. Fit each candidate model and collect fit statistics:\n\n```python\nmodel_results = {}\nfor variant_name in [\"basic\", \"full\"]:\n    fitted_model = fit_ddm(data, variant=variant_name)\n    model_results[variant_name] = {\n        \"log_likelihood\": fitted_model.log_likelihood,\n        \"n_params\": fitted_model.n_free_params,\n        \"bic\": fitted_model.bic,\n        \"aic\": fitted_model.aic\n    }\n```\n\n2. Compute and compare BIC values:\n\n```python\nprint(\"Model Comparison (BIC):\")\nprint(f\"{'Model':\u003C15} {'LL':>10} {'k':>5} {'BIC':>12} {'delta_BIC':>12}\")\nprint(\"-\" * 55)\n\nbest_bic = min(r[\"bic\"] for r in model_results.values())\nfor name, result in sorted(model_results.items(), key=lambda x: x[1][\"bic\"]):\n    delta = result[\"bic\"] - best_bic\n    print(f\"{name:\u003C15} {result['log_likelihood']:>10.1f} {result['n_params']:>5} \"\n          f\"{result['bic']:>12.1f} {delta:>12.1f}\")\n```\n\n3. Interpret BIC differences using standard guidelines:\n\n```python\n# BIC difference interpretation (Kass & Raftery, 1995):\n# 0-2:   Not worth mentioning\n# 2-6:   Positive evidence\n# 6-10:  Strong evidence\n# >10:   Very strong evidence\n```\n\n4. For Bayesian models, use DIC or WAIC:\n\n```python\ndic = hddm_model.dic\nprint(f\"DIC: {dic:.1f}\")\n```\n\n**Got:** A clear winner among models with BIC difference > 6, or a justified decision to retain the simpler model when the difference is \u003C 2.\n\n**If fail:** If models are indistinguishable (BIC difference \u003C 2), prefer the simpler model (parsimony). If the full model wins by a large margin, ensure the basic model was not misspecified due to data issues.\n\n### Step 6: Validate with Parameter Recovery Simulation\n\nVerify the estimation pipeline recovers known parameter values from simulated data.\n\n1. Define the ground-truth parameter grid:\n\n```python\ntrue_params = {\n    \"v\": [0.5, 1.0, 2.0, 3.0],\n    \"a\": [0.6, 1.0, 1.5, 2.0],\n    \"t\": [0.2, 0.3, 0.4]\n}\n```\n\n2. Simulate datasets and re-estimate for each combination:\n\n```python\nfrom itertools import product\n\nrecovery_results = []\nn_simulated_trials = 500  # match empirical trial count\n\nfor v_true, a_true, t_true in product(true_params[\"v\"], true_params[\"a\"], true_params[\"t\"]):\n    simulated_data = simulate_ddm(v=v_true, a=a_true, t=t_true, n=n_simulated_trials)\n    fitted = fit_ddm(simulated_data, variant=\"basic\")\n    recovery_results.append({\n        \"v_true\": v_true, \"v_est\": fitted.params[\"v\"],\n        \"a_true\": a_true, \"a_est\": fitted.params[\"a\"],\n        \"t_true\": t_true, \"t_est\": fitted.params[\"t\"]\n    })\n```\n\n3. Compute recovery statistics:\n\n```python\nrecovery_df = pd.DataFrame(recovery_results)\nfor param in [\"v\", \"a\", \"t\"]:\n    correlation = recovery_df[f\"{param}_true\"].corr(recovery_df[f\"{param}_est\"])\n    bias = (recovery_df[f\"{param}_est\"] - recovery_df[f\"{param}_true\"]).mean()\n    rmse = np.sqrt(((recovery_df[f\"{param}_est\"] - recovery_df[f\"{param}_true\"])**2).mean())\n    print(f\"{param}: r={correlation:.3f}, bias={bias:.4f}, RMSE={rmse:.4f}\")\n```\n\n4. Generate recovery scatter plots:\n\n```python\nfig, axes = plt.subplots(1, 3, figsize=(15, 5))\nfor idx, param in enumerate([\"v\", \"a\", \"t\"]):\n    ax = axes[idx]\n    ax.scatter(recovery_df[f\"{param}_true\"], recovery_df[f\"{param}_est\"], alpha=0.5)\n    lims = [recovery_df[f\"{param}_true\"].min(), recovery_df[f\"{param}_true\"].max()]\n    ax.plot(lims, lims, \"k--\", label=\"Identity\")\n    ax.set_xlabel(f\"True {param}\")\n    ax.set_ylabel(f\"Estimated {param}\")\n    ax.set_title(f\"Recovery: {param} (r={recovery_df[f'{param}_true'].corr(recovery_df[f'{param}_est']):.3f})\")\n    ax.legend()\nfig.tight_layout()\nfig.savefig(\"parameter_recovery.png\", dpi=150)\n```\n\n**Got:** Recovery correlations r > 0.85 for all parameters, bias close to zero (\u003C 5% of parameter range), and RMSE within acceptable bounds for the application.\n\n**If fail:** Low recovery for a specific parameter usually means: (a) insufficient trials -- increase n_simulated_trials, (b) parameter tradeoffs -- drift rate and boundary can trade off; fix one to test recoverability, (c) flat likelihood surface -- consider reparameterization or Bayesian estimation with informative priors.\n\n## Validation\n\n- [ ] Input data has RT and accuracy columns with correct types\n- [ ] Outlier filtering removed fewer than 10% of trials\n- [ ] Every subject-condition cell has at least 40 trials\n- [ ] Parameter estimates are within plausible ranges (v: 0-5, a: 0.3-3.0, t: 0.1-0.6)\n- [ ] Convergence diagnostics pass (R-hat \u003C 1.1 for Bayesian, gradient near zero for MLE)\n- [ ] QP plot shows predicted quantiles within 50ms of observed quantiles\n- [ ] Model comparison yields a clear ranking or justified parsimony decision\n- [ ] Parameter recovery correlations exceed r = 0.85 for all free parameters\n- [ ] Recovery bias is less than 5% of the parameter range\n\n## Pitfalls\n\n- **Insufficient trial counts**: DDM estimation is data-hungry. Fewer than 40 trials per cell leads to unstable estimates and poor recovery. Always verify trial counts before fitting.\n- **Ignoring error RTs**: The DDM jointly models correct and error RT distributions. Discarding error trials throws away information about boundary separation and starting point bias.\n- **Not filtering fast guesses**: RTs below 100ms are likely contaminants (anticipatory responses). Include them and they distort non-decision time estimates.\n- **Confusing DDM variants**: The basic model assumes no cross-trial variability. If error RTs are systematically faster than correct RTs, you need the full model with sv and sz parameters.\n- **Overfitting with the full model**: The 7-parameter DDM can overfit sparse data. Use BIC (which penalizes complexity) rather than AIC for model selection with DDMs.\n- **Skipping parameter recovery**: Without recovery validation, you cannot distinguish estimation bias from true experimental effects. Always run recovery before interpreting condition differences.\n\n## Related Skills\n\n- `analyze-diffusion-dynamics` - mathematical analysis of the diffusion process underlying the DDM\n- `implement-diffusion-network` - generative diffusion models that share the forward-process framework\n- `design-experiment` - experimental design considerations for collecting DDM-quality data\n- `write-testthat-tests` - testing parameter estimation pipelines in R\n","# Fit a Drift-Diffusion Model\n\nEstimate the parameters of a drift-diffusion model (DDM) from reaction time and accuracy data, evaluate model fit against observed quantiles, compare candidate model variants, and validate estimation quality through parameter recovery simulation.\n\n## When to Use\n\n- Modeling binary decision-making with reaction time data\n- Estimating cognitive parameters (drift rate, boundary separation, non-decision time) from experimental data\n- Comparing sequential sampling model variants for a decision task\n- Validating that a DDM fitting pipeline recovers known parameter values\n- Decomposing speed-accuracy tradeoff effects into latent cognitive components\n\n## Inputs\n\n- **Required**: Reaction time data with accuracy labels (correct\u002Ferror) per trial\n- **Required**: Subject and condition identifiers for each trial\n- **Required**: Choice of DDM variant (basic 3-parameter, full 7-parameter, or hierarchical)\n- **Optional**: Prior distributions for Bayesian estimation (default: weakly informative)\n- **Optional**: Number of simulated datasets for parameter recovery (default: 100)\n- **Optional**: RT filtering bounds in seconds (default: 0.1 to 5.0)\n\n## Procedure\n\n### Step 1: Prepare Reaction Time Data\n\nClean and format the raw behavioral data for DDM fitting.\n\n1. Load the dataset and inspect columns for subject ID, condition, RT, and accuracy:\n\n```python\nimport pandas as pd\n\ndata = pd.read_csv(\"behavioral_data.csv\")\nrequired_columns = [\"subject_id\", \"condition\", \"rt\", \"accuracy\"]\nassert all(col in data.columns for col in required_columns), \\\n    f\"Missing columns: {set(required_columns) - set(data.columns)}\"\n```\n\n2. Filter outlier RTs using configurable bounds:\n\n```python\nrt_lower = 0.1  # seconds\nrt_upper = 5.0  # seconds\n\nn_before = len(data)\ndata = data[(data[\"rt\"] >= rt_lower) & (data[\"rt\"] \u003C= rt_upper)]\nn_removed = n_before - len(data)\nprint(f\"Removed {n_removed} trials ({100*n_removed\u002Fn_before:.1f}%) outside [{rt_lower}, {rt_upper}]s\")\n```\n\n3. Compute summary statistics per subject and condition:\n\n```python\nsummary = data.groupby([\"subject_id\", \"condition\"]).agg(\n    n_trials=(\"rt\", \"count\"),\n    mean_rt=(\"rt\", \"mean\"),\n    accuracy=(\"accuracy\", \"mean\")\n).reset_index()\nprint(summary.describe())\n```\n\n4. Verify minimum trial counts (DDM needs sufficient data per cell):\n\n```python\nmin_trials = summary[\"n_trials\"].min()\nassert min_trials >= 40, f\"Minimum trials per cell is {min_trials}; need at least 40 for stable estimation\"\n```\n\n**Got:** Cleaned dataframe with no RT outliers, at least 40 trials per subject-condition cell, and accuracy rates between 0.50 and 0.99.\n\n**If fail:** If trial counts are too low, consider collapsing conditions or removing subjects with excessive missing data. If accuracy is at ceiling (>0.99) or floor (\u003C0.55), the DDM may not be identifiable -- check task difficulty.\n\n### Step 2: Select DDM Variant\n\nChoose the appropriate model complexity based on the research question.\n\n1. Define the candidate model variants:\n\n```python\nmodel_variants = {\n    \"basic\": {\n        \"params\": [\"v\", \"a\", \"t\"],\n        \"description\": \"Drift rate, boundary separation, non-decision time\",\n        \"free_params\": 3\n    },\n    \"full\": {\n        \"params\": [\"v\", \"a\", \"t\", \"z\", \"sv\", \"sz\", \"st\"],\n        \"description\": \"Basic + starting point bias, cross-trial variability\",\n        \"free_params\": 7\n    },\n    \"hddm\": {\n        \"params\": [\"v\", \"a\", \"t\", \"z\"],\n        \"description\": \"Hierarchical with group-level and subject-level parameters\",\n        \"free_params\": \"4 per subject + 8 group-level\"\n    }\n}\n```\n\n2. Select based on data characteristics:\n\n| Criterion | Basic (3-param) | Full (7-param) | Hierarchical |\n|-----------|-----------------|-----------------|--------------|\n| Trials per cell | 40-100 | 200+ | 40+ (pooled) |\n| Subjects | Any | Any | 10+ |\n| Research goal | Group effects | Individual fits | Both levels |\n| Error RT shape | Symmetric | Asymmetric | Either |\n\n3. Configure the selected variant:\n\n```python\nselected_variant = \"basic\"  # adjust based on criteria above\nmodel_config = model_variants[selected_variant]\nprint(f\"Selected: {selected_variant} ({model_config['free_params']} free parameters)\")\nprint(f\"Parameters: {', '.join(model_config['params'])}\")\n```\n\n**Got:** A model variant selected with justification based on trial counts, subject count, and research question.\n\n**If fail:** If unsure between variants, start with the basic model and add complexity only if residual diagnostics indicate systematic misfit (e.g., error RT distribution mismatch).\n\n### Step 3: Estimate Parameters\n\nFit the DDM to data using maximum likelihood or Bayesian estimation.\n\n1. For MLE fitting using the `fast-dm` or Python `pyddm` approach:\n\n```python\nimport pyddm\n\nmodel = pyddm.Model(\n    drift=pyddm.DriftConstant(drift=pyddm.Fittable(minval=0, maxval=5)),\n    bound=pyddm.BoundConstant(B=pyddm.Fittable(minval=0.3, maxval=3.0)),\n    nondecision=pyddm.NonDecisionConstant(t=pyddm.Fittable(minval=0.1, maxval=0.5)),\n    overlay=pyddm.OverlayNonDecision(nondectime=pyddm.Fittable(minval=0.1, maxval=0.5)),\n    T_dur=5.0,\n    dt=0.001,\n    dx=0.001\n)\n```\n\n2. For Bayesian estimation using HDDM:\n\n```python\nimport hddm\n\nhddm_model = hddm.HDDM(data, depends_on={\"v\": \"condition\"})\nhddm_model.find_starting_values()\nhddm_model.sample(5000, burn=1000, thin=2, dbname=\"traces.db\", db=\"pickle\")\n```\n\n3. Extract and store estimated parameters:\n\n```python\nparams = hddm_model.get_group_estimates()\nprint(\"Group-level parameter estimates:\")\nfor param_name, stats in params.items():\n    print(f\"  {param_name}: {stats['mean']:.3f} [{stats['2.5q']:.3f}, {stats['97.5q']:.3f}]\")\n```\n\n4. Check convergence (Bayesian only):\n\n```python\nfrom kabuki.analyze import gelman_rubin\n\nconvergence = gelman_rubin(hddm_model)\nmax_rhat = max(convergence.values())\nprint(f\"Max Gelman-Rubin R-hat: {max_rhat:.3f}\")\nassert max_rhat \u003C 1.1, f\"Chains have not converged (R-hat = {max_rhat:.3f})\"\n```\n\n**Got:** Parameter estimates with standard errors or credible intervals. For Bayesian fits, Gelman-Rubin R-hat \u003C 1.1 for all parameters. Drift rate typically 0.5-4.0, boundary 0.5-2.5, non-decision time 0.15-0.50s.\n\n**If fail:** If estimation fails to converge, try: (a) tighter parameter bounds, (b) better starting values via grid search, (c) longer chains with more burn-in. If MLE hits boundary values, the model may be misspecified.\n\n### Step 4: Evaluate Model Fit\n\nCompare predicted and observed RT distributions using quantile-based diagnostics.\n\n1. Generate predicted RT quantiles from the fitted model:\n\n```python\nimport numpy as np\n\nquantiles = [0.1, 0.3, 0.5, 0.7, 0.9]\n\npredicted_rts = model.simulate(n_trials=10000)\npred_quantiles = np.quantile(predicted_rts[predicted_rts > 0], quantiles)  # correct\npred_quantiles_err = np.quantile(np.abs(predicted_rts[predicted_rts \u003C 0]), quantiles)  # error\n```\n\n2. Compute observed RT quantiles:\n\n```python\nobs_correct = data[data[\"accuracy\"] == 1][\"rt\"]\nobs_error = data[data[\"accuracy\"] == 0][\"rt\"]\n\nobs_quantiles = np.quantile(obs_correct, quantiles)\nobs_quantiles_err = np.quantile(obs_error, quantiles) if len(obs_error) > 10 else None\n```\n\n3. Create a quantile-probability plot (QP plot):\n\n```python\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1, 1, figsize=(8, 6))\nax.scatter(obs_quantiles, quantiles, marker=\"o\", label=\"Observed (correct)\")\nax.scatter(pred_quantiles, quantiles, marker=\"x\", label=\"Predicted (correct)\")\nif obs_quantiles_err is not None:\n    ax.scatter(obs_quantiles_err, quantiles, marker=\"o\", facecolors=\"none\", label=\"Observed (error)\")\n    ax.scatter(pred_quantiles_err, quantiles, marker=\"x\", label=\"Predicted (error)\")\nax.set_xlabel(\"RT (s)\")\nax.set_ylabel(\"Quantile\")\nax.legend()\nax.set_title(\"Quantile-Probability Plot\")\nfig.savefig(\"qp_plot.png\", dpi=150)\n```\n\n4. Compute fit statistic (chi-square on quantile bins):\n\n```python\nfrom scipy.stats import chisquare\n\nobserved_proportions = np.diff(np.concatenate([[0], quantiles, [1]]))\npredicted_proportions = np.diff(np.concatenate([[0], quantiles, [1]]))\nchi2, p_value = chisquare(observed_proportions, predicted_proportions)\nprint(f\"Chi-square fit: chi2={chi2:.3f}, p={p_value:.3f}\")\n```\n\n**Got:** QP plot shows predicted quantiles closely tracking observed quantiles for both correct and error RTs. Chi-square test is non-significant (p > 0.05), indicating adequate fit.\n\n**If fail:** If the model systematically misses fast or slow quantiles, consider adding cross-trial variability parameters (sv, st). If error RT shape is wrong, add starting point variability (sz). Refit with the extended model.\n\n### Step 5: Compare Models\n\nUse information criteria to select among candidate DDM variants.\n\n1. Fit each candidate model and collect fit statistics:\n\n```python\nmodel_results = {}\nfor variant_name in [\"basic\", \"full\"]:\n    fitted_model = fit_ddm(data, variant=variant_name)\n    model_results[variant_name] = {\n        \"log_likelihood\": fitted_model.log_likelihood,\n        \"n_params\": fitted_model.n_free_params,\n        \"bic\": fitted_model.bic,\n        \"aic\": fitted_model.aic\n    }\n```\n\n2. Compute and compare BIC values:\n\n```python\nprint(\"Model Comparison (BIC):\")\nprint(f\"{'Model':\u003C15} {'LL':>10} {'k':>5} {'BIC':>12} {'delta_BIC':>12}\")\nprint(\"-\" * 55)\n\nbest_bic = min(r[\"bic\"] for r in model_results.values())\nfor name, result in sorted(model_results.items(), key=lambda x: x[1][\"bic\"]):\n    delta = result[\"bic\"] - best_bic\n    print(f\"{name:\u003C15} {result['log_likelihood']:>10.1f} {result['n_params']:>5} \"\n          f\"{result['bic']:>12.1f} {delta:>12.1f}\")\n```\n\n3. Interpret BIC differences using standard guidelines:\n\n```python\n# BIC difference interpretation (Kass & Raftery, 1995):\n# 0-2:   Not worth mentioning\n# 2-6:   Positive evidence\n# 6-10:  Strong evidence\n# >10:   Very strong evidence\n```\n\n4. For Bayesian models, use DIC or WAIC:\n\n```python\ndic = hddm_model.dic\nprint(f\"DIC: {dic:.1f}\")\n```\n\n**Got:** A clear winner among models with BIC difference > 6, or a justified decision to retain the simpler model when the difference is \u003C 2.\n\n**If fail:** If models are indistinguishable (BIC difference \u003C 2), prefer the simpler model (parsimony). If the full model wins by a large margin, ensure the basic model was not misspecified due to data issues.\n\n### Step 6: Validate with Parameter Recovery Simulation\n\nVerify the estimation pipeline recovers known parameter values from simulated data.\n\n1. Define the ground-truth parameter grid:\n\n```python\ntrue_params = {\n    \"v\": [0.5, 1.0, 2.0, 3.0],\n    \"a\": [0.6, 1.0, 1.5, 2.0],\n    \"t\": [0.2, 0.3, 0.4]\n}\n```\n\n2. Simulate datasets and re-estimate for each combination:\n\n```python\nfrom itertools import product\n\nrecovery_results = []\nn_simulated_trials = 500  # match empirical trial count\n\nfor v_true, a_true, t_true in product(true_params[\"v\"], true_params[\"a\"], true_params[\"t\"]):\n    simulated_data = simulate_ddm(v=v_true, a=a_true, t=t_true, n=n_simulated_trials)\n    fitted = fit_ddm(simulated_data, variant=\"basic\")\n    recovery_results.append({\n        \"v_true\": v_true, \"v_est\": fitted.params[\"v\"],\n        \"a_true\": a_true, \"a_est\": fitted.params[\"a\"],\n        \"t_true\": t_true, \"t_est\": fitted.params[\"t\"]\n    })\n```\n\n3. Compute recovery statistics:\n\n```python\nrecovery_df = pd.DataFrame(recovery_results)\nfor param in [\"v\", \"a\", \"t\"]:\n    correlation = recovery_df[f\"{param}_true\"].corr(recovery_df[f\"{param}_est\"])\n    bias = (recovery_df[f\"{param}_est\"] - recovery_df[f\"{param}_true\"]).mean()\n    rmse = np.sqrt(((recovery_df[f\"{param}_est\"] - recovery_df[f\"{param}_true\"])**2).mean())\n    print(f\"{param}: r={correlation:.3f}, bias={bias:.4f}, RMSE={rmse:.4f}\")\n```\n\n4. Generate recovery scatter plots:\n\n```python\nfig, axes = plt.subplots(1, 3, figsize=(15, 5))\nfor idx, param in enumerate([\"v\", \"a\", \"t\"]):\n    ax = axes[idx]\n    ax.scatter(recovery_df[f\"{param}_true\"], recovery_df[f\"{param}_est\"], alpha=0.5)\n    lims = [recovery_df[f\"{param}_true\"].min(), recovery_df[f\"{param}_true\"].max()]\n    ax.plot(lims, lims, \"k--\", label=\"Identity\")\n    ax.set_xlabel(f\"True {param}\")\n    ax.set_ylabel(f\"Estimated {param}\")\n    ax.set_title(f\"Recovery: {param} (r={recovery_df[f'{param}_true'].corr(recovery_df[f'{param}_est']):.3f})\")\n    ax.legend()\nfig.tight_layout()\nfig.savefig(\"parameter_recovery.png\", dpi=150)\n```\n\n**Got:** Recovery correlations r > 0.85 for all parameters, bias close to zero (\u003C 5% of parameter range), and RMSE within acceptable bounds for the application.\n\n**If fail:** Low recovery for a specific parameter usually means: (a) insufficient trials -- increase n_simulated_trials, (b) parameter tradeoffs -- drift rate and boundary can trade off; fix one to test recoverability, (c) flat likelihood surface -- consider reparameterization or Bayesian estimation with informative priors.\n\n## Validation\n\n- [ ] Input data has RT and accuracy columns with correct types\n- [ ] Outlier filtering removed fewer than 10% of trials\n- [ ] Every subject-condition cell has at least 40 trials\n- [ ] Parameter estimates are within plausible ranges (v: 0-5, a: 0.3-3.0, t: 0.1-0.6)\n- [ ] Convergence diagnostics pass (R-hat \u003C 1.1 for Bayesian, gradient near zero for MLE)\n- [ ] QP plot shows predicted quantiles within 50ms of observed quantiles\n- [ ] Model comparison yields a clear ranking or justified parsimony decision\n- [ ] Parameter recovery correlations exceed r = 0.85 for all free parameters\n- [ ] Recovery bias is less than 5% of the parameter range\n\n## Pitfalls\n\n- **Insufficient trial counts**: DDM estimation is data-hungry. Fewer than 40 trials per cell leads to unstable estimates and poor recovery. Always verify trial counts before fitting.\n- **Ignoring error RTs**: The DDM jointly models correct and error RT distributions. Discarding error trials throws away information about boundary separation and starting point bias.\n- **Not filtering fast guesses**: RTs below 100ms are likely contaminants (anticipatory responses). Include them and they distort non-decision time estimates.\n- **Confusing DDM variants**: The basic model assumes no cross-trial variability. If error RTs are systematically faster than correct RTs, you need the full model with sv and sz parameters.\n- **Overfitting with the full model**: The 7-parameter DDM can overfit sparse data. Use BIC (which penalizes complexity) rather than AIC for model selection with DDMs.\n- **Skipping parameter recovery**: Without recovery validation, you cannot distinguish estimation bias from true experimental effects. Always run recovery before interpreting condition differences.\n\n## Related Skills\n\n- `analyze-diffusion-dynamics` - mathematical analysis of the diffusion process underlying the DDM\n- `implement-diffusion-network` - generative diffusion models that share the forward-process framework\n- `design-experiment` - experimental design considerations for collecting DDM-quality data\n- `write-testthat-tests` - testing parameter estimation pipelines in R\n",{"name":5,"locale":23,"license":14,"metadata":24,"translator":31,"description":32,"allowed-tools":33,"source_commit":34,"source_locale":35,"translation_date":36},"caveman-lite",{"tags":25,"author":26,"domain":27,"version":28,"language":29,"complexity":30},"diffusion, ddm, drift-diffusion, cognitive, reaction-time, estimation","Philipp Thoss","diffusion","1.0","multi","advanced","Julius Brussee homage — caveman","Fit cognitive drift-diffusion models (Ratcliff DDM) to reaction time and accuracy data with parameter estimation (drift rate, boundary separation, non-decision time), model comparison, and parameter recovery validation. Use when modeling binary decision-making with reaction time data, estimating cognitive parameters from experimental data, comparing sequential sampling model variants, or decomposing speed-accuracy tradeoff effects into latent cognitive components.\n","Read Write Edit Bash Grep Glob","82c77053","en","2026-04-24","master","f483e54f3ad5f202a77d45f2e57f8d970b71195f","skills_library\u002Ffit-drift-diffusion-model",2,"https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills","https:\u002F\u002Fgithub.com\u002Froohe","yoou.link","2026-05-19 15:56:07",{"source":8,"skillName":5,"commands":46,"prompt":56,"zipAvailable":57},[47,50,53],{"tool":48,"command":49},"npx","npx skills add roohe\u002Fagentic-super-skills --skill fit-drift-diffusion-model",{"tool":51,"command":52},"bunx","bunx skills add roohe\u002Fagentic-super-skills --skill fit-drift-diffusion-model",{"tool":54,"command":55},"pnpm","pnpm dlx skills add roohe\u002Fagentic-super-skills --skill fit-drift-diffusion-model","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Ffit-drift-diffusion-model\u002FSKILL.md",true,[59],{"path":60,"resourceType":61,"resourceTypeDesc":62,"sizeBytes":63,"sourceHtmlUrl":64},"references\u002FCITATIONS.bib","REFERENCE","参考文档",2391,"https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Ffit-drift-diffusion-model\u002Freferences\u002FCITATIONS.bib",[66,73,80,87,94,101],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":18},"01M73D865CZME2FCMKA4PQM348","zarr-python","Chunked N-D arrays for cloud storage. Compressed arrays, parallel I\u002FO, S3\u002FGCS integration, NumPy\u002FDask\u002FXarray compatible, for large-scale scientific computing pipelines.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M73D7Z64J4ABWZJD7P44XBBF","youtube-downloader","Download and process YouTube content for research. Use when: downloading competitor videos for analysis; extracting audio for podcasts; getting transcripts for content repurposing; archiving webinars; research content curation","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":18},"01M73D7K8778TGZV3GJFR3703D","yc-pitch-deck","Create a compelling startup pitch deck that follows the structure proven to raise billions from top investors. Master the YC and Sequoia formats that get founders funded. Use when: **Fundraising** to create investor pitch decks; **YC application** to structure your narrative; **Demo Day prep** to craft your 2-minute pitch; **Angel investors** to communicate your opportunity; **Partnership pitches** to structure compelling asks","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyc-pitch-deck\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":18},"01M73D70KJSE0E8Z28YMNNRT04","x-twitter-scraper","Use when the user needs X (Twitter) data or confirmation-gated X actions through Xquik: tweet search, user lookup, follower extraction, media download, monitoring, webhooks, MCP, SDKs, posting, likes, DMs, and profile updates. Requires a Xquik API key. Never ask for X login material.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fx-twitter-scraper\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":18},"01M73D6ED01GV077R7K4NZNFZJ","write-vignette","Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-vignette\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":18},"01M73D69YJR0BK3NFHE0CYG3EF","write-validation-documentation","Write IQ\u002FOQ\u002FPQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-validation-documentation\u002FSKILL.md",[],[]]