RegalFire's picture
Publish verified RegalFire scientific product v2
346ecdb verified
Raw History Blame Contribute Delete
475 kB
{"accepted_answer": {"answer_html": "<p>Rather than fitting separate models, you can handle both age groups in a single <code>gls()</code> model with <code>age</code> interactions. This has two advantages over separate <code>auto.arima()</code> models: you get formal tests of whether intervention effects differ between groups via the interaction terms, and you can account for the fact that the two series have very different variances.</p>\n<p><code>age * (time + step1 + ramp1 + ...)</code> gives each group its own intercept, pre-intervention slope, and intervention effects, plus tests of whether they differ. Then, <code>corAR1(form = ~ 1 | age)</code> fits AR(1) autocorrelation within each group and <code>varIdent(form = ~ 1 | age)</code> allows different residual variances per group, which matters here since children's prevalence is an order of magnitude larger.</p>\n<pre class=\"lang-r prettyprint-override\"><code>library(nlme)\nlibrary(dplyr)\n\ninterventions &lt;- as.Date(c(&quot;2021-09-13&quot;, &quot;2022-06-02&quot;, &quot;2023-06-29&quot;))\n\nd_its &lt;- d |&gt;\n arrange(age, month) |&gt;\n mutate(.by = age,\n time = row_number() - 1,\n step1 = as.numeric(month &gt;= interventions[1]),\n ramp1 = ifelse(step1 == 1, cumsum(step1) - 1, 0),\n step2 = as.numeric(month &gt;= interventions[2]),\n ramp2 = ifelse(step2 == 1, cumsum(step2) - 1, 0),\n step3 = as.numeric(month &gt;= interventions[3]),\n ramp3 = ifelse(step3 == 1, cumsum(step3) - 1, 0),\n sin12 = sin(2 * pi * time / 12),\n cos12 = cos(2 * pi * time / 12),\n sin6 = sin(2 * pi * time / 6),\n cos6 = cos(2 * pi * time / 6),\n sin4 = sin(2 * pi * time / 4),\n cos4 = cos(2 * pi * time / 4)\n ) |&gt;\n mutate(age = factor(age))\n\nfit &lt;- gls(\n prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 +\n sin12 + cos12 + sin6 + cos6 + sin4 + cos4),\n data = d_its,\n correlation = corAR1(form = ~ 1 | age),\n weights = varIdent(form = ~ 1 | age)\n)\n</code></pre>\n<p>The Fourier terms (<code>sin12</code>, <code>cos12</code>, etc.) handle the recurring seasonal pattern, which is more stable than trying to absorb it through ARMA error terms (see <a href=\"https://otexts.com/fpp3/dhr.html\" rel=\"nofollow noreferrer\">https://otexts.com/fpp3/dhr.html</a>).</p>\n<p>The reference level is Adults, so coefficients are interpreted as:</p>\n<ul>\n<li><code>time</code>: pre-intervention slope for adults (prevalence per month)</li>\n<li><code>ageChildren:time</code>: <em>additional</em> slope for children;</li>\n</ul>\n<p>The same logic applies for all <code>ramp</code> and <code>step</code> terms.</p>\n<pre class=\"lang-r prettyprint-override\"><code>coef(fit) |&gt;\n (\\(e) data.frame(\n Segment = c(&quot;Pre&quot;, &quot;Post-1&quot;, &quot;Post-2&quot;, &quot;Post-3&quot;),\n Adults = round(cumsum(c(e[&quot;time&quot;],\n e[&quot;ramp1&quot;],\n e[&quot;ramp2&quot;],\n e[&quot;ramp3&quot;])), 3),\n Children = round(cumsum(c(e[&quot;time&quot;] + e[&quot;ageChildren:time&quot;],\n e[&quot;ramp1&quot;] + e[&quot;ageChildren:ramp1&quot;],\n e[&quot;ramp2&quot;] + e[&quot;ageChildren:ramp2&quot;],\n e[&quot;ramp3&quot;] + e[&quot;ageChildren:ramp3&quot;])), 3)\n))()\n\n#&gt; Segment Adults Children\n#&gt; time Pre 0.152 1.445\n#&gt; ramp1 Post-1 0.919 9.276\n#&gt; ramp2 Post-2 1.265 6.667\n#&gt; ramp3 Post-3 2.387 8.418\n</code></pre>\n<pre class=\"lang-r prettyprint-override\"><code>par(mfrow = c(1, 2))\nacf(residuals(fit)[d_its<span class=\"math-container\">$age == \"Adults\"], main = \"Adults\")\nacf(residuals(fit)[d_its$</span>age == &quot;Children&quot;], main = &quot;Children&quot;)\ndev.off()\n</code></pre>\n<p><img src=\"https://i.sstatic.net/2fnDCjiM.png\" alt=\"\" /></p>\n<pre class=\"lang-r prettyprint-override\"><code>summary(fit)\n\n#&gt; Generalized least squares fit by REML\n#&gt; Model: prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 + sin12 + cos12 + sin6 + cos6 + sin4 + cos4) \n#&gt; Data: d_its \n#&gt; AIC BIC logLik\n#&gt; 1665.172 1769.226 -801.5858\n#&gt; \n#&gt; Correlation Structure: AR(1)\n#&gt; Formula: ~1 | age \n#&gt; Parameter estimate(s):\n#&gt; Phi \n#&gt; 0.1231768 \n#&gt; Variance function:\n#&gt; Structure: Different standard deviations per stratum\n#&gt; Formula: ~1 | age \n#&gt; Parameter estimates:\n#&gt; Adults Children \n#&gt; 1.000000 9.435418 \n#&gt; \n#&gt; Coefficients:\n#&gt; Value Std.Error t-value p-value\n#&gt; (Intercept) 10.25450 0.701853 14.610597 0.0000\n#&gt; ageChildren 177.16318 6.659369 26.603599 0.0000\n#&gt; time 0.15162 0.017799 8.518225 0.0000\n#&gt; step1 1.83019 1.934456 0.946100 0.3452\n#&gt; ramp1 0.76689 0.379858 2.018892 0.0448\n#&gt; step2 -0.98456 2.681497 -0.367167 0.7139\n#&gt; ramp2 0.34620 0.449034 0.770992 0.4416\n#&gt; step3 -4.38832 2.094825 -2.094838 0.0374\n#&gt; ramp3 1.12257 0.257109 4.366133 0.0000\n#&gt; sin12 0.01845 0.399784 0.046145 0.9632\n#&gt; cos12 1.16269 0.380402 3.056467 0.0025\n#&gt; sin6 -0.70555 0.358820 -1.966309 0.0506\n#&gt; cos6 -0.97079 0.355213 -2.732980 0.0068\n#&gt; sin4 0.78337 0.333359 2.349941 0.0197\n#&gt; cos4 0.05479 0.333865 0.164117 0.8698\n#&gt; ageChildren:time 1.29381 0.168883 7.661002 0.0000\n#&gt; ageChildren:step1 -1.02662 18.354630 -0.055933 0.9554\n#&gt; ageChildren:ramp1 7.06407 3.604192 1.959960 0.0513\n#&gt; ageChildren:step2 -35.82645 25.442751 -1.408120 0.1606\n#&gt; ageChildren:ramp2 -2.95530 4.260553 -0.693643 0.4887\n#&gt; ageChildren:step3 -29.49930 19.876247 -1.484148 0.1393\n#&gt; ageChildren:ramp3 0.62770 2.439516 0.257306 0.7972\n#&gt; ageChildren:sin12 4.22521 3.793256 1.113874 0.2666\n#&gt; ageChildren:cos12 36.54005 3.609352 10.123715 0.0000\n#&gt; ageChildren:sin6 -9.76953 3.404578 -2.869528 0.0045\n#&gt; ageChildren:cos6 -25.08251 3.370352 -7.442104 0.0000\n#&gt; ageChildren:sin4 13.68702 3.162997 4.327230 0.0000\n#&gt; ageChildren:cos4 14.66062 3.167797 4.628016 0.0000\n#&gt; \n#&gt; Correlation: \n#&gt; (Intr) agChld time step1 ramp1 step2 ramp2 step3 \n#&gt; ageChildren -0.105 \n#&gt; time -0.862 0.091 \n#&gt; step1 0.173 -0.018 -0.309 \n#&gt; ramp1 0.057 -0.006 -0.063 -0.763 \n#&gt; step2 -0.021 0.002 0.020 0.366 -0.711 \n#&gt; ramp2 -0.004 0.000 0.005 0.655 -0.831 0.306 \n#&gt; step3 -0.015 0.002 0.015 0.007 -0.031 0.300 -0.403 \n#&gt; ramp3 -0.016 0.002 0.016 0.008 -0.023 0.514 -0.520 0.649\n#&gt; sin12 -0.056 0.006 0.043 0.155 -0.247 0.317 0.074 0.209\n#&gt; cos12 -0.050 0.005 0.069 -0.188 0.137 -0.028 -0.155 0.065\n#&gt; sin6 -0.008 0.001 -0.006 0.034 0.018 -0.103 0.052 -0.126\n#&gt; cos6 -0.010 0.001 0.002 0.047 -0.026 -0.035 0.060 -0.071\n#&gt; sin4 -0.024 0.002 0.028 -0.033 -0.004 0.059 -0.040 0.066\n#&gt; cos4 -0.011 0.001 0.002 0.063 -0.078 0.095 0.024 0.069\n#&gt; ageChildren:time 0.091 -0.862 -0.105 0.033 0.007 -0.002 0.000 -0.002\n#&gt; ageChildren:step1 -0.018 0.173 0.033 -0.105 0.080 -0.039 -0.069 -0.001\n#&gt; ageChildren:ramp1 -0.006 0.057 0.007 0.080 -0.105 0.075 0.088 0.003\n#&gt; ageChildren:step2 0.002 -0.021 -0.002 -0.039 0.075 -0.105 -0.032 -0.032\n#&gt; ageChildren:ramp2 0.000 -0.004 0.000 -0.069 0.088 -0.032 -0.105 0.043\n#&gt; ageChildren:step3 0.002 -0.015 -0.002 -0.001 0.003 -0.032 0.043 -0.105\n#&gt; ageChildren:ramp3 0.002 -0.016 -0.002 -0.001 0.002 -0.054 0.055 -0.068\n#&gt; ageChildren:sin12 0.006 -0.056 -0.005 -0.016 0.026 -0.033 -0.008 -0.022\n#&gt; ageChildren:cos12 0.005 -0.050 -0.007 0.020 -0.014 0.003 0.016 -0.007\n#&gt; ageChildren:sin6 0.001 -0.008 0.001 -0.004 -0.002 0.011 -0.005 0.013\n#&gt; ageChildren:cos6 0.001 -0.010 0.000 -0.005 0.003 0.004 -0.006 0.007\n#&gt; ageChildren:sin4 0.002 -0.024 -0.003 0.003 0.000 -0.006 0.004 -0.007\n#&gt; ageChildren:cos4 0.001 -0.011 0.000 -0.007 0.008 -0.010 -0.002 -0.007\n#&gt; ramp3 sin12 cos12 sin6 cos6 sin4 cos4 agChl:\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 0.235 \n#&gt; cos12 0.057 -0.008 \n#&gt; sin6 -0.099 -0.036 -0.015 \n#&gt; cos6 -0.058 -0.011 -0.017 0.017 \n#&gt; sin4 0.074 0.025 0.014 -0.013 -0.006 \n#&gt; cos4 0.073 0.041 -0.007 -0.009 -0.004 0.009 \n#&gt; ageChildren:time -0.002 -0.005 -0.007 0.001 0.000 -0.003 0.000 \n#&gt; ageChildren:step1 -0.001 -0.016 0.020 -0.004 -0.005 0.003 -0.007 -0.309\n#&gt; ageChildren:ramp1 0.002 0.026 -0.014 -0.002 0.003 0.000 0.008 -0.063\n#&gt; ageChildren:step2 -0.054 -0.033 0.003 0.011 0.004 -0.006 -0.010 0.020\n#&gt; ageChildren:ramp2 0.055 -0.008 0.016 -0.005 -0.006 0.004 -0.002 0.005\n#&gt; ageChildren:step3 -0.068 -0.022 -0.007 0.013 0.007 -0.007 -0.007 0.015\n#&gt; ageChildren:ramp3 -0.105 -0.025 -0.006 0.010 0.006 -0.008 -0.008 0.016\n#&gt; ageChildren:sin12 -0.025 -0.105 0.001 0.004 0.001 -0.003 -0.004 0.043\n#&gt; ageChildren:cos12 -0.006 0.001 -0.105 0.002 0.002 -0.002 0.001 0.069\n#&gt; ageChildren:sin6 0.010 0.004 0.002 -0.105 -0.002 0.001 0.001 -0.006\n#&gt; ageChildren:cos6 0.006 0.001 0.002 -0.002 -0.105 0.001 0.000 0.002\n#&gt; ageChildren:sin4 -0.008 -0.003 -0.002 0.001 0.001 -0.105 -0.001 0.028\n#&gt; ageChildren:cos4 -0.008 -0.004 0.001 0.001 0.000 -0.001 -0.105 0.002\n#&gt; agChldrn:s1 agChldrn:r1 agChldrn:s2 agChldrn:r2 agChldrn:s3\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 \n#&gt; cos12 \n#&gt; sin6 \n#&gt; cos6 \n#&gt; sin4 \n#&gt; cos4 \n#&gt; ageChildren:time \n#&gt; ageChildren:step1 \n#&gt; ageChildren:ramp1 -0.763 \n#&gt; ageChildren:step2 0.366 -0.711 \n#&gt; ageChildren:ramp2 0.655 -0.831 0.306 \n#&gt; ageChildren:step3 0.007 -0.031 0.300 -0.403 \n#&gt; ageChildren:ramp3 0.008 -0.023 0.514 -0.520 0.649 \n#&gt; ageChildren:sin12 0.155 -0.247 0.317 0.074 0.209 \n#&gt; ageChildren:cos12 -0.188 0.137 -0.028 -0.155 0.065 \n#&gt; ageChildren:sin6 0.034 0.018 -0.103 0.052 -0.126 \n#&gt; ageChildren:cos6 0.047 -0.026 -0.035 0.060 -0.071 \n#&gt; ageChildren:sin4 -0.033 -0.004 0.059 -0.040 0.066 \n#&gt; ageChildren:cos4 0.063 -0.078 0.095 0.024 0.069 \n#&gt; agChldrn:r3 agChldrn:s12 agChldrn:c12 agChldrn:s6 agChldrn:c6\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 \n#&gt; cos12 \n#&gt; sin6 \n#&gt; cos6 \n#&gt; sin4 \n#&gt; cos4 \n#&gt; ageChildren:time \n#&gt; ageChildren:step1 \n#&gt; ageChildren:ramp1 \n#&gt; ageChildren:step2 \n#&gt; ageChildren:ramp2 \n#&gt; ageChildren:step3 \n#&gt; ageChildren:ramp3 \n#&gt; ageChildren:sin12 0.235 \n#&gt; ageChildren:cos12 0.057 -0.008 \n#&gt; ageChildren:sin6 -0.099 -0.036 -0.015 \n#&gt; ageChildren:cos6 -0.058 -0.011 -0.017 0.017 \n#&gt; ageChildren:sin4 0.074 0.025 0.014 -0.013 -0.006 \n#&gt; ageChildren:cos4 0.073 0.041 -0.007 -0.009 -0.004 \n#&gt; agChldrn:s4\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 \n#&gt; cos12 \n#&gt; sin6 \n#&gt; cos6 \n#&gt; sin4 \n#&gt; cos4 \n#&gt; ageChildren:time \n#&gt; ageChildren:step1 \n#&gt; ageChildren:ramp1 \n#&gt; ageChildren:step2 \n#&gt; ageChildren:ramp2 \n#&gt; ageChildren:step3 \n#&gt; ageChildren:ramp3 \n#&gt; ageChildren:sin12 \n#&gt; ageChildren:cos12 \n#&gt; ageChildren:sin6 \n#&gt; ageChildren:cos6 \n#&gt; ageChildren:sin4 \n#&gt; ageChildren:cos4 0.009 \n#&gt; \n#&gt; Standardized residuals:\n#&gt; Min Q1 Med Q3 Max \n#&gt; -5.25291094 -0.42240774 0.04331099 0.45224365 3.26323939 \n#&gt; \n#&gt; Residual standard error: 2.608572 \n#&gt; Degrees of freedom: 240 total; 212 residual\n</code></pre>\n<p><sup>Created on 2026-08-29 with <a href=\"https://reprex.tidyverse.org\" rel=\"nofollow noreferrer\">reprex v2.1.1</a></sup></p>\n", "answer_id": 676996, "answer_text": "Rather than fitting separate models, you can handle both age groups in a single gls() model with age interactions. This has two advantages over separate auto.arima() models: you get formal tests of whether intervention effects differ between groups via the interaction terms, and you can account for the fact that the two series have very different variances.\n\n\n\n\nage * (time + step1 + ramp1 + ...) gives each group its own intercept, pre-intervention slope, and intervention effects, plus tests of whether they differ. Then, corAR1(form = ~ 1 | age) fits AR(1) autocorrelation within each group and varIdent(form = ~ 1 | age) allows different residual variances per group, which matters here since children's prevalence is an order of magnitude larger.\n\n\n\n\nlibrary(nlme)\nlibrary(dplyr)\n\ninterventions <- as.Date(c(\"2021-09-13\", \"2022-06-02\", \"2023-06-29\"))\n\nd_its <- d |>\n arrange(age, month) |>\n mutate(.by = age,\n time = row_number() - 1,\n step1 = as.numeric(month >= interventions[1]),\n ramp1 = ifelse(step1 == 1, cumsum(step1) - 1, 0),\n step2 = as.numeric(month >= interventions[2]),\n ramp2 = ifelse(step2 == 1, cumsum(step2) - 1, 0),\n step3 = as.numeric(month >= interventions[3]),\n ramp3 = ifelse(step3 == 1, cumsum(step3) - 1, 0),\n sin12 = sin(2 * pi * time / 12),\n cos12 = cos(2 * pi * time / 12),\n sin6 = sin(2 * pi * time / 6),\n cos6 = cos(2 * pi * time / 6),\n sin4 = sin(2 * pi * time / 4),\n cos4 = cos(2 * pi * time / 4)\n ) |>\n mutate(age = factor(age))\n\nfit <- gls(\n prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 +\n sin12 + cos12 + sin6 + cos6 + sin4 + cos4),\n data = d_its,\n correlation = corAR1(form = ~ 1 | age),\n weights = varIdent(form = ~ 1 | age)\n)\n\n\n\n\n\nThe Fourier terms (sin12, cos12, etc.) handle the recurring seasonal pattern, which is more stable than trying to absorb it through ARMA error terms (see https://otexts.com/fpp3/dhr.html (https://otexts.com/fpp3/dhr.html)).\n\n\n\n\nThe reference level is Adults, so coefficients are interpreted as:\n\n\n\n\n\ntime: pre-intervention slope for adults (prevalence per month)\n\n\n\n\nageChildren:time: additional slope for children;\n\n\n\n\n\nThe same logic applies for all ramp and step terms.\n\n\n\n\ncoef(fit) |>\n (\\(e) data.frame(\n Segment = c(\"Pre\", \"Post-1\", \"Post-2\", \"Post-3\"),\n Adults = round(cumsum(c(e[\"time\"],\n e[\"ramp1\"],\n e[\"ramp2\"],\n e[\"ramp3\"])), 3),\n Children = round(cumsum(c(e[\"time\"] + e[\"ageChildren:time\"],\n e[\"ramp1\"] + e[\"ageChildren:ramp1\"],\n e[\"ramp2\"] + e[\"ageChildren:ramp2\"],\n e[\"ramp3\"] + e[\"ageChildren:ramp3\"])), 3)\n))()\n\n#> Segment Adults Children\n#> time Pre 0.152 1.445\n#> ramp1 Post-1 0.919 9.276\n#> ramp2 Post-2 1.265 6.667\n#> ramp3 Post-3 2.387 8.418\n\n\n\n\n\npar(mfrow = c(1, 2))\nacf(residuals(fit)[d_its$age == \"Adults\"], main = \"Adults\")\nacf(residuals(fit)[d_its$age == \"Children\"], main = \"Children\")\ndev.off()\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/2fnDCjiM.png]\n\n\n\n\nsummary(fit)\n\n#> Generalized least squares fit by REML\n#> Model: prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 + sin12 + cos12 + sin6 + cos6 + sin4 + cos4) \n#> Data: d_its \n#> AIC BIC logLik\n#> 1665.172 1769.226 -801.5858\n#> \n#> Correlation Structure: AR(1)\n#> Formula: ~1 | age \n#> Parameter estimate(s):\n#> Phi \n#> 0.1231768 \n#> Variance function:\n#> Structure: Different standard deviations per stratum\n#> Formula: ~1 | age \n#> Parameter estimates:\n#> Adults Children \n#> 1.000000 9.435418 \n#> \n#> Coefficients:\n#> Value Std.Error t-value p-value\n#> (Intercept) 10.25450 0.701853 14.610597 0.0000\n#> ageChildren 177.16318 6.659369 26.603599 0.0000\n#> time 0.15162 0.017799 8.518225 0.0000\n#> step1 1.83019 1.934456 0.946100 0.3452\n#> ramp1 0.76689 0.379858 2.018892 0.0448\n#> step2 -0.98456 2.681497 -0.367167 0.7139\n#> ramp2 0.34620 0.449034 0.770992 0.4416\n#> step3 -4.38832 2.094825 -2.094838 0.0374\n#> ramp3 1.12257 0.257109 4.366133 0.0000\n#> sin12 0.01845 0.399784 0.046145 0.9632\n#> cos12 1.16269 0.380402 3.056467 0.0025\n#> sin6 -0.70555 0.358820 -1.966309 0.0506\n#> cos6 -0.97079 0.355213 -2.732980 0.0068\n#> sin4 0.78337 0.333359 2.349941 0.0197\n#> cos4 0.05479 0.333865 0.164117 0.8698\n#> ageChildren:time 1.29381 0.168883 7.661002 0.0000\n#> ageChildren:step1 -1.02662 18.354630 -0.055933 0.9554\n#> ageChildren:ramp1 7.06407 3.604192 1.959960 0.0513\n#> ageChildren:step2 -35.82645 25.442751 -1.408120 0.1606\n#> ageChildren:ramp2 -2.95530 4.260553 -0.693643 0.4887\n#> ageChildren:step3 -29.49930 19.876247 -1.484148 0.1393\n#> ageChildren:ramp3 0.62770 2.439516 0.257306 0.7972\n#> ageChildren:sin12 4.22521 3.793256 1.113874 0.2666\n#> ageChildren:cos12 36.54005 3.609352 10.123715 0.0000\n#> ageChildren:sin6 -9.76953 3.404578 -2.869528 0.0045\n#> ageChildren:cos6 -25.08251 3.370352 -7.442104 0.0000\n#> ageChildren:sin4 13.68702 3.162997 4.327230 0.0000\n#> ageChildren:cos4 14.66062 3.167797 4.628016 0.0000\n#> \n#> Correlation: \n#> (Intr) agChld time step1 ramp1 step2 ramp2 step3 \n#> ageChildren -0.105 \n#> time -0.862 0.091 \n#> step1 0.173 -0.018 -0.309 \n#> ramp1 0.057 -0.006 -0.063 -0.763 \n#> step2 -0.021 0.002 0.020 0.366 -0.711 \n#> ramp2 -0.004 0.000 0.005 0.655 -0.831 0.306 \n#> step3 -0.015 0.002 0.015 0.007 -0.031 0.300 -0.403 \n#> ramp3 -0.016 0.002 0.016 0.008 -0.023 0.514 -0.520 0.649\n#> sin12 -0.056 0.006 0.043 0.155 -0.247 0.317 0.074 0.209\n#> cos12 -0.050 0.005 0.069 -0.188 0.137 -0.028 -0.155 0.065\n#> sin6 -0.008 0.001 -0.006 0.034 0.018 -0.103 0.052 -0.126\n#> cos6 -0.010 0.001 0.002 0.047 -0.026 -0.035 0.060 -0.071\n#> sin4 -0.024 0.002 0.028 -0.033 -0.004 0.059 -0.040 0.066\n#> cos4 -0.011 0.001 0.002 0.063 -0.078 0.095 0.024 0.069\n#> ageChildren:time 0.091 -0.862 -0.105 0.033 0.007 -0.002 0.000 -0.002\n#> ageChildren:step1 -0.018 0.173 0.033 -0.105 0.080 -0.039 -0.069 -0.001\n#> ageChildren:ramp1 -0.006 0.057 0.007 0.080 -0.105 0.075 0.088 0.003\n#> ageChildren:step2 0.002 -0.021 -0.002 -0.039 0.075 -0.105 -0.032 -0.032\n#> ageChildren:ramp2 0.000 -0.004 0.000 -0.069 0.088 -0.032 -0.105 0.043\n#> ageChildren:step3 0.002 -0.015 -0.002 -0.001 0.003 -0.032 0.043 -0.105\n#> ageChildren:ramp3 0.002 -0.016 -0.002 -0.001 0.002 -0.054 0.055 -0.068\n#> ageChildren:sin12 0.006 -0.056 -0.005 -0.016 0.026 -0.033 -0.008 -0.022\n#> ageChildren:cos12 0.005 -0.050 -0.007 0.020 -0.014 0.003 0.016 -0.007\n#> ageChildren:sin6 0.001 -0.008 0.001 -0.004 -0.002 0.011 -0.005 0.013\n#> ageChildren:cos6 0.001 -0.010 0.000 -0.005 0.003 0.004 -0.006 0.007\n#> ageChildren:sin4 0.002 -0.024 -0.003 0.003 0.000 -0.006 0.004 -0.007\n#> ageChildren:cos4 0.001 -0.011 0.000 -0.007 0.008 -0.010 -0.002 -0.007\n#> ramp3 sin12 cos12 sin6 cos6 sin4 cos4 agChl:\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 0.235 \n#> cos12 0.057 -0.008 \n#> sin6 -0.099 -0.036 -0.015 \n#> cos6 -0.058 -0.011 -0.017 0.017 \n#> sin4 0.074 0.025 0.014 -0.013 -0.006 \n#> cos4 0.073 0.041 -0.007 -0.009 -0.004 0.009 \n#> ageChildren:time -0.002 -0.005 -0.007 0.001 0.000 -0.003 0.000 \n#> ageChildren:step1 -0.001 -0.016 0.020 -0.004 -0.005 0.003 -0.007 -0.309\n#> ageChildren:ramp1 0.002 0.026 -0.014 -0.002 0.003 0.000 0.008 -0.063\n#> ageChildren:step2 -0.054 -0.033 0.003 0.011 0.004 -0.006 -0.010 0.020\n#> ageChildren:ramp2 0.055 -0.008 0.016 -0.005 -0.006 0.004 -0.002 0.005\n#> ageChildren:step3 -0.068 -0.022 -0.007 0.013 0.007 -0.007 -0.007 0.015\n#> ageChildren:ramp3 -0.105 -0.025 -0.006 0.010 0.006 -0.008 -0.008 0.016\n#> ageChildren:sin12 -0.025 -0.105 0.001 0.004 0.001 -0.003 -0.004 0.043\n#> ageChildren:cos12 -0.006 0.001 -0.105 0.002 0.002 -0.002 0.001 0.069\n#> ageChildren:sin6 0.010 0.004 0.002 -0.105 -0.002 0.001 0.001 -0.006\n#> ageChildren:cos6 0.006 0.001 0.002 -0.002 -0.105 0.001 0.000 0.002\n#> ageChildren:sin4 -0.008 -0.003 -0.002 0.001 0.001 -0.105 -0.001 0.028\n#> ageChildren:cos4 -0.008 -0.004 0.001 0.001 0.000 -0.001 -0.105 0.002\n#> agChldrn:s1 agChldrn:r1 agChldrn:s2 agChldrn:r2 agChldrn:s3\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 -0.763 \n#> ageChildren:step2 0.366 -0.711 \n#> ageChildren:ramp2 0.655 -0.831 0.306 \n#> ageChildren:step3 0.007 -0.031 0.300 -0.403 \n#> ageChildren:ramp3 0.008 -0.023 0.514 -0.520 0.649 \n#> ageChildren:sin12 0.155 -0.247 0.317 0.074 0.209 \n#> ageChildren:cos12 -0.188 0.137 -0.028 -0.155 0.065 \n#> ageChildren:sin6 0.034 0.018 -0.103 0.052 -0.126 \n#> ageChildren:cos6 0.047 -0.026 -0.035 0.060 -0.071 \n#> ageChildren:sin4 -0.033 -0.004 0.059 -0.040 0.066 \n#> ageChildren:cos4 0.063 -0.078 0.095 0.024 0.069 \n#> agChldrn:r3 agChldrn:s12 agChldrn:c12 agChldrn:s6 agChldrn:c6\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 \n#> ageChildren:step2 \n#> ageChildren:ramp2 \n#> ageChildren:step3 \n#> ageChildren:ramp3 \n#> ageChildren:sin12 0.235 \n#> ageChildren:cos12 0.057 -0.008 \n#> ageChildren:sin6 -0.099 -0.036 -0.015 \n#> ageChildren:cos6 -0.058 -0.011 -0.017 0.017 \n#> ageChildren:sin4 0.074 0.025 0.014 -0.013 -0.006 \n#> ageChildren:cos4 0.073 0.041 -0.007 -0.009 -0.004 \n#> agChldrn:s4\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 \n#> ageChildren:step2 \n#> ageChildren:ramp2 \n#> ageChildren:step3 \n#> ageChildren:ramp3 \n#> ageChildren:sin12 \n#> ageChildren:cos12 \n#> ageChildren:sin6 \n#> ageChildren:cos6 \n#> ageChildren:sin4 \n#> ageChildren:cos4 0.009 \n#> \n#> Standardized residuals:\n#> Min Q1 Med Q3 Max \n#> -5.25291094 -0.42240774 0.04331099 0.45224365 3.26323939 \n#> \n#> Residual standard error: 2.608572 \n#> Degrees of freedom: 240 total; 212 residual\n\n\n\n\n\nCreated on 2026-08-29 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/676996", "author": "M--", "author_url": "https://stats.stackexchange.com/users/154449/m", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-29T05:35:19+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 676979, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "M--", "profile_url": "https://stats.stackexchange.com/users/154449/m", "user_type": "registered"}, "created_at": "2026-08-29T05:35:19+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "4F437721-3A00-4B4D-BA06-A2F50516CC59", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/4F437721-3A00-4B4D-BA06-A2F50516CC59/view-source"}], "score": 3, "updated_at": "2026-08-29T05:35:19+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "month <- seq(\n from = as.Date(\"2016-01-01\"),\n to = as.Date(\"2025-12-31\"),\n by = \"month\"\n)\nmonth <- rep(month, each = 2)\nage <- rep(c(\"Children\", \"Adults\"), 120)\nprevalence <- c(\n 214.1, 11.3, 194.9, 11.1, 220.3, 11.8, 200.7, 11.7, 213.5, \n 11.7, 197.6, 11.5, 128.2, 10.3, 138.6, 9.9, 215, 12.1, 201.9, \n 11.9, 223.8, 12.2, 204.9, 12.4, 234.1, 12.7, 202, 11.9, 247, \n 13.6, 209.8, 13, 236.7, 13.4, 216.9, 13.1, 145.1, 12, 144.3, \n 11, 235.1, 13.7, 227.5, 13.9, 242.5, 13.9, 229.5, 13.8, 255.3, \n 14.5, 226.3, 13.6, 260.8, 15.2, 229.7, 14.2, 245.5, 14.7, 232.6, \n 14.4, 158.8, 13.4, 165, 12.5, 244.3, 14.8, 249.4, 15.7, 259.4, \n 15.5, 244, 15.3, 275.7, 16.2, 240.7, 14.9, 274.4, 16.2, 256.8, \n 16.3, 274.3, 16.4, 240.3, 15.5, 178.2, 15.5, 180.3, 13.6, 264, \n 16.3, 271.3, 17.4, 277.8, 16.9, 261.5, 16.8, 296.9, 17.8, 265.8, \n 17.2, 270.4, 17.9, 218.8, 16, 214.7, 16, 221.8, 16.7, 183.6, \n 16.8, 185.4, 14.9, 273.6, 18.7, 276.7, 19.3, 285, 19.4, 282.8, \n 19.9, 308.3, 20.2, 279.2, 19.3, 331.1, 22, 289.3, 21.2, 303, \n 20.9, 307.5, 21.8, 221.2, 20.9, 215.4, 18.9, 324, 23.4, 323.3, \n 24.3, 328.3, 24.7, 326.5, 25.8, 349.2, 26.1, 319.1, 25.5, 379.3, \n 29, 341.7, 28.3, 365.1, 28.6, 351.7, 30.1, 253.7, 28.6, 266.9, \n 27, 375, 33.4, 373.5, 34.4, 385.8, 35.5, 368.1, 36, 413.7, 38.8, \n 376, 37.4, 440.1, 42.5, 390.3, 40.8, 409.5, 42.6, 402, 44.9, \n 297.9, 43.4, 297.1, 40.2, 430.9, 49.3, 433.4, 51.2, 454.1, 53.1, \n 441.4, 53.4, 472.9, 57, 455.8, 57, 496.3, 62.6, 475, 63.1, 483.4, \n 63.3, 466, 65.1, 367.3, 66.2, 368.4, 58.6, 499.4, 70.8, 528.3, \n 76.1, 533.8, 76, 525.6, 77.2, 588.3, 84.8, 532.4, 81.1, 599.6, \n 90.9, 580.3, 90.8, 601.5, 93.8, 560.6, 95.1, 455.2, 96.9, 440.6, \n 83.7, 629.2, 107.7, 655.7, 112.8, 653.8, 113.2, 674.9, 118.7\n)\nd <- data.frame(month, age, prevalence)\n\npar(mfrow = c(1, 2))\nplot(prevalence ~ month, d, type = \"l\", main = \"Children\", subset = age == \"Children\")\nplot(prevalence ~ month, d, type = \"l\", main = \"Adults\", subset = age == \"Adults\")\ndev.off()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676979, "sha256": "9cace690276c17ab9dec1c8efa1588d9d0fdb834a516aefaad95181c002107bf", "source_url": "https://stats.stackexchange.com/questions/676979/strategy-for-interrupted-time-series-of-correlated-stratified-time-series"}, {"block_index": 1, "code_text": "d2 <- subset(d, age == \"Children\")\nd2$prevalence <- ts(d2$prevalence, start = 2016, frequency = 12)\n\ninterventions <- as.Date(c(\"2021-09-13\", \"2022-06-02\", \"2023-06-29\"))\n\nstep1 <- as.numeric(d2$month >= interventions[1])\nramp1 <- ifelse(step1 == 1, cumsum(step1) - 1, 0)\n\nstep2 <- as.numeric(d2$month >= interventions[2])\nramp2 <- ifelse(step2 == 1, cumsum(step2) - 1, 0)\n\nstep3 <- as.numeric(d2$month >= interventions[3])\nramp3 <- ifelse(step3 == 1, cumsum(step3) - 1, 0)\n\ntime <- seq(from = 0, along.with = d2$month)\n\nxreg <- cbind(time, step1, ramp1, step2, ramp2, step3, ramp3)\n\ncbind(d2, xreg)\n# month age prevalence time step1 ramp1 step2 ramp2 step3 ramp3\n# 1 2016-01-01 Children 214.1 0 0 0 0 0 0 0\n# 3 2016-02-01 Children 194.9 1 0 0 0 0 0 0\n# 5 2016-03-01 Children 220.3 2 0 0 0 0 0 0\n# 7 2016-04-01 Children 200.7 3 0 0 0 0 0 0\n# 9 2016-05-01 Children 213.5 4 0 0 0 0 0 0\n# 11 2016-06-01 Children 197.6 5 0 0 0 0 0 0\n# 13 2016-07-01 Children 128.2 6 0 0 0 0 0 0\n# 15 2016-08-01 Children 138.6 7 0 0 0 0 0 0\n# 17 2016-09-01 Children 215.0 8 0 0 0 0 0 0\n# 19 2016-10-01 Children 201.9 9 0 0 0 0 0 0\n# 21 2016-11-01 Children 223.8 10 0 0 0 0 0 0\n# 23 2016-12-01 Children 204.9 11 0 0 0 0 0 0\n# 25 2017-01-01 Children 234.1 12 0 0 0 0 0 0\n# 27 2017-02-01 Children 202.0 13 0 0 0 0 0 0\n# 29 2017-03-01 Children 247.0 14 0 0 0 0 0 0\n# 31 2017-04-01 Children 209.8 15 0 0 0 0 0 0\n# 33 2017-05-01 Children 236.7 16 0 0 0 0 0 0\n# 35 2017-06-01 Children 216.9 17 0 0 0 0 0 0\n# 37 2017-07-01 Children 145.1 18 0 0 0 0 0 0\n# 39 2017-08-01 Children 144.3 19 0 0 0 0 0 0\n# 41 2017-09-01 Children 235.1 20 0 0 0 0 0 0\n# 43 2017-10-01 Children 227.5 21 0 0 0 0 0 0\n# 45 2017-11-01 Children 242.5 22 0 0 0 0 0 0\n# 47 2017-12-01 Children 229.5 23 0 0 0 0 0 0\n# 49 2018-01-01 Children 255.3 24 0 0 0 0 0 0\n# 51 2018-02-01 Children 226.3 25 0 0 0 0 0 0\n# 53 2018-03-01 Children 260.8 26 0 0 0 0 0 0\n# 55 2018-04-01 Children 229.7 27 0 0 0 0 0 0\n# 57 2018-05-01 Children 245.5 28 0 0 0 0 0 0\n# 59 2018-06-01 Children 232.6 29 0 0 0 0 0 0\n# 61 2018-07-01 Children 158.8 30 0 0 0 0 0 0\n# 63 2018-08-01 Children 165.0 31 0 0 0 0 0 0\n# 65 2018-09-01 Children 244.3 32 0 0 0 0 0 0\n# 67 2018-10-01 Children 249.4 33 0 0 0 0 0 0\n# 69 2018-11-01 Children 259.4 34 0 0 0 0 0 0\n# 71 2018-12-01 Children 244.0 35 0 0 0 0 0 0\n# 73 2019-01-01 Children 275.7 36 0 0 0 0 0 0\n# 75 2019-02-01 Children 240.7 37 0 0 0 0 0 0\n# 77 2019-03-01 Children 274.4 38 0 0 0 0 0 0\n# 79 2019-04-01 Children 256.8 39 0 0 0 0 0 0\n# 81 2019-05-01 Children 274.3 40 0 0 0 0 0 0\n# 83 2019-06-01 Children 240.3 41 0 0 0 0 0 0\n# 85 2019-07-01 Children 178.2 42 0 0 0 0 0 0\n# 87 2019-08-01 Children 180.3 43 0 0 0 0 0 0\n# 89 2019-09-01 Children 264.0 44 0 0 0 0 0 0\n# 91 2019-10-01 Children 271.3 45 0 0 0 0 0 0\n# 93 2019-11-01 Children 277.8 46 0 0 0 0 0 0\n# 95 2019-12-01 Children 261.5 47 0 0 0 0 0 0\n# 97 2020-01-01 Children 296.9 48 0 0 0 0 0 0\n# 99 2020-02-01 Children 265.8 49 0 0 0 0 0 0\n# 101 2020-03-01 Children 270.4 50 0 0 0 0 0 0\n# 103 2020-04-01 Children 218.8 51 0 0 0 0 0 0\n# 105 2020-05-01 Children 214.7 52 0 0 0 0 0 0\n# 107 2020-06-01 Children 221.8 53 0 0 0 0 0 0\n# 109 2020-07-01 Children 183.6 54 0 0 0 0 0 0\n# 111 2020-08-01 Children 185.4 55 0 0 0 0 0 0\n# 113 2020-09-01 Children 273.6 56 0 0 0 0 0 0\n# 115 2020-10-01 Children 276.7 57 0 0 0 0 0 0\n# 117 2020-11-01 Children 285.0 58 0 0 0 0 0 0\n# 119 2020-12-01 Children 282.8 59 0 0 0 0 0 0\n# 121 2021-01-01 Children 308.3 60 0 0 0 0 0 0\n# 123 2021-02-01 Children 279.2 61 0 0 0 0 0 0\n# 125 2021-03-01 Children 331.1 62 0 0 0 0 0 0\n# 127 2021-04-01 Children 289.3 63 0 0 0 0 0 0\n# 129 2021-05-01 Children 303.0 64 0 0 0 0 0 0\n# 131 2021-06-01 Children 307.5 65 0 0 0 0 0 0\n# 133 2021-07-01 Children 221.2 66 0 0 0 0 0 0\n# 135 2021-08-01 Children 215.4 67 0 0 0 0 0 0\n# 137 2021-09-01 Children 324.0 68 0 0 0 0 0 0\n# 139 2021-10-01 Children 323.3 69 1 0 0 0 0 0\n# 141 2021-11-01 Children 328.3 70 1 1 0 0 0 0\n# 143 2021-12-01 Children 326.5 71 1 2 0 0 0 0\n# 145 2022-01-01 Children 349.2 72 1 3 0 0 0 0\n# 147 2022-02-01 Children 319.1 73 1 4 0 0 0 0\n# 149 2022-03-01 Children 379.3 74 1 5 0 0 0 0\n# 151 2022-04-01 Children 341.7 75 1 6 0 0 0 0\n# 153 2022-05-01 Children 365.1 76 1 7 0 0 0 0\n# 155 2022-06-01 Children 351.7 77 1 8 0 0 0 0\n# 157 2022-07-01 Children 253.7 78 1 9 1 0 0 0\n# 159 2022-08-01 Children 266.9 79 1 10 1 1 0 0\n# 161 2022-09-01 Children 375.0 80 1 11 1 2 0 0\n# 163 2022-10-01 Children 373.5 81 1 12 1 3 0 0\n# 165 2022-11-01 Children 385.8 82 1 13 1 4 0 0\n# 167 2022-12-01 Children 368.1 83 1 14 1 5 0 0\n# 169 2023-01-01 Children 413.7 84 1 15 1 6 0 0\n# 171 2023-02-01 Children 376.0 85 1 16 1 7 0 0\n# 173 2023-03-01 Children 440.1 86 1 17 1 8 0 0\n# 175 2023-04-01 Children 390.3 87 1 18 1 9 0 0\n# 177 2023-05-01 Children 409.5 88 1 19 1 10 0 0\n# 179 2023-06-01 Children 402.0 89 1 20 1 11 0 0\n# 181 2023-07-01 Children 297.9 90 1 21 1 12 1 0\n# 183 2023-08-01 Children 297.1 91 1 22 1 13 1 1\n# 185 2023-09-01 Children 430.9 92 1 23 1 14 1 2\n# 187 2023-10-01 Children 433.4 93 1 24 1 15 1 3\n# 189 2023-11-01 Children 454.1 94 1 25 1 16 1 4\n# 191 2023-12-01 Children 441.4 95 1 26 1 17 1 5\n# 193 2024-01-01 Children 472.9 96 1 27 1 18 1 6\n# 195 2024-02-01 Children 455.8 97 1 28 1 19 1 7\n# 197 2024-03-01 Children 496.3 98 1 29 1 20 1 8\n# 199 2024-04-01 Children 475.0 99 1 30 1 21 1 9\n# 201 2024-05-01 Children 483.4 100 1 31 1 22 1 10\n# 203 2024-06-01 Children 466.0 101 1 32 1 23 1 11\n# 205 2024-07-01 Children 367.3 102 1 33 1 24 1 12\n# 207 2024-08-01 Children 368.4 103 1 34 1 25 1 13\n# 209 2024-09-01 Children 499.4 104 1 35 1 26 1 14\n# 211 2024-10-01 Children 528.3 105 1 36 1 27 1 15\n# 213 2024-11-01 Children 533.8 106 1 37 1 28 1 16\n# 215 2024-12-01 Children 525.6 107 1 38 1 29 1 17\n# 217 2025-01-01 Children 588.3 108 1 39 1 30 1 18\n# 219 2025-02-01 Children 532.4 109 1 40 1 31 1 19\n# 221 2025-03-01 Children 599.6 110 1 41 1 32 1 20\n# 223 2025-04-01 Children 580.3 111 1 42 1 33 1 21\n# 225 2025-05-01 Children 601.5 112 1 43 1 34 1 22\n# 227 2025-06-01 Children 560.6 113 1 44 1 35 1 23\n# 229 2025-07-01 Children 455.2 114 1 45 1 36 1 24\n# 231 2025-08-01 Children 440.6 115 1 46 1 37 1 25\n# 233 2025-09-01 Children 629.2 116 1 47 1 38 1 26\n# 235 2025-10-01 Children 655.7 117 1 48 1 39 1 27\n# 237 2025-11-01 Children 653.8 118 1 49 1 40 1 28\n# 239 2025-12-01 Children 674.9 119 1 50 1 41 1 29\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676979, "sha256": "4c753734c9398639a80aeac59ebd68bf3f63a83e5732ab45ae175d77017a8eda", "source_url": "https://stats.stackexchange.com/questions/676979/strategy-for-interrupted-time-series-of-correlated-stratified-time-series"}, {"block_index": 2, "code_text": "fit <- forecast::auto.arima(\n d2$prevalence,\n d = 0,\n D = 0,\n stepwise = FALSE,\n trace = TRUE,\n approximation = FALSE,\n xreg = xreg\n)\n# \n# Regression with ARIMA(0,0,0) errors : 1422.701\n# Regression with ARIMA(0,0,0) errors : 1256.821\n# Regression with ARIMA(0,0,0)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,0)(0,0,1)[12] errors : 1186.586\n# Regression with ARIMA(0,0,0)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,0)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,2)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,1) errors : 1348.712\n# Regression with ARIMA(0,0,1) errors : 1237.018\n# Regression with ARIMA(0,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,1)(0,0,1)[12] errors : 1167.011\n# Regression with ARIMA(0,0,1)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,1)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,1)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,1)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,2)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,1)(2,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,2) errors : 1304.633\n# Regression with ARIMA(0,0,2) errors : 1235.236\n# Regression with ARIMA(0,0,2)(0,0,1)[12] errors : 1226.35\n# Regression with ARIMA(0,0,2)(0,0,1)[12] errors : 1164.06\n# Regression with ARIMA(0,0,2)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,2)(0,0,2)[12] errors : 1122.153\n# ARIMA(0,0,2)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,2)(1,0,0)[12] errors : Inf\n# ARIMA(0,0,2)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,2)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,2)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,2)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,2)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,3) errors : 1301.979\n# Regression with ARIMA(0,0,3) errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,1)[12] errors : 1166.444\n# Regression with ARIMA(0,0,3)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,3)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,3)(1,0,0)[12] errors : Inf\n# ARIMA(0,0,3)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,3)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,3)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,3)(2,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,4) errors : Inf\n# Regression with ARIMA(0,0,4) errors : Inf\n# Regression with ARIMA(0,0,4)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,4)(0,0,1)[12] errors : 1167.795\n# ARIMA(0,0,4)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,4)(1,0,0)[12] errors : Inf\n# Regression with ARIMA(0,0,5) errors : Inf\n# Regression with ARIMA(0,0,5) errors : Inf\n# Regression with ARIMA(1,0,0) errors : 1269.039\n# Regression with ARIMA(1,0,0) errors : 1236.551\n# Regression with ARIMA(1,0,0)(0,0,1)[12] errors : 1191.463\n# Regression with ARIMA(1,0,0)(0,0,1)[12] errors : 1163.925\n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors : 1144.206\n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors : 1122.139\n# ARIMA(1,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,0)(2,0,0)[12] errors : Inf\n# ARIMA(1,0,0)(2,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,0)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(2,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,0)(2,0,2)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,1) errors : 1269.741\n# Regression with ARIMA(1,0,1) errors : 1237.127\n# Regression with ARIMA(1,0,1)(0,0,1)[12] errors : 1191.287\n# Regression with ARIMA(1,0,1)(0,0,1)[12] errors : 1165.649\n# Regression with ARIMA(1,0,1)(0,0,2)[12] errors : 1145.611\n# Regression with ARIMA(1,0,1)(0,0,2)[12] errors : 1123.56\n# ARIMA(1,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(1,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,1)(2,0,0)[12] errors : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,2) errors : Inf\n# ARIMA(1,0,2) with non-zero mean : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,2) errors : Inf\n# ARIMA(1,0,2) with non-zero mean : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,2)[12] errors : Inf\n# ARIMA(1,0,2)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,2)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,2)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,2)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,2)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,2)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(1,0,3) errors : Inf\n# Regression with ARIMA(1,0,3) errors : Inf\n# Regression with ARIMA(1,0,3)(0,0,1)[12] errors : 1196.785\n# Regression with ARIMA(1,0,3)(0,0,1)[12] errors : Inf\n# ARIMA(1,0,3)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,3)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,4) errors : Inf\n# Regression with ARIMA(1,0,4) errors : Inf\n# Regression with ARIMA(2,0,0) errors : 1270.227\n# Regression with ARIMA(2,0,0) errors : 1235.453\n# Regression with ARIMA(2,0,0)(0,0,1)[12] errors : 1191.855\n# Regression with ARIMA(2,0,0)(0,0,1)[12] errors : 1165.096\n# Regression with ARIMA(2,0,0)(0,0,2)[12] errors : 1145.887\n# Regression with ARIMA(2,0,0)(0,0,2)[12] errors : 1123.031\n# ARIMA(2,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,0)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(2,0,1)[12] with zero mean : Inf\n# Regression with ARIMA(2,0,0)(2,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1) errors : Inf\n# Regression with ARIMA(2,0,1) errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,2)[12] errors : Inf\n# ARIMA(2,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,1)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(2,0,1)(1,0,1)[12] errors : Inf\n# ARIMA(2,0,1)(1,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(2,0,1)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(2,0,2) errors : Inf\n# Regression with ARIMA(2,0,2) errors : Inf\n# ARIMA(2,0,2)(0,0,1)[12] with zero mean : Inf\n# Regression with ARIMA(2,0,2)(0,0,1)[12] errors : Inf\n# ARIMA(2,0,2)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,2)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,3) with zero mean : Inf\n# Regression with ARIMA(2,0,3) errors : Inf\n# Regression with ARIMA(3,0,0) errors : 1271.552\n# Regression with ARIMA(3,0,0) errors : 1234.442\n# Regression with ARIMA(3,0,0)(0,0,1)[12] errors : 1193.944\n# Regression with ARIMA(3,0,0)(0,0,1)[12] errors : 1165.004\n# Regression with ARIMA(3,0,0)(0,0,2)[12] errors : 1147.337\n# Regression with ARIMA(3,0,0)(0,0,2)[12] errors : 1124.69\n# ARIMA(3,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(3,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(3,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(3,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,0)(2,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(3,0,1) errors : Inf\n# Regression with ARIMA(3,0,1) errors : Inf\n# Regression with ARIMA(3,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(3,0,1)(0,0,1)[12] errors : Inf\n# ARIMA(3,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,1)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(3,0,2) errors : Inf\n# Regression with ARIMA(3,0,2) errors : Inf\n# Regression with ARIMA(4,0,0) errors : 1268.176\n# Regression with ARIMA(4,0,0) errors : 1236.501\n# Regression with ARIMA(4,0,0)(0,0,1)[12] errors : 1191.278\n# Regression with ARIMA(4,0,0)(0,0,1)[12] errors : 1167.39\n# ARIMA(4,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(4,0,0)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(4,0,1) errors : Inf\n# Regression with ARIMA(4,0,1) errors : Inf\n# Regression with ARIMA(5,0,0) errors : 1270.388\n# Regression with ARIMA(5,0,0) errors : 1226.449\n# \n# \n# \n# Best model: Regression with ARIMA(1,0,0)(0,0,2)[12] errors \n# \n\nsummary(fit)\n# Series: d2$prevalence \n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors \n# \n# Coefficients:\n# ar1 sma1 sma2 intercept time step1 ramp1 step2 ramp2 step3 ramp3\n# 0.5256 1.0413 0.6987 188.8179 1.5717 3.3284 2.1966 -5.6181 0.4640 0.4378 4.6447\n# s.e. 0.0800 0.1536 0.1312 20.6895 0.4724 13.0492 3.5219 23.9955 3.8197 19.1790 2.5724\n# \n# sigma^2 = 494.9: log likelihood = -547.61\n# AIC=1119.22 AICc=1122.14 BIC=1152.67\n# \n# Training set error measures:\n# ME RMSE MAE MPE MAPE MASE ACF1\n# Training set -0.2760281 21.20232 16.21419 -0.9807653 5.578825 0.3604042 0.05861382\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676979, "sha256": "91f70a0cc2d89034fa701fed928aa731ddc1fd142c8e82f207b970b96a31654f", "source_url": "https://stats.stackexchange.com/questions/676979/strategy-for-interrupted-time-series-of-correlated-stratified-time-series"}, {"block_index": 3, "code_text": "res <- residuals(fit)\nl <- 36\n\npar(mfrow = c(3, 1))\nplot(res)\nacf(res, lag.max = l)\npacf(res, lag.max = l)\ndev.off()\n\nBox.test(res, lag = 24, type = \"Ljung-Box\", fitdf = 3)\n# \n# Box-Ljung test\n# \n# data: res\n# X-squared = 49.814, df = 21, p-value = 0.0003872\n# \n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676979, "sha256": "eceaa543efc075433b65e321fb99244a1259e5c10bf8ecf2c60a1a24e576db3f", "source_url": "https://stats.stackexchange.com/questions/676979/strategy-for-interrupted-time-series-of-correlated-stratified-time-series"}, {"block_index": 0, "code_text": "library(nlme)\nlibrary(dplyr)\n\ninterventions <- as.Date(c(\"2021-09-13\", \"2022-06-02\", \"2023-06-29\"))\n\nd_its <- d |>\n arrange(age, month) |>\n mutate(.by = age,\n time = row_number() - 1,\n step1 = as.numeric(month >= interventions[1]),\n ramp1 = ifelse(step1 == 1, cumsum(step1) - 1, 0),\n step2 = as.numeric(month >= interventions[2]),\n ramp2 = ifelse(step2 == 1, cumsum(step2) - 1, 0),\n step3 = as.numeric(month >= interventions[3]),\n ramp3 = ifelse(step3 == 1, cumsum(step3) - 1, 0),\n sin12 = sin(2 * pi * time / 12),\n cos12 = cos(2 * pi * time / 12),\n sin6 = sin(2 * pi * time / 6),\n cos6 = cos(2 * pi * time / 6),\n sin4 = sin(2 * pi * time / 4),\n cos4 = cos(2 * pi * time / 4)\n ) |>\n mutate(age = factor(age))\n\nfit <- gls(\n prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 +\n sin12 + cos12 + sin6 + cos6 + sin4 + cos4),\n data = d_its,\n correlation = corAR1(form = ~ 1 | age),\n weights = varIdent(form = ~ 1 | age)\n)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676996, "sha256": "62139218828fa06f701a06c8cf502690ac9f06dd8b87b97cf97522170fb9a176", "source_url": "https://stats.stackexchange.com/a/676996"}, {"block_index": 3, "code_text": "summary(fit)\n\n#> Generalized least squares fit by REML\n#> Model: prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 + sin12 + cos12 + sin6 + cos6 + sin4 + cos4) \n#> Data: d_its \n#> AIC BIC logLik\n#> 1665.172 1769.226 -801.5858\n#> \n#> Correlation Structure: AR(1)\n#> Formula: ~1 | age \n#> Parameter estimate(s):\n#> Phi \n#> 0.1231768 \n#> Variance function:\n#> Structure: Different standard deviations per stratum\n#> Formula: ~1 | age \n#> Parameter estimates:\n#> Adults Children \n#> 1.000000 9.435418 \n#> \n#> Coefficients:\n#> Value Std.Error t-value p-value\n#> (Intercept) 10.25450 0.701853 14.610597 0.0000\n#> ageChildren 177.16318 6.659369 26.603599 0.0000\n#> time 0.15162 0.017799 8.518225 0.0000\n#> step1 1.83019 1.934456 0.946100 0.3452\n#> ramp1 0.76689 0.379858 2.018892 0.0448\n#> step2 -0.98456 2.681497 -0.367167 0.7139\n#> ramp2 0.34620 0.449034 0.770992 0.4416\n#> step3 -4.38832 2.094825 -2.094838 0.0374\n#> ramp3 1.12257 0.257109 4.366133 0.0000\n#> sin12 0.01845 0.399784 0.046145 0.9632\n#> cos12 1.16269 0.380402 3.056467 0.0025\n#> sin6 -0.70555 0.358820 -1.966309 0.0506\n#> cos6 -0.97079 0.355213 -2.732980 0.0068\n#> sin4 0.78337 0.333359 2.349941 0.0197\n#> cos4 0.05479 0.333865 0.164117 0.8698\n#> ageChildren:time 1.29381 0.168883 7.661002 0.0000\n#> ageChildren:step1 -1.02662 18.354630 -0.055933 0.9554\n#> ageChildren:ramp1 7.06407 3.604192 1.959960 0.0513\n#> ageChildren:step2 -35.82645 25.442751 -1.408120 0.1606\n#> ageChildren:ramp2 -2.95530 4.260553 -0.693643 0.4887\n#> ageChildren:step3 -29.49930 19.876247 -1.484148 0.1393\n#> ageChildren:ramp3 0.62770 2.439516 0.257306 0.7972\n#> ageChildren:sin12 4.22521 3.793256 1.113874 0.2666\n#> ageChildren:cos12 36.54005 3.609352 10.123715 0.0000\n#> ageChildren:sin6 -9.76953 3.404578 -2.869528 0.0045\n#> ageChildren:cos6 -25.08251 3.370352 -7.442104 0.0000\n#> ageChildren:sin4 13.68702 3.162997 4.327230 0.0000\n#> ageChildren:cos4 14.66062 3.167797 4.628016 0.0000\n#> \n#> Correlation: \n#> (Intr) agChld time step1 ramp1 step2 ramp2 step3 \n#> ageChildren -0.105 \n#> time -0.862 0.091 \n#> step1 0.173 -0.018 -0.309 \n#> ramp1 0.057 -0.006 -0.063 -0.763 \n#> step2 -0.021 0.002 0.020 0.366 -0.711 \n#> ramp2 -0.004 0.000 0.005 0.655 -0.831 0.306 \n#> step3 -0.015 0.002 0.015 0.007 -0.031 0.300 -0.403 \n#> ramp3 -0.016 0.002 0.016 0.008 -0.023 0.514 -0.520 0.649\n#> sin12 -0.056 0.006 0.043 0.155 -0.247 0.317 0.074 0.209\n#> cos12 -0.050 0.005 0.069 -0.188 0.137 -0.028 -0.155 0.065\n#> sin6 -0.008 0.001 -0.006 0.034 0.018 -0.103 0.052 -0.126\n#> cos6 -0.010 0.001 0.002 0.047 -0.026 -0.035 0.060 -0.071\n#> sin4 -0.024 0.002 0.028 -0.033 -0.004 0.059 -0.040 0.066\n#> cos4 -0.011 0.001 0.002 0.063 -0.078 0.095 0.024 0.069\n#> ageChildren:time 0.091 -0.862 -0.105 0.033 0.007 -0.002 0.000 -0.002\n#> ageChildren:step1 -0.018 0.173 0.033 -0.105 0.080 -0.039 -0.069 -0.001\n#> ageChildren:ramp1 -0.006 0.057 0.007 0.080 -0.105 0.075 0.088 0.003\n#> ageChildren:step2 0.002 -0.021 -0.002 -0.039 0.075 -0.105 -0.032 -0.032\n#> ageChildren:ramp2 0.000 -0.004 0.000 -0.069 0.088 -0.032 -0.105 0.043\n#> ageChildren:step3 0.002 -0.015 -0.002 -0.001 0.003 -0.032 0.043 -0.105\n#> ageChildren:ramp3 0.002 -0.016 -0.002 -0.001 0.002 -0.054 0.055 -0.068\n#> ageChildren:sin12 0.006 -0.056 -0.005 -0.016 0.026 -0.033 -0.008 -0.022\n#> ageChildren:cos12 0.005 -0.050 -0.007 0.020 -0.014 0.003 0.016 -0.007\n#> ageChildren:sin6 0.001 -0.008 0.001 -0.004 -0.002 0.011 -0.005 0.013\n#> ageChildren:cos6 0.001 -0.010 0.000 -0.005 0.003 0.004 -0.006 0.007\n#> ageChildren:sin4 0.002 -0.024 -0.003 0.003 0.000 -0.006 0.004 -0.007\n#> ageChildren:cos4 0.001 -0.011 0.000 -0.007 0.008 -0.010 -0.002 -0.007\n#> ramp3 sin12 cos12 sin6 cos6 sin4 cos4 agChl:\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 0.235 \n#> cos12 0.057 -0.008 \n#> sin6 -0.099 -0.036 -0.015 \n#> cos6 -0.058 -0.011 -0.017 0.017 \n#> sin4 0.074 0.025 0.014 -0.013 -0.006 \n#> cos4 0.073 0.041 -0.007 -0.009 -0.004 0.009 \n#> ageChildren:time -0.002 -0.005 -0.007 0.001 0.000 -0.003 0.000 \n#> ageChildren:step1 -0.001 -0.016 0.020 -0.004 -0.005 0.003 -0.007 -0.309\n#> ageChildren:ramp1 0.002 0.026 -0.014 -0.002 0.003 0.000 0.008 -0.063\n#> ageChildren:step2 -0.054 -0.033 0.003 0.011 0.004 -0.006 -0.010 0.020\n#> ageChildren:ramp2 0.055 -0.008 0.016 -0.005 -0.006 0.004 -0.002 0.005\n#> ageChildren:step3 -0.068 -0.022 -0.007 0.013 0.007 -0.007 -0.007 0.015\n#> ageChildren:ramp3 -0.105 -0.025 -0.006 0.010 0.006 -0.008 -0.008 0.016\n#> ageChildren:sin12 -0.025 -0.105 0.001 0.004 0.001 -0.003 -0.004 0.043\n#> ageChildren:cos12 -0.006 0.001 -0.105 0.002 0.002 -0.002 0.001 0.069\n#> ageChildren:sin6 0.010 0.004 0.002 -0.105 -0.002 0.001 0.001 -0.006\n#> ageChildren:cos6 0.006 0.001 0.002 -0.002 -0.105 0.001 0.000 0.002\n#> ageChildren:sin4 -0.008 -0.003 -0.002 0.001 0.001 -0.105 -0.001 0.028\n#> ageChildren:cos4 -0.008 -0.004 0.001 0.001 0.000 -0.001 -0.105 0.002\n#> agChldrn:s1 agChldrn:r1 agChldrn:s2 agChldrn:r2 agChldrn:s3\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 -0.763 \n#> ageChildren:step2 0.366 -0.711 \n#> ageChildren:ramp2 0.655 -0.831 0.306 \n#> ageChildren:step3 0.007 -0.031 0.300 -0.403 \n#> ageChildren:ramp3 0.008 -0.023 0.514 -0.520 0.649 \n#> ageChildren:sin12 0.155 -0.247 0.317 0.074 0.209 \n#> ageChildren:cos12 -0.188 0.137 -0.028 -0.155 0.065 \n#> ageChildren:sin6 0.034 0.018 -0.103 0.052 -0.126 \n#> ageChildren:cos6 0.047 -0.026 -0.035 0.060 -0.071 \n#> ageChildren:sin4 -0.033 -0.004 0.059 -0.040 0.066 \n#> ageChildren:cos4 0.063 -0.078 0.095 0.024 0.069 \n#> agChldrn:r3 agChldrn:s12 agChldrn:c12 agChldrn:s6 agChldrn:c6\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 \n#> ageChildren:step2 \n#> ageChildren:ramp2 \n#> ageChildren:step3 \n#> ageChildren:ramp3 \n#> ageChildren:sin12 0.235 \n#> ageChildren:cos12 0.057 -0.008 \n#> ageChildren:sin6 -0.099 -0.036 -0.015 \n#> ageChildren:cos6 -0.058 -0.011 -0.017 0.017 \n#> ageChildren:sin4 0.074 0.025 0.014 -0.013 -0.006 \n#> ageChildren:cos4 0.073 0.041 -0.007 -0.009 -0.004 \n#> agChldrn:s4\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 \n#> ageChildren:step2 \n#> ageChildren:ramp2 \n#> ageChildren:step3 \n#> ageChildren:ramp3 \n#> ageChildren:sin12 \n#> ageChildren:cos12 \n#> ageChildren:sin6 \n#> ageChildren:cos6 \n#> ageChildren:sin4 \n#> ageChildren:cos4 0.009 \n#> \n#> Standardized residuals:\n#> Min Q1 Med Q3 Max \n#> -5.25291094 -0.42240774 0.04331099 0.45224365 3.26323939 \n#> \n#> Residual standard error: 2.608572 \n#> Degrees of freedom: 240 total; 212 residual\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676996, "sha256": "2efb6dfee26f9f445e3475854cc386d4e974fbf2a8a395357cc7ed6d71558eda", "source_url": "https://stats.stackexchange.com/a/676996"}], "other_answers": [], "product": "code_qa", "question": "Background\n\n\n\n\n\nData: time series of the monthly prevalence of patients receiving a given medication by age group (children or adults) from January 2016 to December 2026\n\n\n\n\nInterventions: three successive regulatory interventions implemented on September 2021, June 2022, and June 2023 to facilitate prescription of the medication (dotted lines on the figure below)\n\n\n\n\nAim: to estimate pre-intervention slope, post-intervention 1 slope, post-intervention 2 slope, and post-intervention 3 slope depending on age group to assess the impact of the interventions (i.e., interrupted time series analysis, ITS)\n\n\n\n\n\nmonth <- seq(\n from = as.Date(\"2016-01-01\"),\n to = as.Date(\"2025-12-31\"),\n by = \"month\"\n)\nmonth <- rep(month, each = 2)\nage <- rep(c(\"Children\", \"Adults\"), 120)\nprevalence <- c(\n 214.1, 11.3, 194.9, 11.1, 220.3, 11.8, 200.7, 11.7, 213.5, \n 11.7, 197.6, 11.5, 128.2, 10.3, 138.6, 9.9, 215, 12.1, 201.9, \n 11.9, 223.8, 12.2, 204.9, 12.4, 234.1, 12.7, 202, 11.9, 247, \n 13.6, 209.8, 13, 236.7, 13.4, 216.9, 13.1, 145.1, 12, 144.3, \n 11, 235.1, 13.7, 227.5, 13.9, 242.5, 13.9, 229.5, 13.8, 255.3, \n 14.5, 226.3, 13.6, 260.8, 15.2, 229.7, 14.2, 245.5, 14.7, 232.6, \n 14.4, 158.8, 13.4, 165, 12.5, 244.3, 14.8, 249.4, 15.7, 259.4, \n 15.5, 244, 15.3, 275.7, 16.2, 240.7, 14.9, 274.4, 16.2, 256.8, \n 16.3, 274.3, 16.4, 240.3, 15.5, 178.2, 15.5, 180.3, 13.6, 264, \n 16.3, 271.3, 17.4, 277.8, 16.9, 261.5, 16.8, 296.9, 17.8, 265.8, \n 17.2, 270.4, 17.9, 218.8, 16, 214.7, 16, 221.8, 16.7, 183.6, \n 16.8, 185.4, 14.9, 273.6, 18.7, 276.7, 19.3, 285, 19.4, 282.8, \n 19.9, 308.3, 20.2, 279.2, 19.3, 331.1, 22, 289.3, 21.2, 303, \n 20.9, 307.5, 21.8, 221.2, 20.9, 215.4, 18.9, 324, 23.4, 323.3, \n 24.3, 328.3, 24.7, 326.5, 25.8, 349.2, 26.1, 319.1, 25.5, 379.3, \n 29, 341.7, 28.3, 365.1, 28.6, 351.7, 30.1, 253.7, 28.6, 266.9, \n 27, 375, 33.4, 373.5, 34.4, 385.8, 35.5, 368.1, 36, 413.7, 38.8, \n 376, 37.4, 440.1, 42.5, 390.3, 40.8, 409.5, 42.6, 402, 44.9, \n 297.9, 43.4, 297.1, 40.2, 430.9, 49.3, 433.4, 51.2, 454.1, 53.1, \n 441.4, 53.4, 472.9, 57, 455.8, 57, 496.3, 62.6, 475, 63.1, 483.4, \n 63.3, 466, 65.1, 367.3, 66.2, 368.4, 58.6, 499.4, 70.8, 528.3, \n 76.1, 533.8, 76, 525.6, 77.2, 588.3, 84.8, 532.4, 81.1, 599.6, \n 90.9, 580.3, 90.8, 601.5, 93.8, 560.6, 95.1, 455.2, 96.9, 440.6, \n 83.7, 629.2, 107.7, 655.7, 112.8, 653.8, 113.2, 674.9, 118.7\n)\nd <- data.frame(month, age, prevalence)\n\npar(mfrow = c(1, 2))\nplot(prevalence ~ month, d, type = \"l\", main = \"Children\", subset = age == \"Children\")\nplot(prevalence ~ month, d, type = \"l\", main = \"Adults\", subset = age == \"Adults\")\ndev.off()\n\n\n\n\n\n[image: time series; source: https://i.sstatic.net/4a0pdydL.png] (https://i.sstatic.net/4a0pdydL.png)\n\n\n\n\nWhat I did\n\n\n\n\nI started with children.\n\n\n\n\nI constructed the ITS variables for the 3 interventions (step1, ramp1, step2, ramp2, step3, ramp3) following Schaffer et al. (https://doi.org/10.1186/s12874-021-01235-8) and Xiao et al. (https://doi.org/10.1093/ije/dyaa148)\n\n\n\n\nd2 <- subset(d, age == \"Children\")\nd2$prevalence <- ts(d2$prevalence, start = 2016, frequency = 12)\n\ninterventions <- as.Date(c(\"2021-09-13\", \"2022-06-02\", \"2023-06-29\"))\n\nstep1 <- as.numeric(d2$month >= interventions[1])\nramp1 <- ifelse(step1 == 1, cumsum(step1) - 1, 0)\n\nstep2 <- as.numeric(d2$month >= interventions[2])\nramp2 <- ifelse(step2 == 1, cumsum(step2) - 1, 0)\n\nstep3 <- as.numeric(d2$month >= interventions[3])\nramp3 <- ifelse(step3 == 1, cumsum(step3) - 1, 0)\n\ntime <- seq(from = 0, along.with = d2$month)\n\nxreg <- cbind(time, step1, ramp1, step2, ramp2, step3, ramp3)\n\ncbind(d2, xreg)\n# month age prevalence time step1 ramp1 step2 ramp2 step3 ramp3\n# 1 2016-01-01 Children 214.1 0 0 0 0 0 0 0\n# 3 2016-02-01 Children 194.9 1 0 0 0 0 0 0\n# 5 2016-03-01 Children 220.3 2 0 0 0 0 0 0\n# 7 2016-04-01 Children 200.7 3 0 0 0 0 0 0\n# 9 2016-05-01 Children 213.5 4 0 0 0 0 0 0\n# 11 2016-06-01 Children 197.6 5 0 0 0 0 0 0\n# 13 2016-07-01 Children 128.2 6 0 0 0 0 0 0\n# 15 2016-08-01 Children 138.6 7 0 0 0 0 0 0\n# 17 2016-09-01 Children 215.0 8 0 0 0 0 0 0\n# 19 2016-10-01 Children 201.9 9 0 0 0 0 0 0\n# 21 2016-11-01 Children 223.8 10 0 0 0 0 0 0\n# 23 2016-12-01 Children 204.9 11 0 0 0 0 0 0\n# 25 2017-01-01 Children 234.1 12 0 0 0 0 0 0\n# 27 2017-02-01 Children 202.0 13 0 0 0 0 0 0\n# 29 2017-03-01 Children 247.0 14 0 0 0 0 0 0\n# 31 2017-04-01 Children 209.8 15 0 0 0 0 0 0\n# 33 2017-05-01 Children 236.7 16 0 0 0 0 0 0\n# 35 2017-06-01 Children 216.9 17 0 0 0 0 0 0\n# 37 2017-07-01 Children 145.1 18 0 0 0 0 0 0\n# 39 2017-08-01 Children 144.3 19 0 0 0 0 0 0\n# 41 2017-09-01 Children 235.1 20 0 0 0 0 0 0\n# 43 2017-10-01 Children 227.5 21 0 0 0 0 0 0\n# 45 2017-11-01 Children 242.5 22 0 0 0 0 0 0\n# 47 2017-12-01 Children 229.5 23 0 0 0 0 0 0\n# 49 2018-01-01 Children 255.3 24 0 0 0 0 0 0\n# 51 2018-02-01 Children 226.3 25 0 0 0 0 0 0\n# 53 2018-03-01 Children 260.8 26 0 0 0 0 0 0\n# 55 2018-04-01 Children 229.7 27 0 0 0 0 0 0\n# 57 2018-05-01 Children 245.5 28 0 0 0 0 0 0\n# 59 2018-06-01 Children 232.6 29 0 0 0 0 0 0\n# 61 2018-07-01 Children 158.8 30 0 0 0 0 0 0\n# 63 2018-08-01 Children 165.0 31 0 0 0 0 0 0\n# 65 2018-09-01 Children 244.3 32 0 0 0 0 0 0\n# 67 2018-10-01 Children 249.4 33 0 0 0 0 0 0\n# 69 2018-11-01 Children 259.4 34 0 0 0 0 0 0\n# 71 2018-12-01 Children 244.0 35 0 0 0 0 0 0\n# 73 2019-01-01 Children 275.7 36 0 0 0 0 0 0\n# 75 2019-02-01 Children 240.7 37 0 0 0 0 0 0\n# 77 2019-03-01 Children 274.4 38 0 0 0 0 0 0\n# 79 2019-04-01 Children 256.8 39 0 0 0 0 0 0\n# 81 2019-05-01 Children 274.3 40 0 0 0 0 0 0\n# 83 2019-06-01 Children 240.3 41 0 0 0 0 0 0\n# 85 2019-07-01 Children 178.2 42 0 0 0 0 0 0\n# 87 2019-08-01 Children 180.3 43 0 0 0 0 0 0\n# 89 2019-09-01 Children 264.0 44 0 0 0 0 0 0\n# 91 2019-10-01 Children 271.3 45 0 0 0 0 0 0\n# 93 2019-11-01 Children 277.8 46 0 0 0 0 0 0\n# 95 2019-12-01 Children 261.5 47 0 0 0 0 0 0\n# 97 2020-01-01 Children 296.9 48 0 0 0 0 0 0\n# 99 2020-02-01 Children 265.8 49 0 0 0 0 0 0\n# 101 2020-03-01 Children 270.4 50 0 0 0 0 0 0\n# 103 2020-04-01 Children 218.8 51 0 0 0 0 0 0\n# 105 2020-05-01 Children 214.7 52 0 0 0 0 0 0\n# 107 2020-06-01 Children 221.8 53 0 0 0 0 0 0\n# 109 2020-07-01 Children 183.6 54 0 0 0 0 0 0\n# 111 2020-08-01 Children 185.4 55 0 0 0 0 0 0\n# 113 2020-09-01 Children 273.6 56 0 0 0 0 0 0\n# 115 2020-10-01 Children 276.7 57 0 0 0 0 0 0\n# 117 2020-11-01 Children 285.0 58 0 0 0 0 0 0\n# 119 2020-12-01 Children 282.8 59 0 0 0 0 0 0\n# 121 2021-01-01 Children 308.3 60 0 0 0 0 0 0\n# 123 2021-02-01 Children 279.2 61 0 0 0 0 0 0\n# 125 2021-03-01 Children 331.1 62 0 0 0 0 0 0\n# 127 2021-04-01 Children 289.3 63 0 0 0 0 0 0\n# 129 2021-05-01 Children 303.0 64 0 0 0 0 0 0\n# 131 2021-06-01 Children 307.5 65 0 0 0 0 0 0\n# 133 2021-07-01 Children 221.2 66 0 0 0 0 0 0\n# 135 2021-08-01 Children 215.4 67 0 0 0 0 0 0\n# 137 2021-09-01 Children 324.0 68 0 0 0 0 0 0\n# 139 2021-10-01 Children 323.3 69 1 0 0 0 0 0\n# 141 2021-11-01 Children 328.3 70 1 1 0 0 0 0\n# 143 2021-12-01 Children 326.5 71 1 2 0 0 0 0\n# 145 2022-01-01 Children 349.2 72 1 3 0 0 0 0\n# 147 2022-02-01 Children 319.1 73 1 4 0 0 0 0\n# 149 2022-03-01 Children 379.3 74 1 5 0 0 0 0\n# 151 2022-04-01 Children 341.7 75 1 6 0 0 0 0\n# 153 2022-05-01 Children 365.1 76 1 7 0 0 0 0\n# 155 2022-06-01 Children 351.7 77 1 8 0 0 0 0\n# 157 2022-07-01 Children 253.7 78 1 9 1 0 0 0\n# 159 2022-08-01 Children 266.9 79 1 10 1 1 0 0\n# 161 2022-09-01 Children 375.0 80 1 11 1 2 0 0\n# 163 2022-10-01 Children 373.5 81 1 12 1 3 0 0\n# 165 2022-11-01 Children 385.8 82 1 13 1 4 0 0\n# 167 2022-12-01 Children 368.1 83 1 14 1 5 0 0\n# 169 2023-01-01 Children 413.7 84 1 15 1 6 0 0\n# 171 2023-02-01 Children 376.0 85 1 16 1 7 0 0\n# 173 2023-03-01 Children 440.1 86 1 17 1 8 0 0\n# 175 2023-04-01 Children 390.3 87 1 18 1 9 0 0\n# 177 2023-05-01 Children 409.5 88 1 19 1 10 0 0\n# 179 2023-06-01 Children 402.0 89 1 20 1 11 0 0\n# 181 2023-07-01 Children 297.9 90 1 21 1 12 1 0\n# 183 2023-08-01 Children 297.1 91 1 22 1 13 1 1\n# 185 2023-09-01 Children 430.9 92 1 23 1 14 1 2\n# 187 2023-10-01 Children 433.4 93 1 24 1 15 1 3\n# 189 2023-11-01 Children 454.1 94 1 25 1 16 1 4\n# 191 2023-12-01 Children 441.4 95 1 26 1 17 1 5\n# 193 2024-01-01 Children 472.9 96 1 27 1 18 1 6\n# 195 2024-02-01 Children 455.8 97 1 28 1 19 1 7\n# 197 2024-03-01 Children 496.3 98 1 29 1 20 1 8\n# 199 2024-04-01 Children 475.0 99 1 30 1 21 1 9\n# 201 2024-05-01 Children 483.4 100 1 31 1 22 1 10\n# 203 2024-06-01 Children 466.0 101 1 32 1 23 1 11\n# 205 2024-07-01 Children 367.3 102 1 33 1 24 1 12\n# 207 2024-08-01 Children 368.4 103 1 34 1 25 1 13\n# 209 2024-09-01 Children 499.4 104 1 35 1 26 1 14\n# 211 2024-10-01 Children 528.3 105 1 36 1 27 1 15\n# 213 2024-11-01 Children 533.8 106 1 37 1 28 1 16\n# 215 2024-12-01 Children 525.6 107 1 38 1 29 1 17\n# 217 2025-01-01 Children 588.3 108 1 39 1 30 1 18\n# 219 2025-02-01 Children 532.4 109 1 40 1 31 1 19\n# 221 2025-03-01 Children 599.6 110 1 41 1 32 1 20\n# 223 2025-04-01 Children 580.3 111 1 42 1 33 1 21\n# 225 2025-05-01 Children 601.5 112 1 43 1 34 1 22\n# 227 2025-06-01 Children 560.6 113 1 44 1 35 1 23\n# 229 2025-07-01 Children 455.2 114 1 45 1 36 1 24\n# 231 2025-08-01 Children 440.6 115 1 46 1 37 1 25\n# 233 2025-09-01 Children 629.2 116 1 47 1 38 1 26\n# 235 2025-10-01 Children 655.7 117 1 48 1 39 1 27\n# 237 2025-11-01 Children 653.8 118 1 49 1 40 1 28\n# 239 2025-12-01 Children 674.9 119 1 50 1 41 1 29\n\n\n\n\n\nAccording to this thread (https://stats.stackexchange.com/q/665216/), I included the ITS variables for the 3 interventions in a single model. I used forecast::auto.arima() to select (p, q) and (P, Q) parameters automatically.\n\n\n\n\nAccording to Schaffer et al. (https://doi.org/10.1186/s12874-021-01235-8), I included a time variable and set $d = 0$ and $D = 0$ (but I am not sure that I need both $d = 0$ and $D = 0$): (emphasis mine)\n\n\n\n\n\n\n\nIn ITS analysis, ARIMA forecasts $Y_t$ in the absence of the intervention (the “counterfactual”) and determines how the observed diverges from this forecast. Unlike segmented regression, including time or seasonal dummy variables in the ARIMA model is not necessary, as ARIMA can eliminate trends and seasonality through differencing. If the trend is eliminated via differencing then the pre- and post-intervention trends cannot be estimated from the model. However, if estimation of the pre- and/or post-intervention slope is desired, this can be accommodated by including time as a covariate and incorporating AR and MA terms to address autocorrelation (e.g. ARMA models) [21 (https://doi.org/10.1186/s12889-017-4998-9), 22 (https://doi.org/10.3111/13696998.2011.626097)].\n\n\n\n\n\n\n\nfit <- forecast::auto.arima(\n d2$prevalence,\n d = 0,\n D = 0,\n stepwise = FALSE,\n trace = TRUE,\n approximation = FALSE,\n xreg = xreg\n)\n# \n# Regression with ARIMA(0,0,0) errors : 1422.701\n# Regression with ARIMA(0,0,0) errors : 1256.821\n# Regression with ARIMA(0,0,0)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,0)(0,0,1)[12] errors : 1186.586\n# Regression with ARIMA(0,0,0)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,0)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,2)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,1) errors : 1348.712\n# Regression with ARIMA(0,0,1) errors : 1237.018\n# Regression with ARIMA(0,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,1)(0,0,1)[12] errors : 1167.011\n# Regression with ARIMA(0,0,1)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,1)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,1)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,1)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,2)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,1)(2,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,2) errors : 1304.633\n# Regression with ARIMA(0,0,2) errors : 1235.236\n# Regression with ARIMA(0,0,2)(0,0,1)[12] errors : 1226.35\n# Regression with ARIMA(0,0,2)(0,0,1)[12] errors : 1164.06\n# Regression with ARIMA(0,0,2)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,2)(0,0,2)[12] errors : 1122.153\n# ARIMA(0,0,2)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,2)(1,0,0)[12] errors : Inf\n# ARIMA(0,0,2)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,2)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,2)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,2)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,2)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,3) errors : 1301.979\n# Regression with ARIMA(0,0,3) errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,1)[12] errors : 1166.444\n# Regression with ARIMA(0,0,3)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,3)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,3)(1,0,0)[12] errors : Inf\n# ARIMA(0,0,3)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,3)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,3)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,3)(2,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,4) errors : Inf\n# Regression with ARIMA(0,0,4) errors : Inf\n# Regression with ARIMA(0,0,4)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,4)(0,0,1)[12] errors : 1167.795\n# ARIMA(0,0,4)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,4)(1,0,0)[12] errors : Inf\n# Regression with ARIMA(0,0,5) errors : Inf\n# Regression with ARIMA(0,0,5) errors : Inf\n# Regression with ARIMA(1,0,0) errors : 1269.039\n# Regression with ARIMA(1,0,0) errors : 1236.551\n# Regression with ARIMA(1,0,0)(0,0,1)[12] errors : 1191.463\n# Regression with ARIMA(1,0,0)(0,0,1)[12] errors : 1163.925\n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors : 1144.206\n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors : 1122.139\n# ARIMA(1,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,0)(2,0,0)[12] errors : Inf\n# ARIMA(1,0,0)(2,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,0)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(2,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,0)(2,0,2)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,1) errors : 1269.741\n# Regression with ARIMA(1,0,1) errors : 1237.127\n# Regression with ARIMA(1,0,1)(0,0,1)[12] errors : 1191.287\n# Regression with ARIMA(1,0,1)(0,0,1)[12] errors : 1165.649\n# Regression with ARIMA(1,0,1)(0,0,2)[12] errors : 1145.611\n# Regression with ARIMA(1,0,1)(0,0,2)[12] errors : 1123.56\n# ARIMA(1,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(1,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,1)(2,0,0)[12] errors : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,2) errors : Inf\n# ARIMA(1,0,2) with non-zero mean : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,2) errors : Inf\n# ARIMA(1,0,2) with non-zero mean : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,2)[12] errors : Inf\n# ARIMA(1,0,2)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,2)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,2)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,2)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,2)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,2)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(1,0,3) errors : Inf\n# Regression with ARIMA(1,0,3) errors : Inf\n# Regression with ARIMA(1,0,3)(0,0,1)[12] errors : 1196.785\n# Regression with ARIMA(1,0,3)(0,0,1)[12] errors : Inf\n# ARIMA(1,0,3)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,3)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,4) errors : Inf\n# Regression with ARIMA(1,0,4) errors : Inf\n# Regression with ARIMA(2,0,0) errors : 1270.227\n# Regression with ARIMA(2,0,0) errors : 1235.453\n# Regression with ARIMA(2,0,0)(0,0,1)[12] errors : 1191.855\n# Regression with ARIMA(2,0,0)(0,0,1)[12] errors : 1165.096\n# Regression with ARIMA(2,0,0)(0,0,2)[12] errors : 1145.887\n# Regression with ARIMA(2,0,0)(0,0,2)[12] errors : 1123.031\n# ARIMA(2,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,0)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(2,0,1)[12] with zero mean : Inf\n# Regression with ARIMA(2,0,0)(2,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1) errors : Inf\n# Regression with ARIMA(2,0,1) errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,2)[12] errors : Inf\n# ARIMA(2,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,1)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(2,0,1)(1,0,1)[12] errors : Inf\n# ARIMA(2,0,1)(1,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(2,0,1)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(2,0,2) errors : Inf\n# Regression with ARIMA(2,0,2) errors : Inf\n# ARIMA(2,0,2)(0,0,1)[12] with zero mean : Inf\n# Regression with ARIMA(2,0,2)(0,0,1)[12] errors : Inf\n# ARIMA(2,0,2)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,2)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,3) with zero mean : Inf\n# Regression with ARIMA(2,0,3) errors : Inf\n# Regression with ARIMA(3,0,0) errors : 1271.552\n# Regression with ARIMA(3,0,0) errors : 1234.442\n# Regression with ARIMA(3,0,0)(0,0,1)[12] errors : 1193.944\n# Regression with ARIMA(3,0,0)(0,0,1)[12] errors : 1165.004\n# Regression with ARIMA(3,0,0)(0,0,2)[12] errors : 1147.337\n# Regression with ARIMA(3,0,0)(0,0,2)[12] errors : 1124.69\n# ARIMA(3,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(3,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(3,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(3,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,0)(2,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(3,0,1) errors : Inf\n# Regression with ARIMA(3,0,1) errors : Inf\n# Regression with ARIMA(3,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(3,0,1)(0,0,1)[12] errors : Inf\n# ARIMA(3,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,1)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(3,0,2) errors : Inf\n# Regression with ARIMA(3,0,2) errors : Inf\n# Regression with ARIMA(4,0,0) errors : 1268.176\n# Regression with ARIMA(4,0,0) errors : 1236.501\n# Regression with ARIMA(4,0,0)(0,0,1)[12] errors : 1191.278\n# Regression with ARIMA(4,0,0)(0,0,1)[12] errors : 1167.39\n# ARIMA(4,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(4,0,0)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(4,0,1) errors : Inf\n# Regression with ARIMA(4,0,1) errors : Inf\n# Regression with ARIMA(5,0,0) errors : 1270.388\n# Regression with ARIMA(5,0,0) errors : 1226.449\n# \n# \n# \n# Best model: Regression with ARIMA(1,0,0)(0,0,2)[12] errors \n# \n\nsummary(fit)\n# Series: d2$prevalence \n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors \n# \n# Coefficients:\n# ar1 sma1 sma2 intercept time step1 ramp1 step2 ramp2 step3 ramp3\n# 0.5256 1.0413 0.6987 188.8179 1.5717 3.3284 2.1966 -5.6181 0.4640 0.4378 4.6447\n# s.e. 0.0800 0.1536 0.1312 20.6895 0.4724 13.0492 3.5219 23.9955 3.8197 19.1790 2.5724\n# \n# sigma^2 = 494.9: log likelihood = -547.61\n# AIC=1119.22 AICc=1122.14 BIC=1152.67\n# \n# Training set error measures:\n# ME RMSE MAE MPE MAPE MASE ACF1\n# Training set -0.2760281 21.20232 16.21419 -0.9807653 5.578825 0.3604042 0.05861382\n\n\n\n\n\nQuestion\n\n\n\n\nShould I just apply the same strategy to adults? Or can such models handle correlated/stratified time series?\n\n\n\n\nI guess that there is a better strategy than fitting separate models within each subgroup. However, I suspect that I cannot simply stack the time series and include age in xreg. Additionally, I probably need an interaction terms (e.g. time * age).\n\n\n\n\nI have also read about nlme::gls() (https://stat.ethz.ch/R-manual/R-devel/library/nlme/html/gls.html) but I would like guidance/confirmation whether it is more appropriate.\n\n\n\n\n\n\n\nBTW, I am not satisfied with the fit, but I will explore that once I have decided the modelling strategy.\n\n\n\n\nres <- residuals(fit)\nl <- 36\n\npar(mfrow = c(3, 1))\nplot(res)\nacf(res, lag.max = l)\npacf(res, lag.max = l)\ndev.off()\n\nBox.test(res, lag = 24, type = \"Ljung-Box\", fitdf = 3)\n# \n# Box-Ljung test\n# \n# data: res\n# X-squared = 49.814, df = 21, p-value = 0.0003872\n# \n\n\n\n\n\n[image: residuals; source: https://i.sstatic.net/pzs11NTf.png] (https://i.sstatic.net/pzs11NTf.png)", "record_id": "Scientific-Code-and-Analysis-QA:stats:676979", "selected_answer": {"answer_html": "<p>Rather than fitting separate models, you can handle both age groups in a single <code>gls()</code> model with <code>age</code> interactions. This has two advantages over separate <code>auto.arima()</code> models: you get formal tests of whether intervention effects differ between groups via the interaction terms, and you can account for the fact that the two series have very different variances.</p>\n<p><code>age * (time + step1 + ramp1 + ...)</code> gives each group its own intercept, pre-intervention slope, and intervention effects, plus tests of whether they differ. Then, <code>corAR1(form = ~ 1 | age)</code> fits AR(1) autocorrelation within each group and <code>varIdent(form = ~ 1 | age)</code> allows different residual variances per group, which matters here since children's prevalence is an order of magnitude larger.</p>\n<pre class=\"lang-r prettyprint-override\"><code>library(nlme)\nlibrary(dplyr)\n\ninterventions &lt;- as.Date(c(&quot;2021-09-13&quot;, &quot;2022-06-02&quot;, &quot;2023-06-29&quot;))\n\nd_its &lt;- d |&gt;\n arrange(age, month) |&gt;\n mutate(.by = age,\n time = row_number() - 1,\n step1 = as.numeric(month &gt;= interventions[1]),\n ramp1 = ifelse(step1 == 1, cumsum(step1) - 1, 0),\n step2 = as.numeric(month &gt;= interventions[2]),\n ramp2 = ifelse(step2 == 1, cumsum(step2) - 1, 0),\n step3 = as.numeric(month &gt;= interventions[3]),\n ramp3 = ifelse(step3 == 1, cumsum(step3) - 1, 0),\n sin12 = sin(2 * pi * time / 12),\n cos12 = cos(2 * pi * time / 12),\n sin6 = sin(2 * pi * time / 6),\n cos6 = cos(2 * pi * time / 6),\n sin4 = sin(2 * pi * time / 4),\n cos4 = cos(2 * pi * time / 4)\n ) |&gt;\n mutate(age = factor(age))\n\nfit &lt;- gls(\n prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 +\n sin12 + cos12 + sin6 + cos6 + sin4 + cos4),\n data = d_its,\n correlation = corAR1(form = ~ 1 | age),\n weights = varIdent(form = ~ 1 | age)\n)\n</code></pre>\n<p>The Fourier terms (<code>sin12</code>, <code>cos12</code>, etc.) handle the recurring seasonal pattern, which is more stable than trying to absorb it through ARMA error terms (see <a href=\"https://otexts.com/fpp3/dhr.html\" rel=\"nofollow noreferrer\">https://otexts.com/fpp3/dhr.html</a>).</p>\n<p>The reference level is Adults, so coefficients are interpreted as:</p>\n<ul>\n<li><code>time</code>: pre-intervention slope for adults (prevalence per month)</li>\n<li><code>ageChildren:time</code>: <em>additional</em> slope for children;</li>\n</ul>\n<p>The same logic applies for all <code>ramp</code> and <code>step</code> terms.</p>\n<pre class=\"lang-r prettyprint-override\"><code>coef(fit) |&gt;\n (\\(e) data.frame(\n Segment = c(&quot;Pre&quot;, &quot;Post-1&quot;, &quot;Post-2&quot;, &quot;Post-3&quot;),\n Adults = round(cumsum(c(e[&quot;time&quot;],\n e[&quot;ramp1&quot;],\n e[&quot;ramp2&quot;],\n e[&quot;ramp3&quot;])), 3),\n Children = round(cumsum(c(e[&quot;time&quot;] + e[&quot;ageChildren:time&quot;],\n e[&quot;ramp1&quot;] + e[&quot;ageChildren:ramp1&quot;],\n e[&quot;ramp2&quot;] + e[&quot;ageChildren:ramp2&quot;],\n e[&quot;ramp3&quot;] + e[&quot;ageChildren:ramp3&quot;])), 3)\n))()\n\n#&gt; Segment Adults Children\n#&gt; time Pre 0.152 1.445\n#&gt; ramp1 Post-1 0.919 9.276\n#&gt; ramp2 Post-2 1.265 6.667\n#&gt; ramp3 Post-3 2.387 8.418\n</code></pre>\n<pre class=\"lang-r prettyprint-override\"><code>par(mfrow = c(1, 2))\nacf(residuals(fit)[d_its<span class=\"math-container\">$age == \"Adults\"], main = \"Adults\")\nacf(residuals(fit)[d_its$</span>age == &quot;Children&quot;], main = &quot;Children&quot;)\ndev.off()\n</code></pre>\n<p><img src=\"https://i.sstatic.net/2fnDCjiM.png\" alt=\"\" /></p>\n<pre class=\"lang-r prettyprint-override\"><code>summary(fit)\n\n#&gt; Generalized least squares fit by REML\n#&gt; Model: prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 + sin12 + cos12 + sin6 + cos6 + sin4 + cos4) \n#&gt; Data: d_its \n#&gt; AIC BIC logLik\n#&gt; 1665.172 1769.226 -801.5858\n#&gt; \n#&gt; Correlation Structure: AR(1)\n#&gt; Formula: ~1 | age \n#&gt; Parameter estimate(s):\n#&gt; Phi \n#&gt; 0.1231768 \n#&gt; Variance function:\n#&gt; Structure: Different standard deviations per stratum\n#&gt; Formula: ~1 | age \n#&gt; Parameter estimates:\n#&gt; Adults Children \n#&gt; 1.000000 9.435418 \n#&gt; \n#&gt; Coefficients:\n#&gt; Value Std.Error t-value p-value\n#&gt; (Intercept) 10.25450 0.701853 14.610597 0.0000\n#&gt; ageChildren 177.16318 6.659369 26.603599 0.0000\n#&gt; time 0.15162 0.017799 8.518225 0.0000\n#&gt; step1 1.83019 1.934456 0.946100 0.3452\n#&gt; ramp1 0.76689 0.379858 2.018892 0.0448\n#&gt; step2 -0.98456 2.681497 -0.367167 0.7139\n#&gt; ramp2 0.34620 0.449034 0.770992 0.4416\n#&gt; step3 -4.38832 2.094825 -2.094838 0.0374\n#&gt; ramp3 1.12257 0.257109 4.366133 0.0000\n#&gt; sin12 0.01845 0.399784 0.046145 0.9632\n#&gt; cos12 1.16269 0.380402 3.056467 0.0025\n#&gt; sin6 -0.70555 0.358820 -1.966309 0.0506\n#&gt; cos6 -0.97079 0.355213 -2.732980 0.0068\n#&gt; sin4 0.78337 0.333359 2.349941 0.0197\n#&gt; cos4 0.05479 0.333865 0.164117 0.8698\n#&gt; ageChildren:time 1.29381 0.168883 7.661002 0.0000\n#&gt; ageChildren:step1 -1.02662 18.354630 -0.055933 0.9554\n#&gt; ageChildren:ramp1 7.06407 3.604192 1.959960 0.0513\n#&gt; ageChildren:step2 -35.82645 25.442751 -1.408120 0.1606\n#&gt; ageChildren:ramp2 -2.95530 4.260553 -0.693643 0.4887\n#&gt; ageChildren:step3 -29.49930 19.876247 -1.484148 0.1393\n#&gt; ageChildren:ramp3 0.62770 2.439516 0.257306 0.7972\n#&gt; ageChildren:sin12 4.22521 3.793256 1.113874 0.2666\n#&gt; ageChildren:cos12 36.54005 3.609352 10.123715 0.0000\n#&gt; ageChildren:sin6 -9.76953 3.404578 -2.869528 0.0045\n#&gt; ageChildren:cos6 -25.08251 3.370352 -7.442104 0.0000\n#&gt; ageChildren:sin4 13.68702 3.162997 4.327230 0.0000\n#&gt; ageChildren:cos4 14.66062 3.167797 4.628016 0.0000\n#&gt; \n#&gt; Correlation: \n#&gt; (Intr) agChld time step1 ramp1 step2 ramp2 step3 \n#&gt; ageChildren -0.105 \n#&gt; time -0.862 0.091 \n#&gt; step1 0.173 -0.018 -0.309 \n#&gt; ramp1 0.057 -0.006 -0.063 -0.763 \n#&gt; step2 -0.021 0.002 0.020 0.366 -0.711 \n#&gt; ramp2 -0.004 0.000 0.005 0.655 -0.831 0.306 \n#&gt; step3 -0.015 0.002 0.015 0.007 -0.031 0.300 -0.403 \n#&gt; ramp3 -0.016 0.002 0.016 0.008 -0.023 0.514 -0.520 0.649\n#&gt; sin12 -0.056 0.006 0.043 0.155 -0.247 0.317 0.074 0.209\n#&gt; cos12 -0.050 0.005 0.069 -0.188 0.137 -0.028 -0.155 0.065\n#&gt; sin6 -0.008 0.001 -0.006 0.034 0.018 -0.103 0.052 -0.126\n#&gt; cos6 -0.010 0.001 0.002 0.047 -0.026 -0.035 0.060 -0.071\n#&gt; sin4 -0.024 0.002 0.028 -0.033 -0.004 0.059 -0.040 0.066\n#&gt; cos4 -0.011 0.001 0.002 0.063 -0.078 0.095 0.024 0.069\n#&gt; ageChildren:time 0.091 -0.862 -0.105 0.033 0.007 -0.002 0.000 -0.002\n#&gt; ageChildren:step1 -0.018 0.173 0.033 -0.105 0.080 -0.039 -0.069 -0.001\n#&gt; ageChildren:ramp1 -0.006 0.057 0.007 0.080 -0.105 0.075 0.088 0.003\n#&gt; ageChildren:step2 0.002 -0.021 -0.002 -0.039 0.075 -0.105 -0.032 -0.032\n#&gt; ageChildren:ramp2 0.000 -0.004 0.000 -0.069 0.088 -0.032 -0.105 0.043\n#&gt; ageChildren:step3 0.002 -0.015 -0.002 -0.001 0.003 -0.032 0.043 -0.105\n#&gt; ageChildren:ramp3 0.002 -0.016 -0.002 -0.001 0.002 -0.054 0.055 -0.068\n#&gt; ageChildren:sin12 0.006 -0.056 -0.005 -0.016 0.026 -0.033 -0.008 -0.022\n#&gt; ageChildren:cos12 0.005 -0.050 -0.007 0.020 -0.014 0.003 0.016 -0.007\n#&gt; ageChildren:sin6 0.001 -0.008 0.001 -0.004 -0.002 0.011 -0.005 0.013\n#&gt; ageChildren:cos6 0.001 -0.010 0.000 -0.005 0.003 0.004 -0.006 0.007\n#&gt; ageChildren:sin4 0.002 -0.024 -0.003 0.003 0.000 -0.006 0.004 -0.007\n#&gt; ageChildren:cos4 0.001 -0.011 0.000 -0.007 0.008 -0.010 -0.002 -0.007\n#&gt; ramp3 sin12 cos12 sin6 cos6 sin4 cos4 agChl:\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 0.235 \n#&gt; cos12 0.057 -0.008 \n#&gt; sin6 -0.099 -0.036 -0.015 \n#&gt; cos6 -0.058 -0.011 -0.017 0.017 \n#&gt; sin4 0.074 0.025 0.014 -0.013 -0.006 \n#&gt; cos4 0.073 0.041 -0.007 -0.009 -0.004 0.009 \n#&gt; ageChildren:time -0.002 -0.005 -0.007 0.001 0.000 -0.003 0.000 \n#&gt; ageChildren:step1 -0.001 -0.016 0.020 -0.004 -0.005 0.003 -0.007 -0.309\n#&gt; ageChildren:ramp1 0.002 0.026 -0.014 -0.002 0.003 0.000 0.008 -0.063\n#&gt; ageChildren:step2 -0.054 -0.033 0.003 0.011 0.004 -0.006 -0.010 0.020\n#&gt; ageChildren:ramp2 0.055 -0.008 0.016 -0.005 -0.006 0.004 -0.002 0.005\n#&gt; ageChildren:step3 -0.068 -0.022 -0.007 0.013 0.007 -0.007 -0.007 0.015\n#&gt; ageChildren:ramp3 -0.105 -0.025 -0.006 0.010 0.006 -0.008 -0.008 0.016\n#&gt; ageChildren:sin12 -0.025 -0.105 0.001 0.004 0.001 -0.003 -0.004 0.043\n#&gt; ageChildren:cos12 -0.006 0.001 -0.105 0.002 0.002 -0.002 0.001 0.069\n#&gt; ageChildren:sin6 0.010 0.004 0.002 -0.105 -0.002 0.001 0.001 -0.006\n#&gt; ageChildren:cos6 0.006 0.001 0.002 -0.002 -0.105 0.001 0.000 0.002\n#&gt; ageChildren:sin4 -0.008 -0.003 -0.002 0.001 0.001 -0.105 -0.001 0.028\n#&gt; ageChildren:cos4 -0.008 -0.004 0.001 0.001 0.000 -0.001 -0.105 0.002\n#&gt; agChldrn:s1 agChldrn:r1 agChldrn:s2 agChldrn:r2 agChldrn:s3\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 \n#&gt; cos12 \n#&gt; sin6 \n#&gt; cos6 \n#&gt; sin4 \n#&gt; cos4 \n#&gt; ageChildren:time \n#&gt; ageChildren:step1 \n#&gt; ageChildren:ramp1 -0.763 \n#&gt; ageChildren:step2 0.366 -0.711 \n#&gt; ageChildren:ramp2 0.655 -0.831 0.306 \n#&gt; ageChildren:step3 0.007 -0.031 0.300 -0.403 \n#&gt; ageChildren:ramp3 0.008 -0.023 0.514 -0.520 0.649 \n#&gt; ageChildren:sin12 0.155 -0.247 0.317 0.074 0.209 \n#&gt; ageChildren:cos12 -0.188 0.137 -0.028 -0.155 0.065 \n#&gt; ageChildren:sin6 0.034 0.018 -0.103 0.052 -0.126 \n#&gt; ageChildren:cos6 0.047 -0.026 -0.035 0.060 -0.071 \n#&gt; ageChildren:sin4 -0.033 -0.004 0.059 -0.040 0.066 \n#&gt; ageChildren:cos4 0.063 -0.078 0.095 0.024 0.069 \n#&gt; agChldrn:r3 agChldrn:s12 agChldrn:c12 agChldrn:s6 agChldrn:c6\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 \n#&gt; cos12 \n#&gt; sin6 \n#&gt; cos6 \n#&gt; sin4 \n#&gt; cos4 \n#&gt; ageChildren:time \n#&gt; ageChildren:step1 \n#&gt; ageChildren:ramp1 \n#&gt; ageChildren:step2 \n#&gt; ageChildren:ramp2 \n#&gt; ageChildren:step3 \n#&gt; ageChildren:ramp3 \n#&gt; ageChildren:sin12 0.235 \n#&gt; ageChildren:cos12 0.057 -0.008 \n#&gt; ageChildren:sin6 -0.099 -0.036 -0.015 \n#&gt; ageChildren:cos6 -0.058 -0.011 -0.017 0.017 \n#&gt; ageChildren:sin4 0.074 0.025 0.014 -0.013 -0.006 \n#&gt; ageChildren:cos4 0.073 0.041 -0.007 -0.009 -0.004 \n#&gt; agChldrn:s4\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 \n#&gt; cos12 \n#&gt; sin6 \n#&gt; cos6 \n#&gt; sin4 \n#&gt; cos4 \n#&gt; ageChildren:time \n#&gt; ageChildren:step1 \n#&gt; ageChildren:ramp1 \n#&gt; ageChildren:step2 \n#&gt; ageChildren:ramp2 \n#&gt; ageChildren:step3 \n#&gt; ageChildren:ramp3 \n#&gt; ageChildren:sin12 \n#&gt; ageChildren:cos12 \n#&gt; ageChildren:sin6 \n#&gt; ageChildren:cos6 \n#&gt; ageChildren:sin4 \n#&gt; ageChildren:cos4 0.009 \n#&gt; \n#&gt; Standardized residuals:\n#&gt; Min Q1 Med Q3 Max \n#&gt; -5.25291094 -0.42240774 0.04331099 0.45224365 3.26323939 \n#&gt; \n#&gt; Residual standard error: 2.608572 \n#&gt; Degrees of freedom: 240 total; 212 residual\n</code></pre>\n<p><sup>Created on 2026-08-29 with <a href=\"https://reprex.tidyverse.org\" rel=\"nofollow noreferrer\">reprex v2.1.1</a></sup></p>\n", "answer_id": 676996, "answer_text": "Rather than fitting separate models, you can handle both age groups in a single gls() model with age interactions. This has two advantages over separate auto.arima() models: you get formal tests of whether intervention effects differ between groups via the interaction terms, and you can account for the fact that the two series have very different variances.\n\n\n\n\nage * (time + step1 + ramp1 + ...) gives each group its own intercept, pre-intervention slope, and intervention effects, plus tests of whether they differ. Then, corAR1(form = ~ 1 | age) fits AR(1) autocorrelation within each group and varIdent(form = ~ 1 | age) allows different residual variances per group, which matters here since children's prevalence is an order of magnitude larger.\n\n\n\n\nlibrary(nlme)\nlibrary(dplyr)\n\ninterventions <- as.Date(c(\"2021-09-13\", \"2022-06-02\", \"2023-06-29\"))\n\nd_its <- d |>\n arrange(age, month) |>\n mutate(.by = age,\n time = row_number() - 1,\n step1 = as.numeric(month >= interventions[1]),\n ramp1 = ifelse(step1 == 1, cumsum(step1) - 1, 0),\n step2 = as.numeric(month >= interventions[2]),\n ramp2 = ifelse(step2 == 1, cumsum(step2) - 1, 0),\n step3 = as.numeric(month >= interventions[3]),\n ramp3 = ifelse(step3 == 1, cumsum(step3) - 1, 0),\n sin12 = sin(2 * pi * time / 12),\n cos12 = cos(2 * pi * time / 12),\n sin6 = sin(2 * pi * time / 6),\n cos6 = cos(2 * pi * time / 6),\n sin4 = sin(2 * pi * time / 4),\n cos4 = cos(2 * pi * time / 4)\n ) |>\n mutate(age = factor(age))\n\nfit <- gls(\n prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 +\n sin12 + cos12 + sin6 + cos6 + sin4 + cos4),\n data = d_its,\n correlation = corAR1(form = ~ 1 | age),\n weights = varIdent(form = ~ 1 | age)\n)\n\n\n\n\n\nThe Fourier terms (sin12, cos12, etc.) handle the recurring seasonal pattern, which is more stable than trying to absorb it through ARMA error terms (see https://otexts.com/fpp3/dhr.html (https://otexts.com/fpp3/dhr.html)).\n\n\n\n\nThe reference level is Adults, so coefficients are interpreted as:\n\n\n\n\n\ntime: pre-intervention slope for adults (prevalence per month)\n\n\n\n\nageChildren:time: additional slope for children;\n\n\n\n\n\nThe same logic applies for all ramp and step terms.\n\n\n\n\ncoef(fit) |>\n (\\(e) data.frame(\n Segment = c(\"Pre\", \"Post-1\", \"Post-2\", \"Post-3\"),\n Adults = round(cumsum(c(e[\"time\"],\n e[\"ramp1\"],\n e[\"ramp2\"],\n e[\"ramp3\"])), 3),\n Children = round(cumsum(c(e[\"time\"] + e[\"ageChildren:time\"],\n e[\"ramp1\"] + e[\"ageChildren:ramp1\"],\n e[\"ramp2\"] + e[\"ageChildren:ramp2\"],\n e[\"ramp3\"] + e[\"ageChildren:ramp3\"])), 3)\n))()\n\n#> Segment Adults Children\n#> time Pre 0.152 1.445\n#> ramp1 Post-1 0.919 9.276\n#> ramp2 Post-2 1.265 6.667\n#> ramp3 Post-3 2.387 8.418\n\n\n\n\n\npar(mfrow = c(1, 2))\nacf(residuals(fit)[d_its$age == \"Adults\"], main = \"Adults\")\nacf(residuals(fit)[d_its$age == \"Children\"], main = \"Children\")\ndev.off()\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/2fnDCjiM.png]\n\n\n\n\nsummary(fit)\n\n#> Generalized least squares fit by REML\n#> Model: prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 + sin12 + cos12 + sin6 + cos6 + sin4 + cos4) \n#> Data: d_its \n#> AIC BIC logLik\n#> 1665.172 1769.226 -801.5858\n#> \n#> Correlation Structure: AR(1)\n#> Formula: ~1 | age \n#> Parameter estimate(s):\n#> Phi \n#> 0.1231768 \n#> Variance function:\n#> Structure: Different standard deviations per stratum\n#> Formula: ~1 | age \n#> Parameter estimates:\n#> Adults Children \n#> 1.000000 9.435418 \n#> \n#> Coefficients:\n#> Value Std.Error t-value p-value\n#> (Intercept) 10.25450 0.701853 14.610597 0.0000\n#> ageChildren 177.16318 6.659369 26.603599 0.0000\n#> time 0.15162 0.017799 8.518225 0.0000\n#> step1 1.83019 1.934456 0.946100 0.3452\n#> ramp1 0.76689 0.379858 2.018892 0.0448\n#> step2 -0.98456 2.681497 -0.367167 0.7139\n#> ramp2 0.34620 0.449034 0.770992 0.4416\n#> step3 -4.38832 2.094825 -2.094838 0.0374\n#> ramp3 1.12257 0.257109 4.366133 0.0000\n#> sin12 0.01845 0.399784 0.046145 0.9632\n#> cos12 1.16269 0.380402 3.056467 0.0025\n#> sin6 -0.70555 0.358820 -1.966309 0.0506\n#> cos6 -0.97079 0.355213 -2.732980 0.0068\n#> sin4 0.78337 0.333359 2.349941 0.0197\n#> cos4 0.05479 0.333865 0.164117 0.8698\n#> ageChildren:time 1.29381 0.168883 7.661002 0.0000\n#> ageChildren:step1 -1.02662 18.354630 -0.055933 0.9554\n#> ageChildren:ramp1 7.06407 3.604192 1.959960 0.0513\n#> ageChildren:step2 -35.82645 25.442751 -1.408120 0.1606\n#> ageChildren:ramp2 -2.95530 4.260553 -0.693643 0.4887\n#> ageChildren:step3 -29.49930 19.876247 -1.484148 0.1393\n#> ageChildren:ramp3 0.62770 2.439516 0.257306 0.7972\n#> ageChildren:sin12 4.22521 3.793256 1.113874 0.2666\n#> ageChildren:cos12 36.54005 3.609352 10.123715 0.0000\n#> ageChildren:sin6 -9.76953 3.404578 -2.869528 0.0045\n#> ageChildren:cos6 -25.08251 3.370352 -7.442104 0.0000\n#> ageChildren:sin4 13.68702 3.162997 4.327230 0.0000\n#> ageChildren:cos4 14.66062 3.167797 4.628016 0.0000\n#> \n#> Correlation: \n#> (Intr) agChld time step1 ramp1 step2 ramp2 step3 \n#> ageChildren -0.105 \n#> time -0.862 0.091 \n#> step1 0.173 -0.018 -0.309 \n#> ramp1 0.057 -0.006 -0.063 -0.763 \n#> step2 -0.021 0.002 0.020 0.366 -0.711 \n#> ramp2 -0.004 0.000 0.005 0.655 -0.831 0.306 \n#> step3 -0.015 0.002 0.015 0.007 -0.031 0.300 -0.403 \n#> ramp3 -0.016 0.002 0.016 0.008 -0.023 0.514 -0.520 0.649\n#> sin12 -0.056 0.006 0.043 0.155 -0.247 0.317 0.074 0.209\n#> cos12 -0.050 0.005 0.069 -0.188 0.137 -0.028 -0.155 0.065\n#> sin6 -0.008 0.001 -0.006 0.034 0.018 -0.103 0.052 -0.126\n#> cos6 -0.010 0.001 0.002 0.047 -0.026 -0.035 0.060 -0.071\n#> sin4 -0.024 0.002 0.028 -0.033 -0.004 0.059 -0.040 0.066\n#> cos4 -0.011 0.001 0.002 0.063 -0.078 0.095 0.024 0.069\n#> ageChildren:time 0.091 -0.862 -0.105 0.033 0.007 -0.002 0.000 -0.002\n#> ageChildren:step1 -0.018 0.173 0.033 -0.105 0.080 -0.039 -0.069 -0.001\n#> ageChildren:ramp1 -0.006 0.057 0.007 0.080 -0.105 0.075 0.088 0.003\n#> ageChildren:step2 0.002 -0.021 -0.002 -0.039 0.075 -0.105 -0.032 -0.032\n#> ageChildren:ramp2 0.000 -0.004 0.000 -0.069 0.088 -0.032 -0.105 0.043\n#> ageChildren:step3 0.002 -0.015 -0.002 -0.001 0.003 -0.032 0.043 -0.105\n#> ageChildren:ramp3 0.002 -0.016 -0.002 -0.001 0.002 -0.054 0.055 -0.068\n#> ageChildren:sin12 0.006 -0.056 -0.005 -0.016 0.026 -0.033 -0.008 -0.022\n#> ageChildren:cos12 0.005 -0.050 -0.007 0.020 -0.014 0.003 0.016 -0.007\n#> ageChildren:sin6 0.001 -0.008 0.001 -0.004 -0.002 0.011 -0.005 0.013\n#> ageChildren:cos6 0.001 -0.010 0.000 -0.005 0.003 0.004 -0.006 0.007\n#> ageChildren:sin4 0.002 -0.024 -0.003 0.003 0.000 -0.006 0.004 -0.007\n#> ageChildren:cos4 0.001 -0.011 0.000 -0.007 0.008 -0.010 -0.002 -0.007\n#> ramp3 sin12 cos12 sin6 cos6 sin4 cos4 agChl:\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 0.235 \n#> cos12 0.057 -0.008 \n#> sin6 -0.099 -0.036 -0.015 \n#> cos6 -0.058 -0.011 -0.017 0.017 \n#> sin4 0.074 0.025 0.014 -0.013 -0.006 \n#> cos4 0.073 0.041 -0.007 -0.009 -0.004 0.009 \n#> ageChildren:time -0.002 -0.005 -0.007 0.001 0.000 -0.003 0.000 \n#> ageChildren:step1 -0.001 -0.016 0.020 -0.004 -0.005 0.003 -0.007 -0.309\n#> ageChildren:ramp1 0.002 0.026 -0.014 -0.002 0.003 0.000 0.008 -0.063\n#> ageChildren:step2 -0.054 -0.033 0.003 0.011 0.004 -0.006 -0.010 0.020\n#> ageChildren:ramp2 0.055 -0.008 0.016 -0.005 -0.006 0.004 -0.002 0.005\n#> ageChildren:step3 -0.068 -0.022 -0.007 0.013 0.007 -0.007 -0.007 0.015\n#> ageChildren:ramp3 -0.105 -0.025 -0.006 0.010 0.006 -0.008 -0.008 0.016\n#> ageChildren:sin12 -0.025 -0.105 0.001 0.004 0.001 -0.003 -0.004 0.043\n#> ageChildren:cos12 -0.006 0.001 -0.105 0.002 0.002 -0.002 0.001 0.069\n#> ageChildren:sin6 0.010 0.004 0.002 -0.105 -0.002 0.001 0.001 -0.006\n#> ageChildren:cos6 0.006 0.001 0.002 -0.002 -0.105 0.001 0.000 0.002\n#> ageChildren:sin4 -0.008 -0.003 -0.002 0.001 0.001 -0.105 -0.001 0.028\n#> ageChildren:cos4 -0.008 -0.004 0.001 0.001 0.000 -0.001 -0.105 0.002\n#> agChldrn:s1 agChldrn:r1 agChldrn:s2 agChldrn:r2 agChldrn:s3\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 -0.763 \n#> ageChildren:step2 0.366 -0.711 \n#> ageChildren:ramp2 0.655 -0.831 0.306 \n#> ageChildren:step3 0.007 -0.031 0.300 -0.403 \n#> ageChildren:ramp3 0.008 -0.023 0.514 -0.520 0.649 \n#> ageChildren:sin12 0.155 -0.247 0.317 0.074 0.209 \n#> ageChildren:cos12 -0.188 0.137 -0.028 -0.155 0.065 \n#> ageChildren:sin6 0.034 0.018 -0.103 0.052 -0.126 \n#> ageChildren:cos6 0.047 -0.026 -0.035 0.060 -0.071 \n#> ageChildren:sin4 -0.033 -0.004 0.059 -0.040 0.066 \n#> ageChildren:cos4 0.063 -0.078 0.095 0.024 0.069 \n#> agChldrn:r3 agChldrn:s12 agChldrn:c12 agChldrn:s6 agChldrn:c6\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 \n#> ageChildren:step2 \n#> ageChildren:ramp2 \n#> ageChildren:step3 \n#> ageChildren:ramp3 \n#> ageChildren:sin12 0.235 \n#> ageChildren:cos12 0.057 -0.008 \n#> ageChildren:sin6 -0.099 -0.036 -0.015 \n#> ageChildren:cos6 -0.058 -0.011 -0.017 0.017 \n#> ageChildren:sin4 0.074 0.025 0.014 -0.013 -0.006 \n#> ageChildren:cos4 0.073 0.041 -0.007 -0.009 -0.004 \n#> agChldrn:s4\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 \n#> ageChildren:step2 \n#> ageChildren:ramp2 \n#> ageChildren:step3 \n#> ageChildren:ramp3 \n#> ageChildren:sin12 \n#> ageChildren:cos12 \n#> ageChildren:sin6 \n#> ageChildren:cos6 \n#> ageChildren:sin4 \n#> ageChildren:cos4 0.009 \n#> \n#> Standardized residuals:\n#> Min Q1 Med Q3 Max \n#> -5.25291094 -0.42240774 0.04331099 0.45224365 3.26323939 \n#> \n#> Residual standard error: 2.608572 \n#> Degrees of freedom: 240 total; 212 residual\n\n\n\n\n\nCreated on 2026-08-29 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/676996", "author": "M--", "author_url": "https://stats.stackexchange.com/users/154449/m", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-29T05:35:19+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 676979, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "M--", "profile_url": "https://stats.stackexchange.com/users/154449/m", "user_type": "registered"}, "created_at": "2026-08-29T05:35:19+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "4F437721-3A00-4B4D-BA06-A2F50516CC59", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/4F437721-3A00-4B4D-BA06-A2F50516CC59/view-source"}], "score": 3, "updated_at": "2026-08-29T05:35:19+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "validation", "thread": {"accepted_answer_id": 676996, "answers": [{"answer_html": "<p>Rather than fitting separate models, you can handle both age groups in a single <code>gls()</code> model with <code>age</code> interactions. This has two advantages over separate <code>auto.arima()</code> models: you get formal tests of whether intervention effects differ between groups via the interaction terms, and you can account for the fact that the two series have very different variances.</p>\n<p><code>age * (time + step1 + ramp1 + ...)</code> gives each group its own intercept, pre-intervention slope, and intervention effects, plus tests of whether they differ. Then, <code>corAR1(form = ~ 1 | age)</code> fits AR(1) autocorrelation within each group and <code>varIdent(form = ~ 1 | age)</code> allows different residual variances per group, which matters here since children's prevalence is an order of magnitude larger.</p>\n<pre class=\"lang-r prettyprint-override\"><code>library(nlme)\nlibrary(dplyr)\n\ninterventions &lt;- as.Date(c(&quot;2021-09-13&quot;, &quot;2022-06-02&quot;, &quot;2023-06-29&quot;))\n\nd_its &lt;- d |&gt;\n arrange(age, month) |&gt;\n mutate(.by = age,\n time = row_number() - 1,\n step1 = as.numeric(month &gt;= interventions[1]),\n ramp1 = ifelse(step1 == 1, cumsum(step1) - 1, 0),\n step2 = as.numeric(month &gt;= interventions[2]),\n ramp2 = ifelse(step2 == 1, cumsum(step2) - 1, 0),\n step3 = as.numeric(month &gt;= interventions[3]),\n ramp3 = ifelse(step3 == 1, cumsum(step3) - 1, 0),\n sin12 = sin(2 * pi * time / 12),\n cos12 = cos(2 * pi * time / 12),\n sin6 = sin(2 * pi * time / 6),\n cos6 = cos(2 * pi * time / 6),\n sin4 = sin(2 * pi * time / 4),\n cos4 = cos(2 * pi * time / 4)\n ) |&gt;\n mutate(age = factor(age))\n\nfit &lt;- gls(\n prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 +\n sin12 + cos12 + sin6 + cos6 + sin4 + cos4),\n data = d_its,\n correlation = corAR1(form = ~ 1 | age),\n weights = varIdent(form = ~ 1 | age)\n)\n</code></pre>\n<p>The Fourier terms (<code>sin12</code>, <code>cos12</code>, etc.) handle the recurring seasonal pattern, which is more stable than trying to absorb it through ARMA error terms (see <a href=\"https://otexts.com/fpp3/dhr.html\" rel=\"nofollow noreferrer\">https://otexts.com/fpp3/dhr.html</a>).</p>\n<p>The reference level is Adults, so coefficients are interpreted as:</p>\n<ul>\n<li><code>time</code>: pre-intervention slope for adults (prevalence per month)</li>\n<li><code>ageChildren:time</code>: <em>additional</em> slope for children;</li>\n</ul>\n<p>The same logic applies for all <code>ramp</code> and <code>step</code> terms.</p>\n<pre class=\"lang-r prettyprint-override\"><code>coef(fit) |&gt;\n (\\(e) data.frame(\n Segment = c(&quot;Pre&quot;, &quot;Post-1&quot;, &quot;Post-2&quot;, &quot;Post-3&quot;),\n Adults = round(cumsum(c(e[&quot;time&quot;],\n e[&quot;ramp1&quot;],\n e[&quot;ramp2&quot;],\n e[&quot;ramp3&quot;])), 3),\n Children = round(cumsum(c(e[&quot;time&quot;] + e[&quot;ageChildren:time&quot;],\n e[&quot;ramp1&quot;] + e[&quot;ageChildren:ramp1&quot;],\n e[&quot;ramp2&quot;] + e[&quot;ageChildren:ramp2&quot;],\n e[&quot;ramp3&quot;] + e[&quot;ageChildren:ramp3&quot;])), 3)\n))()\n\n#&gt; Segment Adults Children\n#&gt; time Pre 0.152 1.445\n#&gt; ramp1 Post-1 0.919 9.276\n#&gt; ramp2 Post-2 1.265 6.667\n#&gt; ramp3 Post-3 2.387 8.418\n</code></pre>\n<pre class=\"lang-r prettyprint-override\"><code>par(mfrow = c(1, 2))\nacf(residuals(fit)[d_its<span class=\"math-container\">$age == \"Adults\"], main = \"Adults\")\nacf(residuals(fit)[d_its$</span>age == &quot;Children&quot;], main = &quot;Children&quot;)\ndev.off()\n</code></pre>\n<p><img src=\"https://i.sstatic.net/2fnDCjiM.png\" alt=\"\" /></p>\n<pre class=\"lang-r prettyprint-override\"><code>summary(fit)\n\n#&gt; Generalized least squares fit by REML\n#&gt; Model: prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 + sin12 + cos12 + sin6 + cos6 + sin4 + cos4) \n#&gt; Data: d_its \n#&gt; AIC BIC logLik\n#&gt; 1665.172 1769.226 -801.5858\n#&gt; \n#&gt; Correlation Structure: AR(1)\n#&gt; Formula: ~1 | age \n#&gt; Parameter estimate(s):\n#&gt; Phi \n#&gt; 0.1231768 \n#&gt; Variance function:\n#&gt; Structure: Different standard deviations per stratum\n#&gt; Formula: ~1 | age \n#&gt; Parameter estimates:\n#&gt; Adults Children \n#&gt; 1.000000 9.435418 \n#&gt; \n#&gt; Coefficients:\n#&gt; Value Std.Error t-value p-value\n#&gt; (Intercept) 10.25450 0.701853 14.610597 0.0000\n#&gt; ageChildren 177.16318 6.659369 26.603599 0.0000\n#&gt; time 0.15162 0.017799 8.518225 0.0000\n#&gt; step1 1.83019 1.934456 0.946100 0.3452\n#&gt; ramp1 0.76689 0.379858 2.018892 0.0448\n#&gt; step2 -0.98456 2.681497 -0.367167 0.7139\n#&gt; ramp2 0.34620 0.449034 0.770992 0.4416\n#&gt; step3 -4.38832 2.094825 -2.094838 0.0374\n#&gt; ramp3 1.12257 0.257109 4.366133 0.0000\n#&gt; sin12 0.01845 0.399784 0.046145 0.9632\n#&gt; cos12 1.16269 0.380402 3.056467 0.0025\n#&gt; sin6 -0.70555 0.358820 -1.966309 0.0506\n#&gt; cos6 -0.97079 0.355213 -2.732980 0.0068\n#&gt; sin4 0.78337 0.333359 2.349941 0.0197\n#&gt; cos4 0.05479 0.333865 0.164117 0.8698\n#&gt; ageChildren:time 1.29381 0.168883 7.661002 0.0000\n#&gt; ageChildren:step1 -1.02662 18.354630 -0.055933 0.9554\n#&gt; ageChildren:ramp1 7.06407 3.604192 1.959960 0.0513\n#&gt; ageChildren:step2 -35.82645 25.442751 -1.408120 0.1606\n#&gt; ageChildren:ramp2 -2.95530 4.260553 -0.693643 0.4887\n#&gt; ageChildren:step3 -29.49930 19.876247 -1.484148 0.1393\n#&gt; ageChildren:ramp3 0.62770 2.439516 0.257306 0.7972\n#&gt; ageChildren:sin12 4.22521 3.793256 1.113874 0.2666\n#&gt; ageChildren:cos12 36.54005 3.609352 10.123715 0.0000\n#&gt; ageChildren:sin6 -9.76953 3.404578 -2.869528 0.0045\n#&gt; ageChildren:cos6 -25.08251 3.370352 -7.442104 0.0000\n#&gt; ageChildren:sin4 13.68702 3.162997 4.327230 0.0000\n#&gt; ageChildren:cos4 14.66062 3.167797 4.628016 0.0000\n#&gt; \n#&gt; Correlation: \n#&gt; (Intr) agChld time step1 ramp1 step2 ramp2 step3 \n#&gt; ageChildren -0.105 \n#&gt; time -0.862 0.091 \n#&gt; step1 0.173 -0.018 -0.309 \n#&gt; ramp1 0.057 -0.006 -0.063 -0.763 \n#&gt; step2 -0.021 0.002 0.020 0.366 -0.711 \n#&gt; ramp2 -0.004 0.000 0.005 0.655 -0.831 0.306 \n#&gt; step3 -0.015 0.002 0.015 0.007 -0.031 0.300 -0.403 \n#&gt; ramp3 -0.016 0.002 0.016 0.008 -0.023 0.514 -0.520 0.649\n#&gt; sin12 -0.056 0.006 0.043 0.155 -0.247 0.317 0.074 0.209\n#&gt; cos12 -0.050 0.005 0.069 -0.188 0.137 -0.028 -0.155 0.065\n#&gt; sin6 -0.008 0.001 -0.006 0.034 0.018 -0.103 0.052 -0.126\n#&gt; cos6 -0.010 0.001 0.002 0.047 -0.026 -0.035 0.060 -0.071\n#&gt; sin4 -0.024 0.002 0.028 -0.033 -0.004 0.059 -0.040 0.066\n#&gt; cos4 -0.011 0.001 0.002 0.063 -0.078 0.095 0.024 0.069\n#&gt; ageChildren:time 0.091 -0.862 -0.105 0.033 0.007 -0.002 0.000 -0.002\n#&gt; ageChildren:step1 -0.018 0.173 0.033 -0.105 0.080 -0.039 -0.069 -0.001\n#&gt; ageChildren:ramp1 -0.006 0.057 0.007 0.080 -0.105 0.075 0.088 0.003\n#&gt; ageChildren:step2 0.002 -0.021 -0.002 -0.039 0.075 -0.105 -0.032 -0.032\n#&gt; ageChildren:ramp2 0.000 -0.004 0.000 -0.069 0.088 -0.032 -0.105 0.043\n#&gt; ageChildren:step3 0.002 -0.015 -0.002 -0.001 0.003 -0.032 0.043 -0.105\n#&gt; ageChildren:ramp3 0.002 -0.016 -0.002 -0.001 0.002 -0.054 0.055 -0.068\n#&gt; ageChildren:sin12 0.006 -0.056 -0.005 -0.016 0.026 -0.033 -0.008 -0.022\n#&gt; ageChildren:cos12 0.005 -0.050 -0.007 0.020 -0.014 0.003 0.016 -0.007\n#&gt; ageChildren:sin6 0.001 -0.008 0.001 -0.004 -0.002 0.011 -0.005 0.013\n#&gt; ageChildren:cos6 0.001 -0.010 0.000 -0.005 0.003 0.004 -0.006 0.007\n#&gt; ageChildren:sin4 0.002 -0.024 -0.003 0.003 0.000 -0.006 0.004 -0.007\n#&gt; ageChildren:cos4 0.001 -0.011 0.000 -0.007 0.008 -0.010 -0.002 -0.007\n#&gt; ramp3 sin12 cos12 sin6 cos6 sin4 cos4 agChl:\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 0.235 \n#&gt; cos12 0.057 -0.008 \n#&gt; sin6 -0.099 -0.036 -0.015 \n#&gt; cos6 -0.058 -0.011 -0.017 0.017 \n#&gt; sin4 0.074 0.025 0.014 -0.013 -0.006 \n#&gt; cos4 0.073 0.041 -0.007 -0.009 -0.004 0.009 \n#&gt; ageChildren:time -0.002 -0.005 -0.007 0.001 0.000 -0.003 0.000 \n#&gt; ageChildren:step1 -0.001 -0.016 0.020 -0.004 -0.005 0.003 -0.007 -0.309\n#&gt; ageChildren:ramp1 0.002 0.026 -0.014 -0.002 0.003 0.000 0.008 -0.063\n#&gt; ageChildren:step2 -0.054 -0.033 0.003 0.011 0.004 -0.006 -0.010 0.020\n#&gt; ageChildren:ramp2 0.055 -0.008 0.016 -0.005 -0.006 0.004 -0.002 0.005\n#&gt; ageChildren:step3 -0.068 -0.022 -0.007 0.013 0.007 -0.007 -0.007 0.015\n#&gt; ageChildren:ramp3 -0.105 -0.025 -0.006 0.010 0.006 -0.008 -0.008 0.016\n#&gt; ageChildren:sin12 -0.025 -0.105 0.001 0.004 0.001 -0.003 -0.004 0.043\n#&gt; ageChildren:cos12 -0.006 0.001 -0.105 0.002 0.002 -0.002 0.001 0.069\n#&gt; ageChildren:sin6 0.010 0.004 0.002 -0.105 -0.002 0.001 0.001 -0.006\n#&gt; ageChildren:cos6 0.006 0.001 0.002 -0.002 -0.105 0.001 0.000 0.002\n#&gt; ageChildren:sin4 -0.008 -0.003 -0.002 0.001 0.001 -0.105 -0.001 0.028\n#&gt; ageChildren:cos4 -0.008 -0.004 0.001 0.001 0.000 -0.001 -0.105 0.002\n#&gt; agChldrn:s1 agChldrn:r1 agChldrn:s2 agChldrn:r2 agChldrn:s3\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 \n#&gt; cos12 \n#&gt; sin6 \n#&gt; cos6 \n#&gt; sin4 \n#&gt; cos4 \n#&gt; ageChildren:time \n#&gt; ageChildren:step1 \n#&gt; ageChildren:ramp1 -0.763 \n#&gt; ageChildren:step2 0.366 -0.711 \n#&gt; ageChildren:ramp2 0.655 -0.831 0.306 \n#&gt; ageChildren:step3 0.007 -0.031 0.300 -0.403 \n#&gt; ageChildren:ramp3 0.008 -0.023 0.514 -0.520 0.649 \n#&gt; ageChildren:sin12 0.155 -0.247 0.317 0.074 0.209 \n#&gt; ageChildren:cos12 -0.188 0.137 -0.028 -0.155 0.065 \n#&gt; ageChildren:sin6 0.034 0.018 -0.103 0.052 -0.126 \n#&gt; ageChildren:cos6 0.047 -0.026 -0.035 0.060 -0.071 \n#&gt; ageChildren:sin4 -0.033 -0.004 0.059 -0.040 0.066 \n#&gt; ageChildren:cos4 0.063 -0.078 0.095 0.024 0.069 \n#&gt; agChldrn:r3 agChldrn:s12 agChldrn:c12 agChldrn:s6 agChldrn:c6\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 \n#&gt; cos12 \n#&gt; sin6 \n#&gt; cos6 \n#&gt; sin4 \n#&gt; cos4 \n#&gt; ageChildren:time \n#&gt; ageChildren:step1 \n#&gt; ageChildren:ramp1 \n#&gt; ageChildren:step2 \n#&gt; ageChildren:ramp2 \n#&gt; ageChildren:step3 \n#&gt; ageChildren:ramp3 \n#&gt; ageChildren:sin12 0.235 \n#&gt; ageChildren:cos12 0.057 -0.008 \n#&gt; ageChildren:sin6 -0.099 -0.036 -0.015 \n#&gt; ageChildren:cos6 -0.058 -0.011 -0.017 0.017 \n#&gt; ageChildren:sin4 0.074 0.025 0.014 -0.013 -0.006 \n#&gt; ageChildren:cos4 0.073 0.041 -0.007 -0.009 -0.004 \n#&gt; agChldrn:s4\n#&gt; ageChildren \n#&gt; time \n#&gt; step1 \n#&gt; ramp1 \n#&gt; step2 \n#&gt; ramp2 \n#&gt; step3 \n#&gt; ramp3 \n#&gt; sin12 \n#&gt; cos12 \n#&gt; sin6 \n#&gt; cos6 \n#&gt; sin4 \n#&gt; cos4 \n#&gt; ageChildren:time \n#&gt; ageChildren:step1 \n#&gt; ageChildren:ramp1 \n#&gt; ageChildren:step2 \n#&gt; ageChildren:ramp2 \n#&gt; ageChildren:step3 \n#&gt; ageChildren:ramp3 \n#&gt; ageChildren:sin12 \n#&gt; ageChildren:cos12 \n#&gt; ageChildren:sin6 \n#&gt; ageChildren:cos6 \n#&gt; ageChildren:sin4 \n#&gt; ageChildren:cos4 0.009 \n#&gt; \n#&gt; Standardized residuals:\n#&gt; Min Q1 Med Q3 Max \n#&gt; -5.25291094 -0.42240774 0.04331099 0.45224365 3.26323939 \n#&gt; \n#&gt; Residual standard error: 2.608572 \n#&gt; Degrees of freedom: 240 total; 212 residual\n</code></pre>\n<p><sup>Created on 2026-08-29 with <a href=\"https://reprex.tidyverse.org\" rel=\"nofollow noreferrer\">reprex v2.1.1</a></sup></p>\n", "answer_id": 676996, "answer_text": "Rather than fitting separate models, you can handle both age groups in a single gls() model with age interactions. This has two advantages over separate auto.arima() models: you get formal tests of whether intervention effects differ between groups via the interaction terms, and you can account for the fact that the two series have very different variances.\n\n\n\n\nage * (time + step1 + ramp1 + ...) gives each group its own intercept, pre-intervention slope, and intervention effects, plus tests of whether they differ. Then, corAR1(form = ~ 1 | age) fits AR(1) autocorrelation within each group and varIdent(form = ~ 1 | age) allows different residual variances per group, which matters here since children's prevalence is an order of magnitude larger.\n\n\n\n\nlibrary(nlme)\nlibrary(dplyr)\n\ninterventions <- as.Date(c(\"2021-09-13\", \"2022-06-02\", \"2023-06-29\"))\n\nd_its <- d |>\n arrange(age, month) |>\n mutate(.by = age,\n time = row_number() - 1,\n step1 = as.numeric(month >= interventions[1]),\n ramp1 = ifelse(step1 == 1, cumsum(step1) - 1, 0),\n step2 = as.numeric(month >= interventions[2]),\n ramp2 = ifelse(step2 == 1, cumsum(step2) - 1, 0),\n step3 = as.numeric(month >= interventions[3]),\n ramp3 = ifelse(step3 == 1, cumsum(step3) - 1, 0),\n sin12 = sin(2 * pi * time / 12),\n cos12 = cos(2 * pi * time / 12),\n sin6 = sin(2 * pi * time / 6),\n cos6 = cos(2 * pi * time / 6),\n sin4 = sin(2 * pi * time / 4),\n cos4 = cos(2 * pi * time / 4)\n ) |>\n mutate(age = factor(age))\n\nfit <- gls(\n prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 +\n sin12 + cos12 + sin6 + cos6 + sin4 + cos4),\n data = d_its,\n correlation = corAR1(form = ~ 1 | age),\n weights = varIdent(form = ~ 1 | age)\n)\n\n\n\n\n\nThe Fourier terms (sin12, cos12, etc.) handle the recurring seasonal pattern, which is more stable than trying to absorb it through ARMA error terms (see https://otexts.com/fpp3/dhr.html (https://otexts.com/fpp3/dhr.html)).\n\n\n\n\nThe reference level is Adults, so coefficients are interpreted as:\n\n\n\n\n\ntime: pre-intervention slope for adults (prevalence per month)\n\n\n\n\nageChildren:time: additional slope for children;\n\n\n\n\n\nThe same logic applies for all ramp and step terms.\n\n\n\n\ncoef(fit) |>\n (\\(e) data.frame(\n Segment = c(\"Pre\", \"Post-1\", \"Post-2\", \"Post-3\"),\n Adults = round(cumsum(c(e[\"time\"],\n e[\"ramp1\"],\n e[\"ramp2\"],\n e[\"ramp3\"])), 3),\n Children = round(cumsum(c(e[\"time\"] + e[\"ageChildren:time\"],\n e[\"ramp1\"] + e[\"ageChildren:ramp1\"],\n e[\"ramp2\"] + e[\"ageChildren:ramp2\"],\n e[\"ramp3\"] + e[\"ageChildren:ramp3\"])), 3)\n))()\n\n#> Segment Adults Children\n#> time Pre 0.152 1.445\n#> ramp1 Post-1 0.919 9.276\n#> ramp2 Post-2 1.265 6.667\n#> ramp3 Post-3 2.387 8.418\n\n\n\n\n\npar(mfrow = c(1, 2))\nacf(residuals(fit)[d_its$age == \"Adults\"], main = \"Adults\")\nacf(residuals(fit)[d_its$age == \"Children\"], main = \"Children\")\ndev.off()\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/2fnDCjiM.png]\n\n\n\n\nsummary(fit)\n\n#> Generalized least squares fit by REML\n#> Model: prevalence ~ age * (time + step1 + ramp1 + step2 + ramp2 + step3 + ramp3 + sin12 + cos12 + sin6 + cos6 + sin4 + cos4) \n#> Data: d_its \n#> AIC BIC logLik\n#> 1665.172 1769.226 -801.5858\n#> \n#> Correlation Structure: AR(1)\n#> Formula: ~1 | age \n#> Parameter estimate(s):\n#> Phi \n#> 0.1231768 \n#> Variance function:\n#> Structure: Different standard deviations per stratum\n#> Formula: ~1 | age \n#> Parameter estimates:\n#> Adults Children \n#> 1.000000 9.435418 \n#> \n#> Coefficients:\n#> Value Std.Error t-value p-value\n#> (Intercept) 10.25450 0.701853 14.610597 0.0000\n#> ageChildren 177.16318 6.659369 26.603599 0.0000\n#> time 0.15162 0.017799 8.518225 0.0000\n#> step1 1.83019 1.934456 0.946100 0.3452\n#> ramp1 0.76689 0.379858 2.018892 0.0448\n#> step2 -0.98456 2.681497 -0.367167 0.7139\n#> ramp2 0.34620 0.449034 0.770992 0.4416\n#> step3 -4.38832 2.094825 -2.094838 0.0374\n#> ramp3 1.12257 0.257109 4.366133 0.0000\n#> sin12 0.01845 0.399784 0.046145 0.9632\n#> cos12 1.16269 0.380402 3.056467 0.0025\n#> sin6 -0.70555 0.358820 -1.966309 0.0506\n#> cos6 -0.97079 0.355213 -2.732980 0.0068\n#> sin4 0.78337 0.333359 2.349941 0.0197\n#> cos4 0.05479 0.333865 0.164117 0.8698\n#> ageChildren:time 1.29381 0.168883 7.661002 0.0000\n#> ageChildren:step1 -1.02662 18.354630 -0.055933 0.9554\n#> ageChildren:ramp1 7.06407 3.604192 1.959960 0.0513\n#> ageChildren:step2 -35.82645 25.442751 -1.408120 0.1606\n#> ageChildren:ramp2 -2.95530 4.260553 -0.693643 0.4887\n#> ageChildren:step3 -29.49930 19.876247 -1.484148 0.1393\n#> ageChildren:ramp3 0.62770 2.439516 0.257306 0.7972\n#> ageChildren:sin12 4.22521 3.793256 1.113874 0.2666\n#> ageChildren:cos12 36.54005 3.609352 10.123715 0.0000\n#> ageChildren:sin6 -9.76953 3.404578 -2.869528 0.0045\n#> ageChildren:cos6 -25.08251 3.370352 -7.442104 0.0000\n#> ageChildren:sin4 13.68702 3.162997 4.327230 0.0000\n#> ageChildren:cos4 14.66062 3.167797 4.628016 0.0000\n#> \n#> Correlation: \n#> (Intr) agChld time step1 ramp1 step2 ramp2 step3 \n#> ageChildren -0.105 \n#> time -0.862 0.091 \n#> step1 0.173 -0.018 -0.309 \n#> ramp1 0.057 -0.006 -0.063 -0.763 \n#> step2 -0.021 0.002 0.020 0.366 -0.711 \n#> ramp2 -0.004 0.000 0.005 0.655 -0.831 0.306 \n#> step3 -0.015 0.002 0.015 0.007 -0.031 0.300 -0.403 \n#> ramp3 -0.016 0.002 0.016 0.008 -0.023 0.514 -0.520 0.649\n#> sin12 -0.056 0.006 0.043 0.155 -0.247 0.317 0.074 0.209\n#> cos12 -0.050 0.005 0.069 -0.188 0.137 -0.028 -0.155 0.065\n#> sin6 -0.008 0.001 -0.006 0.034 0.018 -0.103 0.052 -0.126\n#> cos6 -0.010 0.001 0.002 0.047 -0.026 -0.035 0.060 -0.071\n#> sin4 -0.024 0.002 0.028 -0.033 -0.004 0.059 -0.040 0.066\n#> cos4 -0.011 0.001 0.002 0.063 -0.078 0.095 0.024 0.069\n#> ageChildren:time 0.091 -0.862 -0.105 0.033 0.007 -0.002 0.000 -0.002\n#> ageChildren:step1 -0.018 0.173 0.033 -0.105 0.080 -0.039 -0.069 -0.001\n#> ageChildren:ramp1 -0.006 0.057 0.007 0.080 -0.105 0.075 0.088 0.003\n#> ageChildren:step2 0.002 -0.021 -0.002 -0.039 0.075 -0.105 -0.032 -0.032\n#> ageChildren:ramp2 0.000 -0.004 0.000 -0.069 0.088 -0.032 -0.105 0.043\n#> ageChildren:step3 0.002 -0.015 -0.002 -0.001 0.003 -0.032 0.043 -0.105\n#> ageChildren:ramp3 0.002 -0.016 -0.002 -0.001 0.002 -0.054 0.055 -0.068\n#> ageChildren:sin12 0.006 -0.056 -0.005 -0.016 0.026 -0.033 -0.008 -0.022\n#> ageChildren:cos12 0.005 -0.050 -0.007 0.020 -0.014 0.003 0.016 -0.007\n#> ageChildren:sin6 0.001 -0.008 0.001 -0.004 -0.002 0.011 -0.005 0.013\n#> ageChildren:cos6 0.001 -0.010 0.000 -0.005 0.003 0.004 -0.006 0.007\n#> ageChildren:sin4 0.002 -0.024 -0.003 0.003 0.000 -0.006 0.004 -0.007\n#> ageChildren:cos4 0.001 -0.011 0.000 -0.007 0.008 -0.010 -0.002 -0.007\n#> ramp3 sin12 cos12 sin6 cos6 sin4 cos4 agChl:\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 0.235 \n#> cos12 0.057 -0.008 \n#> sin6 -0.099 -0.036 -0.015 \n#> cos6 -0.058 -0.011 -0.017 0.017 \n#> sin4 0.074 0.025 0.014 -0.013 -0.006 \n#> cos4 0.073 0.041 -0.007 -0.009 -0.004 0.009 \n#> ageChildren:time -0.002 -0.005 -0.007 0.001 0.000 -0.003 0.000 \n#> ageChildren:step1 -0.001 -0.016 0.020 -0.004 -0.005 0.003 -0.007 -0.309\n#> ageChildren:ramp1 0.002 0.026 -0.014 -0.002 0.003 0.000 0.008 -0.063\n#> ageChildren:step2 -0.054 -0.033 0.003 0.011 0.004 -0.006 -0.010 0.020\n#> ageChildren:ramp2 0.055 -0.008 0.016 -0.005 -0.006 0.004 -0.002 0.005\n#> ageChildren:step3 -0.068 -0.022 -0.007 0.013 0.007 -0.007 -0.007 0.015\n#> ageChildren:ramp3 -0.105 -0.025 -0.006 0.010 0.006 -0.008 -0.008 0.016\n#> ageChildren:sin12 -0.025 -0.105 0.001 0.004 0.001 -0.003 -0.004 0.043\n#> ageChildren:cos12 -0.006 0.001 -0.105 0.002 0.002 -0.002 0.001 0.069\n#> ageChildren:sin6 0.010 0.004 0.002 -0.105 -0.002 0.001 0.001 -0.006\n#> ageChildren:cos6 0.006 0.001 0.002 -0.002 -0.105 0.001 0.000 0.002\n#> ageChildren:sin4 -0.008 -0.003 -0.002 0.001 0.001 -0.105 -0.001 0.028\n#> ageChildren:cos4 -0.008 -0.004 0.001 0.001 0.000 -0.001 -0.105 0.002\n#> agChldrn:s1 agChldrn:r1 agChldrn:s2 agChldrn:r2 agChldrn:s3\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 -0.763 \n#> ageChildren:step2 0.366 -0.711 \n#> ageChildren:ramp2 0.655 -0.831 0.306 \n#> ageChildren:step3 0.007 -0.031 0.300 -0.403 \n#> ageChildren:ramp3 0.008 -0.023 0.514 -0.520 0.649 \n#> ageChildren:sin12 0.155 -0.247 0.317 0.074 0.209 \n#> ageChildren:cos12 -0.188 0.137 -0.028 -0.155 0.065 \n#> ageChildren:sin6 0.034 0.018 -0.103 0.052 -0.126 \n#> ageChildren:cos6 0.047 -0.026 -0.035 0.060 -0.071 \n#> ageChildren:sin4 -0.033 -0.004 0.059 -0.040 0.066 \n#> ageChildren:cos4 0.063 -0.078 0.095 0.024 0.069 \n#> agChldrn:r3 agChldrn:s12 agChldrn:c12 agChldrn:s6 agChldrn:c6\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 \n#> ageChildren:step2 \n#> ageChildren:ramp2 \n#> ageChildren:step3 \n#> ageChildren:ramp3 \n#> ageChildren:sin12 0.235 \n#> ageChildren:cos12 0.057 -0.008 \n#> ageChildren:sin6 -0.099 -0.036 -0.015 \n#> ageChildren:cos6 -0.058 -0.011 -0.017 0.017 \n#> ageChildren:sin4 0.074 0.025 0.014 -0.013 -0.006 \n#> ageChildren:cos4 0.073 0.041 -0.007 -0.009 -0.004 \n#> agChldrn:s4\n#> ageChildren \n#> time \n#> step1 \n#> ramp1 \n#> step2 \n#> ramp2 \n#> step3 \n#> ramp3 \n#> sin12 \n#> cos12 \n#> sin6 \n#> cos6 \n#> sin4 \n#> cos4 \n#> ageChildren:time \n#> ageChildren:step1 \n#> ageChildren:ramp1 \n#> ageChildren:step2 \n#> ageChildren:ramp2 \n#> ageChildren:step3 \n#> ageChildren:ramp3 \n#> ageChildren:sin12 \n#> ageChildren:cos12 \n#> ageChildren:sin6 \n#> ageChildren:cos6 \n#> ageChildren:sin4 \n#> ageChildren:cos4 0.009 \n#> \n#> Standardized residuals:\n#> Min Q1 Med Q3 Max \n#> -5.25291094 -0.42240774 0.04331099 0.45224365 3.26323939 \n#> \n#> Residual standard error: 2.608572 \n#> Degrees of freedom: 240 total; 212 residual\n\n\n\n\n\nCreated on 2026-08-29 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/676996", "author": "M--", "author_url": "https://stats.stackexchange.com/users/154449/m", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-29T05:35:19+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 676979, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "M--", "profile_url": "https://stats.stackexchange.com/users/154449/m", "user_type": "registered"}, "created_at": "2026-08-29T05:35:19+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "4F437721-3A00-4B4D-BA06-A2F50516CC59", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/4F437721-3A00-4B4D-BA06-A2F50516CC59/view-source"}], "score": 3, "updated_at": "2026-08-29T05:35:19+00:00"}], "domain": "statistics", "external_links": ["https://doi.org/10.1093/ije/dyaa148", "https://doi.org/10.1186/s12874-021-01235-8", "https://doi.org/10.1186/s12889-017-4998-9", "https://doi.org/10.3111/13696998.2011.626097", "https://i.sstatic.net/2fnDCjiM.png", "https://i.sstatic.net/4a0pdydL.png", "https://i.sstatic.net/pzs11NTf.png", "https://otexts.com/fpp3/dhr.html", "https://reprex.tidyverse.org", "https://stat.ethz.ch/R-manual/R-devel/library/nlme/html/gls.html"], "medical_sensitive": true, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:03.428408+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/774052c18cd9e8fa951e893347bfa3c1a85e743fc46ec4667572002cadb10cbf_1790825224163423600_0.json", "raw_sha256": "fe4dd06d3de6c0b1bb33ba88aee0ed4284118e01f76a58dcdce220a4946329b2", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "Thomas", "question_author_url": "https://stats.stackexchange.com/users/263046/thomas", "question_author_user_type": "registered", "question_created_at": "2026-08-27T20:48:18+00:00", "question_html": "<h2>Background</h2>\n<ul>\n<li>Data: time series of the monthly prevalence of patients receiving a given medication by age group (children or adults) from January 2016 to December 2026</li>\n<li>Interventions: three successive regulatory interventions implemented on September 2021, June 2022, and June 2023 to facilitate prescription of the medication (dotted lines on the figure below)</li>\n<li>Aim: to estimate pre-intervention slope, post-intervention 1 slope, post-intervention 2 slope, and post-intervention 3 slope depending on age group to assess the impact of the interventions (i.e., interrupted time series analysis, ITS)</li>\n</ul>\n<pre class=\"lang-r prettyprint-override\"><code>month &lt;- seq(\n from = as.Date(&quot;2016-01-01&quot;),\n to = as.Date(&quot;2025-12-31&quot;),\n by = &quot;month&quot;\n)\nmonth &lt;- rep(month, each = 2)\nage &lt;- rep(c(&quot;Children&quot;, &quot;Adults&quot;), 120)\nprevalence &lt;- c(\n 214.1, 11.3, 194.9, 11.1, 220.3, 11.8, 200.7, 11.7, 213.5, \n 11.7, 197.6, 11.5, 128.2, 10.3, 138.6, 9.9, 215, 12.1, 201.9, \n 11.9, 223.8, 12.2, 204.9, 12.4, 234.1, 12.7, 202, 11.9, 247, \n 13.6, 209.8, 13, 236.7, 13.4, 216.9, 13.1, 145.1, 12, 144.3, \n 11, 235.1, 13.7, 227.5, 13.9, 242.5, 13.9, 229.5, 13.8, 255.3, \n 14.5, 226.3, 13.6, 260.8, 15.2, 229.7, 14.2, 245.5, 14.7, 232.6, \n 14.4, 158.8, 13.4, 165, 12.5, 244.3, 14.8, 249.4, 15.7, 259.4, \n 15.5, 244, 15.3, 275.7, 16.2, 240.7, 14.9, 274.4, 16.2, 256.8, \n 16.3, 274.3, 16.4, 240.3, 15.5, 178.2, 15.5, 180.3, 13.6, 264, \n 16.3, 271.3, 17.4, 277.8, 16.9, 261.5, 16.8, 296.9, 17.8, 265.8, \n 17.2, 270.4, 17.9, 218.8, 16, 214.7, 16, 221.8, 16.7, 183.6, \n 16.8, 185.4, 14.9, 273.6, 18.7, 276.7, 19.3, 285, 19.4, 282.8, \n 19.9, 308.3, 20.2, 279.2, 19.3, 331.1, 22, 289.3, 21.2, 303, \n 20.9, 307.5, 21.8, 221.2, 20.9, 215.4, 18.9, 324, 23.4, 323.3, \n 24.3, 328.3, 24.7, 326.5, 25.8, 349.2, 26.1, 319.1, 25.5, 379.3, \n 29, 341.7, 28.3, 365.1, 28.6, 351.7, 30.1, 253.7, 28.6, 266.9, \n 27, 375, 33.4, 373.5, 34.4, 385.8, 35.5, 368.1, 36, 413.7, 38.8, \n 376, 37.4, 440.1, 42.5, 390.3, 40.8, 409.5, 42.6, 402, 44.9, \n 297.9, 43.4, 297.1, 40.2, 430.9, 49.3, 433.4, 51.2, 454.1, 53.1, \n 441.4, 53.4, 472.9, 57, 455.8, 57, 496.3, 62.6, 475, 63.1, 483.4, \n 63.3, 466, 65.1, 367.3, 66.2, 368.4, 58.6, 499.4, 70.8, 528.3, \n 76.1, 533.8, 76, 525.6, 77.2, 588.3, 84.8, 532.4, 81.1, 599.6, \n 90.9, 580.3, 90.8, 601.5, 93.8, 560.6, 95.1, 455.2, 96.9, 440.6, \n 83.7, 629.2, 107.7, 655.7, 112.8, 653.8, 113.2, 674.9, 118.7\n)\nd &lt;- data.frame(month, age, prevalence)\n\npar(mfrow = c(1, 2))\nplot(prevalence ~ month, d, type = &quot;l&quot;, main = &quot;Children&quot;, subset = age == &quot;Children&quot;)\nplot(prevalence ~ month, d, type = &quot;l&quot;, main = &quot;Adults&quot;, subset = age == &quot;Adults&quot;)\ndev.off()\n</code></pre>\n<p><a href=\"https://i.sstatic.net/4a0pdydL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/4a0pdydL.png\" alt=\"time series\" /></a></p>\n<h2>What I did</h2>\n<p>I started with children.</p>\n<p>I constructed the ITS variables for the 3 interventions (<code>step1</code>, <code>ramp1</code>, <code>step2</code>, <code>ramp2</code>, <code>step3</code>, <code>ramp3</code>) following <a href=\"https://doi.org/10.1186/s12874-021-01235-8\" rel=\"nofollow noreferrer\">Schaffer et al.</a> and <a href=\"https://doi.org/10.1093/ije/dyaa148\" rel=\"nofollow noreferrer\">Xiao et al.</a></p>\n<pre class=\"lang-r prettyprint-override\"><code>d2 &lt;- subset(d, age == &quot;Children&quot;)\nd2<span class=\"math-container\">$prevalence &lt;- ts(d2$</span>prevalence, start = 2016, frequency = 12)\n\ninterventions &lt;- as.Date(c(&quot;2021-09-13&quot;, &quot;2022-06-02&quot;, &quot;2023-06-29&quot;))\n\nstep1 &lt;- as.numeric(d2$month &gt;= interventions[1])\nramp1 &lt;- ifelse(step1 == 1, cumsum(step1) - 1, 0)\n\nstep2 &lt;- as.numeric(d2$month &gt;= interventions[2])\nramp2 &lt;- ifelse(step2 == 1, cumsum(step2) - 1, 0)\n\nstep3 &lt;- as.numeric(d2$month &gt;= interventions[3])\nramp3 &lt;- ifelse(step3 == 1, cumsum(step3) - 1, 0)\n\ntime &lt;- seq(from = 0, along.with = d2$month)\n\nxreg &lt;- cbind(time, step1, ramp1, step2, ramp2, step3, ramp3)\n\ncbind(d2, xreg)\n# month age prevalence time step1 ramp1 step2 ramp2 step3 ramp3\n# 1 2016-01-01 Children 214.1 0 0 0 0 0 0 0\n# 3 2016-02-01 Children 194.9 1 0 0 0 0 0 0\n# 5 2016-03-01 Children 220.3 2 0 0 0 0 0 0\n# 7 2016-04-01 Children 200.7 3 0 0 0 0 0 0\n# 9 2016-05-01 Children 213.5 4 0 0 0 0 0 0\n# 11 2016-06-01 Children 197.6 5 0 0 0 0 0 0\n# 13 2016-07-01 Children 128.2 6 0 0 0 0 0 0\n# 15 2016-08-01 Children 138.6 7 0 0 0 0 0 0\n# 17 2016-09-01 Children 215.0 8 0 0 0 0 0 0\n# 19 2016-10-01 Children 201.9 9 0 0 0 0 0 0\n# 21 2016-11-01 Children 223.8 10 0 0 0 0 0 0\n# 23 2016-12-01 Children 204.9 11 0 0 0 0 0 0\n# 25 2017-01-01 Children 234.1 12 0 0 0 0 0 0\n# 27 2017-02-01 Children 202.0 13 0 0 0 0 0 0\n# 29 2017-03-01 Children 247.0 14 0 0 0 0 0 0\n# 31 2017-04-01 Children 209.8 15 0 0 0 0 0 0\n# 33 2017-05-01 Children 236.7 16 0 0 0 0 0 0\n# 35 2017-06-01 Children 216.9 17 0 0 0 0 0 0\n# 37 2017-07-01 Children 145.1 18 0 0 0 0 0 0\n# 39 2017-08-01 Children 144.3 19 0 0 0 0 0 0\n# 41 2017-09-01 Children 235.1 20 0 0 0 0 0 0\n# 43 2017-10-01 Children 227.5 21 0 0 0 0 0 0\n# 45 2017-11-01 Children 242.5 22 0 0 0 0 0 0\n# 47 2017-12-01 Children 229.5 23 0 0 0 0 0 0\n# 49 2018-01-01 Children 255.3 24 0 0 0 0 0 0\n# 51 2018-02-01 Children 226.3 25 0 0 0 0 0 0\n# 53 2018-03-01 Children 260.8 26 0 0 0 0 0 0\n# 55 2018-04-01 Children 229.7 27 0 0 0 0 0 0\n# 57 2018-05-01 Children 245.5 28 0 0 0 0 0 0\n# 59 2018-06-01 Children 232.6 29 0 0 0 0 0 0\n# 61 2018-07-01 Children 158.8 30 0 0 0 0 0 0\n# 63 2018-08-01 Children 165.0 31 0 0 0 0 0 0\n# 65 2018-09-01 Children 244.3 32 0 0 0 0 0 0\n# 67 2018-10-01 Children 249.4 33 0 0 0 0 0 0\n# 69 2018-11-01 Children 259.4 34 0 0 0 0 0 0\n# 71 2018-12-01 Children 244.0 35 0 0 0 0 0 0\n# 73 2019-01-01 Children 275.7 36 0 0 0 0 0 0\n# 75 2019-02-01 Children 240.7 37 0 0 0 0 0 0\n# 77 2019-03-01 Children 274.4 38 0 0 0 0 0 0\n# 79 2019-04-01 Children 256.8 39 0 0 0 0 0 0\n# 81 2019-05-01 Children 274.3 40 0 0 0 0 0 0\n# 83 2019-06-01 Children 240.3 41 0 0 0 0 0 0\n# 85 2019-07-01 Children 178.2 42 0 0 0 0 0 0\n# 87 2019-08-01 Children 180.3 43 0 0 0 0 0 0\n# 89 2019-09-01 Children 264.0 44 0 0 0 0 0 0\n# 91 2019-10-01 Children 271.3 45 0 0 0 0 0 0\n# 93 2019-11-01 Children 277.8 46 0 0 0 0 0 0\n# 95 2019-12-01 Children 261.5 47 0 0 0 0 0 0\n# 97 2020-01-01 Children 296.9 48 0 0 0 0 0 0\n# 99 2020-02-01 Children 265.8 49 0 0 0 0 0 0\n# 101 2020-03-01 Children 270.4 50 0 0 0 0 0 0\n# 103 2020-04-01 Children 218.8 51 0 0 0 0 0 0\n# 105 2020-05-01 Children 214.7 52 0 0 0 0 0 0\n# 107 2020-06-01 Children 221.8 53 0 0 0 0 0 0\n# 109 2020-07-01 Children 183.6 54 0 0 0 0 0 0\n# 111 2020-08-01 Children 185.4 55 0 0 0 0 0 0\n# 113 2020-09-01 Children 273.6 56 0 0 0 0 0 0\n# 115 2020-10-01 Children 276.7 57 0 0 0 0 0 0\n# 117 2020-11-01 Children 285.0 58 0 0 0 0 0 0\n# 119 2020-12-01 Children 282.8 59 0 0 0 0 0 0\n# 121 2021-01-01 Children 308.3 60 0 0 0 0 0 0\n# 123 2021-02-01 Children 279.2 61 0 0 0 0 0 0\n# 125 2021-03-01 Children 331.1 62 0 0 0 0 0 0\n# 127 2021-04-01 Children 289.3 63 0 0 0 0 0 0\n# 129 2021-05-01 Children 303.0 64 0 0 0 0 0 0\n# 131 2021-06-01 Children 307.5 65 0 0 0 0 0 0\n# 133 2021-07-01 Children 221.2 66 0 0 0 0 0 0\n# 135 2021-08-01 Children 215.4 67 0 0 0 0 0 0\n# 137 2021-09-01 Children 324.0 68 0 0 0 0 0 0\n# 139 2021-10-01 Children 323.3 69 1 0 0 0 0 0\n# 141 2021-11-01 Children 328.3 70 1 1 0 0 0 0\n# 143 2021-12-01 Children 326.5 71 1 2 0 0 0 0\n# 145 2022-01-01 Children 349.2 72 1 3 0 0 0 0\n# 147 2022-02-01 Children 319.1 73 1 4 0 0 0 0\n# 149 2022-03-01 Children 379.3 74 1 5 0 0 0 0\n# 151 2022-04-01 Children 341.7 75 1 6 0 0 0 0\n# 153 2022-05-01 Children 365.1 76 1 7 0 0 0 0\n# 155 2022-06-01 Children 351.7 77 1 8 0 0 0 0\n# 157 2022-07-01 Children 253.7 78 1 9 1 0 0 0\n# 159 2022-08-01 Children 266.9 79 1 10 1 1 0 0\n# 161 2022-09-01 Children 375.0 80 1 11 1 2 0 0\n# 163 2022-10-01 Children 373.5 81 1 12 1 3 0 0\n# 165 2022-11-01 Children 385.8 82 1 13 1 4 0 0\n# 167 2022-12-01 Children 368.1 83 1 14 1 5 0 0\n# 169 2023-01-01 Children 413.7 84 1 15 1 6 0 0\n# 171 2023-02-01 Children 376.0 85 1 16 1 7 0 0\n# 173 2023-03-01 Children 440.1 86 1 17 1 8 0 0\n# 175 2023-04-01 Children 390.3 87 1 18 1 9 0 0\n# 177 2023-05-01 Children 409.5 88 1 19 1 10 0 0\n# 179 2023-06-01 Children 402.0 89 1 20 1 11 0 0\n# 181 2023-07-01 Children 297.9 90 1 21 1 12 1 0\n# 183 2023-08-01 Children 297.1 91 1 22 1 13 1 1\n# 185 2023-09-01 Children 430.9 92 1 23 1 14 1 2\n# 187 2023-10-01 Children 433.4 93 1 24 1 15 1 3\n# 189 2023-11-01 Children 454.1 94 1 25 1 16 1 4\n# 191 2023-12-01 Children 441.4 95 1 26 1 17 1 5\n# 193 2024-01-01 Children 472.9 96 1 27 1 18 1 6\n# 195 2024-02-01 Children 455.8 97 1 28 1 19 1 7\n# 197 2024-03-01 Children 496.3 98 1 29 1 20 1 8\n# 199 2024-04-01 Children 475.0 99 1 30 1 21 1 9\n# 201 2024-05-01 Children 483.4 100 1 31 1 22 1 10\n# 203 2024-06-01 Children 466.0 101 1 32 1 23 1 11\n# 205 2024-07-01 Children 367.3 102 1 33 1 24 1 12\n# 207 2024-08-01 Children 368.4 103 1 34 1 25 1 13\n# 209 2024-09-01 Children 499.4 104 1 35 1 26 1 14\n# 211 2024-10-01 Children 528.3 105 1 36 1 27 1 15\n# 213 2024-11-01 Children 533.8 106 1 37 1 28 1 16\n# 215 2024-12-01 Children 525.6 107 1 38 1 29 1 17\n# 217 2025-01-01 Children 588.3 108 1 39 1 30 1 18\n# 219 2025-02-01 Children 532.4 109 1 40 1 31 1 19\n# 221 2025-03-01 Children 599.6 110 1 41 1 32 1 20\n# 223 2025-04-01 Children 580.3 111 1 42 1 33 1 21\n# 225 2025-05-01 Children 601.5 112 1 43 1 34 1 22\n# 227 2025-06-01 Children 560.6 113 1 44 1 35 1 23\n# 229 2025-07-01 Children 455.2 114 1 45 1 36 1 24\n# 231 2025-08-01 Children 440.6 115 1 46 1 37 1 25\n# 233 2025-09-01 Children 629.2 116 1 47 1 38 1 26\n# 235 2025-10-01 Children 655.7 117 1 48 1 39 1 27\n# 237 2025-11-01 Children 653.8 118 1 49 1 40 1 28\n# 239 2025-12-01 Children 674.9 119 1 50 1 41 1 29\n</code></pre>\n<p>According to <a href=\"https://stats.stackexchange.com/q/665216/\">this thread</a>, I included the ITS variables for the 3 interventions in a single model. I used <code>forecast::auto.arima()</code> to select (p, q) and (P, Q) parameters automatically.</p>\n<p>According to <a href=\"https://doi.org/10.1186/s12874-021-01235-8\" rel=\"nofollow noreferrer\">Schaffer et al.</a>, I included a <code>time</code> variable and set <span class=\"math-container\">$d = 0$</span> and <span class=\"math-container\">$D = 0$</span> (but I am not sure that I need both <span class=\"math-container\">$d = 0$</span> and <span class=\"math-container\">$D = 0$</span>): (emphasis mine)</p>\n<blockquote>\n<p>In ITS analysis, ARIMA forecasts <span class=\"math-container\">$Y_t$</span> in the absence of the intervention (the “counterfactual”) and determines how the observed diverges from this forecast. Unlike segmented regression, including time or seasonal dummy variables in the ARIMA model is not necessary, as ARIMA can eliminate trends and seasonality through differencing. <em>If the trend is eliminated via differencing then the pre- and post-intervention trends cannot be estimated from the model. However, if estimation of the pre- and/or post-intervention slope is desired, this can be accommodated by including time as a covariate and incorporating AR and MA terms to address autocorrelation (e.g. ARMA models)</em> [<a href=\"https://doi.org/10.1186/s12889-017-4998-9\" rel=\"nofollow noreferrer\">21</a>, <a href=\"https://doi.org/10.3111/13696998.2011.626097\" rel=\"nofollow noreferrer\">22</a>].</p>\n</blockquote>\n<pre class=\"lang-r prettyprint-override\"><code>fit &lt;- forecast::auto.arima(\n d2$prevalence,\n d = 0,\n D = 0,\n stepwise = FALSE,\n trace = TRUE,\n approximation = FALSE,\n xreg = xreg\n)\n# \n# Regression with ARIMA(0,0,0) errors : 1422.701\n# Regression with ARIMA(0,0,0) errors : 1256.821\n# Regression with ARIMA(0,0,0)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,0)(0,0,1)[12] errors : 1186.586\n# Regression with ARIMA(0,0,0)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,0)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,2)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,1) errors : 1348.712\n# Regression with ARIMA(0,0,1) errors : 1237.018\n# Regression with ARIMA(0,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,1)(0,0,1)[12] errors : 1167.011\n# Regression with ARIMA(0,0,1)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,1)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,1)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,1)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,2)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,1)(2,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,2) errors : 1304.633\n# Regression with ARIMA(0,0,2) errors : 1235.236\n# Regression with ARIMA(0,0,2)(0,0,1)[12] errors : 1226.35\n# Regression with ARIMA(0,0,2)(0,0,1)[12] errors : 1164.06\n# Regression with ARIMA(0,0,2)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,2)(0,0,2)[12] errors : 1122.153\n# ARIMA(0,0,2)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,2)(1,0,0)[12] errors : Inf\n# ARIMA(0,0,2)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,2)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,2)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,2)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,2)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,3) errors : 1301.979\n# Regression with ARIMA(0,0,3) errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,1)[12] errors : 1166.444\n# Regression with ARIMA(0,0,3)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,3)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,3)(1,0,0)[12] errors : Inf\n# ARIMA(0,0,3)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,3)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,3)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,3)(2,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,4) errors : Inf\n# Regression with ARIMA(0,0,4) errors : Inf\n# Regression with ARIMA(0,0,4)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,4)(0,0,1)[12] errors : 1167.795\n# ARIMA(0,0,4)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,4)(1,0,0)[12] errors : Inf\n# Regression with ARIMA(0,0,5) errors : Inf\n# Regression with ARIMA(0,0,5) errors : Inf\n# Regression with ARIMA(1,0,0) errors : 1269.039\n# Regression with ARIMA(1,0,0) errors : 1236.551\n# Regression with ARIMA(1,0,0)(0,0,1)[12] errors : 1191.463\n# Regression with ARIMA(1,0,0)(0,0,1)[12] errors : 1163.925\n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors : 1144.206\n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors : 1122.139\n# ARIMA(1,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,0)(2,0,0)[12] errors : Inf\n# ARIMA(1,0,0)(2,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,0)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(2,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,0)(2,0,2)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,1) errors : 1269.741\n# Regression with ARIMA(1,0,1) errors : 1237.127\n# Regression with ARIMA(1,0,1)(0,0,1)[12] errors : 1191.287\n# Regression with ARIMA(1,0,1)(0,0,1)[12] errors : 1165.649\n# Regression with ARIMA(1,0,1)(0,0,2)[12] errors : 1145.611\n# Regression with ARIMA(1,0,1)(0,0,2)[12] errors : 1123.56\n# ARIMA(1,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(1,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,1)(2,0,0)[12] errors : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,2) errors : Inf\n# ARIMA(1,0,2) with non-zero mean : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,2) errors : Inf\n# ARIMA(1,0,2) with non-zero mean : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,2)[12] errors : Inf\n# ARIMA(1,0,2)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,2)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,2)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,2)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,2)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,2)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(1,0,3) errors : Inf\n# Regression with ARIMA(1,0,3) errors : Inf\n# Regression with ARIMA(1,0,3)(0,0,1)[12] errors : 1196.785\n# Regression with ARIMA(1,0,3)(0,0,1)[12] errors : Inf\n# ARIMA(1,0,3)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,3)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,4) errors : Inf\n# Regression with ARIMA(1,0,4) errors : Inf\n# Regression with ARIMA(2,0,0) errors : 1270.227\n# Regression with ARIMA(2,0,0) errors : 1235.453\n# Regression with ARIMA(2,0,0)(0,0,1)[12] errors : 1191.855\n# Regression with ARIMA(2,0,0)(0,0,1)[12] errors : 1165.096\n# Regression with ARIMA(2,0,0)(0,0,2)[12] errors : 1145.887\n# Regression with ARIMA(2,0,0)(0,0,2)[12] errors : 1123.031\n# ARIMA(2,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,0)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(2,0,1)[12] with zero mean : Inf\n# Regression with ARIMA(2,0,0)(2,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1) errors : Inf\n# Regression with ARIMA(2,0,1) errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,2)[12] errors : Inf\n# ARIMA(2,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,1)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(2,0,1)(1,0,1)[12] errors : Inf\n# ARIMA(2,0,1)(1,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(2,0,1)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(2,0,2) errors : Inf\n# Regression with ARIMA(2,0,2) errors : Inf\n# ARIMA(2,0,2)(0,0,1)[12] with zero mean : Inf\n# Regression with ARIMA(2,0,2)(0,0,1)[12] errors : Inf\n# ARIMA(2,0,2)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,2)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,3) with zero mean : Inf\n# Regression with ARIMA(2,0,3) errors : Inf\n# Regression with ARIMA(3,0,0) errors : 1271.552\n# Regression with ARIMA(3,0,0) errors : 1234.442\n# Regression with ARIMA(3,0,0)(0,0,1)[12] errors : 1193.944\n# Regression with ARIMA(3,0,0)(0,0,1)[12] errors : 1165.004\n# Regression with ARIMA(3,0,0)(0,0,2)[12] errors : 1147.337\n# Regression with ARIMA(3,0,0)(0,0,2)[12] errors : 1124.69\n# ARIMA(3,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(3,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(3,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(3,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,0)(2,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(3,0,1) errors : Inf\n# Regression with ARIMA(3,0,1) errors : Inf\n# Regression with ARIMA(3,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(3,0,1)(0,0,1)[12] errors : Inf\n# ARIMA(3,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,1)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(3,0,2) errors : Inf\n# Regression with ARIMA(3,0,2) errors : Inf\n# Regression with ARIMA(4,0,0) errors : 1268.176\n# Regression with ARIMA(4,0,0) errors : 1236.501\n# Regression with ARIMA(4,0,0)(0,0,1)[12] errors : 1191.278\n# Regression with ARIMA(4,0,0)(0,0,1)[12] errors : 1167.39\n# ARIMA(4,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(4,0,0)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(4,0,1) errors : Inf\n# Regression with ARIMA(4,0,1) errors : Inf\n# Regression with ARIMA(5,0,0) errors : 1270.388\n# Regression with ARIMA(5,0,0) errors : 1226.449\n# \n# \n# \n# Best model: Regression with ARIMA(1,0,0)(0,0,2)[12] errors \n# \n\nsummary(fit)\n# Series: d2$prevalence \n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors \n# \n# Coefficients:\n# ar1 sma1 sma2 intercept time step1 ramp1 step2 ramp2 step3 ramp3\n# 0.5256 1.0413 0.6987 188.8179 1.5717 3.3284 2.1966 -5.6181 0.4640 0.4378 4.6447\n# s.e. 0.0800 0.1536 0.1312 20.6895 0.4724 13.0492 3.5219 23.9955 3.8197 19.1790 2.5724\n# \n# sigma^2 = 494.9: log likelihood = -547.61\n# AIC=1119.22 AICc=1122.14 BIC=1152.67\n# \n# Training set error measures:\n# ME RMSE MAE MPE MAPE MASE ACF1\n# Training set -0.2760281 21.20232 16.21419 -0.9807653 5.578825 0.3604042 0.05861382\n</code></pre>\n<h2>Question</h2>\n<p>Should I just apply the same strategy to adults? Or can such models handle correlated/stratified time series?</p>\n<p>I guess that there is a better strategy than fitting separate models within each subgroup. However, I suspect that I cannot simply stack the time series and include <code>age</code> in <code>xreg</code>. Additionally, I probably need an interaction terms (e.g. <code>time * age</code>).</p>\n<p>I have also read about <a href=\"https://stat.ethz.ch/R-manual/R-devel/library/nlme/html/gls.html\" rel=\"nofollow noreferrer\"><code>nlme::gls()</code></a> but I would like guidance/confirmation whether it is more appropriate.</p>\n<hr />\n<p>BTW, I am not satisfied with the fit, but I will explore that once I have decided the modelling strategy.</p>\n<pre class=\"lang-r prettyprint-override\"><code>res &lt;- residuals(fit)\nl &lt;- 36\n\npar(mfrow = c(3, 1))\nplot(res)\nacf(res, lag.max = l)\npacf(res, lag.max = l)\ndev.off()\n\nBox.test(res, lag = 24, type = &quot;Ljung-Box&quot;, fitdf = 3)\n# \n# Box-Ljung test\n# \n# data: res\n# X-squared = 49.814, df = 21, p-value = 0.0003872\n# \n</code></pre>\n<p><a href=\"https://i.sstatic.net/pzs11NTf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/pzs11NTf.png\" alt=\"residuals\" /></a></p>\n", "question_id": 676979, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "Background\n\n\n\n\n\nData: time series of the monthly prevalence of patients receiving a given medication by age group (children or adults) from January 2016 to December 2026\n\n\n\n\nInterventions: three successive regulatory interventions implemented on September 2021, June 2022, and June 2023 to facilitate prescription of the medication (dotted lines on the figure below)\n\n\n\n\nAim: to estimate pre-intervention slope, post-intervention 1 slope, post-intervention 2 slope, and post-intervention 3 slope depending on age group to assess the impact of the interventions (i.e., interrupted time series analysis, ITS)\n\n\n\n\n\nmonth <- seq(\n from = as.Date(\"2016-01-01\"),\n to = as.Date(\"2025-12-31\"),\n by = \"month\"\n)\nmonth <- rep(month, each = 2)\nage <- rep(c(\"Children\", \"Adults\"), 120)\nprevalence <- c(\n 214.1, 11.3, 194.9, 11.1, 220.3, 11.8, 200.7, 11.7, 213.5, \n 11.7, 197.6, 11.5, 128.2, 10.3, 138.6, 9.9, 215, 12.1, 201.9, \n 11.9, 223.8, 12.2, 204.9, 12.4, 234.1, 12.7, 202, 11.9, 247, \n 13.6, 209.8, 13, 236.7, 13.4, 216.9, 13.1, 145.1, 12, 144.3, \n 11, 235.1, 13.7, 227.5, 13.9, 242.5, 13.9, 229.5, 13.8, 255.3, \n 14.5, 226.3, 13.6, 260.8, 15.2, 229.7, 14.2, 245.5, 14.7, 232.6, \n 14.4, 158.8, 13.4, 165, 12.5, 244.3, 14.8, 249.4, 15.7, 259.4, \n 15.5, 244, 15.3, 275.7, 16.2, 240.7, 14.9, 274.4, 16.2, 256.8, \n 16.3, 274.3, 16.4, 240.3, 15.5, 178.2, 15.5, 180.3, 13.6, 264, \n 16.3, 271.3, 17.4, 277.8, 16.9, 261.5, 16.8, 296.9, 17.8, 265.8, \n 17.2, 270.4, 17.9, 218.8, 16, 214.7, 16, 221.8, 16.7, 183.6, \n 16.8, 185.4, 14.9, 273.6, 18.7, 276.7, 19.3, 285, 19.4, 282.8, \n 19.9, 308.3, 20.2, 279.2, 19.3, 331.1, 22, 289.3, 21.2, 303, \n 20.9, 307.5, 21.8, 221.2, 20.9, 215.4, 18.9, 324, 23.4, 323.3, \n 24.3, 328.3, 24.7, 326.5, 25.8, 349.2, 26.1, 319.1, 25.5, 379.3, \n 29, 341.7, 28.3, 365.1, 28.6, 351.7, 30.1, 253.7, 28.6, 266.9, \n 27, 375, 33.4, 373.5, 34.4, 385.8, 35.5, 368.1, 36, 413.7, 38.8, \n 376, 37.4, 440.1, 42.5, 390.3, 40.8, 409.5, 42.6, 402, 44.9, \n 297.9, 43.4, 297.1, 40.2, 430.9, 49.3, 433.4, 51.2, 454.1, 53.1, \n 441.4, 53.4, 472.9, 57, 455.8, 57, 496.3, 62.6, 475, 63.1, 483.4, \n 63.3, 466, 65.1, 367.3, 66.2, 368.4, 58.6, 499.4, 70.8, 528.3, \n 76.1, 533.8, 76, 525.6, 77.2, 588.3, 84.8, 532.4, 81.1, 599.6, \n 90.9, 580.3, 90.8, 601.5, 93.8, 560.6, 95.1, 455.2, 96.9, 440.6, \n 83.7, 629.2, 107.7, 655.7, 112.8, 653.8, 113.2, 674.9, 118.7\n)\nd <- data.frame(month, age, prevalence)\n\npar(mfrow = c(1, 2))\nplot(prevalence ~ month, d, type = \"l\", main = \"Children\", subset = age == \"Children\")\nplot(prevalence ~ month, d, type = \"l\", main = \"Adults\", subset = age == \"Adults\")\ndev.off()\n\n\n\n\n\n[image: time series; source: https://i.sstatic.net/4a0pdydL.png] (https://i.sstatic.net/4a0pdydL.png)\n\n\n\n\nWhat I did\n\n\n\n\nI started with children.\n\n\n\n\nI constructed the ITS variables for the 3 interventions (step1, ramp1, step2, ramp2, step3, ramp3) following Schaffer et al. (https://doi.org/10.1186/s12874-021-01235-8) and Xiao et al. (https://doi.org/10.1093/ije/dyaa148)\n\n\n\n\nd2 <- subset(d, age == \"Children\")\nd2$prevalence <- ts(d2$prevalence, start = 2016, frequency = 12)\n\ninterventions <- as.Date(c(\"2021-09-13\", \"2022-06-02\", \"2023-06-29\"))\n\nstep1 <- as.numeric(d2$month >= interventions[1])\nramp1 <- ifelse(step1 == 1, cumsum(step1) - 1, 0)\n\nstep2 <- as.numeric(d2$month >= interventions[2])\nramp2 <- ifelse(step2 == 1, cumsum(step2) - 1, 0)\n\nstep3 <- as.numeric(d2$month >= interventions[3])\nramp3 <- ifelse(step3 == 1, cumsum(step3) - 1, 0)\n\ntime <- seq(from = 0, along.with = d2$month)\n\nxreg <- cbind(time, step1, ramp1, step2, ramp2, step3, ramp3)\n\ncbind(d2, xreg)\n# month age prevalence time step1 ramp1 step2 ramp2 step3 ramp3\n# 1 2016-01-01 Children 214.1 0 0 0 0 0 0 0\n# 3 2016-02-01 Children 194.9 1 0 0 0 0 0 0\n# 5 2016-03-01 Children 220.3 2 0 0 0 0 0 0\n# 7 2016-04-01 Children 200.7 3 0 0 0 0 0 0\n# 9 2016-05-01 Children 213.5 4 0 0 0 0 0 0\n# 11 2016-06-01 Children 197.6 5 0 0 0 0 0 0\n# 13 2016-07-01 Children 128.2 6 0 0 0 0 0 0\n# 15 2016-08-01 Children 138.6 7 0 0 0 0 0 0\n# 17 2016-09-01 Children 215.0 8 0 0 0 0 0 0\n# 19 2016-10-01 Children 201.9 9 0 0 0 0 0 0\n# 21 2016-11-01 Children 223.8 10 0 0 0 0 0 0\n# 23 2016-12-01 Children 204.9 11 0 0 0 0 0 0\n# 25 2017-01-01 Children 234.1 12 0 0 0 0 0 0\n# 27 2017-02-01 Children 202.0 13 0 0 0 0 0 0\n# 29 2017-03-01 Children 247.0 14 0 0 0 0 0 0\n# 31 2017-04-01 Children 209.8 15 0 0 0 0 0 0\n# 33 2017-05-01 Children 236.7 16 0 0 0 0 0 0\n# 35 2017-06-01 Children 216.9 17 0 0 0 0 0 0\n# 37 2017-07-01 Children 145.1 18 0 0 0 0 0 0\n# 39 2017-08-01 Children 144.3 19 0 0 0 0 0 0\n# 41 2017-09-01 Children 235.1 20 0 0 0 0 0 0\n# 43 2017-10-01 Children 227.5 21 0 0 0 0 0 0\n# 45 2017-11-01 Children 242.5 22 0 0 0 0 0 0\n# 47 2017-12-01 Children 229.5 23 0 0 0 0 0 0\n# 49 2018-01-01 Children 255.3 24 0 0 0 0 0 0\n# 51 2018-02-01 Children 226.3 25 0 0 0 0 0 0\n# 53 2018-03-01 Children 260.8 26 0 0 0 0 0 0\n# 55 2018-04-01 Children 229.7 27 0 0 0 0 0 0\n# 57 2018-05-01 Children 245.5 28 0 0 0 0 0 0\n# 59 2018-06-01 Children 232.6 29 0 0 0 0 0 0\n# 61 2018-07-01 Children 158.8 30 0 0 0 0 0 0\n# 63 2018-08-01 Children 165.0 31 0 0 0 0 0 0\n# 65 2018-09-01 Children 244.3 32 0 0 0 0 0 0\n# 67 2018-10-01 Children 249.4 33 0 0 0 0 0 0\n# 69 2018-11-01 Children 259.4 34 0 0 0 0 0 0\n# 71 2018-12-01 Children 244.0 35 0 0 0 0 0 0\n# 73 2019-01-01 Children 275.7 36 0 0 0 0 0 0\n# 75 2019-02-01 Children 240.7 37 0 0 0 0 0 0\n# 77 2019-03-01 Children 274.4 38 0 0 0 0 0 0\n# 79 2019-04-01 Children 256.8 39 0 0 0 0 0 0\n# 81 2019-05-01 Children 274.3 40 0 0 0 0 0 0\n# 83 2019-06-01 Children 240.3 41 0 0 0 0 0 0\n# 85 2019-07-01 Children 178.2 42 0 0 0 0 0 0\n# 87 2019-08-01 Children 180.3 43 0 0 0 0 0 0\n# 89 2019-09-01 Children 264.0 44 0 0 0 0 0 0\n# 91 2019-10-01 Children 271.3 45 0 0 0 0 0 0\n# 93 2019-11-01 Children 277.8 46 0 0 0 0 0 0\n# 95 2019-12-01 Children 261.5 47 0 0 0 0 0 0\n# 97 2020-01-01 Children 296.9 48 0 0 0 0 0 0\n# 99 2020-02-01 Children 265.8 49 0 0 0 0 0 0\n# 101 2020-03-01 Children 270.4 50 0 0 0 0 0 0\n# 103 2020-04-01 Children 218.8 51 0 0 0 0 0 0\n# 105 2020-05-01 Children 214.7 52 0 0 0 0 0 0\n# 107 2020-06-01 Children 221.8 53 0 0 0 0 0 0\n# 109 2020-07-01 Children 183.6 54 0 0 0 0 0 0\n# 111 2020-08-01 Children 185.4 55 0 0 0 0 0 0\n# 113 2020-09-01 Children 273.6 56 0 0 0 0 0 0\n# 115 2020-10-01 Children 276.7 57 0 0 0 0 0 0\n# 117 2020-11-01 Children 285.0 58 0 0 0 0 0 0\n# 119 2020-12-01 Children 282.8 59 0 0 0 0 0 0\n# 121 2021-01-01 Children 308.3 60 0 0 0 0 0 0\n# 123 2021-02-01 Children 279.2 61 0 0 0 0 0 0\n# 125 2021-03-01 Children 331.1 62 0 0 0 0 0 0\n# 127 2021-04-01 Children 289.3 63 0 0 0 0 0 0\n# 129 2021-05-01 Children 303.0 64 0 0 0 0 0 0\n# 131 2021-06-01 Children 307.5 65 0 0 0 0 0 0\n# 133 2021-07-01 Children 221.2 66 0 0 0 0 0 0\n# 135 2021-08-01 Children 215.4 67 0 0 0 0 0 0\n# 137 2021-09-01 Children 324.0 68 0 0 0 0 0 0\n# 139 2021-10-01 Children 323.3 69 1 0 0 0 0 0\n# 141 2021-11-01 Children 328.3 70 1 1 0 0 0 0\n# 143 2021-12-01 Children 326.5 71 1 2 0 0 0 0\n# 145 2022-01-01 Children 349.2 72 1 3 0 0 0 0\n# 147 2022-02-01 Children 319.1 73 1 4 0 0 0 0\n# 149 2022-03-01 Children 379.3 74 1 5 0 0 0 0\n# 151 2022-04-01 Children 341.7 75 1 6 0 0 0 0\n# 153 2022-05-01 Children 365.1 76 1 7 0 0 0 0\n# 155 2022-06-01 Children 351.7 77 1 8 0 0 0 0\n# 157 2022-07-01 Children 253.7 78 1 9 1 0 0 0\n# 159 2022-08-01 Children 266.9 79 1 10 1 1 0 0\n# 161 2022-09-01 Children 375.0 80 1 11 1 2 0 0\n# 163 2022-10-01 Children 373.5 81 1 12 1 3 0 0\n# 165 2022-11-01 Children 385.8 82 1 13 1 4 0 0\n# 167 2022-12-01 Children 368.1 83 1 14 1 5 0 0\n# 169 2023-01-01 Children 413.7 84 1 15 1 6 0 0\n# 171 2023-02-01 Children 376.0 85 1 16 1 7 0 0\n# 173 2023-03-01 Children 440.1 86 1 17 1 8 0 0\n# 175 2023-04-01 Children 390.3 87 1 18 1 9 0 0\n# 177 2023-05-01 Children 409.5 88 1 19 1 10 0 0\n# 179 2023-06-01 Children 402.0 89 1 20 1 11 0 0\n# 181 2023-07-01 Children 297.9 90 1 21 1 12 1 0\n# 183 2023-08-01 Children 297.1 91 1 22 1 13 1 1\n# 185 2023-09-01 Children 430.9 92 1 23 1 14 1 2\n# 187 2023-10-01 Children 433.4 93 1 24 1 15 1 3\n# 189 2023-11-01 Children 454.1 94 1 25 1 16 1 4\n# 191 2023-12-01 Children 441.4 95 1 26 1 17 1 5\n# 193 2024-01-01 Children 472.9 96 1 27 1 18 1 6\n# 195 2024-02-01 Children 455.8 97 1 28 1 19 1 7\n# 197 2024-03-01 Children 496.3 98 1 29 1 20 1 8\n# 199 2024-04-01 Children 475.0 99 1 30 1 21 1 9\n# 201 2024-05-01 Children 483.4 100 1 31 1 22 1 10\n# 203 2024-06-01 Children 466.0 101 1 32 1 23 1 11\n# 205 2024-07-01 Children 367.3 102 1 33 1 24 1 12\n# 207 2024-08-01 Children 368.4 103 1 34 1 25 1 13\n# 209 2024-09-01 Children 499.4 104 1 35 1 26 1 14\n# 211 2024-10-01 Children 528.3 105 1 36 1 27 1 15\n# 213 2024-11-01 Children 533.8 106 1 37 1 28 1 16\n# 215 2024-12-01 Children 525.6 107 1 38 1 29 1 17\n# 217 2025-01-01 Children 588.3 108 1 39 1 30 1 18\n# 219 2025-02-01 Children 532.4 109 1 40 1 31 1 19\n# 221 2025-03-01 Children 599.6 110 1 41 1 32 1 20\n# 223 2025-04-01 Children 580.3 111 1 42 1 33 1 21\n# 225 2025-05-01 Children 601.5 112 1 43 1 34 1 22\n# 227 2025-06-01 Children 560.6 113 1 44 1 35 1 23\n# 229 2025-07-01 Children 455.2 114 1 45 1 36 1 24\n# 231 2025-08-01 Children 440.6 115 1 46 1 37 1 25\n# 233 2025-09-01 Children 629.2 116 1 47 1 38 1 26\n# 235 2025-10-01 Children 655.7 117 1 48 1 39 1 27\n# 237 2025-11-01 Children 653.8 118 1 49 1 40 1 28\n# 239 2025-12-01 Children 674.9 119 1 50 1 41 1 29\n\n\n\n\n\nAccording to this thread (https://stats.stackexchange.com/q/665216/), I included the ITS variables for the 3 interventions in a single model. I used forecast::auto.arima() to select (p, q) and (P, Q) parameters automatically.\n\n\n\n\nAccording to Schaffer et al. (https://doi.org/10.1186/s12874-021-01235-8), I included a time variable and set $d = 0$ and $D = 0$ (but I am not sure that I need both $d = 0$ and $D = 0$): (emphasis mine)\n\n\n\n\n\n\n\nIn ITS analysis, ARIMA forecasts $Y_t$ in the absence of the intervention (the “counterfactual”) and determines how the observed diverges from this forecast. Unlike segmented regression, including time or seasonal dummy variables in the ARIMA model is not necessary, as ARIMA can eliminate trends and seasonality through differencing. If the trend is eliminated via differencing then the pre- and post-intervention trends cannot be estimated from the model. However, if estimation of the pre- and/or post-intervention slope is desired, this can be accommodated by including time as a covariate and incorporating AR and MA terms to address autocorrelation (e.g. ARMA models) [21 (https://doi.org/10.1186/s12889-017-4998-9), 22 (https://doi.org/10.3111/13696998.2011.626097)].\n\n\n\n\n\n\n\nfit <- forecast::auto.arima(\n d2$prevalence,\n d = 0,\n D = 0,\n stepwise = FALSE,\n trace = TRUE,\n approximation = FALSE,\n xreg = xreg\n)\n# \n# Regression with ARIMA(0,0,0) errors : 1422.701\n# Regression with ARIMA(0,0,0) errors : 1256.821\n# Regression with ARIMA(0,0,0)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,0)(0,0,1)[12] errors : 1186.586\n# Regression with ARIMA(0,0,0)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,0)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,0)(2,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,0)(2,0,2)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,1) errors : 1348.712\n# Regression with ARIMA(0,0,1) errors : 1237.018\n# Regression with ARIMA(0,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,1)(0,0,1)[12] errors : 1167.011\n# Regression with ARIMA(0,0,1)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,1)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,1)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,1)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,1)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,1)(2,0,2)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,1)(2,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,2) errors : 1304.633\n# Regression with ARIMA(0,0,2) errors : 1235.236\n# Regression with ARIMA(0,0,2)(0,0,1)[12] errors : 1226.35\n# Regression with ARIMA(0,0,2)(0,0,1)[12] errors : 1164.06\n# Regression with ARIMA(0,0,2)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,2)(0,0,2)[12] errors : 1122.153\n# ARIMA(0,0,2)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,2)(1,0,0)[12] errors : Inf\n# ARIMA(0,0,2)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,2)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(1,0,2)[12] with zero mean : Inf\n# ARIMA(0,0,2)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,2)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(0,0,2)(2,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,2)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,3) errors : 1301.979\n# Regression with ARIMA(0,0,3) errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,1)[12] errors : 1166.444\n# Regression with ARIMA(0,0,3)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(0,0,3)(0,0,2)[12] errors : Inf\n# ARIMA(0,0,3)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,3)(1,0,0)[12] errors : Inf\n# ARIMA(0,0,3)(1,0,1)[12] with zero mean : Inf\n# ARIMA(0,0,3)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(0,0,3)(2,0,0)[12] with zero mean : Inf\n# ARIMA(0,0,3)(2,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(0,0,4) errors : Inf\n# Regression with ARIMA(0,0,4) errors : Inf\n# Regression with ARIMA(0,0,4)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(0,0,4)(0,0,1)[12] errors : 1167.795\n# ARIMA(0,0,4)(1,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(0,0,4)(1,0,0)[12] errors : Inf\n# Regression with ARIMA(0,0,5) errors : Inf\n# Regression with ARIMA(0,0,5) errors : Inf\n# Regression with ARIMA(1,0,0) errors : 1269.039\n# Regression with ARIMA(1,0,0) errors : 1236.551\n# Regression with ARIMA(1,0,0)(0,0,1)[12] errors : 1191.463\n# Regression with ARIMA(1,0,0)(0,0,1)[12] errors : 1163.925\n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors : 1144.206\n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors : 1122.139\n# ARIMA(1,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,0)(2,0,0)[12] errors : Inf\n# ARIMA(1,0,0)(2,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,0)(2,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,0)(2,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,0)(2,0,2)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,1) errors : 1269.741\n# Regression with ARIMA(1,0,1) errors : 1237.127\n# Regression with ARIMA(1,0,1)(0,0,1)[12] errors : 1191.287\n# Regression with ARIMA(1,0,1)(0,0,1)[12] errors : 1165.649\n# Regression with ARIMA(1,0,1)(0,0,2)[12] errors : 1145.611\n# Regression with ARIMA(1,0,1)(0,0,2)[12] errors : 1123.56\n# ARIMA(1,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(1,0,2)[12] with zero mean : Inf\n# ARIMA(1,0,1)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(1,0,1)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,1)(2,0,0)[12] errors : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,2) errors : Inf\n# ARIMA(1,0,2) with non-zero mean : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# ARIMA(1,0,1)(2,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,2) errors : Inf\n# ARIMA(1,0,2) with non-zero mean : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(1,0,2)(0,0,2)[12] errors : Inf\n# ARIMA(1,0,2)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,2)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(1,0,2)(1,0,1)[12] with zero mean : Inf\n# ARIMA(1,0,2)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(1,0,2)(2,0,0)[12] with zero mean : Inf\n# Regression with ARIMA(1,0,2)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(1,0,3) errors : Inf\n# Regression with ARIMA(1,0,3) errors : Inf\n# Regression with ARIMA(1,0,3)(0,0,1)[12] errors : 1196.785\n# Regression with ARIMA(1,0,3)(0,0,1)[12] errors : Inf\n# ARIMA(1,0,3)(1,0,0)[12] with zero mean : Inf\n# ARIMA(1,0,3)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(1,0,4) errors : Inf\n# Regression with ARIMA(1,0,4) errors : Inf\n# Regression with ARIMA(2,0,0) errors : 1270.227\n# Regression with ARIMA(2,0,0) errors : 1235.453\n# Regression with ARIMA(2,0,0)(0,0,1)[12] errors : 1191.855\n# Regression with ARIMA(2,0,0)(0,0,1)[12] errors : 1165.096\n# Regression with ARIMA(2,0,0)(0,0,2)[12] errors : 1145.887\n# Regression with ARIMA(2,0,0)(0,0,2)[12] errors : 1123.031\n# ARIMA(2,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(1,0,2)[12] with zero mean : Inf\n# ARIMA(2,0,0)(1,0,2)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,0)(2,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,0)(2,0,1)[12] with zero mean : Inf\n# Regression with ARIMA(2,0,0)(2,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1) errors : Inf\n# Regression with ARIMA(2,0,1) errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,2)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(0,0,2)[12] errors : Inf\n# ARIMA(2,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,1)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(2,0,1)(1,0,1)[12] errors : Inf\n# ARIMA(2,0,1)(1,0,1)[12] with non-zero mean : Inf\n# Regression with ARIMA(2,0,1)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(2,0,1)(2,0,0)[12] errors : Inf\n# Regression with ARIMA(2,0,2) errors : Inf\n# Regression with ARIMA(2,0,2) errors : Inf\n# ARIMA(2,0,2)(0,0,1)[12] with zero mean : Inf\n# Regression with ARIMA(2,0,2)(0,0,1)[12] errors : Inf\n# ARIMA(2,0,2)(1,0,0)[12] with zero mean : Inf\n# ARIMA(2,0,2)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(2,0,3) with zero mean : Inf\n# Regression with ARIMA(2,0,3) errors : Inf\n# Regression with ARIMA(3,0,0) errors : 1271.552\n# Regression with ARIMA(3,0,0) errors : 1234.442\n# Regression with ARIMA(3,0,0)(0,0,1)[12] errors : 1193.944\n# Regression with ARIMA(3,0,0)(0,0,1)[12] errors : 1165.004\n# Regression with ARIMA(3,0,0)(0,0,2)[12] errors : 1147.337\n# Regression with ARIMA(3,0,0)(0,0,2)[12] errors : 1124.69\n# ARIMA(3,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,0)(1,0,0)[12] with non-zero mean : Inf\n# ARIMA(3,0,0)(1,0,1)[12] with zero mean : Inf\n# ARIMA(3,0,0)(1,0,1)[12] with non-zero mean : Inf\n# ARIMA(3,0,0)(2,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,0)(2,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(3,0,1) errors : Inf\n# Regression with ARIMA(3,0,1) errors : Inf\n# Regression with ARIMA(3,0,1)(0,0,1)[12] errors : Inf\n# Regression with ARIMA(3,0,1)(0,0,1)[12] errors : Inf\n# ARIMA(3,0,1)(1,0,0)[12] with zero mean : Inf\n# ARIMA(3,0,1)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(3,0,2) errors : Inf\n# Regression with ARIMA(3,0,2) errors : Inf\n# Regression with ARIMA(4,0,0) errors : 1268.176\n# Regression with ARIMA(4,0,0) errors : 1236.501\n# Regression with ARIMA(4,0,0)(0,0,1)[12] errors : 1191.278\n# Regression with ARIMA(4,0,0)(0,0,1)[12] errors : 1167.39\n# ARIMA(4,0,0)(1,0,0)[12] with zero mean : Inf\n# ARIMA(4,0,0)(1,0,0)[12] with non-zero mean : Inf\n# Regression with ARIMA(4,0,1) errors : Inf\n# Regression with ARIMA(4,0,1) errors : Inf\n# Regression with ARIMA(5,0,0) errors : 1270.388\n# Regression with ARIMA(5,0,0) errors : 1226.449\n# \n# \n# \n# Best model: Regression with ARIMA(1,0,0)(0,0,2)[12] errors \n# \n\nsummary(fit)\n# Series: d2$prevalence \n# Regression with ARIMA(1,0,0)(0,0,2)[12] errors \n# \n# Coefficients:\n# ar1 sma1 sma2 intercept time step1 ramp1 step2 ramp2 step3 ramp3\n# 0.5256 1.0413 0.6987 188.8179 1.5717 3.3284 2.1966 -5.6181 0.4640 0.4378 4.6447\n# s.e. 0.0800 0.1536 0.1312 20.6895 0.4724 13.0492 3.5219 23.9955 3.8197 19.1790 2.5724\n# \n# sigma^2 = 494.9: log likelihood = -547.61\n# AIC=1119.22 AICc=1122.14 BIC=1152.67\n# \n# Training set error measures:\n# ME RMSE MAE MPE MAPE MASE ACF1\n# Training set -0.2760281 21.20232 16.21419 -0.9807653 5.578825 0.3604042 0.05861382\n\n\n\n\n\nQuestion\n\n\n\n\nShould I just apply the same strategy to adults? Or can such models handle correlated/stratified time series?\n\n\n\n\nI guess that there is a better strategy than fitting separate models within each subgroup. However, I suspect that I cannot simply stack the time series and include age in xreg. Additionally, I probably need an interaction terms (e.g. time * age).\n\n\n\n\nI have also read about nlme::gls() (https://stat.ethz.ch/R-manual/R-devel/library/nlme/html/gls.html) but I would like guidance/confirmation whether it is more appropriate.\n\n\n\n\n\n\n\nBTW, I am not satisfied with the fit, but I will explore that once I have decided the modelling strategy.\n\n\n\n\nres <- residuals(fit)\nl <- 36\n\npar(mfrow = c(3, 1))\nplot(res)\nacf(res, lag.max = l)\npacf(res, lag.max = l)\ndev.off()\n\nBox.test(res, lag = 24, type = \"Ljung-Box\", fitdf = 3)\n# \n# Box-Ljung test\n# \n# data: res\n# X-squared = 49.814, df = 21, p-value = 0.0003872\n# \n\n\n\n\n\n[image: residuals; source: https://i.sstatic.net/pzs11NTf.png] (https://i.sstatic.net/pzs11NTf.png)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas", "profile_url": "https://stats.stackexchange.com/users/263046/thomas", "user_type": "registered"}, "created_at": "2026-08-27T20:48:18+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "4F68B416-BBB1-4FBC-8F34-014B8106BA46", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/4F68B416-BBB1-4FBC-8F34-014B8106BA46/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas", "profile_url": "https://stats.stackexchange.com/users/263046/thomas", "user_type": "registered"}, "created_at": "2026-08-28T00:03:27+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "FB0908B9-A046-40C1-A08B-E6284215F76C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FB0908B9-A046-40C1-A08B-E6284215F76C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas", "profile_url": "https://stats.stackexchange.com/users/263046/thomas", "user_type": "registered"}, "created_at": "2026-08-28T00:11:08+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "9E9FBC78-84A9-484D-B830-4D1751368045", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9E9FBC78-84A9-484D-B830-4D1751368045/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas", "profile_url": "https://stats.stackexchange.com/users/263046/thomas", "user_type": "registered"}, "created_at": "2026-08-28T09:19:31+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "F52E35E2-A4F3-4D9C-BBE7-6F9246725A84", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F52E35E2-A4F3-4D9C-BBE7-6F9246725A84/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676979/strategy-for-interrupted-time-series-of-correlated-stratified-time-series", "split": "validation", "split_group": "4776dab9c10254abf857639b7a8deff481b81182a68f5330c41a896a7463144f", "tags": ["r", "time-series", "arima", "generalized-least-squares", "intervention-analysis"], "thread_id": "stats:676979", "title": "Strategy for interrupted time series of correlated/stratified time series"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "mod <- glmmTMB(Score ~ th * bd + (1 | obs),\n family = beta_family(link = \"logit\"), data = data_long)\n\n\n AIC BIC logLik -2*log(L) df.resid \n -565.2 -531.6 292.6 -585.2 202 \n\n**Random effects:**\n\nConditional model:\n Groups Name Variance Std.Dev.\n obs (Intercept) 0.03939 0.1985 \nNumber of obs: 212, groups: obs, 53\n\n> model_performance(\n+ mod,\n+ metrics = c(\"R2\", \"AIC\", \"BIC\", \"RMSE\")\n+ )\n# Indices of model performance\n\nAIC | BIC | R2 (cond.) | R2 (marg.) | RMSE\n-------------------------------------------------\n-565.2 | -531.6 | 0.985 | 0.912 | 0.048\n\n\n--- DHARMa diagnostic tests (unconditional simulations, old default) ---\n\n Asymptotic one-sample Kolmogorov-Smirnov test\n\ndata: simulationOutput$scaledResiduals\nD = 0.060925, p-value = 0.4108\nalternative hypothesis: two-sided\n\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated\n\ndata: simulationOutput\ndispersion = 1.0707, p-value = 0.51\nalternative hypothesis: two.sided\n\n\n DHARMa outlier test based on exact binomial test with approximate expectations\n\ndata: sim_res\noutliers at both margin(s) = 3, observations = 212, p-value = 0.009158\nalternative hypothesis: true probability of success is not equal to 0.001998002\n95 percent confidence interval:\n 0.002927826 0.040795871\nsample estimates:\nfrequency of outliers (expected: 0.001998001998002 ) \n 0.01415094 \n\n\n\n# Intraclass Correlation Coefficient\n\n Adjusted ICC: 0.832\n Unadjusted ICC: 0.073\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676982, "sha256": "354ec386048c1b96cd292a620a8a98768e9d875f2a431b280e33bc065be5637f", "source_url": "https://stats.stackexchange.com/questions/676982/glmmtmb-with-beta-distribution-and-repeated-measures-with-high-r-squared-too-g"}], "other_answers": [], "product": "code_qa", "question": "Not sure if someone can help me, but I am trying to fit a model with one fixed continuous predictor (th) to my response variable (Score, continuous proportion without 0 or 1) measured in four different conditions (bd) in the same observers (obs). The data are from a psychological experiment, so I am having a hard time in finding a precedent. The results of the GLMM look too good to be true, so I think something might be very wrong. How can I make sure if the results are okay? Can I have a R^2 over 0.9 for the fixed dispersion model?\n\n\n\n\nI have previously fitted beta regression models separately to each condition, without accounting for repeated measures and random effects, using betareg, and pseudo-R-squared values were also high (ranging from 0.79 to 0.90). Although they are not the same, can they indicate something about this result? And is there a way for me to confirm the appropriateness of this GLMM and its output for my data? Observers' performance is expected to follow this trend, as they can be separated into 2 separate groups by the predictor's test result (a discrimination threshold), but still I have doubts. Maybe the experimental hypothesis is inappropriate, as one group is expected to outperform the other in the threshold, and the response is a hit score based on the control's group performance.\n\n\n\n\nhere's some of the output of the final model, with fixed dispersion:\n\n\n\n\nmod <- glmmTMB(Score ~ th * bd + (1 | obs),\n family = beta_family(link = \"logit\"), data = data_long)\n\n\n AIC BIC logLik -2*log(L) df.resid \n -565.2 -531.6 292.6 -585.2 202 \n\n**Random effects:**\n\nConditional model:\n Groups Name Variance Std.Dev.\n obs (Intercept) 0.03939 0.1985 \nNumber of obs: 212, groups: obs, 53\n\n> model_performance(\n+ mod,\n+ metrics = c(\"R2\", \"AIC\", \"BIC\", \"RMSE\")\n+ )\n# Indices of model performance\n\nAIC | BIC | R2 (cond.) | R2 (marg.) | RMSE\n-------------------------------------------------\n-565.2 | -531.6 | 0.985 | 0.912 | 0.048\n\n\n--- DHARMa diagnostic tests (unconditional simulations, old default) ---\n\n Asymptotic one-sample Kolmogorov-Smirnov test\n\ndata: simulationOutput$scaledResiduals\nD = 0.060925, p-value = 0.4108\nalternative hypothesis: two-sided\n\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated\n\ndata: simulationOutput\ndispersion = 1.0707, p-value = 0.51\nalternative hypothesis: two.sided\n\n\n DHARMa outlier test based on exact binomial test with approximate expectations\n\ndata: sim_res\noutliers at both margin(s) = 3, observations = 212, p-value = 0.009158\nalternative hypothesis: true probability of success is not equal to 0.001998002\n95 percent confidence interval:\n 0.002927826 0.040795871\nsample estimates:\nfrequency of outliers (expected: 0.001998001998002 ) \n 0.01415094 \n\n\n\n# Intraclass Correlation Coefficient\n\n Adjusted ICC: 0.832\n Unadjusted ICC: 0.073\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/V0JjVImt.png] (https://i.sstatic.net/V0JjVImt.png)\n[image: enter image description here; source: https://i.sstatic.net/vTBK3rAo.png] (https://i.sstatic.net/vTBK3rAo.png)\n[image: enter image description here; source: https://i.sstatic.net/zOi948b5.png] (https://i.sstatic.net/zOi948b5.png)\n[image: enter image description here; source: https://i.sstatic.net/7o8KKCNe.png] (https://i.sstatic.net/7o8KKCNe.png)\n[image: enter image description here; source: https://i.sstatic.net/Cf66Rzrk.png] (https://i.sstatic.net/Cf66Rzrk.png)\n[image: enter image description here; source: https://i.sstatic.net/JQ7R4P2C.png] (https://i.sstatic.net/JQ7R4P2C.png)\n[image: enter image description here; source: https://i.sstatic.net/ykzaI4V0.png] (https://i.sstatic.net/ykzaI4V0.png)\n[image: enter image description here; source: https://i.sstatic.net/JprOGOJ2.png] (https://i.sstatic.net/JprOGOJ2.png)\n[image: enter image description here; source: https://i.sstatic.net/YYELEFx7.png] (https://i.sstatic.net/YYELEFx7.png)\n\n\n\n\nafter updating the software, with the new dharma package version, that uses conditional simulations as default, instead of unconditional, I now have significant distribution KS tests... How does this affect model validation?\n\n\n\n\n--- DHARMa diagnostic tests (new default: conditional simulations) ---\n\n Asymptotic one-sample Kolmogorov-Smirnov test\n\ndata: simulationOutput$scaledResiduals\nD = 0.107, p-value = 0.01559\nalternative hypothesis: two-sided\n\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated\n\ndata: simulationOutput\ndispersion = 1.1412, p-value = 0.138\nalternative hypothesis: two.sided\n\n\n DHARMa outlier test based on exact binomial test with approximate expectations\n\ndata: sim_res\noutliers at both margin(s) = 2, observations = 212, p-value = 0.06782\nalternative hypothesis: true probability of success is not equal to 0.001998002\n95 percent confidence interval:\n 0.001144546 0.033661358\nsample estimates:\nfrequency of outliers (expected: 0.001998001998002 ) \n 0.009433962\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/2fs8yraM.png] (https://i.sstatic.net/2fs8yraM.png)\n[image: enter image description here; source: https://i.sstatic.net/2frGxmzM.png] (https://i.sstatic.net/2frGxmzM.png)\n[image: enter image description here; source: https://i.sstatic.net/iOSbUmj8.png] (https://i.sstatic.net/iOSbUmj8.png)\n[image: enter image description here; source: https://i.sstatic.net/03FfH1CY.png] (https://i.sstatic.net/03FfH1CY.png)\n[image: enter image description here; source: https://i.sstatic.net/2f1IsCZM.png] (https://i.sstatic.net/2f1IsCZM.png)\n\n\n\n\nUpdate: Due to the new conditional DHARMa results, I've compared a model with variable dispersion, which seems to be more adequate. I guess this solves the issue of the R-squared values, as they are now inappropriate to calculate... :)\n\n\n\n\n--- Model comparison (LRT and AIC) ---\nData: data_long\nModels:\nmod_disp_constant: Score ~ th * bd + (1 | obs), zi=~0, disp=~1\nmod_disp_background: Score ~ th * bd + (1 | obs), zi=~0,disp=~background\n Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq) \nmod_disp_constant 10 -565.16 -531.60 292.58 -585.16 \nmod_disp_background 13 -576.10 -532.47 301.05 -602.10 16.937 3 0.0007281 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1**\n df AIC\nmod_disp_constant 10 -565.1642\nmod_disp_background 13 -576.1012\n\n--- DHARMa diagnostics: varying dispersion, conditional simulation ---\n\n Asymptotic one-sample Kolmogorov-Smirnov test\n\ndata: simulationOutput$scaledResiduals\nD = 0.071019, p-value = 0.2353\nalternative hypothesis: two-sided\n\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated\n\ndata: simulationOutput\ndispersion = 1.1215, p-value = 0.192\nalternative hypothesis: two.sided\n\n\n DHARMa outlier test based on exact binomial test with approximate expectations\n\ndata: sim_res_dispbg_conditional\noutliers at both margin(s) = 1, observations = 212, p-value = 0.3456\nalternative hypothesis: true probability of success is not equal to 0.001998002\n95 percent confidence interval:\n 0.0001194165 0.0259997103\nsample estimates:\nfrequency of outliers (expected: 0.001998001998002 ) \n 0.004716981 \n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/fmBeMY6t.png] (https://i.sstatic.net/fmBeMY6t.png)\n\n\n\n\n(can't add more plots, I guess)", "record_id": "Scientific-Code-and-Analysis-QA:stats:676982", "selected_answer": {"answer_html": "<p>Based on what I see in the interaction plot, there seems to be a strong association between your continuous predictor and the outcome. Consequently, the confidence intervals are narrow (so it's not very noisy). This is likely what primarily contributes to the <span class=\"math-container\">$R^2$</span> being high.</p>\n<p>It seems there aren't very large differences between groups wrt the outcome and the interaction isn't very strong. Grayscale is the only standout group. It has the same association but has a lower conditional mean and higher variability. So the group-based effects in the model are driving less of the <span class=\"math-container\">$R^2$</span> than the continuous predictor is.</p>\n<p>The model fitness seems fine too, so its not an obvious mis-specification. There is some by-quantile curvature at times and the QQ plot isn't exactly perfect but they're passable for a model. The results would be scarier if the plots were obviously bad.</p>\n<p>It seems one version of your model has an additional categorical variable (based on the DHARMa plots) which isn't included in your R formula. This predictor could also be contributing to the model <span class=\"math-container\">$R^2$</span> in some way too, but its not clear how.</p>\n", "answer_id": 676994, "answer_text": "Based on what I see in the interaction plot, there seems to be a strong association between your continuous predictor and the outcome. Consequently, the confidence intervals are narrow (so it's not very noisy). This is likely what primarily contributes to the $R^2$ being high.\n\n\n\n\nIt seems there aren't very large differences between groups wrt the outcome and the interaction isn't very strong. Grayscale is the only standout group. It has the same association but has a lower conditional mean and higher variability. So the group-based effects in the model are driving less of the $R^2$ than the continuous predictor is.\n\n\n\n\nThe model fitness seems fine too, so its not an obvious mis-specification. There is some by-quantile curvature at times and the QQ plot isn't exactly perfect but they're passable for a model. The results would be scarier if the plots were obviously bad.\n\n\n\n\nIt seems one version of your model has an additional categorical variable (based on the DHARMa plots) which isn't included in your R formula. This predictor could also be contributing to the model $R^2$ in some way too, but its not clear how.", "answer_url": "https://stats.stackexchange.com/a/676994", "author": "Shawn Hemelstrand", "author_url": "https://stats.stackexchange.com/users/345611/shawn-hemelstrand", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-28T23:57:01+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 676982, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Shawn Hemelstrand", "profile_url": "https://stats.stackexchange.com/users/345611/shawn-hemelstrand", "user_type": "registered"}, "created_at": "2026-08-28T23:57:01+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "DB57E1BB-14A5-4645-A356-129C789D7022", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/DB57E1BB-14A5-4645-A356-129C789D7022/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Shawn Hemelstrand", "profile_url": "https://stats.stackexchange.com/users/345611/shawn-hemelstrand", "user_type": "registered"}, "created_at": "2026-08-29T00:41:24+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "0159009C-9F9A-4524-9B80-EAD167E5975F", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/0159009C-9F9A-4524-9B80-EAD167E5975F/view-source"}], "score": 6, "updated_at": "2026-08-29T00:41:24+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "validation", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "<p>Based on what I see in the interaction plot, there seems to be a strong association between your continuous predictor and the outcome. Consequently, the confidence intervals are narrow (so it's not very noisy). This is likely what primarily contributes to the <span class=\"math-container\">$R^2$</span> being high.</p>\n<p>It seems there aren't very large differences between groups wrt the outcome and the interaction isn't very strong. Grayscale is the only standout group. It has the same association but has a lower conditional mean and higher variability. So the group-based effects in the model are driving less of the <span class=\"math-container\">$R^2$</span> than the continuous predictor is.</p>\n<p>The model fitness seems fine too, so its not an obvious mis-specification. There is some by-quantile curvature at times and the QQ plot isn't exactly perfect but they're passable for a model. The results would be scarier if the plots were obviously bad.</p>\n<p>It seems one version of your model has an additional categorical variable (based on the DHARMa plots) which isn't included in your R formula. This predictor could also be contributing to the model <span class=\"math-container\">$R^2$</span> in some way too, but its not clear how.</p>\n", "answer_id": 676994, "answer_text": "Based on what I see in the interaction plot, there seems to be a strong association between your continuous predictor and the outcome. Consequently, the confidence intervals are narrow (so it's not very noisy). This is likely what primarily contributes to the $R^2$ being high.\n\n\n\n\nIt seems there aren't very large differences between groups wrt the outcome and the interaction isn't very strong. Grayscale is the only standout group. It has the same association but has a lower conditional mean and higher variability. So the group-based effects in the model are driving less of the $R^2$ than the continuous predictor is.\n\n\n\n\nThe model fitness seems fine too, so its not an obvious mis-specification. There is some by-quantile curvature at times and the QQ plot isn't exactly perfect but they're passable for a model. The results would be scarier if the plots were obviously bad.\n\n\n\n\nIt seems one version of your model has an additional categorical variable (based on the DHARMa plots) which isn't included in your R formula. This predictor could also be contributing to the model $R^2$ in some way too, but its not clear how.", "answer_url": "https://stats.stackexchange.com/a/676994", "author": "Shawn Hemelstrand", "author_url": "https://stats.stackexchange.com/users/345611/shawn-hemelstrand", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-28T23:57:01+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:06.169765+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json", "raw_sha256": "cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 676982, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Shawn Hemelstrand", "profile_url": "https://stats.stackexchange.com/users/345611/shawn-hemelstrand", "user_type": "registered"}, "created_at": "2026-08-28T23:57:01+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "DB57E1BB-14A5-4645-A356-129C789D7022", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/DB57E1BB-14A5-4645-A356-129C789D7022/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Shawn Hemelstrand", "profile_url": "https://stats.stackexchange.com/users/345611/shawn-hemelstrand", "user_type": "registered"}, "created_at": "2026-08-29T00:41:24+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "0159009C-9F9A-4524-9B80-EAD167E5975F", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/0159009C-9F9A-4524-9B80-EAD167E5975F/view-source"}], "score": 6, "updated_at": "2026-08-29T00:41:24+00:00"}], "domain": "statistics", "external_links": ["https://i.sstatic.net/03FfH1CY.png", "https://i.sstatic.net/2f1IsCZM.png", "https://i.sstatic.net/2frGxmzM.png", "https://i.sstatic.net/2fs8yraM.png", "https://i.sstatic.net/7o8KKCNe.png", "https://i.sstatic.net/Cf66Rzrk.png", "https://i.sstatic.net/JQ7R4P2C.png", "https://i.sstatic.net/JprOGOJ2.png", "https://i.sstatic.net/V0JjVImt.png", "https://i.sstatic.net/YYELEFx7.png", "https://i.sstatic.net/fmBeMY6t.png", "https://i.sstatic.net/iOSbUmj8.png", "https://i.sstatic.net/vTBK3rAo.png", "https://i.sstatic.net/ykzaI4V0.png", "https://i.sstatic.net/zOi948b5.png"], "medical_sensitive": true, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:03.428408+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/774052c18cd9e8fa951e893347bfa3c1a85e743fc46ec4667572002cadb10cbf_1790825224163423600_0.json", "raw_sha256": "fe4dd06d3de6c0b1bb33ba88aee0ed4284118e01f76a58dcdce220a4946329b2", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "Dodo", "question_author_url": "https://stats.stackexchange.com/users/516003/dodo", "question_author_user_type": "registered", "question_created_at": "2026-08-27T23:58:06+00:00", "question_html": "<p>Not sure if someone can help me, but I am trying to fit a model with one fixed continuous predictor (th) to my response variable (Score, continuous proportion without 0 or 1) measured in four different conditions (bd) in the same observers (obs). The data are from a psychological experiment, so I am having a hard time in finding a precedent. The results of the GLMM look too good to be true, so I think something might be very wrong. How can I make sure if the results are okay? Can I have a R^2 over 0.9 for the fixed dispersion model?</p>\n<p>I have previously fitted beta regression models separately to each condition, without accounting for repeated measures and random effects, using <code>betareg</code>, and pseudo-R-squared values were also high (ranging from 0.79 to 0.90). Although they are not the same, can they indicate something about this result? And is there a way for me to confirm the appropriateness of this GLMM and its output for my data? Observers' performance is expected to follow this trend, as they can be separated into 2 separate groups by the predictor's test result (a discrimination threshold), but still I have doubts. Maybe the experimental hypothesis is inappropriate, as one group is expected to outperform the other in the threshold, and the response is a hit score based on the control's group performance.</p>\n<p>here's some of the output of the final model, with fixed dispersion:</p>\n<pre class=\"lang-r prettyprint-override\"><code>mod &lt;- glmmTMB(Score ~ th * bd + (1 | obs),\n family = beta_family(link = &quot;logit&quot;), data = data_long)\n\n\n AIC BIC logLik -2*log(L) df.resid \n -565.2 -531.6 292.6 -585.2 202 \n\n**Random effects:**\n\nConditional model:\n Groups Name Variance Std.Dev.\n obs (Intercept) 0.03939 0.1985 \nNumber of obs: 212, groups: obs, 53\n\n&gt; model_performance(\n+ mod,\n+ metrics = c(&quot;R2&quot;, &quot;AIC&quot;, &quot;BIC&quot;, &quot;RMSE&quot;)\n+ )\n# Indices of model performance\n\nAIC | BIC | R2 (cond.) | R2 (marg.) | RMSE\n-------------------------------------------------\n-565.2 | -531.6 | 0.985 | 0.912 | 0.048\n\n\n--- DHARMa diagnostic tests (unconditional simulations, old default) ---\n\n Asymptotic one-sample Kolmogorov-Smirnov test\n\ndata: simulationOutput$scaledResiduals\nD = 0.060925, p-value = 0.4108\nalternative hypothesis: two-sided\n\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated\n\ndata: simulationOutput\ndispersion = 1.0707, p-value = 0.51\nalternative hypothesis: two.sided\n\n\n DHARMa outlier test based on exact binomial test with approximate expectations\n\ndata: sim_res\noutliers at both margin(s) = 3, observations = 212, p-value = 0.009158\nalternative hypothesis: true probability of success is not equal to 0.001998002\n95 percent confidence interval:\n 0.002927826 0.040795871\nsample estimates:\nfrequency of outliers (expected: 0.001998001998002 ) \n 0.01415094 \n\n\n\n# Intraclass Correlation Coefficient\n\n Adjusted ICC: 0.832\n Unadjusted ICC: 0.073\n</code></pre>\n<p><a href=\"https://i.sstatic.net/V0JjVImt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/V0JjVImt.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/vTBK3rAo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/vTBK3rAo.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/zOi948b5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/zOi948b5.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/7o8KKCNe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/7o8KKCNe.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/Cf66Rzrk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/Cf66Rzrk.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/JQ7R4P2C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/JQ7R4P2C.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/ykzaI4V0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/ykzaI4V0.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/JprOGOJ2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/JprOGOJ2.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/YYELEFx7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/YYELEFx7.png\" alt=\"enter image description here\" /></a></p>\n<p>after updating the software, with the new dharma package version, that uses conditional simulations as default, instead of unconditional, I now have significant distribution KS tests... How does this affect model validation?</p>\n<pre class=\"lang-r prettyprint-override\"><code>--- DHARMa diagnostic tests (new default: conditional simulations) ---\n\n Asymptotic one-sample Kolmogorov-Smirnov test\n\ndata: simulationOutput$scaledResiduals\nD = 0.107, p-value = 0.01559\nalternative hypothesis: two-sided\n\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated\n\ndata: simulationOutput\ndispersion = 1.1412, p-value = 0.138\nalternative hypothesis: two.sided\n\n\n DHARMa outlier test based on exact binomial test with approximate expectations\n\ndata: sim_res\noutliers at both margin(s) = 2, observations = 212, p-value = 0.06782\nalternative hypothesis: true probability of success is not equal to 0.001998002\n95 percent confidence interval:\n 0.001144546 0.033661358\nsample estimates:\nfrequency of outliers (expected: 0.001998001998002 ) \n 0.009433962\n</code></pre>\n<p><a href=\"https://i.sstatic.net/2fs8yraM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/2fs8yraM.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/2frGxmzM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/2frGxmzM.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/iOSbUmj8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/iOSbUmj8.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/03FfH1CY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/03FfH1CY.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.sstatic.net/2f1IsCZM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/2f1IsCZM.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>Update:</strong> Due to the new conditional DHARMa results, I've compared a model with variable dispersion, which seems to be more adequate. I guess this solves the issue of the R-squared values, as they are now inappropriate to calculate... :)</p>\n<pre class=\"lang-r prettyprint-override\"><code>--- Model comparison (LRT and AIC) ---\nData: data_long\nModels:\nmod_disp_constant: Score ~ th * bd + (1 | obs), zi=~0, disp=~1\nmod_disp_background: Score ~ th * bd + (1 | obs), zi=~0,disp=~background\n Df AIC BIC logLik deviance Chisq Chi Df Pr(&gt;Chisq) \nmod_disp_constant 10 -565.16 -531.60 292.58 -585.16 \nmod_disp_background 13 -576.10 -532.47 301.05 -602.10 16.937 3 0.0007281 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1**\n df AIC\nmod_disp_constant 10 -565.1642\nmod_disp_background 13 -576.1012\n\n--- DHARMa diagnostics: varying dispersion, conditional simulation ---\n\n Asymptotic one-sample Kolmogorov-Smirnov test\n\ndata: simulationOutput$scaledResiduals\nD = 0.071019, p-value = 0.2353\nalternative hypothesis: two-sided\n\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated\n\ndata: simulationOutput\ndispersion = 1.1215, p-value = 0.192\nalternative hypothesis: two.sided\n\n\n DHARMa outlier test based on exact binomial test with approximate expectations\n\ndata: sim_res_dispbg_conditional\noutliers at both margin(s) = 1, observations = 212, p-value = 0.3456\nalternative hypothesis: true probability of success is not equal to 0.001998002\n95 percent confidence interval:\n 0.0001194165 0.0259997103\nsample estimates:\nfrequency of outliers (expected: 0.001998001998002 ) \n 0.004716981 \n</code></pre>\n<p><a href=\"https://i.sstatic.net/fmBeMY6t.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/fmBeMY6t.png\" alt=\"enter image description here\" /></a></p>\n<p>(can't add more plots, I guess)</p>\n", "question_id": 676982, "question_license": "CC BY-SA 4.0", "question_score": 5, "question_text": "Not sure if someone can help me, but I am trying to fit a model with one fixed continuous predictor (th) to my response variable (Score, continuous proportion without 0 or 1) measured in four different conditions (bd) in the same observers (obs). The data are from a psychological experiment, so I am having a hard time in finding a precedent. The results of the GLMM look too good to be true, so I think something might be very wrong. How can I make sure if the results are okay? Can I have a R^2 over 0.9 for the fixed dispersion model?\n\n\n\n\nI have previously fitted beta regression models separately to each condition, without accounting for repeated measures and random effects, using betareg, and pseudo-R-squared values were also high (ranging from 0.79 to 0.90). Although they are not the same, can they indicate something about this result? And is there a way for me to confirm the appropriateness of this GLMM and its output for my data? Observers' performance is expected to follow this trend, as they can be separated into 2 separate groups by the predictor's test result (a discrimination threshold), but still I have doubts. Maybe the experimental hypothesis is inappropriate, as one group is expected to outperform the other in the threshold, and the response is a hit score based on the control's group performance.\n\n\n\n\nhere's some of the output of the final model, with fixed dispersion:\n\n\n\n\nmod <- glmmTMB(Score ~ th * bd + (1 | obs),\n family = beta_family(link = \"logit\"), data = data_long)\n\n\n AIC BIC logLik -2*log(L) df.resid \n -565.2 -531.6 292.6 -585.2 202 \n\n**Random effects:**\n\nConditional model:\n Groups Name Variance Std.Dev.\n obs (Intercept) 0.03939 0.1985 \nNumber of obs: 212, groups: obs, 53\n\n> model_performance(\n+ mod,\n+ metrics = c(\"R2\", \"AIC\", \"BIC\", \"RMSE\")\n+ )\n# Indices of model performance\n\nAIC | BIC | R2 (cond.) | R2 (marg.) | RMSE\n-------------------------------------------------\n-565.2 | -531.6 | 0.985 | 0.912 | 0.048\n\n\n--- DHARMa diagnostic tests (unconditional simulations, old default) ---\n\n Asymptotic one-sample Kolmogorov-Smirnov test\n\ndata: simulationOutput$scaledResiduals\nD = 0.060925, p-value = 0.4108\nalternative hypothesis: two-sided\n\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated\n\ndata: simulationOutput\ndispersion = 1.0707, p-value = 0.51\nalternative hypothesis: two.sided\n\n\n DHARMa outlier test based on exact binomial test with approximate expectations\n\ndata: sim_res\noutliers at both margin(s) = 3, observations = 212, p-value = 0.009158\nalternative hypothesis: true probability of success is not equal to 0.001998002\n95 percent confidence interval:\n 0.002927826 0.040795871\nsample estimates:\nfrequency of outliers (expected: 0.001998001998002 ) \n 0.01415094 \n\n\n\n# Intraclass Correlation Coefficient\n\n Adjusted ICC: 0.832\n Unadjusted ICC: 0.073\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/V0JjVImt.png] (https://i.sstatic.net/V0JjVImt.png)\n[image: enter image description here; source: https://i.sstatic.net/vTBK3rAo.png] (https://i.sstatic.net/vTBK3rAo.png)\n[image: enter image description here; source: https://i.sstatic.net/zOi948b5.png] (https://i.sstatic.net/zOi948b5.png)\n[image: enter image description here; source: https://i.sstatic.net/7o8KKCNe.png] (https://i.sstatic.net/7o8KKCNe.png)\n[image: enter image description here; source: https://i.sstatic.net/Cf66Rzrk.png] (https://i.sstatic.net/Cf66Rzrk.png)\n[image: enter image description here; source: https://i.sstatic.net/JQ7R4P2C.png] (https://i.sstatic.net/JQ7R4P2C.png)\n[image: enter image description here; source: https://i.sstatic.net/ykzaI4V0.png] (https://i.sstatic.net/ykzaI4V0.png)\n[image: enter image description here; source: https://i.sstatic.net/JprOGOJ2.png] (https://i.sstatic.net/JprOGOJ2.png)\n[image: enter image description here; source: https://i.sstatic.net/YYELEFx7.png] (https://i.sstatic.net/YYELEFx7.png)\n\n\n\n\nafter updating the software, with the new dharma package version, that uses conditional simulations as default, instead of unconditional, I now have significant distribution KS tests... How does this affect model validation?\n\n\n\n\n--- DHARMa diagnostic tests (new default: conditional simulations) ---\n\n Asymptotic one-sample Kolmogorov-Smirnov test\n\ndata: simulationOutput$scaledResiduals\nD = 0.107, p-value = 0.01559\nalternative hypothesis: two-sided\n\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated\n\ndata: simulationOutput\ndispersion = 1.1412, p-value = 0.138\nalternative hypothesis: two.sided\n\n\n DHARMa outlier test based on exact binomial test with approximate expectations\n\ndata: sim_res\noutliers at both margin(s) = 2, observations = 212, p-value = 0.06782\nalternative hypothesis: true probability of success is not equal to 0.001998002\n95 percent confidence interval:\n 0.001144546 0.033661358\nsample estimates:\nfrequency of outliers (expected: 0.001998001998002 ) \n 0.009433962\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/2fs8yraM.png] (https://i.sstatic.net/2fs8yraM.png)\n[image: enter image description here; source: https://i.sstatic.net/2frGxmzM.png] (https://i.sstatic.net/2frGxmzM.png)\n[image: enter image description here; source: https://i.sstatic.net/iOSbUmj8.png] (https://i.sstatic.net/iOSbUmj8.png)\n[image: enter image description here; source: https://i.sstatic.net/03FfH1CY.png] (https://i.sstatic.net/03FfH1CY.png)\n[image: enter image description here; source: https://i.sstatic.net/2f1IsCZM.png] (https://i.sstatic.net/2f1IsCZM.png)\n\n\n\n\nUpdate: Due to the new conditional DHARMa results, I've compared a model with variable dispersion, which seems to be more adequate. I guess this solves the issue of the R-squared values, as they are now inappropriate to calculate... :)\n\n\n\n\n--- Model comparison (LRT and AIC) ---\nData: data_long\nModels:\nmod_disp_constant: Score ~ th * bd + (1 | obs), zi=~0, disp=~1\nmod_disp_background: Score ~ th * bd + (1 | obs), zi=~0,disp=~background\n Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq) \nmod_disp_constant 10 -565.16 -531.60 292.58 -585.16 \nmod_disp_background 13 -576.10 -532.47 301.05 -602.10 16.937 3 0.0007281 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1**\n df AIC\nmod_disp_constant 10 -565.1642\nmod_disp_background 13 -576.1012\n\n--- DHARMa diagnostics: varying dispersion, conditional simulation ---\n\n Asymptotic one-sample Kolmogorov-Smirnov test\n\ndata: simulationOutput$scaledResiduals\nD = 0.071019, p-value = 0.2353\nalternative hypothesis: two-sided\n\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated\n\ndata: simulationOutput\ndispersion = 1.1215, p-value = 0.192\nalternative hypothesis: two.sided\n\n\n DHARMa outlier test based on exact binomial test with approximate expectations\n\ndata: sim_res_dispbg_conditional\noutliers at both margin(s) = 1, observations = 212, p-value = 0.3456\nalternative hypothesis: true probability of success is not equal to 0.001998002\n95 percent confidence interval:\n 0.0001194165 0.0259997103\nsample estimates:\nfrequency of outliers (expected: 0.001998001998002 ) \n 0.004716981 \n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/fmBeMY6t.png] (https://i.sstatic.net/fmBeMY6t.png)\n\n\n\n\n(can't add more plots, I guess)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dodo", "profile_url": "https://stats.stackexchange.com/users/516003/dodo", "user_type": "registered"}, "created_at": "2026-08-27T23:58:06+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "AD9037CD-0DDE-403F-9F6A-53908AE97FCD", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AD9037CD-0DDE-403F-9F6A-53908AE97FCD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Alex J", "profile_url": "https://stats.stackexchange.com/users/369002/alex-j", "user_type": "registered"}, "created_at": "2026-08-28T01:38:43+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "3EAA59CF-9ACC-4B3D-9AFA-AB5D8ECE34B4", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3EAA59CF-9ACC-4B3D-9AFA-AB5D8ECE34B4/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "User1865345", "profile_url": "https://stats.stackexchange.com/users/362671/user1865345", "user_type": "registered"}, "created_at": "2026-08-28T04:20:19+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "7E6B4854-2230-4F24-8E0A-5B62915E43E4", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7E6B4854-2230-4F24-8E0A-5B62915E43E4/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dodo", "profile_url": "https://stats.stackexchange.com/users/516003/dodo", "user_type": "registered"}, "created_at": "2026-08-28T15:01:14+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "F19DD4EF-9466-40CB-B4D0-9CE189FEB3F1", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F19DD4EF-9466-40CB-B4D0-9CE189FEB3F1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dodo", "profile_url": "https://stats.stackexchange.com/users/516003/dodo", "user_type": "registered"}, "created_at": "2026-08-28T15:09:40+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "007496D1-0D4A-482B-BAD6-609D5895915F", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/007496D1-0D4A-482B-BAD6-609D5895915F/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dodo", "profile_url": "https://stats.stackexchange.com/users/516003/dodo", "user_type": "registered"}, "created_at": "2026-08-28T20:29:14+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "12B957FD-E529-454A-B047-188DDFB56FEC", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/12B957FD-E529-454A-B047-188DDFB56FEC/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-29T05:37:00+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "4E87FA39-5CD2-406D-9D24-0B402CCCA345", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/4E87FA39-5CD2-406D-9D24-0B402CCCA345/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dodo", "profile_url": "https://stats.stackexchange.com/users/516003/dodo", "user_type": "registered"}, "created_at": "2026-08-29T22:21:59+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "E05011F7-55D9-4351-B560-D118A78E2098", "revision_number": 7, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E05011F7-55D9-4351-B560-D118A78E2098/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dodo", "profile_url": "https://stats.stackexchange.com/users/516003/dodo", "user_type": "registered"}, "created_at": "2026-08-29T23:47:46+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "2A145D07-0EC6-4F2F-846F-61F813A88425", "revision_number": 8, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2A145D07-0EC6-4F2F-846F-61F813A88425/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dodo", "profile_url": "https://stats.stackexchange.com/users/516003/dodo", "user_type": "registered"}, "created_at": "2026-08-30T08:44:53+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "9A297BC1-B323-4435-8926-2848718059A9", "revision_number": 9, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9A297BC1-B323-4435-8926-2848718059A9/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "User1865345", "profile_url": "https://stats.stackexchange.com/users/362671/user1865345", "user_type": "registered"}, "created_at": "2026-08-30T09:13:27+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "67969179-E863-4693-B637-9E30F0487804", "revision_number": 10, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/67969179-E863-4693-B637-9E30F0487804/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676982/glmmtmb-with-beta-distribution-and-repeated-measures-with-high-r-squared-too-g", "split": "validation", "split_group": "4a3fc879ae3d375972ec508b97fe4ec07ecf984d1615b6ef74597b17b4827d41", "tags": ["mixed-model", "repeated-measures", "glmm", "beta-distribution", "glmmtmb"], "thread_id": "stats:676982", "title": "glmmTMB with beta distribution and repeated measures with high R-squared - too good to be true"}}
{"accepted_answer": {"answer_html": "<p>Fix treatment arm <span class=\"math-container\">$d$</span> and, to keep the notation light, let all sums and expectations below be taken within that arm. Write</p>\n<p><span class=\"math-container\">$$\n\\widehat{\\tau}\n=\n\\frac{\\overline{Y}}{\\overline{M}}\n=\n\\frac{\\sum_i Y_i}{\\sum_i M_i},\n\\qquad\n\\tau\n=\n\\frac{E[Y]}{E[M]}.\n$$</span></p>\n<p>A first-order Taylor expansion of <span class=\"math-container\">$f(y,m)=y/m$</span> gives</p>\n<p><span class=\"math-container\">$$\n\\begin{aligned}\n\\widehat{\\tau}-\\tau\n&amp;\\approx\n\\frac{\\overline{Y}-E[Y]}{E[M]}\n-\n\\frac{E[Y]}{E[M]^2}\n\\left(\\overline{M}-E[M]\\right) \\\\[4pt]\n&amp;=\n\\frac{1}{E[M]}\n\\left[\n\\left(\\overline{Y}-E[Y]\\right)\n-\n\\tau\\left(\\overline{M}-E[M]\\right)\n\\right] \\\\[4pt]\n&amp;=\n\\frac{1}{nE[M]}\n\\sum_i\\left(Y_i-\\tau M_i\\right).\n\\end{aligned}\n$$</span></p>\n<p>The last equality uses <span class=\"math-container\">$E[Y]=\\tau E[M]$</span>. Therefore, the influence function is</p>\n<p><span class=\"math-container\">$$\n\\operatorname{IF}_i\n=\n\\frac{Y_i-\\tau M_i}{E[M]}.\n$$</span></p>\n<p>Replacing the unknown quantities with their sample estimates gives</p>\n<p><span class=\"math-container\">$$\n\\widehat{\\operatorname{IF}}_i\n=\n\\frac{Y_i-\\widehat{\\tau}M_i}{\\overline{M}}.\n$$</span></p>\n<p>Thus, apart from the constant scaling factor <span class=\"math-container\">$1/\\overline{M}$</span>, the linearized outcome is</p>\n<p><span class=\"math-container\">$$\nZ_i=Y_i-\\widehat{\\tau}M_i.\n$$</span></p>\n<p>Practically speaking, you can run OLS on the ratios and weight them by the number of trials. I'd use robust covariance in this event too</p>\n<pre class=\"lang-r prettyprint-override\"><code>library(sandwich)\n\nset.seed(0)\ncef &lt;- function(x, d) {\n plogis(-2 + 0.8 * x + 0.3 * d)\n}\n\ntau &lt;- integrate(\n f = function(x) (cef(x, 1) - cef(x, 0)) * dnorm(x, 0, 1),\n lower = -Inf,\n upper = Inf\n)$value\n\nn &lt;- 1000\nsims &lt;- replicate(50000, {\n x1 &lt;- rnorm(n)\n d &lt;- rbinom(n, 1, 0.5)\n M &lt;- pmax(1, rpois(n, 10))\n y &lt;- rbinom(n, M, cef(x1, d))\n r &lt;- y / M\n \n fit &lt;- lm(r ~ x1 + d, weights = M)\n \n est &lt;- coef(fit)[[&quot;d&quot;]]\n se &lt;- sqrt(sandwich::vcovHC(fit, type = &quot;HC0&quot;)[[&quot;d&quot;, &quot;d&quot;]])\n \n lower &lt;- est - qnorm(0.975) * se\n upper &lt;- est + qnorm(0.975) * se\n \n c(\n estimate = est,\n se = se,\n lower = lower,\n upper = upper,\n error = est - tau\n )\n})\n\nsims &lt;- t(sims)\n\nc(\n mean_error = mean(sims[, &quot;error&quot;]),\n coverage = mean(\n sims[, &quot;lower&quot;] &lt;= tau &amp;\n tau &lt;= sims[, &quot;upper&quot;]\n )\n)\n#&gt; mean_error coverage \n#&gt; -5.571571e-05 9.514200e-01\n</code></pre>\n<p><sup>Created on 2026-09-15 with <a href=\"https://reprex.tidyverse.org\" rel=\"noreferrer\">reprex v2.1.1</a></sup></p>\n", "answer_id": 677181, "answer_text": "Fix treatment arm $d$ and, to keep the notation light, let all sums and expectations below be taken within that arm. Write\n\n\n\n\n$$\n\\widehat{\\tau}\n=\n\\frac{\\overline{Y}}{\\overline{M}}\n=\n\\frac{\\sum_i Y_i}{\\sum_i M_i},\n\\qquad\n\\tau\n=\n\\frac{E[Y]}{E[M]}.\n$$\n\n\n\n\nA first-order Taylor expansion of $f(y,m)=y/m$ gives\n\n\n\n\n$$\n\\begin{aligned}\n\\widehat{\\tau}-\\tau\n&\\approx\n\\frac{\\overline{Y}-E[Y]}{E[M]}\n-\n\\frac{E[Y]}{E[M]^2}\n\\left(\\overline{M}-E[M]\\right) \\\\[4pt]\n&=\n\\frac{1}{E[M]}\n\\left[\n\\left(\\overline{Y}-E[Y]\\right)\n-\n\\tau\\left(\\overline{M}-E[M]\\right)\n\\right] \\\\[4pt]\n&=\n\\frac{1}{nE[M]}\n\\sum_i\\left(Y_i-\\tau M_i\\right).\n\\end{aligned}\n$$\n\n\n\n\nThe last equality uses $E[Y]=\\tau E[M]$. Therefore, the influence function is\n\n\n\n\n$$\n\\operatorname{IF}_i\n=\n\\frac{Y_i-\\tau M_i}{E[M]}.\n$$\n\n\n\n\nReplacing the unknown quantities with their sample estimates gives\n\n\n\n\n$$\n\\widehat{\\operatorname{IF}}_i\n=\n\\frac{Y_i-\\widehat{\\tau}M_i}{\\overline{M}}.\n$$\n\n\n\n\nThus, apart from the constant scaling factor $1/\\overline{M}$, the linearized outcome is\n\n\n\n\n$$\nZ_i=Y_i-\\widehat{\\tau}M_i.\n$$\n\n\n\n\nPractically speaking, you can run OLS on the ratios and weight them by the number of trials. I'd use robust covariance in this event too\n\n\n\n\nlibrary(sandwich)\n\nset.seed(0)\ncef <- function(x, d) {\n plogis(-2 + 0.8 * x + 0.3 * d)\n}\n\ntau <- integrate(\n f = function(x) (cef(x, 1) - cef(x, 0)) * dnorm(x, 0, 1),\n lower = -Inf,\n upper = Inf\n)$value\n\nn <- 1000\nsims <- replicate(50000, {\n x1 <- rnorm(n)\n d <- rbinom(n, 1, 0.5)\n M <- pmax(1, rpois(n, 10))\n y <- rbinom(n, M, cef(x1, d))\n r <- y / M\n \n fit <- lm(r ~ x1 + d, weights = M)\n \n est <- coef(fit)[[\"d\"]]\n se <- sqrt(sandwich::vcovHC(fit, type = \"HC0\")[[\"d\", \"d\"]])\n \n lower <- est - qnorm(0.975) * se\n upper <- est + qnorm(0.975) * se\n \n c(\n estimate = est,\n se = se,\n lower = lower,\n upper = upper,\n error = est - tau\n )\n})\n\nsims <- t(sims)\n\nc(\n mean_error = mean(sims[, \"error\"]),\n coverage = mean(\n sims[, \"lower\"] <= tau &\n tau <= sims[, \"upper\"]\n )\n)\n#> mean_error coverage \n#> -5.571571e-05 9.514200e-01\n\n\n\n\n\nCreated on 2026-09-15 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/677181", "author": "Demetri Pananos", "author_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-15T16:27:34+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677179, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Demetri Pananos", "profile_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "user_type": "registered"}, "created_at": "2026-09-15T16:27:34+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "AC30AD7E-7B7F-4D55-B05C-76A70A413D78", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AC30AD7E-7B7F-4D55-B05C-76A70A413D78/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Demetri Pananos", "profile_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "user_type": "registered"}, "created_at": "2026-09-15T16:35:13+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "755739D7-7C88-4D82-AD57-75C2AE33AFBC", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/755739D7-7C88-4D82-AD57-75C2AE33AFBC/view-source"}], "score": 6, "updated_at": "2026-09-15T16:35:13+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "library(sandwich)\n\nset.seed(0)\ncef <- function(x, d) {\n plogis(-2 + 0.8 * x + 0.3 * d)\n}\n\ntau <- integrate(\n f = function(x) (cef(x, 1) - cef(x, 0)) * dnorm(x, 0, 1),\n lower = -Inf,\n upper = Inf\n)$value\n\nn <- 1000\nsims <- replicate(50000, {\n x1 <- rnorm(n)\n d <- rbinom(n, 1, 0.5)\n M <- pmax(1, rpois(n, 10))\n y <- rbinom(n, M, cef(x1, d))\n r <- y / M\n \n fit <- lm(r ~ x1 + d, weights = M)\n \n est <- coef(fit)[[\"d\"]]\n se <- sqrt(sandwich::vcovHC(fit, type = \"HC0\")[[\"d\", \"d\"]])\n \n lower <- est - qnorm(0.975) * se\n upper <- est + qnorm(0.975) * se\n \n c(\n estimate = est,\n se = se,\n lower = lower,\n upper = upper,\n error = est - tau\n )\n})\n\nsims <- t(sims)\n\nc(\n mean_error = mean(sims[, \"error\"]),\n coverage = mean(\n sims[, \"lower\"] <= tau &\n tau <= sims[, \"upper\"]\n )\n)\n#> mean_error coverage \n#> -5.571571e-05 9.514200e-01\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677181, "sha256": "81de0612369946033ca8dc22b444077bc3b93be2cce4467298145c37dff0cdb6", "source_url": "https://stats.stackexchange.com/a/677181"}], "other_answers": [], "product": "code_qa", "question": "In my workplace, I came across an idea that OLS can be retooled to solve ratio metric inference problems.\n\n\n\n\nWhen I think of $k_i$ successes out of $m_i$ trials for individual $i$, this seems to be a perfect use case for binomial regression. Where your chief interest is estimating the conditional probability of success. Its strength, natively handling non-linearity, is also its weakness: Extracting the marginal probability of success is a nontrivial operation; marginalization via G-computation would be needed:\n$$logit(K=k|M=m, X=x, d=1) - logit(K=k|M=m, X=x, d=0)$$\n\n\n\n\nAnd this is a large computational burden to assume with millions or billions of observations. So, I've been pointed to the OLS solution, which I understand to be based on the \"delta method\", correcting the linear solution with gradient information to accommodate curvature in the nonlinearity (ratio function), through the Taylor Series Expansion.\n\n\n\n\nNaively, we have two options for OLS.\n\n\n\n\nFirst, infer in the ratio space directly. But this approach completely mutes the number of trials and biases inference when $corr(K, M)$ exists.\n\n\n\n\n$$ \\frac{k_i}{m_i} = \\alpha + \\lambda d_i + \\beta X +\\epsilon $$\n\n\n\n\nThe second naive option is to infer the difference of global ratios directly where $D_j$ is the binary design vector for treatment exposure.This is equally problematic due to a sample size of one.\n\n\n\n\n$$ \\frac{\\sum_{j=1} K_j D_j}{\\sum_{j=1} M_j D_j} - \\frac{\\sum_{j=1} K_j (1-D_j)}{\\sum_{j=1} M_j (1-D_j)} = \\alpha + \\lambda d_i + \\beta X +\\epsilon $$\n\n\n\n\nThe end solution seems to address the bias shortcoming in naive approach 1 and the variance shortcoming in naive solution 2; it has two parts, computing $z_i$ as the difference between the actual successes and expected successes, and regressing $z_i$ via OLS given treatment exposure among other covariates.\n\n\n\n\n$$ z_i = k_i - (\\frac{\\sum_{j=1} K_j}{\\sum_{j=1} M_j}) m_i $$\n\n\n\n\n$$ z_i = \\alpha + \\lambda d_i + \\beta X_i +\\epsilon $$\n\n\n\n\nIf all of the above, is correct, and that's a big if, where I'm lost at is seeing the connection between the $z_i$ form and the Taylor Series Expansion.\n\n\n\n\nQuestion: How does the TSE prove $z_i$ to be the correct solution accounting for the nonlinearity in the ratio function?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677179", "selected_answer": {"answer_html": "<p>Fix treatment arm <span class=\"math-container\">$d$</span> and, to keep the notation light, let all sums and expectations below be taken within that arm. Write</p>\n<p><span class=\"math-container\">$$\n\\widehat{\\tau}\n=\n\\frac{\\overline{Y}}{\\overline{M}}\n=\n\\frac{\\sum_i Y_i}{\\sum_i M_i},\n\\qquad\n\\tau\n=\n\\frac{E[Y]}{E[M]}.\n$$</span></p>\n<p>A first-order Taylor expansion of <span class=\"math-container\">$f(y,m)=y/m$</span> gives</p>\n<p><span class=\"math-container\">$$\n\\begin{aligned}\n\\widehat{\\tau}-\\tau\n&amp;\\approx\n\\frac{\\overline{Y}-E[Y]}{E[M]}\n-\n\\frac{E[Y]}{E[M]^2}\n\\left(\\overline{M}-E[M]\\right) \\\\[4pt]\n&amp;=\n\\frac{1}{E[M]}\n\\left[\n\\left(\\overline{Y}-E[Y]\\right)\n-\n\\tau\\left(\\overline{M}-E[M]\\right)\n\\right] \\\\[4pt]\n&amp;=\n\\frac{1}{nE[M]}\n\\sum_i\\left(Y_i-\\tau M_i\\right).\n\\end{aligned}\n$$</span></p>\n<p>The last equality uses <span class=\"math-container\">$E[Y]=\\tau E[M]$</span>. Therefore, the influence function is</p>\n<p><span class=\"math-container\">$$\n\\operatorname{IF}_i\n=\n\\frac{Y_i-\\tau M_i}{E[M]}.\n$$</span></p>\n<p>Replacing the unknown quantities with their sample estimates gives</p>\n<p><span class=\"math-container\">$$\n\\widehat{\\operatorname{IF}}_i\n=\n\\frac{Y_i-\\widehat{\\tau}M_i}{\\overline{M}}.\n$$</span></p>\n<p>Thus, apart from the constant scaling factor <span class=\"math-container\">$1/\\overline{M}$</span>, the linearized outcome is</p>\n<p><span class=\"math-container\">$$\nZ_i=Y_i-\\widehat{\\tau}M_i.\n$$</span></p>\n<p>Practically speaking, you can run OLS on the ratios and weight them by the number of trials. I'd use robust covariance in this event too</p>\n<pre class=\"lang-r prettyprint-override\"><code>library(sandwich)\n\nset.seed(0)\ncef &lt;- function(x, d) {\n plogis(-2 + 0.8 * x + 0.3 * d)\n}\n\ntau &lt;- integrate(\n f = function(x) (cef(x, 1) - cef(x, 0)) * dnorm(x, 0, 1),\n lower = -Inf,\n upper = Inf\n)$value\n\nn &lt;- 1000\nsims &lt;- replicate(50000, {\n x1 &lt;- rnorm(n)\n d &lt;- rbinom(n, 1, 0.5)\n M &lt;- pmax(1, rpois(n, 10))\n y &lt;- rbinom(n, M, cef(x1, d))\n r &lt;- y / M\n \n fit &lt;- lm(r ~ x1 + d, weights = M)\n \n est &lt;- coef(fit)[[&quot;d&quot;]]\n se &lt;- sqrt(sandwich::vcovHC(fit, type = &quot;HC0&quot;)[[&quot;d&quot;, &quot;d&quot;]])\n \n lower &lt;- est - qnorm(0.975) * se\n upper &lt;- est + qnorm(0.975) * se\n \n c(\n estimate = est,\n se = se,\n lower = lower,\n upper = upper,\n error = est - tau\n )\n})\n\nsims &lt;- t(sims)\n\nc(\n mean_error = mean(sims[, &quot;error&quot;]),\n coverage = mean(\n sims[, &quot;lower&quot;] &lt;= tau &amp;\n tau &lt;= sims[, &quot;upper&quot;]\n )\n)\n#&gt; mean_error coverage \n#&gt; -5.571571e-05 9.514200e-01\n</code></pre>\n<p><sup>Created on 2026-09-15 with <a href=\"https://reprex.tidyverse.org\" rel=\"noreferrer\">reprex v2.1.1</a></sup></p>\n", "answer_id": 677181, "answer_text": "Fix treatment arm $d$ and, to keep the notation light, let all sums and expectations below be taken within that arm. Write\n\n\n\n\n$$\n\\widehat{\\tau}\n=\n\\frac{\\overline{Y}}{\\overline{M}}\n=\n\\frac{\\sum_i Y_i}{\\sum_i M_i},\n\\qquad\n\\tau\n=\n\\frac{E[Y]}{E[M]}.\n$$\n\n\n\n\nA first-order Taylor expansion of $f(y,m)=y/m$ gives\n\n\n\n\n$$\n\\begin{aligned}\n\\widehat{\\tau}-\\tau\n&\\approx\n\\frac{\\overline{Y}-E[Y]}{E[M]}\n-\n\\frac{E[Y]}{E[M]^2}\n\\left(\\overline{M}-E[M]\\right) \\\\[4pt]\n&=\n\\frac{1}{E[M]}\n\\left[\n\\left(\\overline{Y}-E[Y]\\right)\n-\n\\tau\\left(\\overline{M}-E[M]\\right)\n\\right] \\\\[4pt]\n&=\n\\frac{1}{nE[M]}\n\\sum_i\\left(Y_i-\\tau M_i\\right).\n\\end{aligned}\n$$\n\n\n\n\nThe last equality uses $E[Y]=\\tau E[M]$. Therefore, the influence function is\n\n\n\n\n$$\n\\operatorname{IF}_i\n=\n\\frac{Y_i-\\tau M_i}{E[M]}.\n$$\n\n\n\n\nReplacing the unknown quantities with their sample estimates gives\n\n\n\n\n$$\n\\widehat{\\operatorname{IF}}_i\n=\n\\frac{Y_i-\\widehat{\\tau}M_i}{\\overline{M}}.\n$$\n\n\n\n\nThus, apart from the constant scaling factor $1/\\overline{M}$, the linearized outcome is\n\n\n\n\n$$\nZ_i=Y_i-\\widehat{\\tau}M_i.\n$$\n\n\n\n\nPractically speaking, you can run OLS on the ratios and weight them by the number of trials. I'd use robust covariance in this event too\n\n\n\n\nlibrary(sandwich)\n\nset.seed(0)\ncef <- function(x, d) {\n plogis(-2 + 0.8 * x + 0.3 * d)\n}\n\ntau <- integrate(\n f = function(x) (cef(x, 1) - cef(x, 0)) * dnorm(x, 0, 1),\n lower = -Inf,\n upper = Inf\n)$value\n\nn <- 1000\nsims <- replicate(50000, {\n x1 <- rnorm(n)\n d <- rbinom(n, 1, 0.5)\n M <- pmax(1, rpois(n, 10))\n y <- rbinom(n, M, cef(x1, d))\n r <- y / M\n \n fit <- lm(r ~ x1 + d, weights = M)\n \n est <- coef(fit)[[\"d\"]]\n se <- sqrt(sandwich::vcovHC(fit, type = \"HC0\")[[\"d\", \"d\"]])\n \n lower <- est - qnorm(0.975) * se\n upper <- est + qnorm(0.975) * se\n \n c(\n estimate = est,\n se = se,\n lower = lower,\n upper = upper,\n error = est - tau\n )\n})\n\nsims <- t(sims)\n\nc(\n mean_error = mean(sims[, \"error\"]),\n coverage = mean(\n sims[, \"lower\"] <= tau &\n tau <= sims[, \"upper\"]\n )\n)\n#> mean_error coverage \n#> -5.571571e-05 9.514200e-01\n\n\n\n\n\nCreated on 2026-09-15 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/677181", "author": "Demetri Pananos", "author_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-15T16:27:34+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677179, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Demetri Pananos", "profile_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "user_type": "registered"}, "created_at": "2026-09-15T16:27:34+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "AC30AD7E-7B7F-4D55-B05C-76A70A413D78", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AC30AD7E-7B7F-4D55-B05C-76A70A413D78/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Demetri Pananos", "profile_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "user_type": "registered"}, "created_at": "2026-09-15T16:35:13+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "755739D7-7C88-4D82-AD57-75C2AE33AFBC", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/755739D7-7C88-4D82-AD57-75C2AE33AFBC/view-source"}], "score": 6, "updated_at": "2026-09-15T16:35:13+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "validation", "thread": {"accepted_answer_id": 677181, "answers": [{"answer_html": "<p>Fix treatment arm <span class=\"math-container\">$d$</span> and, to keep the notation light, let all sums and expectations below be taken within that arm. Write</p>\n<p><span class=\"math-container\">$$\n\\widehat{\\tau}\n=\n\\frac{\\overline{Y}}{\\overline{M}}\n=\n\\frac{\\sum_i Y_i}{\\sum_i M_i},\n\\qquad\n\\tau\n=\n\\frac{E[Y]}{E[M]}.\n$$</span></p>\n<p>A first-order Taylor expansion of <span class=\"math-container\">$f(y,m)=y/m$</span> gives</p>\n<p><span class=\"math-container\">$$\n\\begin{aligned}\n\\widehat{\\tau}-\\tau\n&amp;\\approx\n\\frac{\\overline{Y}-E[Y]}{E[M]}\n-\n\\frac{E[Y]}{E[M]^2}\n\\left(\\overline{M}-E[M]\\right) \\\\[4pt]\n&amp;=\n\\frac{1}{E[M]}\n\\left[\n\\left(\\overline{Y}-E[Y]\\right)\n-\n\\tau\\left(\\overline{M}-E[M]\\right)\n\\right] \\\\[4pt]\n&amp;=\n\\frac{1}{nE[M]}\n\\sum_i\\left(Y_i-\\tau M_i\\right).\n\\end{aligned}\n$$</span></p>\n<p>The last equality uses <span class=\"math-container\">$E[Y]=\\tau E[M]$</span>. Therefore, the influence function is</p>\n<p><span class=\"math-container\">$$\n\\operatorname{IF}_i\n=\n\\frac{Y_i-\\tau M_i}{E[M]}.\n$$</span></p>\n<p>Replacing the unknown quantities with their sample estimates gives</p>\n<p><span class=\"math-container\">$$\n\\widehat{\\operatorname{IF}}_i\n=\n\\frac{Y_i-\\widehat{\\tau}M_i}{\\overline{M}}.\n$$</span></p>\n<p>Thus, apart from the constant scaling factor <span class=\"math-container\">$1/\\overline{M}$</span>, the linearized outcome is</p>\n<p><span class=\"math-container\">$$\nZ_i=Y_i-\\widehat{\\tau}M_i.\n$$</span></p>\n<p>Practically speaking, you can run OLS on the ratios and weight them by the number of trials. I'd use robust covariance in this event too</p>\n<pre class=\"lang-r prettyprint-override\"><code>library(sandwich)\n\nset.seed(0)\ncef &lt;- function(x, d) {\n plogis(-2 + 0.8 * x + 0.3 * d)\n}\n\ntau &lt;- integrate(\n f = function(x) (cef(x, 1) - cef(x, 0)) * dnorm(x, 0, 1),\n lower = -Inf,\n upper = Inf\n)$value\n\nn &lt;- 1000\nsims &lt;- replicate(50000, {\n x1 &lt;- rnorm(n)\n d &lt;- rbinom(n, 1, 0.5)\n M &lt;- pmax(1, rpois(n, 10))\n y &lt;- rbinom(n, M, cef(x1, d))\n r &lt;- y / M\n \n fit &lt;- lm(r ~ x1 + d, weights = M)\n \n est &lt;- coef(fit)[[&quot;d&quot;]]\n se &lt;- sqrt(sandwich::vcovHC(fit, type = &quot;HC0&quot;)[[&quot;d&quot;, &quot;d&quot;]])\n \n lower &lt;- est - qnorm(0.975) * se\n upper &lt;- est + qnorm(0.975) * se\n \n c(\n estimate = est,\n se = se,\n lower = lower,\n upper = upper,\n error = est - tau\n )\n})\n\nsims &lt;- t(sims)\n\nc(\n mean_error = mean(sims[, &quot;error&quot;]),\n coverage = mean(\n sims[, &quot;lower&quot;] &lt;= tau &amp;\n tau &lt;= sims[, &quot;upper&quot;]\n )\n)\n#&gt; mean_error coverage \n#&gt; -5.571571e-05 9.514200e-01\n</code></pre>\n<p><sup>Created on 2026-09-15 with <a href=\"https://reprex.tidyverse.org\" rel=\"noreferrer\">reprex v2.1.1</a></sup></p>\n", "answer_id": 677181, "answer_text": "Fix treatment arm $d$ and, to keep the notation light, let all sums and expectations below be taken within that arm. Write\n\n\n\n\n$$\n\\widehat{\\tau}\n=\n\\frac{\\overline{Y}}{\\overline{M}}\n=\n\\frac{\\sum_i Y_i}{\\sum_i M_i},\n\\qquad\n\\tau\n=\n\\frac{E[Y]}{E[M]}.\n$$\n\n\n\n\nA first-order Taylor expansion of $f(y,m)=y/m$ gives\n\n\n\n\n$$\n\\begin{aligned}\n\\widehat{\\tau}-\\tau\n&\\approx\n\\frac{\\overline{Y}-E[Y]}{E[M]}\n-\n\\frac{E[Y]}{E[M]^2}\n\\left(\\overline{M}-E[M]\\right) \\\\[4pt]\n&=\n\\frac{1}{E[M]}\n\\left[\n\\left(\\overline{Y}-E[Y]\\right)\n-\n\\tau\\left(\\overline{M}-E[M]\\right)\n\\right] \\\\[4pt]\n&=\n\\frac{1}{nE[M]}\n\\sum_i\\left(Y_i-\\tau M_i\\right).\n\\end{aligned}\n$$\n\n\n\n\nThe last equality uses $E[Y]=\\tau E[M]$. Therefore, the influence function is\n\n\n\n\n$$\n\\operatorname{IF}_i\n=\n\\frac{Y_i-\\tau M_i}{E[M]}.\n$$\n\n\n\n\nReplacing the unknown quantities with their sample estimates gives\n\n\n\n\n$$\n\\widehat{\\operatorname{IF}}_i\n=\n\\frac{Y_i-\\widehat{\\tau}M_i}{\\overline{M}}.\n$$\n\n\n\n\nThus, apart from the constant scaling factor $1/\\overline{M}$, the linearized outcome is\n\n\n\n\n$$\nZ_i=Y_i-\\widehat{\\tau}M_i.\n$$\n\n\n\n\nPractically speaking, you can run OLS on the ratios and weight them by the number of trials. I'd use robust covariance in this event too\n\n\n\n\nlibrary(sandwich)\n\nset.seed(0)\ncef <- function(x, d) {\n plogis(-2 + 0.8 * x + 0.3 * d)\n}\n\ntau <- integrate(\n f = function(x) (cef(x, 1) - cef(x, 0)) * dnorm(x, 0, 1),\n lower = -Inf,\n upper = Inf\n)$value\n\nn <- 1000\nsims <- replicate(50000, {\n x1 <- rnorm(n)\n d <- rbinom(n, 1, 0.5)\n M <- pmax(1, rpois(n, 10))\n y <- rbinom(n, M, cef(x1, d))\n r <- y / M\n \n fit <- lm(r ~ x1 + d, weights = M)\n \n est <- coef(fit)[[\"d\"]]\n se <- sqrt(sandwich::vcovHC(fit, type = \"HC0\")[[\"d\", \"d\"]])\n \n lower <- est - qnorm(0.975) * se\n upper <- est + qnorm(0.975) * se\n \n c(\n estimate = est,\n se = se,\n lower = lower,\n upper = upper,\n error = est - tau\n )\n})\n\nsims <- t(sims)\n\nc(\n mean_error = mean(sims[, \"error\"]),\n coverage = mean(\n sims[, \"lower\"] <= tau &\n tau <= sims[, \"upper\"]\n )\n)\n#> mean_error coverage \n#> -5.571571e-05 9.514200e-01\n\n\n\n\n\nCreated on 2026-09-15 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/677181", "author": "Demetri Pananos", "author_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-15T16:27:34+00:00", "is_accepted": true, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:08.569053+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/ba8a114171cbec551f0a7f4b9f04e95c559131a62357d51e159434d4acc7183d_1790825228829630100_0.json", "raw_sha256": "a03822ca860dd0b0fb0cc402754ae4cdbaad51d18873dfd19aed56ffe1cf7ec8", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=2&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 677179, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Demetri Pananos", "profile_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "user_type": "registered"}, "created_at": "2026-09-15T16:27:34+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "AC30AD7E-7B7F-4D55-B05C-76A70A413D78", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AC30AD7E-7B7F-4D55-B05C-76A70A413D78/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Demetri Pananos", "profile_url": "https://stats.stackexchange.com/users/111259/demetri-pananos", "user_type": "registered"}, "created_at": "2026-09-15T16:35:13+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "755739D7-7C88-4D82-AD57-75C2AE33AFBC", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/755739D7-7C88-4D82-AD57-75C2AE33AFBC/view-source"}], "score": 6, "updated_at": "2026-09-15T16:35:13+00:00"}], "domain": "statistics", "external_links": ["https://reprex.tidyverse.org"], "medical_sensitive": true, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:27:03.428408+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/774052c18cd9e8fa951e893347bfa3c1a85e743fc46ec4667572002cadb10cbf_1790825224163423600_0.json", "raw_sha256": "fe4dd06d3de6c0b1bb33ba88aee0ed4284118e01f76a58dcdce220a4946329b2", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=stats&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "jbuddy_13", "question_author_url": "https://stats.stackexchange.com/users/288172/jbuddy-13", "question_author_user_type": "registered", "question_created_at": "2026-09-15T15:25:50+00:00", "question_html": "<p>In my workplace, I came across an idea that OLS can be retooled to solve ratio metric inference problems.</p>\n<p>When I think of <span class=\"math-container\">$k_i$</span> successes out of <span class=\"math-container\">$m_i$</span> trials for individual <span class=\"math-container\">$i$</span>, this seems to be a perfect use case for binomial regression. Where your chief interest is estimating the conditional probability of success. Its strength, natively handling non-linearity, is also its weakness: Extracting the marginal probability of success is a nontrivial operation; marginalization via G-computation would be needed:\n<span class=\"math-container\">$$logit(K=k|M=m, X=x, d=1) - logit(K=k|M=m, X=x, d=0)$$</span></p>\n<p>And this is a large computational burden to assume with millions or billions of observations. So, I've been pointed to the OLS solution, which I understand to be based on the &quot;delta method&quot;, correcting the linear solution with gradient information to accommodate curvature in the nonlinearity (ratio function), through the Taylor Series Expansion.</p>\n<p>Naively, we have two options for OLS.</p>\n<p>First, infer in the ratio space directly. But this approach completely mutes the number of trials and biases inference when <span class=\"math-container\">$corr(K, M)$</span> exists.</p>\n<p><span class=\"math-container\">$$ \\frac{k_i}{m_i} = \\alpha + \\lambda d_i + \\beta X +\\epsilon $$</span></p>\n<p>The second naive option is to infer the difference of global ratios directly where <span class=\"math-container\">$D_j$</span> is the binary design vector for treatment exposure.This is equally problematic due to a sample size of one.</p>\n<p><span class=\"math-container\">$$ \\frac{\\sum_{j=1} K_j D_j}{\\sum_{j=1} M_j D_j} - \\frac{\\sum_{j=1} K_j (1-D_j)}{\\sum_{j=1} M_j (1-D_j)} = \\alpha + \\lambda d_i + \\beta X +\\epsilon $$</span></p>\n<p>The end solution seems to address the bias shortcoming in naive approach 1 and the variance shortcoming in naive solution 2; it has two parts, computing <span class=\"math-container\">$z_i$</span> as the difference between the actual successes and expected successes, and regressing <span class=\"math-container\">$z_i$</span> via OLS given treatment exposure among other covariates.</p>\n<p><span class=\"math-container\">$$ z_i = k_i - (\\frac{\\sum_{j=1} K_j}{\\sum_{j=1} M_j}) m_i $$</span></p>\n<p><span class=\"math-container\">$$ z_i = \\alpha + \\lambda d_i + \\beta X_i +\\epsilon $$</span></p>\n<p>If all of the above, is correct, and that's a <strong>big if</strong>, where I'm lost at is seeing the connection between the <span class=\"math-container\">$z_i$</span> form and the Taylor Series Expansion.</p>\n<p><strong>Question</strong>: <em>How does the TSE prove <span class=\"math-container\">$z_i$</span> to be the correct solution accounting for the nonlinearity in the ratio function?</em></p>\n", "question_id": 677179, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "In my workplace, I came across an idea that OLS can be retooled to solve ratio metric inference problems.\n\n\n\n\nWhen I think of $k_i$ successes out of $m_i$ trials for individual $i$, this seems to be a perfect use case for binomial regression. Where your chief interest is estimating the conditional probability of success. Its strength, natively handling non-linearity, is also its weakness: Extracting the marginal probability of success is a nontrivial operation; marginalization via G-computation would be needed:\n$$logit(K=k|M=m, X=x, d=1) - logit(K=k|M=m, X=x, d=0)$$\n\n\n\n\nAnd this is a large computational burden to assume with millions or billions of observations. So, I've been pointed to the OLS solution, which I understand to be based on the \"delta method\", correcting the linear solution with gradient information to accommodate curvature in the nonlinearity (ratio function), through the Taylor Series Expansion.\n\n\n\n\nNaively, we have two options for OLS.\n\n\n\n\nFirst, infer in the ratio space directly. But this approach completely mutes the number of trials and biases inference when $corr(K, M)$ exists.\n\n\n\n\n$$ \\frac{k_i}{m_i} = \\alpha + \\lambda d_i + \\beta X +\\epsilon $$\n\n\n\n\nThe second naive option is to infer the difference of global ratios directly where $D_j$ is the binary design vector for treatment exposure.This is equally problematic due to a sample size of one.\n\n\n\n\n$$ \\frac{\\sum_{j=1} K_j D_j}{\\sum_{j=1} M_j D_j} - \\frac{\\sum_{j=1} K_j (1-D_j)}{\\sum_{j=1} M_j (1-D_j)} = \\alpha + \\lambda d_i + \\beta X +\\epsilon $$\n\n\n\n\nThe end solution seems to address the bias shortcoming in naive approach 1 and the variance shortcoming in naive solution 2; it has two parts, computing $z_i$ as the difference between the actual successes and expected successes, and regressing $z_i$ via OLS given treatment exposure among other covariates.\n\n\n\n\n$$ z_i = k_i - (\\frac{\\sum_{j=1} K_j}{\\sum_{j=1} M_j}) m_i $$\n\n\n\n\n$$ z_i = \\alpha + \\lambda d_i + \\beta X_i +\\epsilon $$\n\n\n\n\nIf all of the above, is correct, and that's a big if, where I'm lost at is seeing the connection between the $z_i$ form and the Taylor Series Expansion.\n\n\n\n\nQuestion: How does the TSE prove $z_i$ to be the correct solution accounting for the nonlinearity in the ratio function?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "jbuddy_13", "profile_url": "https://stats.stackexchange.com/users/288172/jbuddy-13", "user_type": "registered"}, "created_at": "2026-09-15T15:25:50+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "E477C4E5-8119-4D6D-8EB7-06E7F1147CE1", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E477C4E5-8119-4D6D-8EB7-06E7F1147CE1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "jbuddy_13", "profile_url": "https://stats.stackexchange.com/users/288172/jbuddy-13", "user_type": "registered"}, "created_at": "2026-09-15T15:51:31+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "7C5055B2-E916-464C-9092-9B0B51019D05", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7C5055B2-E916-464C-9092-9B0B51019D05/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-15T23:37:38+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "0015EC33-1DEB-456C-8D58-1E9522CF13C1", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/0015EC33-1DEB-456C-8D58-1E9522CF13C1/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677179/delta-method-for-linearizing-success-rate-inference", "split": "validation", "split_group": "bb14fd5ee1c3dd00639ebb6fa31a6ba50a54e417aaf3c07d0873f8be08a6ced7", "tags": ["logistic", "binomial-distribution", "delta-method"], "thread_id": "stats:677179", "title": "Delta method for linearizing success rate inference"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\nfrom math import pi\nimport random\n\n# constants\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\ng = 9.81\n\n# Cauchy problem\n\n# y = [theta_1, theta_2, theta_1_dot, theta_2_dot]\n# y0 = [theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0]\n\n# generating initial conditions for some energy E\n\nnumber_of_initial_conditions = 50\n\ntheta_1_0 = []\n# theta_2_0 = []\ntheta_2_0 = np.linspace(-pi/2, pi/2, number_of_initial_conditions)\ntheta_1_dot_0 = []\ntheta_2_dot_0 = []\n\n# Energy = np.linspace(5,5.6,8) # [0,100] 1.\n# Energy = np.linspace(5.6,6.2,8) # [0,300] 2.\n# Energy = np.linspace(6.2,6.4,8) # [0,500] 3.\n# Energy = np.linspace(6.4,6.8,8) # [0,1000] 4.\n# Energy = np.linspace(5.9,6.3,8) # [0,700] 2-3.\n# Energy = np.linspace(6.3,6.8,12) # [0,1200] 3-4.\n# Energy = np.linspace(5.4,6.8,20) # [0,2000] 0.\n# Energy = np.linspace(5.6, 6.4, 16) # [0,700] 2_3\n# Energy = np.linspace(6.2,6.8,18) # [0,1200] 3_4.\n\n# Energy = [5.865]\nEnergy = [6.09]\n# Energy = [6.075]\n# Energy = [6.095]\n# Energy = [6.079]\n# Energy = [6.12]\n\n# number_of_initial_conditions = 1\n\ntotal_numbers_of_initial_conditions = number_of_initial_conditions*len(Energy)\n\ndef initial_conditions(E, number_of_initial_conditions):\n\n for i in range(number_of_initial_conditions):\n theta_1_0.append(0)\n # theta_2_0.append(np.random.uniform(-pi/4, pi/4))\n theta_2_dot_0.append(0)\n bucket = []\n bucket.append(np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n bucket.append(-np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n theta_1_dot_0.append(bucket[random.randint(0,1)])\n\nfor i in range(len(Energy)):\n initial_conditions(Energy[i], number_of_initial_conditions)\n\ndef f(t,y):\n return [y[2], \n y[3], \n (-g*np.sin(y[0])*(2*m_1+m_2)-g*m_2*np.sin(y[0]-2*y[1])-2*m_2*np.sin(y[0]-y[1])*(y[2]**2*l_1*np.cos(y[0]-y[1])+l_2*y[3]**2))/(l_1*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1]))), \n (2*np.sin(y[0]-y[1])*(np.cos(y[0])*g*(m_1+m_2)+l_1*(m_1+m_2)*y[2]**2+m_2*l_2*y[3]**2*np.cos(y[0]-y[1])))/(l_2*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1])))]\n\n# energy of the system\ndef E(y_1, y_2, y_3, y_4):\n total_energy = 0.5*l_1**2*y_3**2*(m_1+m_2)+0.5*m_2*l_2**2*y_4**2+m_2*l_1*l_2*y_3*y_4*np.cos(y_1-y_2)-l_1*g*np.cos(y_1)*(m_1+m_2)-l_2*m_2*g*np.cos(y_2)+(l_1+l_2)*g*(m_1+m_2)\n return total_energy\n\n# Poincaré section\ndef Poincare_section(total_numbers_of_initial_conditions):\n theta_2 = []\n theta_2_dot = []\n\n colors = []\n\n color = [\n \"#2C3E50\", \"#3A3F64\", \"#484078\", \"#56428D\", \"#6B469E\",\n \"#804AAF\", \"#954EBF\", \"#A753C4\", \"#BA58C8\", \"#CE5DCD\",\n \"#E062C9\", \"#E971B4\", \"#F1809F\", \"#F98F8A\", \"#FFA07A\",\n \"#FF9C65\", \"#FF9850\", \"#FF943B\", \"#FF9026\", \"#FF8C11\",\n \"#F97F0D\", \"#F3730A\", \"#ED6606\", \"#E75A03\", \"#E04E00\",\n \"#D4431E\", \"#C8383C\", \"#BC2D5A\", \"#B02178\", \"#A41596\",\n \"#9710A3\", \"#880EA7\", \"#790CAB\", \"#6A0AAF\", \"#5C08B2\",\n \"#4D06B6\", \"#3E04BA\", \"#2F02BD\", \"#2000C1\", \"#1800B8\",\n \"#1000AF\", \"#0800A6\", \"#00009D\", \"#00008F\", \"#000081\",\n \"#0B006C\", \"#160057\", \"#210043\", \"#2C002E\", \"#37001A\"\n ]\n\n for i in range(total_numbers_of_initial_conditions):\n # color = [\"#\"+''.join([random.choice('0123456789ABCDEF') for r in range(6)])\n # for s in range(1)]\n\n number_of_points = len(solutions[i].t)\n\n for j in range(number_of_points-1):\n if solutions[i].y[0][j] <= 0 and solutions[i].y[0][j+1] >= 0:\n colors.append(color[i])\n theta_2.append(solutions[i].y[1][j+1])\n theta_2_dot.append(solutions[i].y[3][j+1])\n\n for m in range(len(theta_2)):\n plt.scatter((theta_2[m]+np.pi)%(2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n plt.xlabel(r\"$\\theta_2\\ [rad]$\")\n plt.ylabel(r\"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$\")\n plt.show()\n\n# solving the equations of motion\nsolutions = []\n\nerror = 0.001\n\n# defining time interval\nt_span = [0,750]\n\nfor i in range(total_numbers_of_initial_conditions):\n y0 = [theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i]]\n system_energy = E(y0[0], y0[1], y0[2], y0[3])\n print(y0)\n print(system_energy)\n solutions.append(solve_ivp(f, t_span, y0, dense_output=True, rtol = 1e-12, atol = 1e-14))\n number_of_points = len(solutions[i].t)\n \n for j in range(number_of_points):\n solution_energy = E(solutions[i].y[0][j], solutions[i].y[1][j], solutions[i].y[2][j], solutions[i].y[3][j])\n if np.abs(solution_energy - system_energy) > error:\n sys.exit('Maximum energy drift of {} exceeded.'.format(error))\n\nPoincare_section(total_numbers_of_initial_conditions)\n\nx_1 = []\nx_2 = []\ny_1 = []\ny_2 = []\n\nfor i in range(len(solutions[0].t)):\n x_1.append(l_1*np.sin(solutions[0].y[0][i]))\n x_2.append(x_1[i]+l_2*np.sin(solutions[0].y[1][i]))\n y_1.append(-l_1*np.cos(solutions[0].y[0][i]))\n y_2.append(y_1[i]-l_2*np.cos(solutions[0].y[1][i]))\n\nplt.plot(solutions[0].y[0], solutions[0].y[1])\nplt.xlabel(r\"$\\theta_1\\ [rad]$\")\nplt.ylabel(r\"$\\theta_2\\ [rad]$\")\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.show()\nplt.plot(x_2, y_2)\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.plot(x_2, y_2)\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45171, "sha256": "1d67820d96c570166fb54e56067d4cef4f8c2e54fa592f7764a9d6f5c940d00b", "source_url": "https://scicomp.stackexchange.com/questions/45171/poincar%c3%a9-section-for-double-pendulum-code-improvement"}, {"block_index": 0, "code_text": "import time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp, OdeSolution\n\nfrom scipy.constants import g\nfrom scipy.integrate._ivp.ivp import OdeResult\n\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\n\n\ndef initial_conditions(\n E: float, n_initial_conditions: int, rand: np.random.Generator,\n) -> tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n theta_1_0 = np.zeros(n_initial_conditions)\n theta_2_0 = np.linspace(-0.5*np.pi, 0.5*np.pi, n_initial_conditions)\n theta_2_dot_0 = np.zeros(n_initial_conditions)\n\n abs_t10 = np.sqrt(\n 2*(\n (\n E + l_2*m_2*g*np.cos(theta_2_0)\n )/(m_1 + m_2)\n - l_2*g\n )\n )/l_1\n\n theta_1_dot_0 = abs_t10*rand.choice((-1, 1), size=n_initial_conditions)\n\n return theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0\n\n\ndef f(t: float, y: np.ndarray) -> tuple[\n float, float, float, float,\n]:\n y0, y1, y2, y3 = y\n sin_y01 = 2*np.sin(y0 - y1)\n cos_y01 = np.cos(y0 - y1)\n m12m2 = 2*m_1 + m_2\n den = m12m2 - m_2*np.cos(2*y0 - 2*y1)\n y22l1 = y2**2*l_1\n y32l2 = l_2*y3**2\n\n res = (\n y2,\n y3,\n (\n -g*np.sin(y0)*m12m2 - m_2*(\n g*np.sin(y0 - 2*y1)\n + sin_y01*(\n y22l1*cos_y01 + y32l2\n )\n )\n ) / (l_1*den),\n (\n sin_y01*(\n (m_1 + m_2)*(\n np.cos(y0)*g + y22l1\n )\n + m_2*y32l2*cos_y01\n )\n ) / (l_2*den),\n )\n return res\n\n\ndef E(y_1: float, y_2: float, y_3: float, y_4: float) -> float:\n \"\"\"energy of the system\"\"\"\n total_energy = (\n 0.5*l_1**2*y_3**2*(m_1 + m_2)\n + 0.5*m_2*l_2**2*y_4**2\n + m_2*l_1*l_2*y_3*y_4*np.cos(y_1 - y_2)\n - l_1*g*np.cos(y_1)*(m_1 + m_2)\n - l_2*m_2*g*np.cos(y_2)\n + (l_1 + l_2)*g*(m_1 + m_2)\n )\n return total_energy\n\n\ndef plot_poincaré_section(solutions: list[OdeSolution]) -> plt.Figure:\n theta_2 = []\n theta_2_dot = []\n colors = []\n\n color = (\n \"#2C3E50\", \"#3A3F64\", \"#484078\", \"#56428D\", \"#6B469E\",\n \"#804AAF\", \"#954EBF\", \"#A753C4\", \"#BA58C8\", \"#CE5DCD\",\n \"#E062C9\", \"#E971B4\", \"#F1809F\", \"#F98F8A\", \"#FFA07A\",\n \"#FF9C65\", \"#FF9850\", \"#FF943B\", \"#FF9026\", \"#FF8C11\",\n \"#F97F0D\", \"#F3730A\", \"#ED6606\", \"#E75A03\", \"#E04E00\",\n \"#D4431E\", \"#C8383C\", \"#BC2D5A\", \"#B02178\", \"#A41596\",\n \"#9710A3\", \"#880EA7\", \"#790CAB\", \"#6A0AAF\", \"#5C08B2\",\n \"#4D06B6\", \"#3E04BA\", \"#2F02BD\", \"#2000C1\", \"#1800B8\",\n \"#1000AF\", \"#0800A6\", \"#00009D\", \"#00008F\", \"#000081\",\n \"#0B006C\", \"#160057\", \"#210043\", \"#2C002E\", \"#37001A\"\n )\n\n for solution, colori in zip(solutions, color):\n n_points = len(solution.t)\n y0, y1, y2, y3 = solution.y\n\n for j in range(n_points - 1):\n if y0[j] <= 0 <= y0[j + 1]:\n colors.append(colori)\n theta_2.append(y1[j + 1])\n theta_2_dot.append(y3[j + 1])\n\n fig, ax = plt.subplots()\n\n for m in range(len(theta_2)):\n ax.scatter((theta_2[m] + np.pi) % (2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n ax.set_xlabel(r\"$\\theta_2\\ [rad]$\")\n ax.set_ylabel(r\"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$\")\n return fig\n\n\ndef solve_motion_equations(\n theta_1_0: np.ndarray,\n theta_2_0: np.ndarray,\n theta_1_dot_0: np.ndarray,\n theta_2_dot_0: np.ndarray,\n strict: bool = True,\n error_max: float = 1e-3,\n rtol: float = 1e-4, atol: float = 1e-6,\n) -> list[OdeResult]:\n \"\"\"solving the equations of motion\"\"\"\n solutions = []\n\n # defining time interval\n t_span = (0, 750)\n jac_sparsity = np.array(( # All methods but LSODA\n (0, 0, 1, 0),\n (0, 0, 0, 1),\n (1, 1, 1, 1),\n (1, 1, 1, 1),\n ))\n # LSODA band parameters only reduce the Jacobian by one element; probably not worth it\n\n for i in range(len(theta_1_0)):\n y0 = (theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i])\n t0 = time.perf_counter()\n solutions.append(solve_ivp(\n fun=f, t_span=t_span, y0=y0, dense_output=True, method='LSODA',\n # jac_sparsity=jac_sparsity,\n rtol=rtol, atol=atol,\n ))\n t1 = time.perf_counter()\n print(t1 - t0)\n\n system_energy = E(*y0)\n for y in solutions[i].y.T:\n solution_energy = E(*y)\n error = np.abs(solution_energy - system_energy)\n if strict and error > error_max:\n message = f'Energy drift of {error_max} exceeds maximum {error_max}'\n raise ValueError(message)\n\n return solutions\n\n\ndef fill_xy(solutions: list[OdeSolution]) -> tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n x_1 = l_1*np.sin(solutions[0].y[0])\n x_2 = l_2*np.sin(solutions[0].y[1]) + x_1\n y_1 = -l_1*np.cos(solutions[0].y[0])\n y_2 = -l_2*np.cos(solutions[0].y[1]) + y_1\n return x_1, x_2, y_1, y_2\n\n\ndef plot(\n solutions: list[OdeSolution],\n x_1: np.ndarray, x_2: np.ndarray,\n y_1: np.ndarray, y_2: np.ndarray,\n) -> None:\n fig, ax = plt.subplots()\n ax.plot(solutions[0].y[0], solutions[0].y[1])\n ax.set_xlabel(r\"$\\theta_1\\ [rad]$\")\n ax.set_ylabel(r\"$\\theta_2\\ [rad]$\")\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1)\n ax.set_xlabel('x_1')\n ax.set_ylabel('y_1')\n\n fig, ax = plt.subplots()\n ax.plot(x_2, y_2)\n ax.set_xlabel('x_2')\n ax.set_ylabel('y_2')\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1, label='y_1')\n ax.plot(x_2, y_2, label='y_2')\n ax.legend()\n\n\ndef main() -> None:\n n_initial_conditions = 3 # 50\n rand = np.random.default_rng(seed=0)\n\n theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0 = initial_conditions(\n E=6.09, n_initial_conditions=n_initial_conditions, rand=rand,\n )\n solutions = solve_motion_equations(\n theta_1_0=theta_1_0, theta_1_dot_0=theta_1_dot_0,\n theta_2_0=theta_2_0, theta_2_dot_0=theta_2_dot_0,\n error_max=0.1,\n )\n plot_poincaré_section(solutions)\n x_1, x_2, y_1, y_2 = fill_xy(solutions)\n plot(solutions, x_1, x_2, y_1, y_2)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45267, "sha256": "ae3ad9e84c6f094fe7cfe99f0f34dd3421a235cc15f4e45eab8309949d15b321", "source_url": "https://scicomp.stackexchange.com/a/45267"}], "other_answers": [], "product": "code_qa", "question": "I wanted to try numerical analysis of a chaotic system. So I decided to write my own code for the Poincaré section of a double pendulum in Python. The code works and the Poincaré section should be correct, but I can't get a nice picture of the section, like you see in textbooks or on the internet. I don't know if the problem is in the choice of energies, the (number of) initial conditions, or the integration \"time interval\" and steps. Can someone more experienced advise me on a good approach to obtaining nice Poincaré sections? The code can also be improved, so if anyone has any suggestions for improvements, I would be very happy to hear them!\n\n\n\n\nHere is the code: https://github.com/DJopek/chaos/blob/main/double_pendulum.py (https://github.com/DJopek/chaos/blob/main/double_pendulum.py)\n\n\n\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\nfrom math import pi\nimport random\n\n# constants\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\ng = 9.81\n\n# Cauchy problem\n\n# y = [theta_1, theta_2, theta_1_dot, theta_2_dot]\n# y0 = [theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0]\n\n# generating initial conditions for some energy E\n\nnumber_of_initial_conditions = 50\n\ntheta_1_0 = []\n# theta_2_0 = []\ntheta_2_0 = np.linspace(-pi/2, pi/2, number_of_initial_conditions)\ntheta_1_dot_0 = []\ntheta_2_dot_0 = []\n\n# Energy = np.linspace(5,5.6,8) # [0,100] 1.\n# Energy = np.linspace(5.6,6.2,8) # [0,300] 2.\n# Energy = np.linspace(6.2,6.4,8) # [0,500] 3.\n# Energy = np.linspace(6.4,6.8,8) # [0,1000] 4.\n# Energy = np.linspace(5.9,6.3,8) # [0,700] 2-3.\n# Energy = np.linspace(6.3,6.8,12) # [0,1200] 3-4.\n# Energy = np.linspace(5.4,6.8,20) # [0,2000] 0.\n# Energy = np.linspace(5.6, 6.4, 16) # [0,700] 2_3\n# Energy = np.linspace(6.2,6.8,18) # [0,1200] 3_4.\n\n# Energy = [5.865]\nEnergy = [6.09]\n# Energy = [6.075]\n# Energy = [6.095]\n# Energy = [6.079]\n# Energy = [6.12]\n\n# number_of_initial_conditions = 1\n\ntotal_numbers_of_initial_conditions = number_of_initial_conditions*len(Energy)\n\ndef initial_conditions(E, number_of_initial_conditions):\n\n for i in range(number_of_initial_conditions):\n theta_1_0.append(0)\n # theta_2_0.append(np.random.uniform(-pi/4, pi/4))\n theta_2_dot_0.append(0)\n bucket = []\n bucket.append(np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n bucket.append(-np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n theta_1_dot_0.append(bucket[random.randint(0,1)])\n\nfor i in range(len(Energy)):\n initial_conditions(Energy[i], number_of_initial_conditions)\n\ndef f(t,y):\n return [y[2], \n y[3], \n (-g*np.sin(y[0])*(2*m_1+m_2)-g*m_2*np.sin(y[0]-2*y[1])-2*m_2*np.sin(y[0]-y[1])*(y[2]**2*l_1*np.cos(y[0]-y[1])+l_2*y[3]**2))/(l_1*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1]))), \n (2*np.sin(y[0]-y[1])*(np.cos(y[0])*g*(m_1+m_2)+l_1*(m_1+m_2)*y[2]**2+m_2*l_2*y[3]**2*np.cos(y[0]-y[1])))/(l_2*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1])))]\n\n# energy of the system\ndef E(y_1, y_2, y_3, y_4):\n total_energy = 0.5*l_1**2*y_3**2*(m_1+m_2)+0.5*m_2*l_2**2*y_4**2+m_2*l_1*l_2*y_3*y_4*np.cos(y_1-y_2)-l_1*g*np.cos(y_1)*(m_1+m_2)-l_2*m_2*g*np.cos(y_2)+(l_1+l_2)*g*(m_1+m_2)\n return total_energy\n\n# Poincaré section\ndef Poincare_section(total_numbers_of_initial_conditions):\n theta_2 = []\n theta_2_dot = []\n\n colors = []\n\n color = [\n \"#2C3E50\", \"#3A3F64\", \"#484078\", \"#56428D\", \"#6B469E\",\n \"#804AAF\", \"#954EBF\", \"#A753C4\", \"#BA58C8\", \"#CE5DCD\",\n \"#E062C9\", \"#E971B4\", \"#F1809F\", \"#F98F8A\", \"#FFA07A\",\n \"#FF9C65\", \"#FF9850\", \"#FF943B\", \"#FF9026\", \"#FF8C11\",\n \"#F97F0D\", \"#F3730A\", \"#ED6606\", \"#E75A03\", \"#E04E00\",\n \"#D4431E\", \"#C8383C\", \"#BC2D5A\", \"#B02178\", \"#A41596\",\n \"#9710A3\", \"#880EA7\", \"#790CAB\", \"#6A0AAF\", \"#5C08B2\",\n \"#4D06B6\", \"#3E04BA\", \"#2F02BD\", \"#2000C1\", \"#1800B8\",\n \"#1000AF\", \"#0800A6\", \"#00009D\", \"#00008F\", \"#000081\",\n \"#0B006C\", \"#160057\", \"#210043\", \"#2C002E\", \"#37001A\"\n ]\n\n for i in range(total_numbers_of_initial_conditions):\n # color = [\"#\"+''.join([random.choice('0123456789ABCDEF') for r in range(6)])\n # for s in range(1)]\n\n number_of_points = len(solutions[i].t)\n\n for j in range(number_of_points-1):\n if solutions[i].y[0][j] <= 0 and solutions[i].y[0][j+1] >= 0:\n colors.append(color[i])\n theta_2.append(solutions[i].y[1][j+1])\n theta_2_dot.append(solutions[i].y[3][j+1])\n\n for m in range(len(theta_2)):\n plt.scatter((theta_2[m]+np.pi)%(2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n plt.xlabel(r\"$\\theta_2\\ [rad]$\")\n plt.ylabel(r\"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$\")\n plt.show()\n\n# solving the equations of motion\nsolutions = []\n\nerror = 0.001\n\n# defining time interval\nt_span = [0,750]\n\nfor i in range(total_numbers_of_initial_conditions):\n y0 = [theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i]]\n system_energy = E(y0[0], y0[1], y0[2], y0[3])\n print(y0)\n print(system_energy)\n solutions.append(solve_ivp(f, t_span, y0, dense_output=True, rtol = 1e-12, atol = 1e-14))\n number_of_points = len(solutions[i].t)\n \n for j in range(number_of_points):\n solution_energy = E(solutions[i].y[0][j], solutions[i].y[1][j], solutions[i].y[2][j], solutions[i].y[3][j])\n if np.abs(solution_energy - system_energy) > error:\n sys.exit('Maximum energy drift of {} exceeded.'.format(error))\n\nPoincare_section(total_numbers_of_initial_conditions)\n\nx_1 = []\nx_2 = []\ny_1 = []\ny_2 = []\n\nfor i in range(len(solutions[0].t)):\n x_1.append(l_1*np.sin(solutions[0].y[0][i]))\n x_2.append(x_1[i]+l_2*np.sin(solutions[0].y[1][i]))\n y_1.append(-l_1*np.cos(solutions[0].y[0][i]))\n y_2.append(y_1[i]-l_2*np.cos(solutions[0].y[1][i]))\n\nplt.plot(solutions[0].y[0], solutions[0].y[1])\nplt.xlabel(r\"$\\theta_1\\ [rad]$\")\nplt.ylabel(r\"$\\theta_2\\ [rad]$\")\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.show()\nplt.plot(x_2, y_2)\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.plot(x_2, y_2)\nplt.show()\n\n\n\n\n\nPoincaré section obtained by conditions in the code:\n[image: Poincaré section obtained by conditions in the code; source: https://i.sstatic.net/U0nOulED.png] (https://i.sstatic.net/U0nOulED.png)\n\n\n\n\nEDIT:\nPoincaré section obtained by conditions in the code with labels[image: Poincaré section obtained by conditions in the code with labels; source: https://i.sstatic.net/oJaBUfA4.png] (https://i.sstatic.net/oJaBUfA4.png)", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45171", "selected_answer": {"answer_html": "<blockquote>\n<p>Poincaré section obtained by conditions in the code</p>\n</blockquote>\n<p>I very much cannot reproduce what you've generated, after refactoring - I suspect due to moving to the more sophisticated LSODA and its accompanying parameters. I get results more similar to the resonances seen in e.g. <a href=\"https://duetosymmetry.com/tool/poincare-section-clicker-toy/\" rel=\"nofollow noreferrer\">Leo Stein's Poincaré sections</a>.</p>\n<blockquote>\n<p>The code can also be improved, so if anyone has any suggestions</p>\n</blockquote>\n<p>Well... There's a lot. Since this is the Computational Science site and not the Code Review site, I will elide much of my feedback by saying &quot;improve your Python&quot;. For the numerics:</p>\n<ul>\n<li>Your <code>g</code> is both wrong and unnecessary; get the correct value from Scipy instead</li>\n<li>Don't use the <code>math</code> module; stick to Numpy</li>\n<li><code>f()</code> is both pretty slow and wholly illegible. It can be somewhat sped up by identifying common expressions, and should be broken up into many more lines. The same applies to <code>E()</code>.</li>\n<li>The current parameters to <code>solve_ivp</code> produce a very slow solution. Switch to LSODA and go easy on those tolerances.</li>\n<li>For plotting, only call <code>plt.show()</code> once.</li>\n</ul>\n<p><a href=\"https://i.sstatic.net/INKhjIWk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/INKhjIWk.png\" alt=\"poincare\" /></a></p>\n<pre class=\"lang-py prettyprint-override\"><code>import time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp, OdeSolution\n\nfrom scipy.constants import g\nfrom scipy.integrate._ivp.ivp import OdeResult\n\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\n\n\ndef initial_conditions(\n E: float, n_initial_conditions: int, rand: np.random.Generator,\n) -&gt; tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n theta_1_0 = np.zeros(n_initial_conditions)\n theta_2_0 = np.linspace(-0.5*np.pi, 0.5*np.pi, n_initial_conditions)\n theta_2_dot_0 = np.zeros(n_initial_conditions)\n\n abs_t10 = np.sqrt(\n 2*(\n (\n E + l_2*m_2*g*np.cos(theta_2_0)\n )/(m_1 + m_2)\n - l_2*g\n )\n )/l_1\n\n theta_1_dot_0 = abs_t10*rand.choice((-1, 1), size=n_initial_conditions)\n\n return theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0\n\n\ndef f(t: float, y: np.ndarray) -&gt; tuple[\n float, float, float, float,\n]:\n y0, y1, y2, y3 = y\n sin_y01 = 2*np.sin(y0 - y1)\n cos_y01 = np.cos(y0 - y1)\n m12m2 = 2*m_1 + m_2\n den = m12m2 - m_2*np.cos(2*y0 - 2*y1)\n y22l1 = y2**2*l_1\n y32l2 = l_2*y3**2\n\n res = (\n y2,\n y3,\n (\n -g*np.sin(y0)*m12m2 - m_2*(\n g*np.sin(y0 - 2*y1)\n + sin_y01*(\n y22l1*cos_y01 + y32l2\n )\n )\n ) / (l_1*den),\n (\n sin_y01*(\n (m_1 + m_2)*(\n np.cos(y0)*g + y22l1\n )\n + m_2*y32l2*cos_y01\n )\n ) / (l_2*den),\n )\n return res\n\n\ndef E(y_1: float, y_2: float, y_3: float, y_4: float) -&gt; float:\n &quot;&quot;&quot;energy of the system&quot;&quot;&quot;\n total_energy = (\n 0.5*l_1**2*y_3**2*(m_1 + m_2)\n + 0.5*m_2*l_2**2*y_4**2\n + m_2*l_1*l_2*y_3*y_4*np.cos(y_1 - y_2)\n - l_1*g*np.cos(y_1)*(m_1 + m_2)\n - l_2*m_2*g*np.cos(y_2)\n + (l_1 + l_2)*g*(m_1 + m_2)\n )\n return total_energy\n\n\ndef plot_poincaré_section(solutions: list[OdeSolution]) -&gt; plt.Figure:\n theta_2 = []\n theta_2_dot = []\n colors = []\n\n color = (\n &quot;#2C3E50&quot;, &quot;#3A3F64&quot;, &quot;#484078&quot;, &quot;#56428D&quot;, &quot;#6B469E&quot;,\n &quot;#804AAF&quot;, &quot;#954EBF&quot;, &quot;#A753C4&quot;, &quot;#BA58C8&quot;, &quot;#CE5DCD&quot;,\n &quot;#E062C9&quot;, &quot;#E971B4&quot;, &quot;#F1809F&quot;, &quot;#F98F8A&quot;, &quot;#FFA07A&quot;,\n &quot;#FF9C65&quot;, &quot;#FF9850&quot;, &quot;#FF943B&quot;, &quot;#FF9026&quot;, &quot;#FF8C11&quot;,\n &quot;#F97F0D&quot;, &quot;#F3730A&quot;, &quot;#ED6606&quot;, &quot;#E75A03&quot;, &quot;#E04E00&quot;,\n &quot;#D4431E&quot;, &quot;#C8383C&quot;, &quot;#BC2D5A&quot;, &quot;#B02178&quot;, &quot;#A41596&quot;,\n &quot;#9710A3&quot;, &quot;#880EA7&quot;, &quot;#790CAB&quot;, &quot;#6A0AAF&quot;, &quot;#5C08B2&quot;,\n &quot;#4D06B6&quot;, &quot;#3E04BA&quot;, &quot;#2F02BD&quot;, &quot;#2000C1&quot;, &quot;#1800B8&quot;,\n &quot;#1000AF&quot;, &quot;#0800A6&quot;, &quot;#00009D&quot;, &quot;#00008F&quot;, &quot;#000081&quot;,\n &quot;#0B006C&quot;, &quot;#160057&quot;, &quot;#210043&quot;, &quot;#2C002E&quot;, &quot;#37001A&quot;\n )\n\n for solution, colori in zip(solutions, color):\n n_points = len(solution.t)\n y0, y1, y2, y3 = solution.y\n\n for j in range(n_points - 1):\n if y0[j] &lt;= 0 &lt;= y0[j + 1]:\n colors.append(colori)\n theta_2.append(y1[j + 1])\n theta_2_dot.append(y3[j + 1])\n\n fig, ax = plt.subplots()\n\n for m in range(len(theta_2)):\n ax.scatter((theta_2[m] + np.pi) % (2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n ax.set_xlabel(r&quot;<span class=\"math-container\">$\\theta_2\\ [rad]$</span>&quot;)\n ax.set_ylabel(r&quot;<span class=\"math-container\">$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$</span>&quot;)\n return fig\n\n\ndef solve_motion_equations(\n theta_1_0: np.ndarray,\n theta_2_0: np.ndarray,\n theta_1_dot_0: np.ndarray,\n theta_2_dot_0: np.ndarray,\n strict: bool = True,\n error_max: float = 1e-3,\n rtol: float = 1e-4, atol: float = 1e-6,\n) -&gt; list[OdeResult]:\n &quot;&quot;&quot;solving the equations of motion&quot;&quot;&quot;\n solutions = []\n\n # defining time interval\n t_span = (0, 750)\n jac_sparsity = np.array(( # All methods but LSODA\n (0, 0, 1, 0),\n (0, 0, 0, 1),\n (1, 1, 1, 1),\n (1, 1, 1, 1),\n ))\n # LSODA band parameters only reduce the Jacobian by one element; probably not worth it\n\n for i in range(len(theta_1_0)):\n y0 = (theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i])\n t0 = time.perf_counter()\n solutions.append(solve_ivp(\n fun=f, t_span=t_span, y0=y0, dense_output=True, method='LSODA',\n # jac_sparsity=jac_sparsity,\n rtol=rtol, atol=atol,\n ))\n t1 = time.perf_counter()\n print(t1 - t0)\n\n system_energy = E(*y0)\n for y in solutions[i].y.T:\n solution_energy = E(*y)\n error = np.abs(solution_energy - system_energy)\n if strict and error &gt; error_max:\n message = f'Energy drift of {error_max} exceeds maximum {error_max}'\n raise ValueError(message)\n\n return solutions\n\n\ndef fill_xy(solutions: list[OdeSolution]) -&gt; tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n x_1 = l_1*np.sin(solutions[0].y[0])\n x_2 = l_2*np.sin(solutions[0].y[1]) + x_1\n y_1 = -l_1*np.cos(solutions[0].y[0])\n y_2 = -l_2*np.cos(solutions[0].y[1]) + y_1\n return x_1, x_2, y_1, y_2\n\n\ndef plot(\n solutions: list[OdeSolution],\n x_1: np.ndarray, x_2: np.ndarray,\n y_1: np.ndarray, y_2: np.ndarray,\n) -&gt; None:\n fig, ax = plt.subplots()\n ax.plot(solutions[0].y[0], solutions[0].y[1])\n ax.set_xlabel(r&quot;<span class=\"math-container\">$\\theta_1\\ [rad]$</span>&quot;)\n ax.set_ylabel(r&quot;<span class=\"math-container\">$\\theta_2\\ [rad]$</span>&quot;)\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1)\n ax.set_xlabel('x_1')\n ax.set_ylabel('y_1')\n\n fig, ax = plt.subplots()\n ax.plot(x_2, y_2)\n ax.set_xlabel('x_2')\n ax.set_ylabel('y_2')\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1, label='y_1')\n ax.plot(x_2, y_2, label='y_2')\n ax.legend()\n\n\ndef main() -&gt; None:\n n_initial_conditions = 3 # 50\n rand = np.random.default_rng(seed=0)\n\n theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0 = initial_conditions(\n E=6.09, n_initial_conditions=n_initial_conditions, rand=rand,\n )\n solutions = solve_motion_equations(\n theta_1_0=theta_1_0, theta_1_dot_0=theta_1_dot_0,\n theta_2_0=theta_2_0, theta_2_dot_0=theta_2_dot_0,\n error_max=0.1,\n )\n plot_poincaré_section(solutions)\n x_1, x_2, y_1, y_2 = fill_xy(solutions)\n plot(solutions, x_1, x_2, y_1, y_2)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "answer_id": 45267, "answer_text": "Poincaré section obtained by conditions in the code\n\n\n\n\n\n\n\nI very much cannot reproduce what you've generated, after refactoring - I suspect due to moving to the more sophisticated LSODA and its accompanying parameters. I get results more similar to the resonances seen in e.g. Leo Stein's Poincaré sections (https://duetosymmetry.com/tool/poincare-section-clicker-toy/).\n\n\n\n\n\n\n\nThe code can also be improved, so if anyone has any suggestions\n\n\n\n\n\n\n\nWell... There's a lot. Since this is the Computational Science site and not the Code Review site, I will elide much of my feedback by saying \"improve your Python\". For the numerics:\n\n\n\n\n\nYour g is both wrong and unnecessary; get the correct value from Scipy instead\n\n\n\n\nDon't use the math module; stick to Numpy\n\n\n\n\nf() is both pretty slow and wholly illegible. It can be somewhat sped up by identifying common expressions, and should be broken up into many more lines. The same applies to E().\n\n\n\n\nThe current parameters to solve_ivp produce a very slow solution. Switch to LSODA and go easy on those tolerances.\n\n\n\n\nFor plotting, only call plt.show() once.\n\n\n\n\n\n[image: poincare; source: https://i.sstatic.net/INKhjIWk.png] (https://i.sstatic.net/INKhjIWk.png)\n\n\n\n\nimport time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp, OdeSolution\n\nfrom scipy.constants import g\nfrom scipy.integrate._ivp.ivp import OdeResult\n\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\n\n\ndef initial_conditions(\n E: float, n_initial_conditions: int, rand: np.random.Generator,\n) -> tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n theta_1_0 = np.zeros(n_initial_conditions)\n theta_2_0 = np.linspace(-0.5*np.pi, 0.5*np.pi, n_initial_conditions)\n theta_2_dot_0 = np.zeros(n_initial_conditions)\n\n abs_t10 = np.sqrt(\n 2*(\n (\n E + l_2*m_2*g*np.cos(theta_2_0)\n )/(m_1 + m_2)\n - l_2*g\n )\n )/l_1\n\n theta_1_dot_0 = abs_t10*rand.choice((-1, 1), size=n_initial_conditions)\n\n return theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0\n\n\ndef f(t: float, y: np.ndarray) -> tuple[\n float, float, float, float,\n]:\n y0, y1, y2, y3 = y\n sin_y01 = 2*np.sin(y0 - y1)\n cos_y01 = np.cos(y0 - y1)\n m12m2 = 2*m_1 + m_2\n den = m12m2 - m_2*np.cos(2*y0 - 2*y1)\n y22l1 = y2**2*l_1\n y32l2 = l_2*y3**2\n\n res = (\n y2,\n y3,\n (\n -g*np.sin(y0)*m12m2 - m_2*(\n g*np.sin(y0 - 2*y1)\n + sin_y01*(\n y22l1*cos_y01 + y32l2\n )\n )\n ) / (l_1*den),\n (\n sin_y01*(\n (m_1 + m_2)*(\n np.cos(y0)*g + y22l1\n )\n + m_2*y32l2*cos_y01\n )\n ) / (l_2*den),\n )\n return res\n\n\ndef E(y_1: float, y_2: float, y_3: float, y_4: float) -> float:\n \"\"\"energy of the system\"\"\"\n total_energy = (\n 0.5*l_1**2*y_3**2*(m_1 + m_2)\n + 0.5*m_2*l_2**2*y_4**2\n + m_2*l_1*l_2*y_3*y_4*np.cos(y_1 - y_2)\n - l_1*g*np.cos(y_1)*(m_1 + m_2)\n - l_2*m_2*g*np.cos(y_2)\n + (l_1 + l_2)*g*(m_1 + m_2)\n )\n return total_energy\n\n\ndef plot_poincaré_section(solutions: list[OdeSolution]) -> plt.Figure:\n theta_2 = []\n theta_2_dot = []\n colors = []\n\n color = (\n \"#2C3E50\", \"#3A3F64\", \"#484078\", \"#56428D\", \"#6B469E\",\n \"#804AAF\", \"#954EBF\", \"#A753C4\", \"#BA58C8\", \"#CE5DCD\",\n \"#E062C9\", \"#E971B4\", \"#F1809F\", \"#F98F8A\", \"#FFA07A\",\n \"#FF9C65\", \"#FF9850\", \"#FF943B\", \"#FF9026\", \"#FF8C11\",\n \"#F97F0D\", \"#F3730A\", \"#ED6606\", \"#E75A03\", \"#E04E00\",\n \"#D4431E\", \"#C8383C\", \"#BC2D5A\", \"#B02178\", \"#A41596\",\n \"#9710A3\", \"#880EA7\", \"#790CAB\", \"#6A0AAF\", \"#5C08B2\",\n \"#4D06B6\", \"#3E04BA\", \"#2F02BD\", \"#2000C1\", \"#1800B8\",\n \"#1000AF\", \"#0800A6\", \"#00009D\", \"#00008F\", \"#000081\",\n \"#0B006C\", \"#160057\", \"#210043\", \"#2C002E\", \"#37001A\"\n )\n\n for solution, colori in zip(solutions, color):\n n_points = len(solution.t)\n y0, y1, y2, y3 = solution.y\n\n for j in range(n_points - 1):\n if y0[j] <= 0 <= y0[j + 1]:\n colors.append(colori)\n theta_2.append(y1[j + 1])\n theta_2_dot.append(y3[j + 1])\n\n fig, ax = plt.subplots()\n\n for m in range(len(theta_2)):\n ax.scatter((theta_2[m] + np.pi) % (2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n ax.set_xlabel(r\"$\\theta_2\\ [rad]$\")\n ax.set_ylabel(r\"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$\")\n return fig\n\n\ndef solve_motion_equations(\n theta_1_0: np.ndarray,\n theta_2_0: np.ndarray,\n theta_1_dot_0: np.ndarray,\n theta_2_dot_0: np.ndarray,\n strict: bool = True,\n error_max: float = 1e-3,\n rtol: float = 1e-4, atol: float = 1e-6,\n) -> list[OdeResult]:\n \"\"\"solving the equations of motion\"\"\"\n solutions = []\n\n # defining time interval\n t_span = (0, 750)\n jac_sparsity = np.array(( # All methods but LSODA\n (0, 0, 1, 0),\n (0, 0, 0, 1),\n (1, 1, 1, 1),\n (1, 1, 1, 1),\n ))\n # LSODA band parameters only reduce the Jacobian by one element; probably not worth it\n\n for i in range(len(theta_1_0)):\n y0 = (theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i])\n t0 = time.perf_counter()\n solutions.append(solve_ivp(\n fun=f, t_span=t_span, y0=y0, dense_output=True, method='LSODA',\n # jac_sparsity=jac_sparsity,\n rtol=rtol, atol=atol,\n ))\n t1 = time.perf_counter()\n print(t1 - t0)\n\n system_energy = E(*y0)\n for y in solutions[i].y.T:\n solution_energy = E(*y)\n error = np.abs(solution_energy - system_energy)\n if strict and error > error_max:\n message = f'Energy drift of {error_max} exceeds maximum {error_max}'\n raise ValueError(message)\n\n return solutions\n\n\ndef fill_xy(solutions: list[OdeSolution]) -> tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n x_1 = l_1*np.sin(solutions[0].y[0])\n x_2 = l_2*np.sin(solutions[0].y[1]) + x_1\n y_1 = -l_1*np.cos(solutions[0].y[0])\n y_2 = -l_2*np.cos(solutions[0].y[1]) + y_1\n return x_1, x_2, y_1, y_2\n\n\ndef plot(\n solutions: list[OdeSolution],\n x_1: np.ndarray, x_2: np.ndarray,\n y_1: np.ndarray, y_2: np.ndarray,\n) -> None:\n fig, ax = plt.subplots()\n ax.plot(solutions[0].y[0], solutions[0].y[1])\n ax.set_xlabel(r\"$\\theta_1\\ [rad]$\")\n ax.set_ylabel(r\"$\\theta_2\\ [rad]$\")\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1)\n ax.set_xlabel('x_1')\n ax.set_ylabel('y_1')\n\n fig, ax = plt.subplots()\n ax.plot(x_2, y_2)\n ax.set_xlabel('x_2')\n ax.set_ylabel('y_2')\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1, label='y_1')\n ax.plot(x_2, y_2, label='y_2')\n ax.legend()\n\n\ndef main() -> None:\n n_initial_conditions = 3 # 50\n rand = np.random.default_rng(seed=0)\n\n theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0 = initial_conditions(\n E=6.09, n_initial_conditions=n_initial_conditions, rand=rand,\n )\n solutions = solve_motion_equations(\n theta_1_0=theta_1_0, theta_1_dot_0=theta_1_dot_0,\n theta_2_0=theta_2_0, theta_2_dot_0=theta_2_dot_0,\n error_max=0.1,\n )\n plot_poincaré_section(solutions)\n x_1, x_2, y_1, y_2 = fill_xy(solutions)\n plot(solutions, x_1, x_2, y_1, y_2)\n plt.show()\n\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45267", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-26T03:59:29+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45171, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2025-10-26T03:59:29+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "1952C7E4-BD5B-442D-86E8-1FF1EBB10DF9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/1952C7E4-BD5B-442D-86E8-1FF1EBB10DF9/view-source"}], "score": 3, "updated_at": "2025-10-26T03:59:29+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "validation", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "<blockquote>\n<p>Poincaré section obtained by conditions in the code</p>\n</blockquote>\n<p>I very much cannot reproduce what you've generated, after refactoring - I suspect due to moving to the more sophisticated LSODA and its accompanying parameters. I get results more similar to the resonances seen in e.g. <a href=\"https://duetosymmetry.com/tool/poincare-section-clicker-toy/\" rel=\"nofollow noreferrer\">Leo Stein's Poincaré sections</a>.</p>\n<blockquote>\n<p>The code can also be improved, so if anyone has any suggestions</p>\n</blockquote>\n<p>Well... There's a lot. Since this is the Computational Science site and not the Code Review site, I will elide much of my feedback by saying &quot;improve your Python&quot;. For the numerics:</p>\n<ul>\n<li>Your <code>g</code> is both wrong and unnecessary; get the correct value from Scipy instead</li>\n<li>Don't use the <code>math</code> module; stick to Numpy</li>\n<li><code>f()</code> is both pretty slow and wholly illegible. It can be somewhat sped up by identifying common expressions, and should be broken up into many more lines. The same applies to <code>E()</code>.</li>\n<li>The current parameters to <code>solve_ivp</code> produce a very slow solution. Switch to LSODA and go easy on those tolerances.</li>\n<li>For plotting, only call <code>plt.show()</code> once.</li>\n</ul>\n<p><a href=\"https://i.sstatic.net/INKhjIWk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/INKhjIWk.png\" alt=\"poincare\" /></a></p>\n<pre class=\"lang-py prettyprint-override\"><code>import time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp, OdeSolution\n\nfrom scipy.constants import g\nfrom scipy.integrate._ivp.ivp import OdeResult\n\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\n\n\ndef initial_conditions(\n E: float, n_initial_conditions: int, rand: np.random.Generator,\n) -&gt; tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n theta_1_0 = np.zeros(n_initial_conditions)\n theta_2_0 = np.linspace(-0.5*np.pi, 0.5*np.pi, n_initial_conditions)\n theta_2_dot_0 = np.zeros(n_initial_conditions)\n\n abs_t10 = np.sqrt(\n 2*(\n (\n E + l_2*m_2*g*np.cos(theta_2_0)\n )/(m_1 + m_2)\n - l_2*g\n )\n )/l_1\n\n theta_1_dot_0 = abs_t10*rand.choice((-1, 1), size=n_initial_conditions)\n\n return theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0\n\n\ndef f(t: float, y: np.ndarray) -&gt; tuple[\n float, float, float, float,\n]:\n y0, y1, y2, y3 = y\n sin_y01 = 2*np.sin(y0 - y1)\n cos_y01 = np.cos(y0 - y1)\n m12m2 = 2*m_1 + m_2\n den = m12m2 - m_2*np.cos(2*y0 - 2*y1)\n y22l1 = y2**2*l_1\n y32l2 = l_2*y3**2\n\n res = (\n y2,\n y3,\n (\n -g*np.sin(y0)*m12m2 - m_2*(\n g*np.sin(y0 - 2*y1)\n + sin_y01*(\n y22l1*cos_y01 + y32l2\n )\n )\n ) / (l_1*den),\n (\n sin_y01*(\n (m_1 + m_2)*(\n np.cos(y0)*g + y22l1\n )\n + m_2*y32l2*cos_y01\n )\n ) / (l_2*den),\n )\n return res\n\n\ndef E(y_1: float, y_2: float, y_3: float, y_4: float) -&gt; float:\n &quot;&quot;&quot;energy of the system&quot;&quot;&quot;\n total_energy = (\n 0.5*l_1**2*y_3**2*(m_1 + m_2)\n + 0.5*m_2*l_2**2*y_4**2\n + m_2*l_1*l_2*y_3*y_4*np.cos(y_1 - y_2)\n - l_1*g*np.cos(y_1)*(m_1 + m_2)\n - l_2*m_2*g*np.cos(y_2)\n + (l_1 + l_2)*g*(m_1 + m_2)\n )\n return total_energy\n\n\ndef plot_poincaré_section(solutions: list[OdeSolution]) -&gt; plt.Figure:\n theta_2 = []\n theta_2_dot = []\n colors = []\n\n color = (\n &quot;#2C3E50&quot;, &quot;#3A3F64&quot;, &quot;#484078&quot;, &quot;#56428D&quot;, &quot;#6B469E&quot;,\n &quot;#804AAF&quot;, &quot;#954EBF&quot;, &quot;#A753C4&quot;, &quot;#BA58C8&quot;, &quot;#CE5DCD&quot;,\n &quot;#E062C9&quot;, &quot;#E971B4&quot;, &quot;#F1809F&quot;, &quot;#F98F8A&quot;, &quot;#FFA07A&quot;,\n &quot;#FF9C65&quot;, &quot;#FF9850&quot;, &quot;#FF943B&quot;, &quot;#FF9026&quot;, &quot;#FF8C11&quot;,\n &quot;#F97F0D&quot;, &quot;#F3730A&quot;, &quot;#ED6606&quot;, &quot;#E75A03&quot;, &quot;#E04E00&quot;,\n &quot;#D4431E&quot;, &quot;#C8383C&quot;, &quot;#BC2D5A&quot;, &quot;#B02178&quot;, &quot;#A41596&quot;,\n &quot;#9710A3&quot;, &quot;#880EA7&quot;, &quot;#790CAB&quot;, &quot;#6A0AAF&quot;, &quot;#5C08B2&quot;,\n &quot;#4D06B6&quot;, &quot;#3E04BA&quot;, &quot;#2F02BD&quot;, &quot;#2000C1&quot;, &quot;#1800B8&quot;,\n &quot;#1000AF&quot;, &quot;#0800A6&quot;, &quot;#00009D&quot;, &quot;#00008F&quot;, &quot;#000081&quot;,\n &quot;#0B006C&quot;, &quot;#160057&quot;, &quot;#210043&quot;, &quot;#2C002E&quot;, &quot;#37001A&quot;\n )\n\n for solution, colori in zip(solutions, color):\n n_points = len(solution.t)\n y0, y1, y2, y3 = solution.y\n\n for j in range(n_points - 1):\n if y0[j] &lt;= 0 &lt;= y0[j + 1]:\n colors.append(colori)\n theta_2.append(y1[j + 1])\n theta_2_dot.append(y3[j + 1])\n\n fig, ax = plt.subplots()\n\n for m in range(len(theta_2)):\n ax.scatter((theta_2[m] + np.pi) % (2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n ax.set_xlabel(r&quot;<span class=\"math-container\">$\\theta_2\\ [rad]$</span>&quot;)\n ax.set_ylabel(r&quot;<span class=\"math-container\">$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$</span>&quot;)\n return fig\n\n\ndef solve_motion_equations(\n theta_1_0: np.ndarray,\n theta_2_0: np.ndarray,\n theta_1_dot_0: np.ndarray,\n theta_2_dot_0: np.ndarray,\n strict: bool = True,\n error_max: float = 1e-3,\n rtol: float = 1e-4, atol: float = 1e-6,\n) -&gt; list[OdeResult]:\n &quot;&quot;&quot;solving the equations of motion&quot;&quot;&quot;\n solutions = []\n\n # defining time interval\n t_span = (0, 750)\n jac_sparsity = np.array(( # All methods but LSODA\n (0, 0, 1, 0),\n (0, 0, 0, 1),\n (1, 1, 1, 1),\n (1, 1, 1, 1),\n ))\n # LSODA band parameters only reduce the Jacobian by one element; probably not worth it\n\n for i in range(len(theta_1_0)):\n y0 = (theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i])\n t0 = time.perf_counter()\n solutions.append(solve_ivp(\n fun=f, t_span=t_span, y0=y0, dense_output=True, method='LSODA',\n # jac_sparsity=jac_sparsity,\n rtol=rtol, atol=atol,\n ))\n t1 = time.perf_counter()\n print(t1 - t0)\n\n system_energy = E(*y0)\n for y in solutions[i].y.T:\n solution_energy = E(*y)\n error = np.abs(solution_energy - system_energy)\n if strict and error &gt; error_max:\n message = f'Energy drift of {error_max} exceeds maximum {error_max}'\n raise ValueError(message)\n\n return solutions\n\n\ndef fill_xy(solutions: list[OdeSolution]) -&gt; tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n x_1 = l_1*np.sin(solutions[0].y[0])\n x_2 = l_2*np.sin(solutions[0].y[1]) + x_1\n y_1 = -l_1*np.cos(solutions[0].y[0])\n y_2 = -l_2*np.cos(solutions[0].y[1]) + y_1\n return x_1, x_2, y_1, y_2\n\n\ndef plot(\n solutions: list[OdeSolution],\n x_1: np.ndarray, x_2: np.ndarray,\n y_1: np.ndarray, y_2: np.ndarray,\n) -&gt; None:\n fig, ax = plt.subplots()\n ax.plot(solutions[0].y[0], solutions[0].y[1])\n ax.set_xlabel(r&quot;<span class=\"math-container\">$\\theta_1\\ [rad]$</span>&quot;)\n ax.set_ylabel(r&quot;<span class=\"math-container\">$\\theta_2\\ [rad]$</span>&quot;)\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1)\n ax.set_xlabel('x_1')\n ax.set_ylabel('y_1')\n\n fig, ax = plt.subplots()\n ax.plot(x_2, y_2)\n ax.set_xlabel('x_2')\n ax.set_ylabel('y_2')\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1, label='y_1')\n ax.plot(x_2, y_2, label='y_2')\n ax.legend()\n\n\ndef main() -&gt; None:\n n_initial_conditions = 3 # 50\n rand = np.random.default_rng(seed=0)\n\n theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0 = initial_conditions(\n E=6.09, n_initial_conditions=n_initial_conditions, rand=rand,\n )\n solutions = solve_motion_equations(\n theta_1_0=theta_1_0, theta_1_dot_0=theta_1_dot_0,\n theta_2_0=theta_2_0, theta_2_dot_0=theta_2_dot_0,\n error_max=0.1,\n )\n plot_poincaré_section(solutions)\n x_1, x_2, y_1, y_2 = fill_xy(solutions)\n plot(solutions, x_1, x_2, y_1, y_2)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "answer_id": 45267, "answer_text": "Poincaré section obtained by conditions in the code\n\n\n\n\n\n\n\nI very much cannot reproduce what you've generated, after refactoring - I suspect due to moving to the more sophisticated LSODA and its accompanying parameters. I get results more similar to the resonances seen in e.g. Leo Stein's Poincaré sections (https://duetosymmetry.com/tool/poincare-section-clicker-toy/).\n\n\n\n\n\n\n\nThe code can also be improved, so if anyone has any suggestions\n\n\n\n\n\n\n\nWell... There's a lot. Since this is the Computational Science site and not the Code Review site, I will elide much of my feedback by saying \"improve your Python\". For the numerics:\n\n\n\n\n\nYour g is both wrong and unnecessary; get the correct value from Scipy instead\n\n\n\n\nDon't use the math module; stick to Numpy\n\n\n\n\nf() is both pretty slow and wholly illegible. It can be somewhat sped up by identifying common expressions, and should be broken up into many more lines. The same applies to E().\n\n\n\n\nThe current parameters to solve_ivp produce a very slow solution. Switch to LSODA and go easy on those tolerances.\n\n\n\n\nFor plotting, only call plt.show() once.\n\n\n\n\n\n[image: poincare; source: https://i.sstatic.net/INKhjIWk.png] (https://i.sstatic.net/INKhjIWk.png)\n\n\n\n\nimport time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp, OdeSolution\n\nfrom scipy.constants import g\nfrom scipy.integrate._ivp.ivp import OdeResult\n\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\n\n\ndef initial_conditions(\n E: float, n_initial_conditions: int, rand: np.random.Generator,\n) -> tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n theta_1_0 = np.zeros(n_initial_conditions)\n theta_2_0 = np.linspace(-0.5*np.pi, 0.5*np.pi, n_initial_conditions)\n theta_2_dot_0 = np.zeros(n_initial_conditions)\n\n abs_t10 = np.sqrt(\n 2*(\n (\n E + l_2*m_2*g*np.cos(theta_2_0)\n )/(m_1 + m_2)\n - l_2*g\n )\n )/l_1\n\n theta_1_dot_0 = abs_t10*rand.choice((-1, 1), size=n_initial_conditions)\n\n return theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0\n\n\ndef f(t: float, y: np.ndarray) -> tuple[\n float, float, float, float,\n]:\n y0, y1, y2, y3 = y\n sin_y01 = 2*np.sin(y0 - y1)\n cos_y01 = np.cos(y0 - y1)\n m12m2 = 2*m_1 + m_2\n den = m12m2 - m_2*np.cos(2*y0 - 2*y1)\n y22l1 = y2**2*l_1\n y32l2 = l_2*y3**2\n\n res = (\n y2,\n y3,\n (\n -g*np.sin(y0)*m12m2 - m_2*(\n g*np.sin(y0 - 2*y1)\n + sin_y01*(\n y22l1*cos_y01 + y32l2\n )\n )\n ) / (l_1*den),\n (\n sin_y01*(\n (m_1 + m_2)*(\n np.cos(y0)*g + y22l1\n )\n + m_2*y32l2*cos_y01\n )\n ) / (l_2*den),\n )\n return res\n\n\ndef E(y_1: float, y_2: float, y_3: float, y_4: float) -> float:\n \"\"\"energy of the system\"\"\"\n total_energy = (\n 0.5*l_1**2*y_3**2*(m_1 + m_2)\n + 0.5*m_2*l_2**2*y_4**2\n + m_2*l_1*l_2*y_3*y_4*np.cos(y_1 - y_2)\n - l_1*g*np.cos(y_1)*(m_1 + m_2)\n - l_2*m_2*g*np.cos(y_2)\n + (l_1 + l_2)*g*(m_1 + m_2)\n )\n return total_energy\n\n\ndef plot_poincaré_section(solutions: list[OdeSolution]) -> plt.Figure:\n theta_2 = []\n theta_2_dot = []\n colors = []\n\n color = (\n \"#2C3E50\", \"#3A3F64\", \"#484078\", \"#56428D\", \"#6B469E\",\n \"#804AAF\", \"#954EBF\", \"#A753C4\", \"#BA58C8\", \"#CE5DCD\",\n \"#E062C9\", \"#E971B4\", \"#F1809F\", \"#F98F8A\", \"#FFA07A\",\n \"#FF9C65\", \"#FF9850\", \"#FF943B\", \"#FF9026\", \"#FF8C11\",\n \"#F97F0D\", \"#F3730A\", \"#ED6606\", \"#E75A03\", \"#E04E00\",\n \"#D4431E\", \"#C8383C\", \"#BC2D5A\", \"#B02178\", \"#A41596\",\n \"#9710A3\", \"#880EA7\", \"#790CAB\", \"#6A0AAF\", \"#5C08B2\",\n \"#4D06B6\", \"#3E04BA\", \"#2F02BD\", \"#2000C1\", \"#1800B8\",\n \"#1000AF\", \"#0800A6\", \"#00009D\", \"#00008F\", \"#000081\",\n \"#0B006C\", \"#160057\", \"#210043\", \"#2C002E\", \"#37001A\"\n )\n\n for solution, colori in zip(solutions, color):\n n_points = len(solution.t)\n y0, y1, y2, y3 = solution.y\n\n for j in range(n_points - 1):\n if y0[j] <= 0 <= y0[j + 1]:\n colors.append(colori)\n theta_2.append(y1[j + 1])\n theta_2_dot.append(y3[j + 1])\n\n fig, ax = plt.subplots()\n\n for m in range(len(theta_2)):\n ax.scatter((theta_2[m] + np.pi) % (2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n ax.set_xlabel(r\"$\\theta_2\\ [rad]$\")\n ax.set_ylabel(r\"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$\")\n return fig\n\n\ndef solve_motion_equations(\n theta_1_0: np.ndarray,\n theta_2_0: np.ndarray,\n theta_1_dot_0: np.ndarray,\n theta_2_dot_0: np.ndarray,\n strict: bool = True,\n error_max: float = 1e-3,\n rtol: float = 1e-4, atol: float = 1e-6,\n) -> list[OdeResult]:\n \"\"\"solving the equations of motion\"\"\"\n solutions = []\n\n # defining time interval\n t_span = (0, 750)\n jac_sparsity = np.array(( # All methods but LSODA\n (0, 0, 1, 0),\n (0, 0, 0, 1),\n (1, 1, 1, 1),\n (1, 1, 1, 1),\n ))\n # LSODA band parameters only reduce the Jacobian by one element; probably not worth it\n\n for i in range(len(theta_1_0)):\n y0 = (theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i])\n t0 = time.perf_counter()\n solutions.append(solve_ivp(\n fun=f, t_span=t_span, y0=y0, dense_output=True, method='LSODA',\n # jac_sparsity=jac_sparsity,\n rtol=rtol, atol=atol,\n ))\n t1 = time.perf_counter()\n print(t1 - t0)\n\n system_energy = E(*y0)\n for y in solutions[i].y.T:\n solution_energy = E(*y)\n error = np.abs(solution_energy - system_energy)\n if strict and error > error_max:\n message = f'Energy drift of {error_max} exceeds maximum {error_max}'\n raise ValueError(message)\n\n return solutions\n\n\ndef fill_xy(solutions: list[OdeSolution]) -> tuple[\n np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n]:\n x_1 = l_1*np.sin(solutions[0].y[0])\n x_2 = l_2*np.sin(solutions[0].y[1]) + x_1\n y_1 = -l_1*np.cos(solutions[0].y[0])\n y_2 = -l_2*np.cos(solutions[0].y[1]) + y_1\n return x_1, x_2, y_1, y_2\n\n\ndef plot(\n solutions: list[OdeSolution],\n x_1: np.ndarray, x_2: np.ndarray,\n y_1: np.ndarray, y_2: np.ndarray,\n) -> None:\n fig, ax = plt.subplots()\n ax.plot(solutions[0].y[0], solutions[0].y[1])\n ax.set_xlabel(r\"$\\theta_1\\ [rad]$\")\n ax.set_ylabel(r\"$\\theta_2\\ [rad]$\")\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1)\n ax.set_xlabel('x_1')\n ax.set_ylabel('y_1')\n\n fig, ax = plt.subplots()\n ax.plot(x_2, y_2)\n ax.set_xlabel('x_2')\n ax.set_ylabel('y_2')\n\n fig, ax = plt.subplots()\n ax.plot(x_1, y_1, label='y_1')\n ax.plot(x_2, y_2, label='y_2')\n ax.legend()\n\n\ndef main() -> None:\n n_initial_conditions = 3 # 50\n rand = np.random.default_rng(seed=0)\n\n theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0 = initial_conditions(\n E=6.09, n_initial_conditions=n_initial_conditions, rand=rand,\n )\n solutions = solve_motion_equations(\n theta_1_0=theta_1_0, theta_1_dot_0=theta_1_dot_0,\n theta_2_0=theta_2_0, theta_2_dot_0=theta_2_dot_0,\n error_max=0.1,\n )\n plot_poincaré_section(solutions)\n x_1, x_2, y_1, y_2 = fill_xy(solutions)\n plot(solutions, x_1, x_2, y_1, y_2)\n plt.show()\n\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45267", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-26T03:59:29+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45171, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2025-10-26T03:59:29+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "1952C7E4-BD5B-442D-86E8-1FF1EBB10DF9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/1952C7E4-BD5B-442D-86E8-1FF1EBB10DF9/view-source"}], "score": 3, "updated_at": "2025-10-26T03:59:29+00:00"}], "domain": "computational_science", "external_links": ["https://duetosymmetry.com/tool/poincare-section-clicker-toy/", "https://github.com/DJopek/chaos/blob/main/double_pendulum.py", "https://i.sstatic.net/INKhjIWk.png", "https://i.sstatic.net/U0nOulED.png", "https://i.sstatic.net/oJaBUfA4.png"], "medical_sensitive": false, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:44.584971+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json", "raw_sha256": "27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "Dávid Jopek", "question_author_url": "https://scicomp.stackexchange.com/users/54327/d%c3%a1vid-jopek", "question_author_user_type": "registered", "question_created_at": "2025-07-15T18:16:26+00:00", "question_html": "<p>I wanted to try numerical analysis of a chaotic system. So I decided to write my own code for the Poincaré section of a double pendulum in Python. The code works and the Poincaré section should be correct, but I can't get a nice picture of the section, like you see in textbooks or on the internet. I don't know if the problem is in the choice of energies, the (number of) initial conditions, or the integration &quot;time interval&quot; and steps. Can someone more experienced advise me on a good approach to obtaining nice Poincaré sections? The code can also be improved, so if anyone has any suggestions for improvements, I would be very happy to hear them!</p>\n<p>Here is the code: <a href=\"https://github.com/DJopek/chaos/blob/main/double_pendulum.py\" rel=\"nofollow noreferrer\">https://github.com/DJopek/chaos/blob/main/double_pendulum.py</a></p>\n<pre class=\"lang-py prettyprint-override\"><code>import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\nfrom math import pi\nimport random\n\n# constants\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\ng = 9.81\n\n# Cauchy problem\n\n# y = [theta_1, theta_2, theta_1_dot, theta_2_dot]\n# y0 = [theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0]\n\n# generating initial conditions for some energy E\n\nnumber_of_initial_conditions = 50\n\ntheta_1_0 = []\n# theta_2_0 = []\ntheta_2_0 = np.linspace(-pi/2, pi/2, number_of_initial_conditions)\ntheta_1_dot_0 = []\ntheta_2_dot_0 = []\n\n# Energy = np.linspace(5,5.6,8) # [0,100] 1.\n# Energy = np.linspace(5.6,6.2,8) # [0,300] 2.\n# Energy = np.linspace(6.2,6.4,8) # [0,500] 3.\n# Energy = np.linspace(6.4,6.8,8) # [0,1000] 4.\n# Energy = np.linspace(5.9,6.3,8) # [0,700] 2-3.\n# Energy = np.linspace(6.3,6.8,12) # [0,1200] 3-4.\n# Energy = np.linspace(5.4,6.8,20) # [0,2000] 0.\n# Energy = np.linspace(5.6, 6.4, 16) # [0,700] 2_3\n# Energy = np.linspace(6.2,6.8,18) # [0,1200] 3_4.\n\n# Energy = [5.865]\nEnergy = [6.09]\n# Energy = [6.075]\n# Energy = [6.095]\n# Energy = [6.079]\n# Energy = [6.12]\n\n# number_of_initial_conditions = 1\n\ntotal_numbers_of_initial_conditions = number_of_initial_conditions*len(Energy)\n\ndef initial_conditions(E, number_of_initial_conditions):\n\n for i in range(number_of_initial_conditions):\n theta_1_0.append(0)\n # theta_2_0.append(np.random.uniform(-pi/4, pi/4))\n theta_2_dot_0.append(0)\n bucket = []\n bucket.append(np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n bucket.append(-np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n theta_1_dot_0.append(bucket[random.randint(0,1)])\n\nfor i in range(len(Energy)):\n initial_conditions(Energy[i], number_of_initial_conditions)\n\ndef f(t,y):\n return [y[2], \n y[3], \n (-g*np.sin(y[0])*(2*m_1+m_2)-g*m_2*np.sin(y[0]-2*y[1])-2*m_2*np.sin(y[0]-y[1])*(y[2]**2*l_1*np.cos(y[0]-y[1])+l_2*y[3]**2))/(l_1*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1]))), \n (2*np.sin(y[0]-y[1])*(np.cos(y[0])*g*(m_1+m_2)+l_1*(m_1+m_2)*y[2]**2+m_2*l_2*y[3]**2*np.cos(y[0]-y[1])))/(l_2*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1])))]\n\n# energy of the system\ndef E(y_1, y_2, y_3, y_4):\n total_energy = 0.5*l_1**2*y_3**2*(m_1+m_2)+0.5*m_2*l_2**2*y_4**2+m_2*l_1*l_2*y_3*y_4*np.cos(y_1-y_2)-l_1*g*np.cos(y_1)*(m_1+m_2)-l_2*m_2*g*np.cos(y_2)+(l_1+l_2)*g*(m_1+m_2)\n return total_energy\n\n# Poincaré section\ndef Poincare_section(total_numbers_of_initial_conditions):\n theta_2 = []\n theta_2_dot = []\n\n colors = []\n\n color = [\n &quot;#2C3E50&quot;, &quot;#3A3F64&quot;, &quot;#484078&quot;, &quot;#56428D&quot;, &quot;#6B469E&quot;,\n &quot;#804AAF&quot;, &quot;#954EBF&quot;, &quot;#A753C4&quot;, &quot;#BA58C8&quot;, &quot;#CE5DCD&quot;,\n &quot;#E062C9&quot;, &quot;#E971B4&quot;, &quot;#F1809F&quot;, &quot;#F98F8A&quot;, &quot;#FFA07A&quot;,\n &quot;#FF9C65&quot;, &quot;#FF9850&quot;, &quot;#FF943B&quot;, &quot;#FF9026&quot;, &quot;#FF8C11&quot;,\n &quot;#F97F0D&quot;, &quot;#F3730A&quot;, &quot;#ED6606&quot;, &quot;#E75A03&quot;, &quot;#E04E00&quot;,\n &quot;#D4431E&quot;, &quot;#C8383C&quot;, &quot;#BC2D5A&quot;, &quot;#B02178&quot;, &quot;#A41596&quot;,\n &quot;#9710A3&quot;, &quot;#880EA7&quot;, &quot;#790CAB&quot;, &quot;#6A0AAF&quot;, &quot;#5C08B2&quot;,\n &quot;#4D06B6&quot;, &quot;#3E04BA&quot;, &quot;#2F02BD&quot;, &quot;#2000C1&quot;, &quot;#1800B8&quot;,\n &quot;#1000AF&quot;, &quot;#0800A6&quot;, &quot;#00009D&quot;, &quot;#00008F&quot;, &quot;#000081&quot;,\n &quot;#0B006C&quot;, &quot;#160057&quot;, &quot;#210043&quot;, &quot;#2C002E&quot;, &quot;#37001A&quot;\n ]\n\n for i in range(total_numbers_of_initial_conditions):\n # color = [&quot;#&quot;+''.join([random.choice('0123456789ABCDEF') for r in range(6)])\n # for s in range(1)]\n\n number_of_points = len(solutions[i].t)\n\n for j in range(number_of_points-1):\n if solutions[i].y[0][j] &lt;= 0 and solutions[i].y[0][j+1] &gt;= 0:\n colors.append(color[i])\n theta_2.append(solutions[i].y[1][j+1])\n theta_2_dot.append(solutions[i].y[3][j+1])\n\n for m in range(len(theta_2)):\n plt.scatter((theta_2[m]+np.pi)%(2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n plt.xlabel(r&quot;<span class=\"math-container\">$\\theta_2\\ [rad]$</span>&quot;)\n plt.ylabel(r&quot;<span class=\"math-container\">$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$</span>&quot;)\n plt.show()\n\n# solving the equations of motion\nsolutions = []\n\nerror = 0.001\n\n# defining time interval\nt_span = [0,750]\n\nfor i in range(total_numbers_of_initial_conditions):\n y0 = [theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i]]\n system_energy = E(y0[0], y0[1], y0[2], y0[3])\n print(y0)\n print(system_energy)\n solutions.append(solve_ivp(f, t_span, y0, dense_output=True, rtol = 1e-12, atol = 1e-14))\n number_of_points = len(solutions[i].t)\n \n for j in range(number_of_points):\n solution_energy = E(solutions[i].y[0][j], solutions[i].y[1][j], solutions[i].y[2][j], solutions[i].y[3][j])\n if np.abs(solution_energy - system_energy) &gt; error:\n sys.exit('Maximum energy drift of {} exceeded.'.format(error))\n\nPoincare_section(total_numbers_of_initial_conditions)\n\nx_1 = []\nx_2 = []\ny_1 = []\ny_2 = []\n\nfor i in range(len(solutions[0].t)):\n x_1.append(l_1*np.sin(solutions[0].y[0][i]))\n x_2.append(x_1[i]+l_2*np.sin(solutions[0].y[1][i]))\n y_1.append(-l_1*np.cos(solutions[0].y[0][i]))\n y_2.append(y_1[i]-l_2*np.cos(solutions[0].y[1][i]))\n\nplt.plot(solutions[0].y[0], solutions[0].y[1])\nplt.xlabel(r&quot;<span class=\"math-container\">$\\theta_1\\ [rad]$</span>&quot;)\nplt.ylabel(r&quot;<span class=\"math-container\">$\\theta_2\\ [rad]$</span>&quot;)\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.show()\nplt.plot(x_2, y_2)\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.plot(x_2, y_2)\nplt.show()\n</code></pre>\n<p>Poincaré section obtained by conditions in the code:\n<a href=\"https://i.sstatic.net/U0nOulED.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/U0nOulED.png\" alt=\"Poincaré section obtained by conditions in the code\" /></a></p>\n<p>EDIT:\nPoincaré section obtained by conditions in the code with labels<a href=\"https://i.sstatic.net/oJaBUfA4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/oJaBUfA4.png\" alt=\"Poincaré section obtained by conditions in the code with labels\" /></a></p>\n", "question_id": 45171, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I wanted to try numerical analysis of a chaotic system. So I decided to write my own code for the Poincaré section of a double pendulum in Python. The code works and the Poincaré section should be correct, but I can't get a nice picture of the section, like you see in textbooks or on the internet. I don't know if the problem is in the choice of energies, the (number of) initial conditions, or the integration \"time interval\" and steps. Can someone more experienced advise me on a good approach to obtaining nice Poincaré sections? The code can also be improved, so if anyone has any suggestions for improvements, I would be very happy to hear them!\n\n\n\n\nHere is the code: https://github.com/DJopek/chaos/blob/main/double_pendulum.py (https://github.com/DJopek/chaos/blob/main/double_pendulum.py)\n\n\n\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\nfrom math import pi\nimport random\n\n# constants\nl_1 = 0.1\nl_2 = 0.5\nm_1 = 0.8\nm_2 = 0.3\ng = 9.81\n\n# Cauchy problem\n\n# y = [theta_1, theta_2, theta_1_dot, theta_2_dot]\n# y0 = [theta_1_0, theta_2_0, theta_1_dot_0, theta_2_dot_0]\n\n# generating initial conditions for some energy E\n\nnumber_of_initial_conditions = 50\n\ntheta_1_0 = []\n# theta_2_0 = []\ntheta_2_0 = np.linspace(-pi/2, pi/2, number_of_initial_conditions)\ntheta_1_dot_0 = []\ntheta_2_dot_0 = []\n\n# Energy = np.linspace(5,5.6,8) # [0,100] 1.\n# Energy = np.linspace(5.6,6.2,8) # [0,300] 2.\n# Energy = np.linspace(6.2,6.4,8) # [0,500] 3.\n# Energy = np.linspace(6.4,6.8,8) # [0,1000] 4.\n# Energy = np.linspace(5.9,6.3,8) # [0,700] 2-3.\n# Energy = np.linspace(6.3,6.8,12) # [0,1200] 3-4.\n# Energy = np.linspace(5.4,6.8,20) # [0,2000] 0.\n# Energy = np.linspace(5.6, 6.4, 16) # [0,700] 2_3\n# Energy = np.linspace(6.2,6.8,18) # [0,1200] 3_4.\n\n# Energy = [5.865]\nEnergy = [6.09]\n# Energy = [6.075]\n# Energy = [6.095]\n# Energy = [6.079]\n# Energy = [6.12]\n\n# number_of_initial_conditions = 1\n\ntotal_numbers_of_initial_conditions = number_of_initial_conditions*len(Energy)\n\ndef initial_conditions(E, number_of_initial_conditions):\n\n for i in range(number_of_initial_conditions):\n theta_1_0.append(0)\n # theta_2_0.append(np.random.uniform(-pi/4, pi/4))\n theta_2_dot_0.append(0)\n bucket = []\n bucket.append(np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n bucket.append(-np.sqrt(2*(E+l_1*g*(m_1+m_2)+l_2*m_2*g*np.cos(theta_2_0[i])-(l_1+l_2)*(m_1+m_2)*g)/(l_1**2*(m_1+m_2))))\n theta_1_dot_0.append(bucket[random.randint(0,1)])\n\nfor i in range(len(Energy)):\n initial_conditions(Energy[i], number_of_initial_conditions)\n\ndef f(t,y):\n return [y[2], \n y[3], \n (-g*np.sin(y[0])*(2*m_1+m_2)-g*m_2*np.sin(y[0]-2*y[1])-2*m_2*np.sin(y[0]-y[1])*(y[2]**2*l_1*np.cos(y[0]-y[1])+l_2*y[3]**2))/(l_1*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1]))), \n (2*np.sin(y[0]-y[1])*(np.cos(y[0])*g*(m_1+m_2)+l_1*(m_1+m_2)*y[2]**2+m_2*l_2*y[3]**2*np.cos(y[0]-y[1])))/(l_2*(2*m_1+m_2-m_2*np.cos(2*y[0]-2*y[1])))]\n\n# energy of the system\ndef E(y_1, y_2, y_3, y_4):\n total_energy = 0.5*l_1**2*y_3**2*(m_1+m_2)+0.5*m_2*l_2**2*y_4**2+m_2*l_1*l_2*y_3*y_4*np.cos(y_1-y_2)-l_1*g*np.cos(y_1)*(m_1+m_2)-l_2*m_2*g*np.cos(y_2)+(l_1+l_2)*g*(m_1+m_2)\n return total_energy\n\n# Poincaré section\ndef Poincare_section(total_numbers_of_initial_conditions):\n theta_2 = []\n theta_2_dot = []\n\n colors = []\n\n color = [\n \"#2C3E50\", \"#3A3F64\", \"#484078\", \"#56428D\", \"#6B469E\",\n \"#804AAF\", \"#954EBF\", \"#A753C4\", \"#BA58C8\", \"#CE5DCD\",\n \"#E062C9\", \"#E971B4\", \"#F1809F\", \"#F98F8A\", \"#FFA07A\",\n \"#FF9C65\", \"#FF9850\", \"#FF943B\", \"#FF9026\", \"#FF8C11\",\n \"#F97F0D\", \"#F3730A\", \"#ED6606\", \"#E75A03\", \"#E04E00\",\n \"#D4431E\", \"#C8383C\", \"#BC2D5A\", \"#B02178\", \"#A41596\",\n \"#9710A3\", \"#880EA7\", \"#790CAB\", \"#6A0AAF\", \"#5C08B2\",\n \"#4D06B6\", \"#3E04BA\", \"#2F02BD\", \"#2000C1\", \"#1800B8\",\n \"#1000AF\", \"#0800A6\", \"#00009D\", \"#00008F\", \"#000081\",\n \"#0B006C\", \"#160057\", \"#210043\", \"#2C002E\", \"#37001A\"\n ]\n\n for i in range(total_numbers_of_initial_conditions):\n # color = [\"#\"+''.join([random.choice('0123456789ABCDEF') for r in range(6)])\n # for s in range(1)]\n\n number_of_points = len(solutions[i].t)\n\n for j in range(number_of_points-1):\n if solutions[i].y[0][j] <= 0 and solutions[i].y[0][j+1] >= 0:\n colors.append(color[i])\n theta_2.append(solutions[i].y[1][j+1])\n theta_2_dot.append(solutions[i].y[3][j+1])\n\n for m in range(len(theta_2)):\n plt.scatter((theta_2[m]+np.pi)%(2 * np.pi) - np.pi, theta_2_dot[m], c=colors[m], s=0.1)\n\n plt.xlabel(r\"$\\theta_2\\ [rad]$\")\n plt.ylabel(r\"$\\dot{\\theta_2}\\ [rad \\cdot s^{-1}]$\")\n plt.show()\n\n# solving the equations of motion\nsolutions = []\n\nerror = 0.001\n\n# defining time interval\nt_span = [0,750]\n\nfor i in range(total_numbers_of_initial_conditions):\n y0 = [theta_1_0[i], theta_2_0[i], theta_1_dot_0[i], theta_2_dot_0[i]]\n system_energy = E(y0[0], y0[1], y0[2], y0[3])\n print(y0)\n print(system_energy)\n solutions.append(solve_ivp(f, t_span, y0, dense_output=True, rtol = 1e-12, atol = 1e-14))\n number_of_points = len(solutions[i].t)\n \n for j in range(number_of_points):\n solution_energy = E(solutions[i].y[0][j], solutions[i].y[1][j], solutions[i].y[2][j], solutions[i].y[3][j])\n if np.abs(solution_energy - system_energy) > error:\n sys.exit('Maximum energy drift of {} exceeded.'.format(error))\n\nPoincare_section(total_numbers_of_initial_conditions)\n\nx_1 = []\nx_2 = []\ny_1 = []\ny_2 = []\n\nfor i in range(len(solutions[0].t)):\n x_1.append(l_1*np.sin(solutions[0].y[0][i]))\n x_2.append(x_1[i]+l_2*np.sin(solutions[0].y[1][i]))\n y_1.append(-l_1*np.cos(solutions[0].y[0][i]))\n y_2.append(y_1[i]-l_2*np.cos(solutions[0].y[1][i]))\n\nplt.plot(solutions[0].y[0], solutions[0].y[1])\nplt.xlabel(r\"$\\theta_1\\ [rad]$\")\nplt.ylabel(r\"$\\theta_2\\ [rad]$\")\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.show()\nplt.plot(x_2, y_2)\nplt.show()\n\nplt.plot(x_1, y_1)\nplt.plot(x_2, y_2)\nplt.show()\n\n\n\n\n\nPoincaré section obtained by conditions in the code:\n[image: Poincaré section obtained by conditions in the code; source: https://i.sstatic.net/U0nOulED.png] (https://i.sstatic.net/U0nOulED.png)\n\n\n\n\nEDIT:\nPoincaré section obtained by conditions in the code with labels[image: Poincaré section obtained by conditions in the code with labels; source: https://i.sstatic.net/oJaBUfA4.png] (https://i.sstatic.net/oJaBUfA4.png)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dávid Jopek", "profile_url": "https://scicomp.stackexchange.com/users/54327/d%c3%a1vid-jopek", "user_type": "registered"}, "created_at": "2025-07-15T18:16:26+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "650653BB-F748-411A-AA5A-3EB629C84696", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/650653BB-F748-411A-AA5A-3EB629C84696/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dávid Jopek", "profile_url": "https://scicomp.stackexchange.com/users/54327/d%c3%a1vid-jopek", "user_type": "registered"}, "created_at": "2025-07-15T20:05:50+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "95B2D6D6-09DE-443D-9C99-ED7070A24120", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/95B2D6D6-09DE-443D-9C99-ED7070A24120/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2025-10-26T02:04:23+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "9709635F-9F4A-425B-AB66-BE60E6D8B46F", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9709635F-9F4A-425B-AB66-BE60E6D8B46F/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45171/poincar%c3%a9-section-for-double-pendulum-code-improvement", "split": "validation", "split_group": "381f73da7d816e1e3458beb0f1f8068c97e333253953f864c60d0e95d85a8757", "tags": ["python", "numerics", "ode", "computational-physics", "chaotic-systems"], "thread_id": "scicomp:45171", "title": "Poincaré section for double pendulum code improvement"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "function SolveDysktra( vY :: Vector{T}, mA :: Matrix{T}, vB :: Vector{T}, vL :: Vector{T}, vU :: Vector{T}; numIterations = 100 ) where {T <: AbstractFloat}\n\n numElements = length(vY);\n vX = copy(vY);\n vZ = zeros(T, numElements);\n vP = zeros(T, numElements);\n vQ = zeros(T, numElements);\n vT = zeros(T, numElements);\n\n sSvd = svd(mA);\n mVV = sSvd.V * sSvd.Vt;\n # mVS⁺Uᵗ = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U';\n\n vBB = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U' * vB;\n \n for _ in 1:numIterations\n\n vZ .= vX .+ vP;\n # Project `vZ` onto the Linear Equality\n mul!(vT, mVV, vZ);\n # vZ .= vZ .- vT .+ vBB;\n vZ .+= vBB .- vT;\n\n vP .+= vX .- vZ;\n\n vX .= vZ .+ vQ;\n # Project `vX` onto the Box Constraints\n vX .= clamp.(vX, vL, vU);\n vQ .+= vZ .- vX;\n\n end\n\n return vX;\n\nend\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45265, "sha256": "c49ef47f96ab84381961c2e6489a86e35d441ba6449536f790984a9a44cb1dd9", "source_url": "https://scicomp.stackexchange.com/a/45265"}], "other_answers": [{"answer_html": "<p>The <a href=\"https://en.wikipedia.org/wiki/Dykstra%27s_projection_algorithm\" rel=\"nofollow noreferrer\">Dykstra Projection Algorithm</a> is basically the ADMM Framework.<br />\nHence my idea is to use adaptive <span class=\"math-container\">$\\rho$</span> parameter according to the different relative errors as in <a href=\"https://web.stanford.edu/%7Eboyd/papers/admm_distr_stats.html\" rel=\"nofollow noreferrer\">Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers</a> in part 3.4.</p>\n", "answer_id": 45264, "answer_text": "The Dykstra Projection Algorithm (https://en.wikipedia.org/wiki/Dykstra%27s_projection_algorithm) is basically the ADMM Framework.\n\nHence my idea is to use adaptive $\\rho$ parameter according to the different relative errors as in Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers (https://web.stanford.edu/%7Eboyd/papers/admm_distr_stats.html) in part 3.4.", "answer_url": "https://scicomp.stackexchange.com/a/45264", "author": "Royi", "author_url": "https://scicomp.stackexchange.com/users/7951/royi", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-25T08:06:52+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45263, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2025-10-25T08:06:52+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "CB7599F6-93BC-4F4B-AEE5-1088862B4D12", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/CB7599F6-93BC-4F4B-AEE5-1088862B4D12/view-source"}], "score": 0, "updated_at": "2025-10-25T08:06:52+00:00"}, {"answer_html": "<p>Assuming the matrix <span class=\"math-container\">$\\boldsymbol{A}$</span> is dense:</p>\n<pre class=\"lang-julia prettyprint-override\"><code>function SolveDysktra( vY :: Vector{T}, mA :: Matrix{T}, vB :: Vector{T}, vL :: Vector{T}, vU :: Vector{T}; numIterations = 100 ) where {T &lt;: AbstractFloat}\n\n numElements = length(vY);\n vX = copy(vY);\n vZ = zeros(T, numElements);\n vP = zeros(T, numElements);\n vQ = zeros(T, numElements);\n vT = zeros(T, numElements);\n\n sSvd = svd(mA);\n mVV = sSvd.V * sSvd.Vt;\n # mVS⁺Uᵗ = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U';\n\n vBB = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U' * vB;\n \n for _ in 1:numIterations\n\n vZ .= vX .+ vP;\n # Project `vZ` onto the Linear Equality\n mul!(vT, mVV, vZ);\n # vZ .= vZ .- vT .+ vBB;\n vZ .+= vBB .- vT;\n\n vP .+= vX .- vZ;\n\n vX .= vZ .+ vQ;\n # Project `vX` onto the Box Constraints\n vX .= clamp.(vX, vL, vU);\n vQ .+= vZ .- vX;\n\n end\n\n return vX;\n\nend\n</code></pre>\n<p><strong>Remark</strong>: I'd be happy to see an efficient case of the Sparse case.</p>\n", "answer_id": 45265, "answer_text": "Assuming the matrix $\\boldsymbol{A}$ is dense:\n\n\n\n\nfunction SolveDysktra( vY :: Vector{T}, mA :: Matrix{T}, vB :: Vector{T}, vL :: Vector{T}, vU :: Vector{T}; numIterations = 100 ) where {T <: AbstractFloat}\n\n numElements = length(vY);\n vX = copy(vY);\n vZ = zeros(T, numElements);\n vP = zeros(T, numElements);\n vQ = zeros(T, numElements);\n vT = zeros(T, numElements);\n\n sSvd = svd(mA);\n mVV = sSvd.V * sSvd.Vt;\n # mVS⁺Uᵗ = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U';\n\n vBB = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U' * vB;\n \n for _ in 1:numIterations\n\n vZ .= vX .+ vP;\n # Project `vZ` onto the Linear Equality\n mul!(vT, mVV, vZ);\n # vZ .= vZ .- vT .+ vBB;\n vZ .+= vBB .- vT;\n\n vP .+= vX .- vZ;\n\n vX .= vZ .+ vQ;\n # Project `vX` onto the Box Constraints\n vX .= clamp.(vX, vL, vU);\n vQ .+= vZ .- vX;\n\n end\n\n return vX;\n\nend\n\n\n\n\n\nRemark: I'd be happy to see an efficient case of the Sparse case.", "answer_url": "https://scicomp.stackexchange.com/a/45265", "author": "Royi", "author_url": "https://scicomp.stackexchange.com/users/7951/royi", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-25T12:41:28+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45263, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2025-10-25T12:41:28+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "DEFDA34D-10C0-48A1-B4C0-85196E02AF64", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DEFDA34D-10C0-48A1-B4C0-85196E02AF64/view-source"}], "score": 1, "updated_at": "2025-10-25T12:41:28+00:00"}], "product": "code_qa", "question": "Solve the following problem:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A} \\boldsymbol{x} = \\boldsymbol{b} \\\\\n& \\quad & \\boldsymbol{x} \\leq \\boldsymbol{u} \\\\\n& \\quad & \\boldsymbol{x} \\geq \\boldsymbol{l} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{A} \\in \\mathbb{R}^{m \\times n}, \\; n \\gg m$ with independent rows.\n\n\n\n\nI want to solve it for the cases:\n\n\n\n\n\nThe matrix $\\boldsymbol{A}$ is dense.\n\n\n\n\nThe matrix $\\boldsymbol{A}$ is sparse.\n\n\n\n\n\nIn most efficient way without using high level solvers.\n\nBut just Use MATLAB / Python / Julia with their own Linear Algebra / Sparse libraries.\n\n\n\n\nCurrently my approach is to use Dykstra Projection Algorithm (https://en.wikipedia.org/wiki/Dykstra%27s_projection_algorithm).\n\nI wonder if there are some acceleration tricks.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45263", "selected_answer": {"answer_html": "<p>Read (if you're lucky, from your university's library)\n<a href=\"https://epubs.siam.org/doi/book/10.1137/1.9780898719857\" rel=\"nofollow noreferrer\"><em>Trust Region Methods</em>, Conn, Gould, and Toint [SIAM (2000)]</a> and its associated implementation in <a href=\"https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustconstr.html\" rel=\"nofollow noreferrer\">scipy.optimize.minimize(method='trust-constr')</a>. It will run for both the sparse and dense cases, though it may or may not be the most efficient approach in the dense case.</p>\n<p>Set:</p>\n<ul>\n<li><code>sparse_jacobian = True</code></li>\n<li><code>factorization_method = 'AugmentedSystem'</code></li>\n<li>Your <code>jac</code> and <code>hess</code> to functions where you provide the analytic Jacobian and Hessian of the cost function. Very simply, the Jacobian is <span class=\"math-container\">$x - y$</span>, and the Hessian is the (sparse) identity matrix.</li>\n<li>In the upper-level <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html\" rel=\"nofollow noreferrer\">minimize</a> interface, <code>bounds</code> by your <span class=\"math-container\">$l$</span> and <span class=\"math-container\">$u$</span></li>\n<li><code>constraints</code> to a <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.LinearConstraint.html\" rel=\"nofollow noreferrer\">LinearConstraint</a> by your <span class=\"math-container\">$A$</span> and using a scipy sparse array</li>\n<li><code>x0</code> to a sensible initial estimate</li>\n</ul>\n<p>In my testing, this converges to an optimality of <span class=\"math-container\">$2.7 \\times 10^{-5}$</span> within 14 calls to the cost function for a problem size of 15x200 and density 15%.</p>\n<p><a href=\"https://i.sstatic.net/YJ8UEXx7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/YJ8UEXx7.png\" alt=\"convergence\" /></a></p>\n", "answer_id": 45266, "answer_text": "Read (if you're lucky, from your university's library)\nTrust Region Methods, Conn, Gould, and Toint [SIAM (2000)] (https://epubs.siam.org/doi/book/10.1137/1.9780898719857) and its associated implementation in scipy.optimize.minimize(method='trust-constr') (https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustconstr.html). It will run for both the sparse and dense cases, though it may or may not be the most efficient approach in the dense case.\n\n\n\n\nSet:\n\n\n\n\n\nsparse_jacobian = True\n\n\n\n\nfactorization_method = 'AugmentedSystem'\n\n\n\n\nYour jac and hess to functions where you provide the analytic Jacobian and Hessian of the cost function. Very simply, the Jacobian is $x - y$, and the Hessian is the (sparse) identity matrix.\n\n\n\n\nIn the upper-level minimize (https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) interface, bounds by your $l$ and $u$\n\n\n\n\nconstraints to a LinearConstraint (https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.LinearConstraint.html) by your $A$ and using a scipy sparse array\n\n\n\n\nx0 to a sensible initial estimate\n\n\n\n\n\nIn my testing, this converges to an optimality of $2.7 \\times 10^{-5}$ within 14 calls to the cost function for a problem size of 15x200 and density 15%.\n\n\n\n\n[image: convergence; source: https://i.sstatic.net/YJ8UEXx7.png] (https://i.sstatic.net/YJ8UEXx7.png)", "answer_url": "https://scicomp.stackexchange.com/a/45266", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-25T13:17:14+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45263, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2025-10-25T13:17:14+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "77444703-E320-475F-B89E-303773BDEE64", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/77444703-E320-475F-B89E-303773BDEE64/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2025-10-25T19:40:38+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "C04032E9-FCDC-40CF-857D-605E6541C00E", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C04032E9-FCDC-40CF-857D-605E6541C00E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2025-10-25T19:54:56+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "09D74CCF-7C0C-4138-9B77-B959EBA73CBB", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/09D74CCF-7C0C-4138-9B77-B959EBA73CBB/view-source"}], "score": 2, "updated_at": "2025-10-25T19:54:56+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "validation", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "<p>The <a href=\"https://en.wikipedia.org/wiki/Dykstra%27s_projection_algorithm\" rel=\"nofollow noreferrer\">Dykstra Projection Algorithm</a> is basically the ADMM Framework.<br />\nHence my idea is to use adaptive <span class=\"math-container\">$\\rho$</span> parameter according to the different relative errors as in <a href=\"https://web.stanford.edu/%7Eboyd/papers/admm_distr_stats.html\" rel=\"nofollow noreferrer\">Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers</a> in part 3.4.</p>\n", "answer_id": 45264, "answer_text": "The Dykstra Projection Algorithm (https://en.wikipedia.org/wiki/Dykstra%27s_projection_algorithm) is basically the ADMM Framework.\n\nHence my idea is to use adaptive $\\rho$ parameter according to the different relative errors as in Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers (https://web.stanford.edu/%7Eboyd/papers/admm_distr_stats.html) in part 3.4.", "answer_url": "https://scicomp.stackexchange.com/a/45264", "author": "Royi", "author_url": "https://scicomp.stackexchange.com/users/7951/royi", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-25T08:06:52+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45263, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2025-10-25T08:06:52+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "CB7599F6-93BC-4F4B-AEE5-1088862B4D12", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/CB7599F6-93BC-4F4B-AEE5-1088862B4D12/view-source"}], "score": 0, "updated_at": "2025-10-25T08:06:52+00:00"}, {"answer_html": "<p>Assuming the matrix <span class=\"math-container\">$\\boldsymbol{A}$</span> is dense:</p>\n<pre class=\"lang-julia prettyprint-override\"><code>function SolveDysktra( vY :: Vector{T}, mA :: Matrix{T}, vB :: Vector{T}, vL :: Vector{T}, vU :: Vector{T}; numIterations = 100 ) where {T &lt;: AbstractFloat}\n\n numElements = length(vY);\n vX = copy(vY);\n vZ = zeros(T, numElements);\n vP = zeros(T, numElements);\n vQ = zeros(T, numElements);\n vT = zeros(T, numElements);\n\n sSvd = svd(mA);\n mVV = sSvd.V * sSvd.Vt;\n # mVS⁺Uᵗ = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U';\n\n vBB = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U' * vB;\n \n for _ in 1:numIterations\n\n vZ .= vX .+ vP;\n # Project `vZ` onto the Linear Equality\n mul!(vT, mVV, vZ);\n # vZ .= vZ .- vT .+ vBB;\n vZ .+= vBB .- vT;\n\n vP .+= vX .- vZ;\n\n vX .= vZ .+ vQ;\n # Project `vX` onto the Box Constraints\n vX .= clamp.(vX, vL, vU);\n vQ .+= vZ .- vX;\n\n end\n\n return vX;\n\nend\n</code></pre>\n<p><strong>Remark</strong>: I'd be happy to see an efficient case of the Sparse case.</p>\n", "answer_id": 45265, "answer_text": "Assuming the matrix $\\boldsymbol{A}$ is dense:\n\n\n\n\nfunction SolveDysktra( vY :: Vector{T}, mA :: Matrix{T}, vB :: Vector{T}, vL :: Vector{T}, vU :: Vector{T}; numIterations = 100 ) where {T <: AbstractFloat}\n\n numElements = length(vY);\n vX = copy(vY);\n vZ = zeros(T, numElements);\n vP = zeros(T, numElements);\n vQ = zeros(T, numElements);\n vT = zeros(T, numElements);\n\n sSvd = svd(mA);\n mVV = sSvd.V * sSvd.Vt;\n # mVS⁺Uᵗ = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U';\n\n vBB = sSvd.V * Diagonal(inv.(sSvd.S)) * sSvd.U' * vB;\n \n for _ in 1:numIterations\n\n vZ .= vX .+ vP;\n # Project `vZ` onto the Linear Equality\n mul!(vT, mVV, vZ);\n # vZ .= vZ .- vT .+ vBB;\n vZ .+= vBB .- vT;\n\n vP .+= vX .- vZ;\n\n vX .= vZ .+ vQ;\n # Project `vX` onto the Box Constraints\n vX .= clamp.(vX, vL, vU);\n vQ .+= vZ .- vX;\n\n end\n\n return vX;\n\nend\n\n\n\n\n\nRemark: I'd be happy to see an efficient case of the Sparse case.", "answer_url": "https://scicomp.stackexchange.com/a/45265", "author": "Royi", "author_url": "https://scicomp.stackexchange.com/users/7951/royi", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-25T12:41:28+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45263, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2025-10-25T12:41:28+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "DEFDA34D-10C0-48A1-B4C0-85196E02AF64", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DEFDA34D-10C0-48A1-B4C0-85196E02AF64/view-source"}], "score": 1, "updated_at": "2025-10-25T12:41:28+00:00"}, {"answer_html": "<p>Read (if you're lucky, from your university's library)\n<a href=\"https://epubs.siam.org/doi/book/10.1137/1.9780898719857\" rel=\"nofollow noreferrer\"><em>Trust Region Methods</em>, Conn, Gould, and Toint [SIAM (2000)]</a> and its associated implementation in <a href=\"https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustconstr.html\" rel=\"nofollow noreferrer\">scipy.optimize.minimize(method='trust-constr')</a>. It will run for both the sparse and dense cases, though it may or may not be the most efficient approach in the dense case.</p>\n<p>Set:</p>\n<ul>\n<li><code>sparse_jacobian = True</code></li>\n<li><code>factorization_method = 'AugmentedSystem'</code></li>\n<li>Your <code>jac</code> and <code>hess</code> to functions where you provide the analytic Jacobian and Hessian of the cost function. Very simply, the Jacobian is <span class=\"math-container\">$x - y$</span>, and the Hessian is the (sparse) identity matrix.</li>\n<li>In the upper-level <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html\" rel=\"nofollow noreferrer\">minimize</a> interface, <code>bounds</code> by your <span class=\"math-container\">$l$</span> and <span class=\"math-container\">$u$</span></li>\n<li><code>constraints</code> to a <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.LinearConstraint.html\" rel=\"nofollow noreferrer\">LinearConstraint</a> by your <span class=\"math-container\">$A$</span> and using a scipy sparse array</li>\n<li><code>x0</code> to a sensible initial estimate</li>\n</ul>\n<p>In my testing, this converges to an optimality of <span class=\"math-container\">$2.7 \\times 10^{-5}$</span> within 14 calls to the cost function for a problem size of 15x200 and density 15%.</p>\n<p><a href=\"https://i.sstatic.net/YJ8UEXx7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/YJ8UEXx7.png\" alt=\"convergence\" /></a></p>\n", "answer_id": 45266, "answer_text": "Read (if you're lucky, from your university's library)\nTrust Region Methods, Conn, Gould, and Toint [SIAM (2000)] (https://epubs.siam.org/doi/book/10.1137/1.9780898719857) and its associated implementation in scipy.optimize.minimize(method='trust-constr') (https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustconstr.html). It will run for both the sparse and dense cases, though it may or may not be the most efficient approach in the dense case.\n\n\n\n\nSet:\n\n\n\n\n\nsparse_jacobian = True\n\n\n\n\nfactorization_method = 'AugmentedSystem'\n\n\n\n\nYour jac and hess to functions where you provide the analytic Jacobian and Hessian of the cost function. Very simply, the Jacobian is $x - y$, and the Hessian is the (sparse) identity matrix.\n\n\n\n\nIn the upper-level minimize (https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) interface, bounds by your $l$ and $u$\n\n\n\n\nconstraints to a LinearConstraint (https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.LinearConstraint.html) by your $A$ and using a scipy sparse array\n\n\n\n\nx0 to a sensible initial estimate\n\n\n\n\n\nIn my testing, this converges to an optimality of $2.7 \\times 10^{-5}$ within 14 calls to the cost function for a problem size of 15x200 and density 15%.\n\n\n\n\n[image: convergence; source: https://i.sstatic.net/YJ8UEXx7.png] (https://i.sstatic.net/YJ8UEXx7.png)", "answer_url": "https://scicomp.stackexchange.com/a/45266", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-25T13:17:14+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:47.033952+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json", "raw_sha256": "1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45263, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2025-10-25T13:17:14+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "77444703-E320-475F-B89E-303773BDEE64", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/77444703-E320-475F-B89E-303773BDEE64/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2025-10-25T19:40:38+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "C04032E9-FCDC-40CF-857D-605E6541C00E", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C04032E9-FCDC-40CF-857D-605E6541C00E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2025-10-25T19:54:56+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "09D74CCF-7C0C-4138-9B77-B959EBA73CBB", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/09D74CCF-7C0C-4138-9B77-B959EBA73CBB/view-source"}], "score": 2, "updated_at": "2025-10-25T19:54:56+00:00"}], "domain": "computational_science", "external_links": ["https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.LinearConstraint.html", "https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html", "https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustconstr.html", "https://en.wikipedia.org/wiki/Dykstra%27s_projection_algorithm", "https://epubs.siam.org/doi/book/10.1137/1.9780898719857", "https://i.sstatic.net/YJ8UEXx7.png", "https://web.stanford.edu/%7Eboyd/papers/admm_distr_stats.html"], "medical_sensitive": false, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:44.584971+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json", "raw_sha256": "27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "Royi", "question_author_url": "https://scicomp.stackexchange.com/users/7951/royi", "question_author_user_type": "registered", "question_created_at": "2025-10-25T07:56:29+00:00", "question_html": "<p>Solve the following problem:</p>\n<p><span class=\"math-container\">$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } &amp; \\quad &amp; \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} \\\\\n\\text{subject to} &amp; \\quad &amp; \\boldsymbol{A} \\boldsymbol{x} = \\boldsymbol{b} \\\\\n&amp; \\quad &amp; \\boldsymbol{x} \\leq \\boldsymbol{u} \\\\\n&amp; \\quad &amp; \\boldsymbol{x} \\geq \\boldsymbol{l} \\\\\n\\end{alignat*}\n$$</span></p>\n<p>Where <span class=\"math-container\">$\\boldsymbol{A} \\in \\mathbb{R}^{m \\times n}, \\; n \\gg m$</span> with independent rows.</p>\n<p>I want to solve it for the cases:</p>\n<ul>\n<li>The matrix <span class=\"math-container\">$\\boldsymbol{A}$</span> is dense.</li>\n<li>The matrix <span class=\"math-container\">$\\boldsymbol{A}$</span> is sparse.</li>\n</ul>\n<p>In most efficient way without using high level solvers.<br />\nBut just Use MATLAB / Python / Julia with their own Linear Algebra / Sparse libraries.</p>\n<p>Currently my approach is to use <a href=\"https://en.wikipedia.org/wiki/Dykstra%27s_projection_algorithm\" rel=\"nofollow noreferrer\">Dykstra Projection Algorithm</a>.<br />\nI wonder if there are some <em>acceleration</em> tricks.</p>\n", "question_id": 45263, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "Solve the following problem:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A} \\boldsymbol{x} = \\boldsymbol{b} \\\\\n& \\quad & \\boldsymbol{x} \\leq \\boldsymbol{u} \\\\\n& \\quad & \\boldsymbol{x} \\geq \\boldsymbol{l} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{A} \\in \\mathbb{R}^{m \\times n}, \\; n \\gg m$ with independent rows.\n\n\n\n\nI want to solve it for the cases:\n\n\n\n\n\nThe matrix $\\boldsymbol{A}$ is dense.\n\n\n\n\nThe matrix $\\boldsymbol{A}$ is sparse.\n\n\n\n\n\nIn most efficient way without using high level solvers.\n\nBut just Use MATLAB / Python / Julia with their own Linear Algebra / Sparse libraries.\n\n\n\n\nCurrently my approach is to use Dykstra Projection Algorithm (https://en.wikipedia.org/wiki/Dykstra%27s_projection_algorithm).\n\nI wonder if there are some acceleration tricks.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2025-10-25T07:56:29+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "DF5239D1-D290-4E4D-8617-75F92FF57C54", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DF5239D1-D290-4E4D-8617-75F92FF57C54/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2025-10-25T08:26:46+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "2BF9CB7D-E76F-4860-A4F6-A56EC7531A4A", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/2BF9CB7D-E76F-4860-A4F6-A56EC7531A4A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Royi", "profile_url": "https://scicomp.stackexchange.com/users/7951/royi", "user_type": "registered"}, "created_at": "2025-10-25T13:00:20+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "2EBDE250-18A1-48AB-86D2-B3F738B95AF9", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/2EBDE250-18A1-48AB-86D2-B3F738B95AF9/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2025-10-25T14:18:00+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "A9C67614-2757-42FE-A099-DC88CD488EA4", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A9C67614-2757-42FE-A099-DC88CD488EA4/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2025-10-25T16:07:18+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "317E066A-AF61-43AC-9D80-48169DD78101", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/317E066A-AF61-43AC-9D80-48169DD78101/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45263/solve-projection-problem-with-linear-equality-and-box-constraints", "split": "validation", "split_group": "db5d84e70e2cb0351ad77431557fa05dcc2c5f563d95a98224a953d7fd1bf99c", "tags": ["linear-algebra", "convex-optimization", "projection"], "thread_id": "scicomp:45263", "title": "Solve Projection Problem with Linear Equality and Box Constraints"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -> np.ndarray:\n \"\"\"\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n \"\"\"\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -> np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 <= xp) & (xp <= x1) & (y0 <= yp) & (yp <= y1)\n hits[:-1, :-1] &= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -> np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 < xi) & (xi < x1) & (y0 < yi) & (yi < y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -> int:\n norm2 = np.einsum('ij,ij->j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -> None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -> None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45537, "sha256": "6637077f835d130cffa7ea8578142da4476921b98d0380a50f965b7d7ccb12a0", "source_url": "https://scicomp.stackexchange.com/a/45537"}], "other_answers": [], "product": "code_qa", "question": "I have a collection of axis-aligned bounding boxes (AABBs). The AABBs may overlap each other and may form multiple disconnected groups.\n\n\n\n\n\nIf P is not inside any AABB, I don't need to do anything.\n\n\n\n\nIf P is inside one or more AABBs, I need to find the closest point to P that is outside all AABBs\n\n\n\n\nA point lying exactly on the edge/boundary of an AABB is considered valid (not inside). Therefore, when P is inside an AABB group, the desired result will normally be a point on the edge of one of the AABBs.\n\n\n\n\n\nIs there a known algorithm for this problem?\n\n\n\n\nThanks.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45533", "selected_answer": {"answer_html": "<p>The key insight (also reflected in <a href=\"https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them#comment93668_45533\">this comment</a>) is that the closest non-occluded point will either be at the intersection of two bounding box segments, or will be at the intersection of one bounding box segment and one axis - after the problem space has been translated so that <span class=\"math-container\">$P = (0,0)$</span>. The axis intersection is because of the 'axis-aligned' bounding boxes and the fact that Euclidean norm to a point on vertical segments will scale as <span class=\"math-container\">$\\frac 1 {\\cos(\\theta)}$</span> and norm to a point on horizontal segments will scale as <span class=\"math-container\">$\\frac 1 {\\sin(\\theta)}$</span>. In both cases, the result is that the norm minima are seen at axis intersections (<span class=\"math-container\">$\\theta = \\frac {\\pi n} 2$</span>).</p>\n<p>Since you've failed to describe the scale of the problem, start with a simple <span class=\"math-container\">$O(n^2)$</span> implementation - which, for small problems, may actually out-perform anything more sophisticated. That depends on a lot of things and requires benchmarking diligence. Loosely,</p>\n<ol>\n<li>Union the set of all box-box intersections and all box-axis intersections</li>\n<li>From that set, exclude all points that are occluded by a box</li>\n<li>Do a tensor contraction to get the squared norm for the remaining intersections</li>\n<li>Choose the smallest one.</li>\n</ol>\n<p>For small bounding box count, it's very frequent that an axis intersection is selected:</p>\n<p><a href=\"https://i.sstatic.net/rLLW3nkZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/rLLW3nkZ.png\" alt=\"small problem\" /></a></p>\n<p>For 90 bounding boxes, we see a non-axis intersection being selected:</p>\n<p><a href=\"https://i.sstatic.net/B0XWwMzu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/B0XWwMzu.png\" alt=\"90 boxes\" /></a></p>\n<p>On my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -&gt; np.ndarray:\n &quot;&quot;&quot;\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n &quot;&quot;&quot;\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -&gt; np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 &lt;= xp) &amp; (xp &lt;= x1) &amp; (y0 &lt;= yp) &amp; (yp &lt;= y1)\n hits[:-1, :-1] &amp;= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -&gt; np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 &lt; xi) &amp; (xi &lt; x1) &amp; (y0 &lt; yi) &amp; (yi &lt; y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -&gt; int:\n norm2 = np.einsum('ij,ij-&gt;j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -&gt; None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -&gt; None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "answer_id": 45537, "answer_text": "The key insight (also reflected in this comment (https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them#comment93668_45533)) is that the closest non-occluded point will either be at the intersection of two bounding box segments, or will be at the intersection of one bounding box segment and one axis - after the problem space has been translated so that $P = (0,0)$. The axis intersection is because of the 'axis-aligned' bounding boxes and the fact that Euclidean norm to a point on vertical segments will scale as $\\frac 1 {\\cos(\\theta)}$ and norm to a point on horizontal segments will scale as $\\frac 1 {\\sin(\\theta)}$. In both cases, the result is that the norm minima are seen at axis intersections ($\\theta = \\frac {\\pi n} 2$).\n\n\n\n\nSince you've failed to describe the scale of the problem, start with a simple $O(n^2)$ implementation - which, for small problems, may actually out-perform anything more sophisticated. That depends on a lot of things and requires benchmarking diligence. Loosely,\n\n\n\n\n\nUnion the set of all box-box intersections and all box-axis intersections\n\n\n\n\nFrom that set, exclude all points that are occluded by a box\n\n\n\n\nDo a tensor contraction to get the squared norm for the remaining intersections\n\n\n\n\nChoose the smallest one.\n\n\n\n\n\nFor small bounding box count, it's very frequent that an axis intersection is selected:\n\n\n\n\n[image: small problem; source: https://i.sstatic.net/rLLW3nkZ.png] (https://i.sstatic.net/rLLW3nkZ.png)\n\n\n\n\nFor 90 bounding boxes, we see a non-axis intersection being selected:\n\n\n\n\n[image: 90 boxes; source: https://i.sstatic.net/B0XWwMzu.png] (https://i.sstatic.net/B0XWwMzu.png)\n\n\n\n\nOn my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -> np.ndarray:\n \"\"\"\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n \"\"\"\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -> np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 <= xp) & (xp <= x1) & (y0 <= yp) & (yp <= y1)\n hits[:-1, :-1] &= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -> np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 < xi) & (xi < x1) & (y0 < yi) & (yi < y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -> int:\n norm2 = np.einsum('ij,ij->j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -> None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -> None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45537", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-07T22:20:58+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45533, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2026-09-07T22:20:58+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "EA034CBB-245E-47BE-9F83-73186A65FD54", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/EA034CBB-245E-47BE-9F83-73186A65FD54/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2026-09-07T22:53:19+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "13520681-83F3-4234-8A59-CE187F0BEA29", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/13520681-83F3-4234-8A59-CE187F0BEA29/view-source"}], "score": 2, "updated_at": "2026-09-07T22:53:19+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "validation", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "<p>The key insight (also reflected in <a href=\"https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them#comment93668_45533\">this comment</a>) is that the closest non-occluded point will either be at the intersection of two bounding box segments, or will be at the intersection of one bounding box segment and one axis - after the problem space has been translated so that <span class=\"math-container\">$P = (0,0)$</span>. The axis intersection is because of the 'axis-aligned' bounding boxes and the fact that Euclidean norm to a point on vertical segments will scale as <span class=\"math-container\">$\\frac 1 {\\cos(\\theta)}$</span> and norm to a point on horizontal segments will scale as <span class=\"math-container\">$\\frac 1 {\\sin(\\theta)}$</span>. In both cases, the result is that the norm minima are seen at axis intersections (<span class=\"math-container\">$\\theta = \\frac {\\pi n} 2$</span>).</p>\n<p>Since you've failed to describe the scale of the problem, start with a simple <span class=\"math-container\">$O(n^2)$</span> implementation - which, for small problems, may actually out-perform anything more sophisticated. That depends on a lot of things and requires benchmarking diligence. Loosely,</p>\n<ol>\n<li>Union the set of all box-box intersections and all box-axis intersections</li>\n<li>From that set, exclude all points that are occluded by a box</li>\n<li>Do a tensor contraction to get the squared norm for the remaining intersections</li>\n<li>Choose the smallest one.</li>\n</ol>\n<p>For small bounding box count, it's very frequent that an axis intersection is selected:</p>\n<p><a href=\"https://i.sstatic.net/rLLW3nkZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/rLLW3nkZ.png\" alt=\"small problem\" /></a></p>\n<p>For 90 bounding boxes, we see a non-axis intersection being selected:</p>\n<p><a href=\"https://i.sstatic.net/B0XWwMzu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/B0XWwMzu.png\" alt=\"90 boxes\" /></a></p>\n<p>On my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -&gt; np.ndarray:\n &quot;&quot;&quot;\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n &quot;&quot;&quot;\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -&gt; np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 &lt;= xp) &amp; (xp &lt;= x1) &amp; (y0 &lt;= yp) &amp; (yp &lt;= y1)\n hits[:-1, :-1] &amp;= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -&gt; np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 &lt; xi) &amp; (xi &lt; x1) &amp; (y0 &lt; yi) &amp; (yi &lt; y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -&gt; int:\n norm2 = np.einsum('ij,ij-&gt;j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -&gt; None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -&gt; None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "answer_id": 45537, "answer_text": "The key insight (also reflected in this comment (https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them#comment93668_45533)) is that the closest non-occluded point will either be at the intersection of two bounding box segments, or will be at the intersection of one bounding box segment and one axis - after the problem space has been translated so that $P = (0,0)$. The axis intersection is because of the 'axis-aligned' bounding boxes and the fact that Euclidean norm to a point on vertical segments will scale as $\\frac 1 {\\cos(\\theta)}$ and norm to a point on horizontal segments will scale as $\\frac 1 {\\sin(\\theta)}$. In both cases, the result is that the norm minima are seen at axis intersections ($\\theta = \\frac {\\pi n} 2$).\n\n\n\n\nSince you've failed to describe the scale of the problem, start with a simple $O(n^2)$ implementation - which, for small problems, may actually out-perform anything more sophisticated. That depends on a lot of things and requires benchmarking diligence. Loosely,\n\n\n\n\n\nUnion the set of all box-box intersections and all box-axis intersections\n\n\n\n\nFrom that set, exclude all points that are occluded by a box\n\n\n\n\nDo a tensor contraction to get the squared norm for the remaining intersections\n\n\n\n\nChoose the smallest one.\n\n\n\n\n\nFor small bounding box count, it's very frequent that an axis intersection is selected:\n\n\n\n\n[image: small problem; source: https://i.sstatic.net/rLLW3nkZ.png] (https://i.sstatic.net/rLLW3nkZ.png)\n\n\n\n\nFor 90 bounding boxes, we see a non-axis intersection being selected:\n\n\n\n\n[image: 90 boxes; source: https://i.sstatic.net/B0XWwMzu.png] (https://i.sstatic.net/B0XWwMzu.png)\n\n\n\n\nOn my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -> np.ndarray:\n \"\"\"\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n \"\"\"\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -> np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 <= xp) & (xp <= x1) & (y0 <= yp) & (yp <= y1)\n hits[:-1, :-1] &= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -> np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 < xi) & (xi < x1) & (y0 < yi) & (yi < y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -> int:\n norm2 = np.einsum('ij,ij->j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -> None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -> None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45537", "author": "Reinderien", "author_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-07T22:20:58+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:49.393498+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json", "raw_sha256": "dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 45533, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2026-09-07T22:20:58+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "EA034CBB-245E-47BE-9F83-73186A65FD54", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/EA034CBB-245E-47BE-9F83-73186A65FD54/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Reinderien", "profile_url": "https://scicomp.stackexchange.com/users/41212/reinderien", "user_type": "registered"}, "created_at": "2026-09-07T22:53:19+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "13520681-83F3-4234-8A59-CE187F0BEA29", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/13520681-83F3-4234-8A59-CE187F0BEA29/view-source"}], "score": 2, "updated_at": "2026-09-07T22:53:19+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/B0XWwMzu.png", "https://i.sstatic.net/rLLW3nkZ.png"], "medical_sensitive": false, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:28:44.584971+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/272744bcc95b58699f7df6e6979b288bb8b00a80ab9c7982dbe170a6d0b63584_1790825325025901700_0.json", "raw_sha256": "27a81850a40920682c29ada76a2b55e80340a5c82764a3e9dde8a9c2ba23db4e", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=1&pagesize=100&site=scicomp&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "ffbh", "question_author_url": "https://scicomp.stackexchange.com/users/57252/ffbh", "question_author_user_type": "registered", "question_created_at": "2026-09-03T03:48:42+00:00", "question_html": "<p>I have a collection of axis-aligned bounding boxes (AABBs). The AABBs may overlap each other and may form multiple disconnected groups.</p>\n<ol>\n<li>If P is not inside any AABB, I don't need to do anything.</li>\n<li>If P is inside one or more AABBs, I need to find the closest point to P that is outside all AABBs</li>\n<li>A point lying exactly on the edge/boundary of an AABB is considered valid (not inside). Therefore, when P is inside an AABB group, the desired result will normally be a point on the edge of one of the AABBs.</li>\n</ol>\n<p>Is there a known algorithm for this problem?</p>\n<p>Thanks.</p>\n", "question_id": 45533, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I have a collection of axis-aligned bounding boxes (AABBs). The AABBs may overlap each other and may form multiple disconnected groups.\n\n\n\n\n\nIf P is not inside any AABB, I don't need to do anything.\n\n\n\n\nIf P is inside one or more AABBs, I need to find the closest point to P that is outside all AABBs\n\n\n\n\nA point lying exactly on the edge/boundary of an AABB is considered valid (not inside). Therefore, when P is inside an AABB group, the desired result will normally be a point on the edge of one of the AABBs.\n\n\n\n\n\nIs there a known algorithm for this problem?\n\n\n\n\nThanks.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "ffbh", "profile_url": "https://scicomp.stackexchange.com/users/57252/ffbh", "user_type": "registered"}, "created_at": "2026-09-03T03:48:42+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "4165EEB0-A429-43DE-A4E0-E9FB5F902B12", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/4165EEB0-A429-43DE-A4E0-E9FB5F902B12/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them", "split": "validation", "split_group": "71a1e1aa9ca97a050ab7c198593fba301c532fe3b80fdc4f0cab34aff62615f9", "tags": ["algorithms", "computational-geometry", "geometry"], "thread_id": "scicomp:45533", "title": "Find the closest point outside overlapping AABBs from a point inside them"}}